From 60f1e21d032d1f980ddfc069799ecfd3d4d7698b Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Sun, 3 Feb 2019 19:27:07 +0100 Subject: [PATCH] Added checkstyle --- .editorconfig | 14 + .settings.xml | 6 +- .springformat | 0 pom.xml | 54 +- spring-cloud-starter-task/pom.xml | 4 +- spring-cloud-task-batch/pom.xml | 9 +- .../TaskBatchAutoConfiguration.java | 28 +- ...tchExecutionListenerBeanPostProcessor.java | 20 +- ...TaskBatchExecutionListenerFactoryBean.java | 52 +- .../configuration/TaskBatchProperties.java | 38 +- .../TaskJobLauncherAutoConfiguration.java | 41 +- ...bLauncherCommandLineRunnerFactoryBean.java | 37 +- .../TaskJobLauncherCommandLineRunner.java | 63 +- .../task/batch/listener/TaskBatchDao.java | 5 +- .../listener/TaskBatchExecutionListener.java | 24 +- .../listener/support/JdbcTaskBatchDao.java | 15 +- .../listener/support/MapTaskBatchDao.java | 15 +- .../partition/CommandLineArgsProvider.java | 7 +- .../partition/DeployerPartitionHandler.java | 200 ++--- .../DeployerStepExecutionHandler.java | 80 +- .../EnvironmentVariablesProvider.java | 12 +- .../NoOpEnvironmentVariablesProvider.java | 13 +- .../PassThroughCommandLineArgsProvider.java | 6 +- .../SimpleCommandLineArgsProvider.java | 14 +- .../SimpleEnvironmentVariablesProvider.java | 36 +- ...itional-spring-configuration-metadata.json | 124 +-- .../batch/configuration/TaskBatchTest.java | 21 +- ...TaskJobLauncherAutoConfigurationTests.java | 56 +- ...JobLauncherCommandLineRunnerCoreTests.java | 53 +- ...TaskJobLauncherCommandLineRunnerTests.java | 158 ++-- .../task/batch/listener/PrefixTests.java | 40 +- .../TaskBatchExecutionListenerTests.java | 190 +++-- .../DeployerPartitionHandlerTests.java | 493 +++++++----- .../DeployerStepExecutionHandlerTests.java | 206 +++-- ...NoOpEnvironmentVariablesProviderTests.java | 19 +- ...ssThroughCommandLineArgsProviderTests.java | 13 +- .../SimpleCommandLineArgsProviderTests.java | 41 +- spring-cloud-task-core/pom.xml | 4 +- .../configuration/DefaultTaskConfigurer.java | 63 +- .../cloud/task/configuration/EnableTask.java | 17 +- .../SimpleTaskAutoConfiguration.java | 45 +- .../SingleInstanceTaskListener.java | 60 +- .../SingleTaskConfiguration.java | 34 +- .../task/configuration/TaskConfigurer.java | 19 +- .../TaskLifecycleConfiguration.java | 41 +- .../task/configuration/TaskProperties.java | 72 +- .../task/configuration/package-info.java | 16 + .../cloud/task/listener/TaskException.java | 7 +- .../task/listener/TaskExecutionException.java | 7 +- .../task/listener/TaskExecutionListener.java | 17 +- .../TaskExecutionListenerSupport.java | 5 +- .../task/listener/TaskLifecycleListener.java | 190 +++-- .../TaskListenerExecutorObjectFactory.java | 100 ++- .../task/listener/annotation/AfterTask.java | 10 +- .../task/listener/annotation/BeforeTask.java | 10 +- .../task/listener/annotation/FailedTask.java | 10 +- .../annotation/TaskListenerExecutor.java | 55 +- .../cloud/task/package-info.java | 16 + .../cloud/task/repository/TaskExecution.java | 69 +- .../cloud/task/repository/TaskExplorer.java | 52 +- .../task/repository/TaskNameResolver.java | 4 +- .../cloud/task/repository/TaskRepository.java | 62 +- .../repository/dao/JdbcTaskExecutionDao.java | 347 ++++---- .../repository/dao/MapTaskExecutionDao.java | 180 +++-- .../task/repository/dao/TaskExecutionDao.java | 95 +-- .../task/repository/dao/package-info.java | 16 + .../database/PagingQueryProvider.java | 14 +- .../AbstractSqlPagingQueryProvider.java | 94 +-- .../support/Db2PagingQueryProvider.java | 22 +- .../support/H2PagingQueryProvider.java | 6 +- .../support/HsqlPagingQueryProvider.java | 9 +- .../support/MySqlPagingQueryProvider.java | 7 +- .../support/OraclePagingQueryProvider.java | 23 +- .../support/PostgresPagingQueryProvider.java | 12 +- .../SqlPagingQueryProviderFactoryBean.java | 87 ++- .../database/support/SqlPagingQueryUtils.java | 56 +- .../support/SqlServerPagingQueryProvider.java | 26 +- .../task/repository/support/DatabaseType.java | 101 ++- .../support/SimpleTaskExplorer.java | 35 +- .../support/SimpleTaskNameResolver.java | 19 +- .../support/SimpleTaskRepository.java | 118 +-- .../support/TaskExecutionDaoFactoryBean.java | 19 +- .../support/TaskRepositoryInitializer.java | 34 +- .../task/repository/support/package-info.java | 16 + ...itional-spring-configuration-metadata.json | 16 +- ...impleSingleTaskAutoConfigurationTests.java | 36 +- ...kAutoConfigurationWithDataSourceTests.java | 36 +- .../SimpleTaskAutoConfigurationTests.java | 106 +-- .../cloud/task/TaskCoreTests.java | 114 +-- ...InitializerDefaultTaskConfigurerTests.java | 33 +- ...alizerNoDataSourceTaskConfigurerTests.java | 35 +- .../DefaultTaskConfigurerTests.java | 92 ++- .../configuration/TaskPropertiesTests.java | 29 +- .../task/configuration/TestConfiguration.java | 15 +- .../task/listener/TaskExceptionTests.java | 40 +- .../listener/TaskExecutionListenerTests.java | 279 ++++--- .../listener/TaskLifecycleListenerTests.java | 237 +++--- ...askListenerExecutorObjectFactoryTests.java | 53 +- .../dao/BaseTaskExecutionDaoTestCases.java | 215 ++--- .../dao/JdbcTaskExecutionDaoTests.java | 149 ++-- .../dao/MapTaskExecutionDaoTests.java | 125 +-- .../FindAllPagingQueryProviderTests.java | 67 +- .../InvalidPagingQueryProviderTests.java | 6 +- ...qlPagingQueryProviderFactoryBeanTests.java | 33 +- .../WhereClausePagingQueryProviderTests.java | 72 +- .../repository/support/DatabaseTypeTests.java | 32 +- .../support/SimpleTaskExplorerTests.java | 249 +++--- .../support/SimpleTaskNameResolverTests.java | 17 +- .../SimpleTaskRepositoryJdbcTests.java | 233 +++--- .../support/SimpleTaskRepositoryMapTests.java | 104 +-- .../support/TaskDatabaseInitializerTests.java | 35 +- .../TaskExecutionDaoFactoryBeanTests.java | 43 +- .../cloud/task/util/TaskExecutionCreator.java | 27 +- .../cloud/task/util/TestDBUtils.java | 81 +- .../task/util/TestDefaultConfiguration.java | 19 +- .../cloud/task/util/TestListener.java | 25 +- .../cloud/task/util/TestVerifierUtils.java | 118 ++- spring-cloud-task-dependencies/pom.xml | 6 +- spring-cloud-task-docs/pom.xml | 187 +++-- .../src/main/asciidoc/Guardfile | 16 +- .../src/main/asciidoc/index-docinfo.xml | 16 +- .../src/main/docbook/css/highlight.css | 22 +- .../src/main/docbook/css/manual-multipage.css | 2 +- .../src/main/docbook/css/manual.css | 64 +- .../src/main/docbook/xsl/common.xsl | 8 +- .../src/main/docbook/xsl/epub.xsl | 8 +- .../src/main/docbook/xsl/html-multipage.xsl | 6 +- .../src/main/docbook/xsl/html.xsl | 42 +- .../src/main/docbook/xsl/pdf.xsl | 88 ++- .../src/main/docbook/xsl/xslthl-config.xml | 40 +- .../main/docbook/xsl/xslthl/asciidoc-hl.xml | 66 +- .../src/main/docbook/xsl/xslthl/bourne-hl.xml | 12 +- .../src/main/docbook/xsl/xslthl/c-hl.xml | 8 +- .../src/main/docbook/xsl/xslthl/cpp-hl.xml | 6 +- .../src/main/docbook/xsl/xslthl/csharp-hl.xml | 8 +- .../src/main/docbook/xsl/xslthl/css-hl.xml | 282 +++---- .../src/main/docbook/xsl/xslthl/html-hl.xml | 218 +++--- .../src/main/docbook/xsl/xslthl/java-hl.xml | 4 +- .../main/docbook/xsl/xslthl/javascript-hl.xml | 4 +- .../src/main/docbook/xsl/xslthl/json-hl.xml | 2 +- .../src/main/docbook/xsl/xslthl/perl-hl.xml | 6 +- .../src/main/docbook/xsl/xslthl/php-hl.xml | 10 +- .../src/main/docbook/xsl/xslthl/python-hl.xml | 10 +- .../src/main/docbook/xsl/xslthl/ruby-hl.xml | 4 +- .../main/docbook/xsl/xslthl/sql2003-hl.xml | 16 +- .../src/main/docbook/xsl/xslthl/yaml-hl.xml | 2 +- .../src/main/javadoc/spring-javadoc.css | 738 ++++++++++-------- spring-cloud-task-integration-tests/pom.xml | 7 +- .../java/configuration/JobConfiguration.java | 35 +- .../configuration/JobSkipConfiguration.java | 36 +- .../java/configuration/SkipItemReader.java | 35 +- .../java/configuration/SkipItemWriter.java | 25 +- .../executionid/TaskStartApplication.java | 6 +- .../task/executionid/TaskStartTests.java | 150 ++-- .../task/launcher/TaskLauncherSinkTests.java | 94 ++- .../util/TaskLauncherSinkApplication.java | 3 +- .../listener/BatchExecutionEventTests.java | 206 +++-- .../cloud/task/listener/TaskEventTests.java | 33 +- .../chunk-events-sink-channel.properties | 3 +- .../item-process-sink-channel.properties | 3 +- .../item-read-events-sink-channel.properties | 3 +- .../item-write-events-sink-channel.properties | 3 +- .../job-execution-sink-channel.properties | 3 +- .../task/listener/sink-channel.properties | 3 +- .../skip-events-sink-channel.properties | 3 +- .../step-execution-sink-channel.properties | 3 +- .../batch-events/pom.xml | 8 +- .../spring/cloud/BatchEventsApplication.java | 70 +- .../cloud/BatchEventsApplicationTests.java | 40 +- .../job-listener-sink-channel.properties | 3 +- spring-cloud-task-samples/batch-job/pom.xml | 6 +- .../java/io/spring/BatchJobApplication.java | 3 +- .../configuration/JobConfiguration.java | 47 +- .../io/spring/BatchJobApplicationTests.java | 14 +- .../src/test/resources/application.properties | 3 +- spring-cloud-task-samples/jpa-sample/pom.xml | 9 +- .../main/java/io/spring/JpaApplication.java | 20 +- .../configuration/TaskRunComponent.java | 24 +- .../spring/configuration/TaskRunOutput.java | 28 +- .../configuration/TaskRunRepository.java | 20 +- .../src/main/resources/application.yml | 8 +- .../java/io/spring/JpaApplicationTests.java | 58 +- .../src/test/resources/application.properties | 3 +- .../multiple-datasources/pom.xml | 9 +- .../MultipleDataSourcesApplication.java | 20 +- .../configuration/CustomTaskConfigurer.java | 3 +- .../DataSourceConfiguration.java | 11 +- .../spring/task/SampleCommandLineRunner.java | 8 +- .../MultiDataSourcesApplicationTests.java | 17 +- .../src/test/resources/application.properties | 3 +- .../partitioned-batch-job/pom.xml | 8 +- .../main/java/io/spring/JobConfiguration.java | 52 +- .../PartitionedBatchJobApplication.java | 3 +- .../partitioner/TaskPartitionerTests.java | 54 +- spring-cloud-task-samples/pom.xml | 4 +- spring-cloud-task-samples/task-events/pom.xml | 8 +- .../java/io/spring/TaskEventsApplication.java | 3 +- .../taskprocessor/pom.xml | 9 +- .../main/java/io/spring/TaskProcessor.java | 32 +- .../io/spring/TaskProcessorApplication.java | 2 +- .../io/spring/TaskProcessorProperties.java | 17 +- .../spring/TaskProcessorApplicationTests.java | 34 +- spring-cloud-task-samples/tasksink/pom.xml | 10 +- .../java/io/spring/TaskSinkApplication.java | 2 +- .../io/spring/TaskSinkApplicationTests.java | 29 +- .../configuration/TaskSinkConfiguration.java | 2 +- spring-cloud-task-samples/timestamp/pom.xml | 9 +- .../cloud/task/timestamp/TaskApplication.java | 15 +- .../timestamp/TimestampTaskProperties.java | 6 +- .../task/timestamp/TaskApplicationTests.java | 26 +- .../TimestampTaskPropertiesTests.java | 24 +- .../src/test/resources/application.properties | 3 +- spring-cloud-task-stream/pom.xml | 6 +- .../listener/BatchEventAutoConfiguration.java | 228 ++++-- .../listener/EventEmittingChunkListener.java | 19 +- .../EventEmittingItemProcessListener.java | 14 +- .../EventEmittingItemReadListener.java | 38 +- .../EventEmittingItemWriteListener.java | 37 +- .../EventEmittingJobExecutionListener.java | 23 +- .../listener/EventEmittingSkipListener.java | 34 +- .../EventEmittingStepExecutionListener.java | 12 +- .../listener/support/BatchJobHeaders.java | 26 +- .../batch/listener/support/ExitStatus.java | 32 +- .../listener/support/JobExecutionEvent.java | 128 ++- .../listener/support/JobInstanceEvent.java | 29 +- .../listener/support/JobParameterEvent.java | 63 +- .../listener/support/JobParametersEvent.java | 165 ++-- .../listener/support/MessagePublisher.java | 32 +- .../listener/support/StepExecutionEvent.java | 191 +++-- ...skBatchEventListenerBeanPostProcessor.java | 117 +-- .../listener/support/TaskEventProperties.java | 61 +- .../task/launcher/TaskLaunchRequest.java | 89 +-- .../cloud/task/launcher/TaskLauncherSink.java | 20 +- .../annotation/EnableTaskLauncher.java | 11 +- .../listener/TaskEventAutoConfiguration.java | 36 +- ...itional-spring-configuration-metadata.json | 16 +- .../batch/listener/EventListenerTests.java | 245 +++--- .../listener/JobExecutionEventTests.java | 273 ++++--- .../batch/listener/JobInstanceEventTests.java | 35 +- .../listener/JobParameterEventTests.java | 46 +- .../listener/JobParametersEventTests.java | 99 ++- .../listener/StepExecutionEventTests.java | 184 +++-- ...chEventListenerBeanPostProcessorTests.java | 91 ++- .../TaskLaunchConfigurationExistingTests.java | 52 +- .../task/launcher/TaskLaunchRequestTests.java | 77 +- .../task/launcher/TaskLauncherSinkTests.java | 100 ++- .../configuration/TaskConfiguration.java | 16 +- .../util/TaskLauncherSinkApplication.java | 3 +- .../cloud/task/listener/TaskEventTests.java | 18 +- 249 files changed, 7450 insertions(+), 5857 deletions(-) create mode 100644 .editorconfig create mode 100644 .springformat diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..0679d88a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# top-most EditorConfig file +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +insert_final_newline = true + +[*.yml] +indent_style = space +indent_size = 2 diff --git a/.settings.xml b/.settings.xml index 8c8fdc70..d9004c57 100644 --- a/.settings.xml +++ b/.settings.xml @@ -1,7 +1,7 @@ spring - true + + true + spring-snapshots diff --git a/.springformat b/.springformat new file mode 100644 index 00000000..e69de29b diff --git a/pom.xml b/pom.xml index bdf5a886..a5df1e39 100755 --- a/pom.xml +++ b/pom.xml @@ -1,12 +1,14 @@ - + 4.0.0 org.springframework.cloud spring-cloud-build - 2.1.1.RELEASE - + 2.1.3.BUILD-SNAPSHOT + org.springframework.cloud @@ -126,15 +128,24 @@ 2.1.0.RELEASE 2.0.0.RELEASE - 2.0.0.RELEASE - 2.1.0.RELEASE + 2.0.0.RELEASE + + 2.1.0.RELEASE + 4.1.1.RELEASE 1.1 8.0 5.3.1 UTF-8 - ${project.build.directory}/coverage-reports/jacoco-ut.exec + + ${project.build.directory}/coverage-reports/jacoco-ut.exec + + true + true + + true + @@ -211,7 +222,9 @@ - ${project.build.directory}/coverage-reports/jacoco-ut.exec + + ${project.build.directory}/coverage-reports/jacoco-ut.exec + - ${project.build.directory}/coverage-reports/jacoco-ut.exec + + ${project.build.directory}/coverage-reports/jacoco-ut.exec + - ${project.reporting.outputDirectory}/jacoco-ut + + ${project.reporting.outputDirectory}/jacoco-ut + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + io.spring.javaformat + spring-javaformat-maven-plugin + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + + spring diff --git a/spring-cloud-starter-task/pom.xml b/spring-cloud-starter-task/pom.xml index 9a99b465..f7d29288 100644 --- a/spring-cloud-starter-task/pom.xml +++ b/spring-cloud-starter-task/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 diff --git a/spring-cloud-task-batch/pom.xml b/spring-cloud-task-batch/pom.xml index 5232f24e..b8c80ca2 100644 --- a/spring-cloud-task-batch/pom.xml +++ b/spring-cloud-task-batch/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 @@ -12,7 +14,8 @@ spring-cloud-task-batch jar Spring Cloud Task Batch - Module for use when combining Spring Cloud Task with Spring Batch + Module for use when combining Spring Cloud Task with Spring Batch + @@ -79,7 +82,7 @@ org.assertj assertj-core test - + org.junit.jupiter junit-jupiter-api 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 8167f30e..f2f672a5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.configuration; import org.springframework.batch.core.Job; @@ -38,8 +39,9 @@ import org.springframework.context.annotation.Configuration; * @author Michael Minella */ @Configuration -@ConditionalOnBean({Job.class}) -@ConditionalOnProperty(name = {"spring.cloud.task.batch.listener.enable", "spring.cloud.task.batch.listener.enabled"}, havingValue = "true", matchIfMissing = true) +@ConditionalOnBean({ Job.class }) +@ConditionalOnProperty(name = { "spring.cloud.task.batch.listener.enable", + "spring.cloud.task.batch.listener.enabled" }, havingValue = "true", matchIfMissing = true) public class TaskBatchAutoConfiguration { @Bean @@ -48,6 +50,9 @@ public class TaskBatchAutoConfiguration { return new TaskBatchExecutionListenerBeanPostProcessor(); } + /** + * Auto configuration for Task Batch Execution Listener. + */ @Configuration @ConditionalOnMissingBean(name = "taskBatchExecutionListener") @EnableConfigurationProperties(TaskProperties.class) @@ -60,20 +65,23 @@ 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()) { + if (!this.context.getBeansOfType(TaskConfigurer.class).isEmpty()) { taskConfigurer = this.context.getBean(TaskConfigurer.class); } - if(taskConfigurer != null && taskConfigurer.getTaskDataSource() != null) { + if (taskConfigurer != null && taskConfigurer.getTaskDataSource() != null) { return new TaskBatchExecutionListenerFactoryBean( - taskConfigurer.getTaskDataSource(), - taskExplorer, taskProperties.getTablePrefix()); + taskConfigurer.getTaskDataSource(), taskExplorer, + this.taskProperties.getTablePrefix()); } else { - return new TaskBatchExecutionListenerFactoryBean(null, - taskExplorer, taskProperties.getTablePrefix()); + return new TaskBatchExecutionListenerFactoryBean(null, taskExplorer, + this.taskProperties.getTablePrefix()); } } + } + } 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 556bd038..384b499c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.configuration; import java.util.ArrayList; @@ -28,7 +29,7 @@ import org.springframework.util.Assert; /** * Injects a configured {@link TaskBatchExecutionListener} into any batch jobs (beans - * assignable to {@link AbstractJob}) that are executed within the scope of a task. The + * assignable to {@link AbstractJob}) that are executed within the scope of a task. The * context this is used within is expected to have only one bean of type * {@link TaskBatchExecutionListener}. * @@ -50,17 +51,17 @@ public class TaskBatchExecutionListenerBeanPostProcessor implements BeanPostProc @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if(jobNames.size() > 0 && !jobNames.contains(beanName)) { - return bean; + if (this.jobNames.size() > 0 && !this.jobNames.contains(beanName)) { + return bean; } 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); + 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); } ((AbstractJob) bean).registerJobExecutionListener( this.applicationContext.getBean(TaskBatchExecutionListener.class)); @@ -73,4 +74,5 @@ public class TaskBatchExecutionListenerBeanPostProcessor implements BeanPostProc this.jobNames = jobNames; } + } 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 15ed62be..d8397b80 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.configuration; import java.lang.reflect.Field; + import javax.sql.DataSource; import org.springframework.aop.framework.Advised; @@ -32,13 +34,14 @@ import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; /** - * {@link FactoryBean} for a {@link TaskBatchExecutionListener}. Provides a jdbc based - * listener if there is a {@link DataSource} available. Otherwise, builds a listener that + * {@link FactoryBean} for a {@link TaskBatchExecutionListener}. Provides a jdbc based + * listener if there is a {@link DataSource} available. Otherwise, builds a listener that * uses the map based implementation. * * @author Michael Minella */ -public class TaskBatchExecutionListenerFactoryBean implements FactoryBean { +public class TaskBatchExecutionListenerFactoryBean + implements FactoryBean { private TaskBatchExecutionListener listener; @@ -49,45 +52,45 @@ public class TaskBatchExecutionListenerFactoryBean implements FactoryBean jobs, JobRegistry jobRegistry, JobRepository jobRepository) { - TaskJobLauncherCommandLineRunnerFactoryBean taskJobLauncherCommandLineRunnerFactoryBean = - new TaskJobLauncherCommandLineRunnerFactoryBean(jobLauncher, - jobExplorer, - jobs, - this.properties, - jobRegistry, - jobRepository); + public TaskJobLauncherCommandLineRunnerFactoryBean jobLauncherCommandLineRunner( + JobLauncher jobLauncher, JobExplorer jobExplorer, List jobs, + JobRegistry jobRegistry, JobRepository jobRepository) { + TaskJobLauncherCommandLineRunnerFactoryBean taskJobLauncherCommandLineRunnerFactoryBean; + taskJobLauncherCommandLineRunnerFactoryBean = new TaskJobLauncherCommandLineRunnerFactoryBean( + jobLauncher, jobExplorer, jobs, this.properties, jobRegistry, + jobRepository); return taskJobLauncherCommandLineRunnerFactoryBean; } + } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherCommandLineRunnerFactoryBean.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherCommandLineRunnerFactoryBean.java index 1a658d52..eb0c439a 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherCommandLineRunnerFactoryBean.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherCommandLineRunnerFactoryBean.java @@ -1,17 +1,17 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.configuration; @@ -33,7 +33,8 @@ import org.springframework.util.StringUtils; * * @author Glenn Renfro */ -public class TaskJobLauncherCommandLineRunnerFactoryBean implements FactoryBean { +public class TaskJobLauncherCommandLineRunnerFactoryBean + implements FactoryBean { private JobLauncher jobLauncher; @@ -52,8 +53,9 @@ public class TaskJobLauncherCommandLineRunnerFactoryBean implements FactoryBean< private JobRepository jobRepository; public TaskJobLauncherCommandLineRunnerFactoryBean(JobLauncher jobLauncher, - JobExplorer jobExplorer, List jobs, TaskBatchProperties taskBatchProperties, - JobRegistry jobRegistry, JobRepository jobRepository) { + JobExplorer jobExplorer, List jobs, + TaskBatchProperties taskBatchProperties, JobRegistry jobRegistry, + JobRepository jobRepository) { Assert.notNull(taskBatchProperties, "properties must not be null"); this.jobLauncher = jobLauncher; this.jobExplorer = jobExplorer; @@ -72,15 +74,16 @@ public class TaskJobLauncherCommandLineRunnerFactoryBean implements FactoryBean< @Override public TaskJobLauncherCommandLineRunner getObject() { - TaskJobLauncherCommandLineRunner taskJobLauncherCommandLineRunner = - new TaskJobLauncherCommandLineRunner(this.jobLauncher, this.jobExplorer, this.jobRepository, this.taskBatchProperties); + TaskJobLauncherCommandLineRunner taskJobLauncherCommandLineRunner = new TaskJobLauncherCommandLineRunner( + this.jobLauncher, this.jobExplorer, this.jobRepository, + this.taskBatchProperties); taskJobLauncherCommandLineRunner.setJobs(this.jobs); - if(StringUtils.hasText(this.jobNames)) { + if (StringUtils.hasText(this.jobNames)) { taskJobLauncherCommandLineRunner.setJobNames(this.jobNames); } taskJobLauncherCommandLineRunner.setJobRegistry(this.jobRegistry); - if(this.order != null) { + if (this.order != null) { taskJobLauncherCommandLineRunner.setOrder(this.order); } return taskJobLauncherCommandLineRunner; diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunner.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunner.java index 9690ce13..c18f1bf4 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunner.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunner.java @@ -1,17 +1,17 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.handler; @@ -57,11 +57,11 @@ import org.springframework.util.StringUtils; * {@link CommandLineRunner} to {@link JobLauncher launch} Spring Batch jobs. Runs all * jobs in the surrounding context by default and throws an exception upon the first job * that returns an {@link BatchStatus} of FAILED if a {@link TaskExecutor} in the - * {@link JobLauncher} is not specified. If a {@link TaskExecutor} is specified - * in the {@link JobLauncher} then all Jobs are launched and an - * exception is thrown if one or more of the jobs has an {@link BatchStatus} of FAILED. - * TaskJobLauncherCommandLineRunner can also be used to launch a specific job by - * providing a jobName. The TaskJobLaunchercommandLineRunner takes the place of the + * {@link JobLauncher} is not specified. If a {@link TaskExecutor} is specified in the + * {@link JobLauncher} then all Jobs are launched and an exception is thrown if one or + * more of the jobs has an {@link BatchStatus} of FAILED. TaskJobLauncherCommandLineRunner + * can also be used to launch a specific job by providing a jobName. The + * TaskJobLaunchercommandLineRunner takes the place of the * {@link org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner} when * it is in use. * @@ -70,15 +70,15 @@ import org.springframework.util.StringUtils; */ public class TaskJobLauncherCommandLineRunner extends JobLauncherCommandLineRunner { + private static final Log logger = LogFactory + .getLog(TaskJobLauncherCommandLineRunner.class); + private JobLauncher taskJobLauncher; private JobExplorer taskJobExplorer; private JobRepository taskJobRepository; - private static final Log logger = LogFactory - .getLog(TaskJobLauncherCommandLineRunner.class); - private List jobExecutionList = new ArrayList<>(); private ApplicationEventPublisher taskApplicationEventPublisher; @@ -91,10 +91,12 @@ public class TaskJobLauncherCommandLineRunner extends JobLauncherCommandLineRunn * @param jobExplorer to check the job repository for previous executions * @param jobRepository to check if a job instance exists with the given parameters * when running a job - * @param taskBatchProperties the properties used to configure the taskBatchProperties. + * @param taskBatchProperties the properties used to configure the + * taskBatchProperties. */ - public TaskJobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer, - JobRepository jobRepository, TaskBatchProperties taskBatchProperties) { + public TaskJobLauncherCommandLineRunner(JobLauncher jobLauncher, + JobExplorer jobExplorer, JobRepository jobRepository, + TaskBatchProperties taskBatchProperties) { super(jobLauncher, jobExplorer, jobRepository); this.taskJobLauncher = jobLauncher; this.taskJobExplorer = jobExplorer; @@ -151,7 +153,8 @@ public class TaskJobLauncherCommandLineRunner extends JobLauncherCommandLineRunn } 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)) { @@ -168,8 +171,9 @@ public class TaskJobLauncherCommandLineRunner extends JobLauncherCommandLineRunn List failedJobExecutions = new ArrayList<>(); RepeatStatus repeatStatus = RepeatStatus.FINISHED; - for (JobExecution jobExecution : jobExecutionList) { - JobExecution currentJobExecution = taskJobExplorer.getJobExecution(jobExecution.getId()); + for (JobExecution jobExecution : this.jobExecutionList) { + JobExecution currentJobExecution = this.taskJobExplorer + .getJobExecution(jobExecution.getId()); BatchStatus batchStatus = currentJobExecution.getStatus(); if (batchStatus.isRunning()) { repeatStatus = RepeatStatus.CONTINUABLE; @@ -178,9 +182,10 @@ public class TaskJobLauncherCommandLineRunner extends JobLauncherCommandLineRunn failedJobExecutions.add(jobExecution); } } - Thread.sleep(taskBatchProperties.getFailOnJobFailurePollInterval()); + 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; @@ -190,8 +195,8 @@ public class TaskJobLauncherCommandLineRunner extends JobLauncherCommandLineRunn 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", + 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())); } @@ -201,6 +206,7 @@ public class TaskJobLauncherCommandLineRunner extends JobLauncherCommandLineRunn throw new TaskException(message.toString()); } + private JobParameters removeNonIdentifying(JobParameters parameters) { Map parameterMap = parameters.getParameters(); HashMap copy = new HashMap<>(parameterMap); @@ -225,4 +231,5 @@ public class TaskJobLauncherCommandLineRunner extends JobLauncherCommandLineRunn merged.putAll(additionals.getParameters()); return new JobParameters(merged); } + } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/TaskBatchDao.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/TaskBatchDao.java index 940793f0..90e1b70d 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/TaskBatchDao.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/listener/TaskBatchDao.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.listener; import org.springframework.batch.core.JobExecution; @@ -28,9 +29,9 @@ public interface TaskBatchDao { /** * Saves the relationship between a task execution and a job execution. - * * @param taskExecution task execution * @param jobExecution job execution */ void saveRelationship(TaskExecution taskExecution, JobExecution jobExecution); + } 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 0296476f..0e595d72 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.listener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.listener.JobExecutionListenerSupport; import org.springframework.cloud.task.listener.annotation.BeforeTask; @@ -31,14 +33,14 @@ import org.springframework.util.Assert; */ public class TaskBatchExecutionListener extends JobExecutionListenerSupport { + private static final Log logger = LogFactory.getLog(TaskBatchExecutionListener.class); + private TaskExecution taskExecution; private TaskBatchDao taskBatchDao; - private static final Log logger = LogFactory.getLog(TaskBatchExecutionListener.class); - /** - * @param taskBatchDao dao used to persist the relationship. Must not be null + * @param taskBatchDao dao used to persist the relationship. Must not be null */ public TaskBatchExecutionListener(TaskBatchDao taskBatchDao) { Assert.notNull(taskBatchDao, "A TaskBatchDao is required"); @@ -53,14 +55,16 @@ public class TaskBatchExecutionListener extends JobExecutionListenerSupport { @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."); + if (this.taskExecution == null) { + 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", - jobExecution.getId(), - this.taskExecution.getExecutionId())); - taskBatchDao.saveRelationship(taskExecution, jobExecution); + 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); } } + } 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 c058d378..8725af7a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.listener.support; import javax.sql.DataSource; @@ -27,7 +28,7 @@ import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** - * JDBC based implementation of the {@link TaskBatchDao}. Intended to be used in + * JDBC based implementation of the {@link TaskBatchDao}. Intended to be used in * conjunction with the JDBC based * {@link org.springframework.cloud.task.repository.TaskRepository} * @@ -36,10 +37,10 @@ import org.springframework.util.StringUtils; */ public class JdbcTaskBatchDao implements TaskBatchDao { - private String tablePrefix = TaskProperties.DEFAULT_TABLE_PREFIX; - private static final String INSERT_STATEMENT = "INSERT INTO %PREFIX%TASK_BATCH VALUES(?, ?)"; + private String tablePrefix = TaskProperties.DEFAULT_TABLE_PREFIX; + private JdbcOperations jdbcTemplate; /** @@ -68,10 +69,12 @@ 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"); - jdbcTemplate.update(getQuery(INSERT_STATEMENT), taskExecution.getExecutionId(), jobExecution.getId()); + this.jdbcTemplate.update(getQuery(INSERT_STATEMENT), + taskExecution.getExecutionId(), jobExecution.getId()); } private String getQuery(String base) { - return StringUtils.replace(base, "%PREFIX%", tablePrefix); + return StringUtils.replace(base, "%PREFIX%", this.tablePrefix); } + } 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 35ed7102..81e17eeb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.listener.support; import java.util.Map; @@ -25,8 +26,10 @@ import org.springframework.cloud.task.repository.TaskExecution; import org.springframework.util.Assert; /** - * Map implementation of the {@link TaskBatchDao}.

This is intended for - * testing purposes only!

+ * Map implementation of the {@link TaskBatchDao}. + *

+ * This is intended for testing purposes only! + *

* * @author Michael Minella */ @@ -44,8 +47,9 @@ public class MapTaskBatchDao implements TaskBatchDao { Assert.notNull(taskExecution, "A taskExecution is required"); Assert.notNull(jobExecution, "A jobExecution is required"); - if(this.relationships.containsKey(taskExecution.getExecutionId())) { - this.relationships.get(taskExecution.getExecutionId()).add(jobExecution.getId()); + if (this.relationships.containsKey(taskExecution.getExecutionId())) { + this.relationships.get(taskExecution.getExecutionId()) + .add(jobExecution.getId()); } else { TreeSet jobExecutionIds = new TreeSet<>(); @@ -54,4 +58,5 @@ public class MapTaskBatchDao implements TaskBatchDao { this.relationships.put(taskExecution.getExecutionId(), jobExecutionIds); } } + } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/CommandLineArgsProvider.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/CommandLineArgsProvider.java index 37635142..93eb54e8 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/CommandLineArgsProvider.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/CommandLineArgsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import java.util.List; @@ -33,10 +34,10 @@ public interface CommandLineArgsProvider { * worker for the specified {@link ExecutionContext}. * * Note: This method is called once per partition. - * * @param executionContext the unique state for the step to be executed. * @return a list of formatted command line arguments to be passed to the worker (the - * list will be joined via spaces). + * list will be joined via spaces). */ List getCommandLineArgs(ExecutionContext executionContext); + } 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 f23c8c46..91946cf6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import java.util.ArrayList; @@ -51,39 +52,57 @@ import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; /** - *

A {@link PartitionHandler} implementation that delegates to a {@link TaskLauncher} for - * each of the workers. The id of the worker's StepExecution is passed as an environment - * variable to the worker. The worker, bootstrapped by the + *

+ * A {@link PartitionHandler} implementation that delegates to a {@link TaskLauncher} for + * each of the workers. The id of the worker's StepExecution is passed as an environment + * variable to the worker. The worker, bootstrapped by the * {@link DeployerStepExecutionHandler}, looks up the StepExecution in the JobRepository - * and executes it. This PartitionHandler polls the JobRepository for the results.

+ * and executes it. This PartitionHandler polls the JobRepository for the results. + *

* - *

If the job fails, the partitions will be re-executed per normal batch rules (steps that + *

+ * If the job fails, the partitions will be re-executed per normal batch rules (steps that * are complete should do nothing, failed steps should restart based on their - * configurations).

+ * configurations). + *

* - *

This PartitionHandler and all of the worker processes must share the same JobRepository - * data store (aka point the same database).

+ *

+ * This PartitionHandler and all of the worker processes must share the same JobRepository + * data store (aka point the same database). + *

* * @author Michael Minella */ -public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAware, InitializingBean { +public class DeployerPartitionHandler + implements PartitionHandler, EnvironmentAware, InitializingBean { + + /** + * ID of Spring Cloud Task job execution. + */ + public static final String SPRING_CLOUD_TASK_JOB_EXECUTION_ID = "spring.cloud.task.job-execution-id"; + + /** + * ID of Spring Cloud Task step execution. + */ + public static final String SPRING_CLOUD_TASK_STEP_EXECUTION_ID = "spring.cloud.task.step-execution-id"; + + /** + * Name of Spring Cloud Task step. + */ + public static final String SPRING_CLOUD_TASK_STEP_NAME = "spring.cloud.task.step-name"; + + /** + * ID of Spring Cloud Task parent execution. + */ + public static final String SPRING_CLOUD_TASK_PARENT_EXECUTION_ID = "spring.cloud.task.parentExecutionId"; + + /** + * Spring Cloud Task property name. + */ + public static final String SPRING_CLOUD_TASK_NAME = "spring.cloud.task.name"; private static final long DEFAULT_POLL_INTERVAL = 10000; - public static final String SPRING_CLOUD_TASK_JOB_EXECUTION_ID = - "spring.cloud.task.job-execution-id"; - - public static final String SPRING_CLOUD_TASK_STEP_EXECUTION_ID = - "spring.cloud.task.step-execution-id"; - - public static final String SPRING_CLOUD_TASK_STEP_NAME = - "spring.cloud.task.step-name"; - - public static final String SPRING_CLOUD_TASK_PARENT_EXECUTION_ID = - "spring.cloud.task.parentExecutionId"; - - public static final String SPRING_CLOUD_TASK_NAME = "spring.cloud.task.name"; - private int maxWorkers = -1; private int gridSize = 1; @@ -118,10 +137,8 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw private boolean defaultArgsAsEnvironmentVars = false; - public DeployerPartitionHandler(TaskLauncher taskLauncher, - JobExplorer jobExplorer, - Resource resource, - String stepName) { + public DeployerPartitionHandler(TaskLauncher taskLauncher, JobExplorer jobExplorer, + Resource resource, String stepName) { Assert.notNull(taskLauncher, "A taskLauncher is required"); Assert.notNull(jobExplorer, "A jobExplorer is required"); Assert.notNull(resource, "A resource is required"); @@ -135,17 +152,16 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw /** * 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; } /** * 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 defaultArgsAsEnvironmentVars defaults to false */ public void setDefaultArgsAsEnvironmentVars(boolean defaultArgsAsEnvironmentVars) { @@ -154,17 +170,16 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw /** * 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; } /** * The maximum number of workers to be executing at once. - * - * @param maxWorkers number of workers. Defaults to -1 (unlimited) + * @param maxWorkers number of workers. Defaults to -1 (unlimited) */ public void setMaxWorkers(int maxWorkers) { Assert.isTrue(maxWorkers != 0, "maxWorkers cannot be 0"); @@ -172,11 +187,11 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw } /** - * Approximate size of the pool of worker JVMs available. May be used by the + * Approximate size of the pool of worker JVMs available. May be used by the * {@link StepExecutionSplitter} to determine how many partitions to create (at the - * discretion of the {@link org.springframework.batch.core.partition.support.Partitioner}). - * - * @param gridSize size of grid. Defaults to 1 + * discretion of the + * {@link org.springframework.batch.core.partition.support.Partitioner}). + * @param gridSize size of grid. Defaults to 1 */ public void setGridSize(int gridSize) { this.gridSize = gridSize; @@ -184,25 +199,22 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw /** * The interval to check the job repository for completed steps. - * - * @param pollInterval interval. Defaults to 10 seconds + * @param pollInterval interval. Defaults to 10 seconds */ public void setPollInterval(long pollInterval) { this.pollInterval = pollInterval; } /** - * Timeout for the master step. This is a timeout for all workers to complete. - * - * @param timeout timeout. Defaults to none (-1). + * Timeout for the master step. This is a timeout for all workers to complete. + * @param timeout timeout. Defaults to none (-1). */ public void setTimeout(long timeout) { this.timeout = timeout; } /** - * Map of deployment properties to be used by the {@link TaskLauncher} - * + * Map of deployment properties to be used by the {@link TaskLauncher}. * @param deploymentProperties properties to be used by the {@link TaskLauncher} */ public void setDeploymentProperties(Map deploymentProperties) { @@ -210,9 +222,8 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw } /** - * The name of the application to be launched. Useful in environments where + * The name of the application to be launched. Useful in environments where * application deployments are reused (such as CloudFoundry). - * * @param applicationName The name of the application to be launched */ public void setApplicationName(String applicationName) { @@ -223,9 +234,9 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw public void beforeTask(TaskExecution taskExecution) { this.taskExecution = taskExecution; - if(this.commandLineArgsProvider == null) { - SimpleCommandLineArgsProvider provider = new - SimpleCommandLineArgsProvider(taskExecution); + if (this.commandLineArgsProvider == null) { + SimpleCommandLineArgsProvider provider = new SimpleCommandLineArgsProvider( + taskExecution); this.commandLineArgsProvider = provider; } @@ -235,8 +246,8 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw 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()); @@ -244,7 +255,7 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw int partitions = candidates.size(); - logger.debug(String.format("%s partitions were returned", partitions)); + this.logger.debug(String.format("%s partitions were returned", partitions)); final Set executed = new HashSet<>(candidates.size()); @@ -259,7 +270,8 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw return pollReplies(stepExecution, executed, candidates, partitions); } - private void launchWorkers(Set candidates, Set executed) { + private void launchWorkers(Set candidates, + Set executed) { for (StepExecution execution : candidates) { if (this.currentWorkers < this.maxWorkers || this.maxWorkers < 0) { launchWorker(execution); @@ -273,59 +285,59 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw private 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)); + arguments.addAll(this.commandLineArgsProvider.getCommandLineArgs(copyContext)); - if(!this.defaultArgsAsEnvironmentVars) { + if (!this.defaultArgsAsEnvironmentVars) { arguments.add(formatArgument(SPRING_CLOUD_TASK_JOB_EXECUTION_ID, String.valueOf(workerStepExecution.getJobExecution().getId()))); arguments.add(formatArgument(SPRING_CLOUD_TASK_STEP_EXECUTION_ID, String.valueOf(workerStepExecution.getId()))); arguments.add(formatArgument(SPRING_CLOUD_TASK_STEP_NAME, this.stepName)); - arguments.add(formatArgument(SPRING_CLOUD_TASK_NAME, String.format("%s_%s_%s", - taskExecution.getTaskName(), - workerStepExecution.getJobExecution().getJobInstance().getJobName(), - workerStepExecution.getStepName()))); + arguments + .add(formatArgument(SPRING_CLOUD_TASK_NAME, + String.format("%s_%s_%s", this.taskExecution.getTaskName(), + workerStepExecution.getJobExecution().getJobInstance() + .getJobName(), + workerStepExecution.getStepName()))); arguments.add(formatArgument(SPRING_CLOUD_TASK_PARENT_EXECUTION_ID, - String.valueOf(taskExecution.getExecutionId()))); + String.valueOf(this.taskExecution.getExecutionId()))); } copyContext = new ExecutionContext(workerStepExecution.getExecutionContext()); - Map environmentVariables = this.environmentVariablesProvider.getEnvironmentVariables(copyContext); + Map environmentVariables = this.environmentVariablesProvider + .getEnvironmentVariables(copyContext); - if(this.defaultArgsAsEnvironmentVars) { + if (this.defaultArgsAsEnvironmentVars) { environmentVariables.put(SPRING_CLOUD_TASK_JOB_EXECUTION_ID, String.valueOf(workerStepExecution.getJobExecution().getId())); environmentVariables.put(SPRING_CLOUD_TASK_STEP_EXECUTION_ID, String.valueOf(workerStepExecution.getId())); environmentVariables.put(SPRING_CLOUD_TASK_STEP_NAME, this.stepName); - environmentVariables.put(SPRING_CLOUD_TASK_NAME, String.format("%s_%s_%s", - taskExecution.getTaskName(), - workerStepExecution.getJobExecution().getJobInstance().getJobName(), - workerStepExecution.getStepName())); + environmentVariables + .put(SPRING_CLOUD_TASK_NAME, + String.format("%s_%s_%s", this.taskExecution.getTaskName(), + workerStepExecution.getJobExecution().getJobInstance() + .getJobName(), + workerStepExecution.getStepName())); environmentVariables.put(SPRING_CLOUD_TASK_PARENT_EXECUTION_ID, - String.valueOf(taskExecution.getExecutionId())); + String.valueOf(this.taskExecution.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); - taskLauncher.launch(request); + this.taskLauncher.launch(request); } private String resolveApplicationName() { - if(StringUtils.hasText(this.applicationName)) { + if (StringUtils.hasText(this.applicationName)) { return this.applicationName; } else { @@ -338,8 +350,7 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw } private Collection pollReplies(final StepExecution masterStepExecution, - final Set executed, - final Set candidates, + final Set executed, final Set candidates, final int size) throws Exception { final Collection result = new ArrayList<>(executed.size()); @@ -351,13 +362,14 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw for (StepExecution curStepExecution : executed) { if (!result.contains(curStepExecution)) { - StepExecution partitionStepExecution = - jobExplorer.getStepExecution(masterStepExecution.getJobExecutionId(), curStepExecution.getId()); + StepExecution partitionStepExecution = DeployerPartitionHandler.this.jobExplorer + .getStepExecution(masterStepExecution.getJobExecutionId(), + curStepExecution.getId()); BatchStatus batchStatus = partitionStepExecution.getStatus(); if (batchStatus != null && isComplete(batchStatus)) { result.add(partitionStepExecution); - currentWorkers--; + DeployerPartitionHandler.this.currentWorkers--; if (!candidates.isEmpty()) { @@ -382,8 +394,8 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw Poller> poller = new DirectPoller<>(this.pollInterval); Future> resultsFuture = poller.poll(callback); - if (timeout >= 0) { - return resultsFuture.get(timeout, TimeUnit.MILLISECONDS); + if (this.timeout >= 0) { + return resultsFuture.get(this.timeout, TimeUnit.MILLISECONDS); } else { return resultsFuture.get(); @@ -391,7 +403,8 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw } private boolean isComplete(BatchStatus status) { - return status.equals(BatchStatus.COMPLETED) || status.isGreaterThan(BatchStatus.STARTED); + return status.equals(BatchStatus.COMPLETED) + || status.isGreaterThan(BatchStatus.STARTED); } @Override @@ -401,10 +414,11 @@ public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAw @Override public void afterPropertiesSet() throws Exception { - if(this.environmentVariablesProvider == null) { - this.environmentVariablesProvider = - new SimpleEnvironmentVariablesProvider(this.environment); + if (this.environmentVariablesProvider == null) { + 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 20f652c5..d2a8b178 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import org.apache.commons.logging.Log; @@ -34,20 +35,24 @@ import org.springframework.core.env.Environment; import org.springframework.util.Assert; /** - *

A {@link CommandLineRunner} used to execute a {@link Step}. No result is provided + *

+ * A {@link CommandLineRunner} used to execute a {@link Step}. No result is provided * directly to the associated {@link DeployerPartitionHandler} as it will obtain the step - * results directly from the shared job repository.

+ * results directly from the shared job repository. + *

* - *

The {@link StepExecution} is rehydrated based on the environment variables provided. - * Specifically, the following variables are required:

+ *

+ * The {@link StepExecution} is rehydrated based on the environment variables provided. + * Specifically, the following variables are required: + *

*
    - *
  • {@link DeployerPartitionHandler#SPRING_CLOUD_TASK_JOB_EXECUTION_ID}: The id of - * the JobExecution.
  • - *
  • {@link DeployerPartitionHandler#SPRING_CLOUD_TASK_STEP_EXECUTION_ID}: The id of - * the StepExecution.
  • - *
  • {@link DeployerPartitionHandler#SPRING_CLOUD_TASK_STEP_NAME}: The id of the - * bean definition for the Step to execute. The id must be found within the provided - * {@link BeanFactory}
  • + *
  • {@link DeployerPartitionHandler#SPRING_CLOUD_TASK_JOB_EXECUTION_ID}: The id of the + * JobExecution.
  • + *
  • {@link DeployerPartitionHandler#SPRING_CLOUD_TASK_STEP_EXECUTION_ID}: The id of the + * StepExecution.
  • + *
  • {@link DeployerPartitionHandler#SPRING_CLOUD_TASK_STEP_NAME}: The id of the bean + * definition for the Step to execute. The id must be found within the provided + * {@link BeanFactory}
  • *
* * @author Michael Minella @@ -65,7 +70,8 @@ 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"); @@ -82,38 +88,60 @@ public class DeployerStepExecutionHandler implements CommandLineRunner { validateRequest(); - Long jobExecutionId = Long.parseLong(environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)); - Long stepExecutionId = Long.parseLong(environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)); - StepExecution stepExecution = 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 = environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME); - Step step = stepLocator.getStep(stepName); + String stepName = this.environment + .getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME); + Step step = this.stepLocator.getStep(stepName); try { - logger.debug(String.format("Executing step %s with step execution id %s and job execution id %s", stepExecution.getStepName(), stepExecutionId, jobExecutionId)); + 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); } catch (JobInterruptedException e) { stepExecution.setStatus(BatchStatus.STOPPED); - jobRepository.update(stepExecution); + this.jobRepository.update(stepExecution); } catch (Throwable e) { stepExecution.addFailureException(e); stepExecution.setStatus(BatchStatus.FAILED); - jobRepository.update(stepExecution); + this.jobRepository.update(stepExecution); } } private void validateRequest() { - Assert.isTrue(environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID), "A job execution id is required"); - Assert.isTrue(environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID), "A step execution id is required"); - Assert.isTrue(environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME), "A step name is required"); + 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), + "A step execution id is required"); + Assert.isTrue( + this.environment.containsProperty( + DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME), + "A step name is required"); - Assert.isTrue(this.stepLocator.getStepNames().contains(environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)), "The step requested cannot be found in the provided BeanFactory"); + Assert.isTrue( + this.stepLocator.getStepNames() + .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/EnvironmentVariablesProvider.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/EnvironmentVariablesProvider.java index 7a7fb428..6910d661 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/EnvironmentVariablesProvider.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/EnvironmentVariablesProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import java.util.Map; @@ -24,19 +25,18 @@ import org.springframework.batch.item.ExecutionContext; * each worker in a partitioned job. * * @author Michael Minella - * * @since 1.0.2 */ public interface EnvironmentVariablesProvider { /** - * Provides a {@link Map} of Strings to be used as environment variables. This method - * will be called for each worker step. For example, if there are 5 partitions, this + * Provides a {@link Map} of Strings to be used as environment variables. This method + * will be called for each worker step. For example, if there are 5 partitions, this * method will be called 5 times. - * * @param executionContext the {@link ExecutionContext} associated with the worker's - * step + * step * @return A {@link Map} of values to be used as environment variables */ Map getEnvironmentVariables(ExecutionContext executionContext); + } 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 02b49f63..5de4770f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import java.util.Collections; @@ -21,23 +22,23 @@ import java.util.Map; import org.springframework.batch.item.ExecutionContext; /** - * A simple no-op implementation of the {@link EnvironmentVariablesProvider}. It returns + * A simple no-op implementation of the {@link EnvironmentVariablesProvider}. It returns * an empty {@link Map}. * * @author Michael Minella - * * @since 1.0.2 */ public class NoOpEnvironmentVariablesProvider implements EnvironmentVariablesProvider { /** - * * @param executionContext the {@link ExecutionContext} associated with the worker's - * step + * step * @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/PassThroughCommandLineArgsProvider.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/PassThroughCommandLineArgsProvider.java index e2ef58d4..c7bbb338 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/PassThroughCommandLineArgsProvider.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/PassThroughCommandLineArgsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import java.util.List; @@ -38,6 +39,7 @@ public class PassThroughCommandLineArgsProvider implements CommandLineArgsProvid @Override public List getCommandLineArgs(ExecutionContext executionContext) { - return commandLineArgs; + return this.commandLineArgs; } + } diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleCommandLineArgsProvider.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleCommandLineArgsProvider.java index e19cfd9b..4afbacb9 100644 --- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleCommandLineArgsProvider.java +++ b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleCommandLineArgsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import java.util.ArrayList; @@ -31,7 +32,8 @@ import org.springframework.util.Assert; * @author Glenn Renfro * @since 1.1.0 */ -public class SimpleCommandLineArgsProvider extends TaskExecutionListenerSupport implements CommandLineArgsProvider { +public class SimpleCommandLineArgsProvider extends TaskExecutionListenerSupport + implements CommandLineArgsProvider { private TaskExecution taskExecution; @@ -56,7 +58,6 @@ public class SimpleCommandLineArgsProvider extends TaskExecutionListenerSupport /** * Additional command line args to be appended. - * * @param appendedArgs list of arguments * @since 1.2 */ @@ -67,17 +68,18 @@ public class SimpleCommandLineArgsProvider extends TaskExecutionListenerSupport @Override public List getCommandLineArgs(ExecutionContext executionContext) { - int listSize = this.taskExecution.getArguments().size() + - (this.appendedArgs != null ? this.appendedArgs.size() : 0); + int listSize = this.taskExecution.getArguments().size() + + (this.appendedArgs != null ? this.appendedArgs.size() : 0); List args = new ArrayList<>(listSize); args.addAll(this.taskExecution.getArguments()); - if(this.appendedArgs != null) { + if (this.appendedArgs != null) { args.addAll(this.appendedArgs); } return args; } + } 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 c75b33a4..576daaf0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import java.util.Arrays; @@ -29,12 +30,11 @@ import org.springframework.core.env.PropertySource; /** * Copies all existing environment variables as made available in the {@link Environment} - * only if includeCurrentEnvironment is set to true (default). - * The environmentProperties option provides the ability to override any - * specific values on an as needed basis. + * only if includeCurrentEnvironment is set to true (default). The + * environmentProperties option provides the ability to override any specific + * values on an as needed basis. * * @author Michael Minella - * * @since 1.0.2 */ public class SimpleEnvironmentVariablesProvider implements EnvironmentVariablesProvider { @@ -53,28 +53,31 @@ public class SimpleEnvironmentVariablesProvider implements EnvironmentVariablesP } /** - * @param environmentProperties a {@link Map} of properties used to override any values - * configured in the current {@link Environment} + * @param environmentProperties a {@link Map} of properties used to override any + * values configured in the current {@link Environment} */ public void setEnvironmentProperties(Map environmentProperties) { this.environmentProperties = environmentProperties; } /** - * Establishes if current environment variables will be included as a part of the provider. - * @param includeCurrentEnvironment true(default) include local environment properties. False do not include - * current environment properties. + * Establishes if current environment variables will be included as a part of the + * provider. + * @param includeCurrentEnvironment true(default) include local environment + * properties. False do not include current environment properties. */ public void setIncludeCurrentEnvironment(boolean includeCurrentEnvironment) { this.includeCurrentEnvironment = includeCurrentEnvironment; } @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(includeCurrentEnvironment) { + if (this.includeCurrentEnvironment) { environmentProperties.putAll(getCurrentEnvironmentProperties()); } @@ -88,9 +91,11 @@ 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())); } } @@ -100,4 +105,5 @@ public class SimpleEnvironmentVariablesProvider implements EnvironmentVariablesP return currentEnvironment; } + } diff --git a/spring-cloud-task-batch/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-task-batch/src/main/resources/META-INF/additional-spring-configuration-metadata.json index cca0a097..246cffc2 100644 --- a/spring-cloud-task-batch/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/spring-cloud-task-batch/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -1,64 +1,64 @@ { - "properties": [ - { - "defaultValue": true, - "name": "spring.cloud.task.batch.listener.enabled", - "description": "This property is used to determine if a task will be linked to the batch jobs that are run.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": false, - "name": "spring.cloud.task.batch.fail-on-job-failure", - "description": "This property is used to determine if a task app should return with a non zero exit code if a batch job fails.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.task.batch.events.enabled", - "description": "This property is used to determine if a task should listen for batch events.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.task.batch.events.chunk.enabled", - "description": "This property is used to determine if a task should listen for batch chunk events.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.task.batch.events.item-process.enabled", - "description": "This property is used to determine if a task should listen for batch item processed events.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.task.batch.events.item-read.enabled", - "description": "This property is used to determine if a task should listen for batch item read events.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.task.batch.events.item-write.enabled", - "description": "This property is used to determine if a task should listen for batch item write events.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.task.batch.events.job-execution.enabled", - "description": "This property is used to determine if a task should listen for batch job execution events.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.task.batch.events.skip.enabled", - "description": "This property is used to determine if a task should listen for batch skip events.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.task.batch.events.step-execution.enabled", - "description": "This property is used to determine if a task should listen for batch step execution events.", - "type": "java.lang.Boolean" - } - ] + "properties": [ + { + "defaultValue": true, + "name": "spring.cloud.task.batch.listener.enabled", + "description": "This property is used to determine if a task will be linked to the batch jobs that are run.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": false, + "name": "spring.cloud.task.batch.fail-on-job-failure", + "description": "This property is used to determine if a task app should return with a non zero exit code if a batch job fails.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.task.batch.events.enabled", + "description": "This property is used to determine if a task should listen for batch events.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.task.batch.events.chunk.enabled", + "description": "This property is used to determine if a task should listen for batch chunk events.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.task.batch.events.item-process.enabled", + "description": "This property is used to determine if a task should listen for batch item processed events.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.task.batch.events.item-read.enabled", + "description": "This property is used to determine if a task should listen for batch item read events.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.task.batch.events.item-write.enabled", + "description": "This property is used to determine if a task should listen for batch item write events.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.task.batch.events.job-execution.enabled", + "description": "This property is used to determine if a task should listen for batch job execution events.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.task.batch.events.skip.enabled", + "description": "This property is used to determine if a task should listen for batch skip events.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.task.batch.events.step-execution.enabled", + "description": "This property is used to determine if a task should listen for batch step execution events.", + "type": "java.lang.Boolean" + } + ] } diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskBatchTest.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskBatchTest.java index e5797cb0..9e43e6be 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskBatchTest.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskBatchTest.java @@ -1,17 +1,17 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.configuration; @@ -35,4 +35,5 @@ import org.springframework.boot.autoconfigure.ImportAutoConfiguration; @Documented @ImportAutoConfiguration public @interface TaskBatchTest { + } 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 9d7ecd2f..16b45e76 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 @@ -1,17 +1,17 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.configuration; @@ -33,33 +33,33 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class TaskJobLauncherAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(). - withUserConfiguration(TaskBatchExecutionListenerTests.JobConfiguration.class, + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withUserConfiguration(TaskBatchExecutionListenerTests.JobConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - EmbeddedDataSourceConfiguration.class, - BatchAutoConfiguration.class, + EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, TaskJobLauncherAutoConfiguration.class); @Test public void testAutoBuiltDataSourceWithTaskJobLauncherCLR() { - this.contextRunner.withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true").run(context -> { - assertThat(context).hasSingleBean(TaskJobLauncherCommandLineRunner.class); - assertThat(context.getBean(TaskJobLauncherCommandLineRunner.class) - .getOrder()) - .isEqualTo(0); - }); + this.contextRunner + .withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true") + .run(context -> { + assertThat(context) + .hasSingleBean(TaskJobLauncherCommandLineRunner.class); + assertThat(context.getBean(TaskJobLauncherCommandLineRunner.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 -> { + this.contextRunner + .withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true", + "spring.cloud.task.batch.commandLineRunnerOrder=100") + .run(context -> { assertThat(context.getBean(TaskJobLauncherCommandLineRunner.class) - .getOrder()) - .isEqualTo(100); - }); + .getOrder()).isEqualTo(100); + }); } @Test @@ -69,5 +69,5 @@ public class TaskJobLauncherAutoConfigurationTests { assertThat(context).doesNotHaveBean(TaskJobLauncherCommandLineRunner.class); }); } -} +} diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunnerCoreTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunnerCoreTests.java index 07672de2..f25890e5 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunnerCoreTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunnerCoreTests.java @@ -1,23 +1,21 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.handler; - -import org.assertj.core.api.AssertionsForClassTypes; import org.junit.Before; import org.junit.Test; import org.junit.jupiter.api.function.Executable; @@ -55,13 +53,14 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.PlatformTransactionManager; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Glenn Renfro */ @RunWith(SpringRunner.class) -@ContextConfiguration(classes = {TaskJobLauncherCommandLineRunnerCoreTests.BatchConfiguration.class}) +@ContextConfiguration(classes = { + TaskJobLauncherCommandLineRunnerCoreTests.BatchConfiguration.class }) public class TaskJobLauncherCommandLineRunnerCoreTests { @Autowired @@ -93,11 +92,11 @@ public class TaskJobLauncherCommandLineRunnerCoreTests { 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 TaskJobLauncherCommandLineRunner(this.jobLauncher, this.jobExplorer, jobRepository, new TaskBatchProperties()); + this.runner = new TaskJobLauncherCommandLineRunner(this.jobLauncher, + this.jobExplorer, this.jobRepository, new TaskBatchProperties()); } - @DirtiesContext @Test public void basicExecution() throws Exception { @@ -146,7 +145,6 @@ public class TaskJobLauncherCommandLineRunnerCoreTests { assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); } - @DirtiesContext @Test public void retryFailedExecutionOnNonRestartableJob() throws Exception { @@ -162,9 +160,9 @@ public class TaskJobLauncherCommandLineRunnerCoreTests { // try to re-run a failed execution Executable executable = () -> this.runner.execute(this.job, new JobParametersBuilder().addLong("run.id", 1L).toJobParameters()); - Throwable exception = assertThrows(JobRestartException.class, executable); - AssertionsForClassTypes.assertThat(exception.getMessage()) - .isEqualTo("JobInstance already exists and is not restartable"); + assertThatExceptionOfType(JobRestartException.class) + .isThrownBy(executable::execute) + .withMessage("JobInstance already exists and is not restartable"); } @DirtiesContext @@ -177,12 +175,11 @@ public class TaskJobLauncherCommandLineRunnerCoreTests { .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() @@ -195,7 +192,7 @@ public class TaskJobLauncherCommandLineRunnerCoreTests { 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) + 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 = this.jobExplorer.getJobInstance(0L); @@ -216,7 +213,6 @@ public class TaskJobLauncherCommandLineRunnerCoreTests { assertThat(parameters.getLong("foo")).isEqualTo(3L); } - private Tasklet throwingTasklet() { return (contribution, chunkContext) -> { throw new RuntimeException("Planned"); @@ -238,13 +234,11 @@ public class TaskJobLauncherCommandLineRunnerCoreTests { @EnableBatchProcessing protected static class BatchConfiguration implements BatchConfigurer { - private ResourcelessTransactionManager transactionManager = - new ResourcelessTransactionManager(); + private ResourcelessTransactionManager transactionManager = new ResourcelessTransactionManager(); private JobRepository jobRepository; - private MapJobRepositoryFactoryBean jobRepositoryFactory = - new MapJobRepositoryFactoryBean( + private MapJobRepositoryFactoryBean jobRepositoryFactory = new MapJobRepositoryFactoryBean( this.transactionManager); public BatchConfiguration() throws Exception { @@ -275,4 +269,5 @@ public class TaskJobLauncherCommandLineRunnerCoreTests { } } + } diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunnerTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunnerTests.java index 0c4a8478..c47f19b2 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunnerTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherCommandLineRunnerTests.java @@ -1,17 +1,17 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.handler; @@ -20,6 +20,7 @@ import java.util.Set; import javax.sql.DataSource; +import org.assertj.core.api.Condition; import org.junit.After; import org.junit.Test; import org.junit.jupiter.api.function.Executable; @@ -59,18 +60,18 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Glenn Renfro */ public class TaskJobLauncherCommandLineRunnerTests { - private ConfigurableApplicationContext applicationContext; + private static final String DEFAULT_ERROR_MESSAGE = "The following Jobs have failed: \n" + + "Job jobA failed during execution for job instance id 1 with jobExecutionId of 1 \n"; - private static final String DEFAULT_ERROR_MESSAGE = "The following Jobs have failed: \n" + - "Job jobA failed during execution for job instance id 1 with jobExecutionId of 1 \n"; + private ConfigurableApplicationContext applicationContext; @After public void tearDown() { @@ -82,20 +83,22 @@ public class TaskJobLauncherCommandLineRunnerTests { @Test public void testTaskJobLauncherCLRSuccessFail() { String[] enabledArgs = new String[] { - "--spring.cloud.task.batch.failOnJobFailure=true"}; - validateForFail(DEFAULT_ERROR_MESSAGE, TaskJobLauncherCommandLineRunnerTests.JobWithFailureConfiguration.class, + "--spring.cloud.task.batch.failOnJobFailure=true" }; + validateForFail(DEFAULT_ERROR_MESSAGE, + TaskJobLauncherCommandLineRunnerTests.JobWithFailureConfiguration.class, enabledArgs); } /** - * Verifies that the task will return an exit code other than zero if the - * job fails with the deprecated EnableTask annotation. + * Verifies that the task will return an exit code other than zero if the job fails + * with the deprecated EnableTask annotation. */ @Test public void testTaskJobLauncherCLRSuccessFailWithAnnotation() { String[] enabledArgs = new String[] { - "--spring.cloud.task.batch.failOnJobFailure=true"}; - validateForFail(DEFAULT_ERROR_MESSAGE, TaskJobLauncherCommandLineRunnerTests.JobWithFailureAnnotatedConfiguration.class, + "--spring.cloud.task.batch.failOnJobFailure=true" }; + validateForFail(DEFAULT_ERROR_MESSAGE, + TaskJobLauncherCommandLineRunnerTests.JobWithFailureAnnotatedConfiguration.class, enabledArgs); } @@ -103,8 +106,9 @@ public class TaskJobLauncherCommandLineRunnerTests { public void testTaskJobLauncherCLRSuccessFailWithTaskExecutor() { String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true", - "--spring.cloud.task.batch.failOnJobFailurePollInterval=500"}; - validateForFail(DEFAULT_ERROR_MESSAGE, TaskJobLauncherCommandLineRunnerTests.JobWithFailureTaskExecutorConfiguration.class, + "--spring.cloud.task.batch.failOnJobFailurePollInterval=500" }; + validateForFail(DEFAULT_ERROR_MESSAGE, + TaskJobLauncherCommandLineRunnerTests.JobWithFailureTaskExecutorConfiguration.class, enabledArgs); } @@ -112,11 +116,12 @@ public class TaskJobLauncherCommandLineRunnerTests { public void testTaskJobLauncherPickOneJob() { String[] enabledArgs = new String[] { "--spring.cloud.task.batch.fail-on-job-failure=true", - "--spring.cloud.task.batch.jobNames=jobSucceed"}; + "--spring.cloud.task.batch.jobNames=jobSucceed" }; boolean isExceptionThrown = false; try { - this.applicationContext = SpringApplication - .run(new Class[] { TaskJobLauncherCommandLineRunnerTests.JobWithFailureConfiguration.class }, enabledArgs); + this.applicationContext = SpringApplication.run(new Class[] { + TaskJobLauncherCommandLineRunnerTests.JobWithFailureConfiguration.class }, + enabledArgs); } catch (IllegalStateException exception) { isExceptionThrown = true; @@ -128,40 +133,51 @@ public class TaskJobLauncherCommandLineRunnerTests { @Test public void testCommandLineRunnerSetToFalse() { String[] enabledArgs = new String[] {}; - this.applicationContext = SpringApplication - .run(new Class[] { TaskJobLauncherCommandLineRunnerTests.JobConfiguration.class }, enabledArgs); + this.applicationContext = SpringApplication.run( + new Class[] { + TaskJobLauncherCommandLineRunnerTests.JobConfiguration.class }, + enabledArgs); validateContext(); - assertThat(applicationContext.getBean(JobLauncherCommandLineRunner.class)).isNotNull(); + assertThat(this.applicationContext.getBean(JobLauncherCommandLineRunner.class)) + .isNotNull(); - Executable executable = () -> applicationContext.getBean(TaskJobLauncherCommandLineRunner.class); + Executable executable = () -> this.applicationContext + .getBean(TaskJobLauncherCommandLineRunner.class); - Throwable exception = assertThrows(NoSuchBeanDefinitionException.class, executable); - assertThat(exception.getMessage()).isEqualTo("No qualifying bean of type " + - "'org.springframework.cloud.task.batch.handler.TaskJobLauncherCommandLineRunner' available"); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(executable::execute).withMessage("No qualifying bean of type " + + "'org.springframework.cloud.task.batch.handler.TaskJobLauncherCommandLineRunner' available"); 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); } - private void validateForFail(String errorMessage, Class clazz, String [] enabledArgs) { - Executable executable = () -> this.applicationContext = SpringApplication - .run(new Class[] { clazz,PropertyPlaceholderAutoConfiguration.class}, enabledArgs); + private void validateForFail(String errorMessage, Class clazz, String[] enabledArgs) { + Executable executable = () -> this.applicationContext = SpringApplication.run( + new Class[] { clazz, PropertyPlaceholderAutoConfiguration.class }, + enabledArgs); - Throwable exception = assertThrows(IllegalStateException.class, executable); - assertThat(exception.getCause().getMessage()).isEqualTo(errorMessage); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(executable::execute).has(new Condition() { + @Override + public boolean matches(Throwable value) { + return errorMessage.equals(value.getCause().getMessage()); + } + }); } - @EnableBatchProcessing @TaskBatchTest @Import(EmbeddedDataSourceConfiguration.class) @@ -176,25 +192,23 @@ public class TaskJobLauncherCommandLineRunnerTests { @Bean public Job job() { - return jobBuilderFactory.get("job") - .start(stepBuilderFactory.get("step1").tasklet(new Tasklet() { + return this.jobBuilderFactory.get("job") + .start(this.stepBuilderFactory.get("step1").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; } - }).build()) - .build(); + }).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 @@ -208,50 +222,54 @@ public class TaskJobLauncherCommandLineRunnerTests { @Bean public Job jobFail() { - return jobBuilderFactory.get("jobA") - .start(stepBuilderFactory.get("step1").tasklet(new Tasklet() { + return this.jobBuilderFactory.get("jobA") + .start(this.stepBuilderFactory.get("step1").tasklet(new Tasklet() { @Override public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) - throws Exception { + ChunkContext chunkContext) throws Exception { System.out.println("Executed"); - throw new IllegalStateException("WHOOPS"); + throw new IllegalStateException("WHOOPS"); } - }).build()) - .build(); + }).build()).build(); } @Bean public Job jobFun() { - return jobBuilderFactory.get("jobSucceed") - .start(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) { System.out.println("Executed"); return RepeatStatus.FINISHED; } - }).build()) - .build(); + }).build()).build(); } + } @EnableTask - public static class JobWithFailureAnnotatedConfiguration extends JobWithFailureConfiguration{ + public static class JobWithFailureAnnotatedConfiguration + extends JobWithFailureConfiguration { } - public static class JobWithFailureTaskExecutorConfiguration extends JobWithFailureConfiguration{ + public static class JobWithFailureTaskExecutorConfiguration + extends JobWithFailureConfiguration { + @Bean public BatchConfigurer batchConfigurer(DataSource dataSource) { return new TestBatchConfigurer(dataSource); } + } - private static class TestBatchConfigurer extends DefaultBatchConfigurer{ - public TestBatchConfigurer(DataSource dataSource) { + private static class TestBatchConfigurer extends DefaultBatchConfigurer { + + TestBatchConfigurer(DataSource dataSource) { super(dataSource); } + protected JobLauncher createJobLauncher() throws Exception { SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); jobLauncher.setJobRepository(getJobRepository()); @@ -259,5 +277,7 @@ public class TaskJobLauncherCommandLineRunnerTests { jobLauncher.afterPropertiesSet(); return jobLauncher; } + } + } 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 a4bd7daf..ac6c00ce 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 @@ -1,22 +1,23 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener; import java.util.Set; + import javax.sql.DataSource; import org.junit.After; @@ -56,8 +57,8 @@ 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); @@ -80,22 +81,19 @@ public class PrefixTests { @Bean public Job job() { - return jobBuilderFactory.get("job") - .start(stepBuilderFactory.get("step1") - .tasklet((contribution, chunkContext) -> { + return this.jobBuilderFactory.get("job").start(this.stepBuilderFactory + .get("step1").tasklet((contribution, chunkContext) -> { System.out.println("Executed"); return RepeatStatus.FINISHED; - }).build()) - .build(); + }).build()).build(); } @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 1bebcf9a..5e916ffb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.listener; import java.util.ArrayList; @@ -61,7 +62,7 @@ import org.springframework.data.domain.PageRequest; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michael Minella @@ -75,15 +76,14 @@ public class TaskBatchExecutionListenerTests { @After public void tearDown() { - if(this.applicationContext != null && this.applicationContext.isActive()) { + if (this.applicationContext != null && this.applicationContext.isActive()) { this.applicationContext.close(); } } @Test public void testAutobuiltDataSource() { - this.applicationContext = SpringApplication.run(JobConfiguration.class , - ARGS); + this.applicationContext = SpringApplication.run(JobConfiguration.class, ARGS); validateContext(); } @@ -96,28 +96,28 @@ public class TaskBatchExecutionListenerTests { @Test(expected = AssertionError.class) public void testNoAutoConfigurationEnable() { - this.applicationContext = SpringApplication.run(JobConfiguration.class , + this.applicationContext = SpringApplication.run(JobConfiguration.class, "--spring.cloud.task.batch.listener.enable=false"); validateContext(); } @Test(expected = AssertionError.class) public void testNoAutoConfigurationBothDisabled() { - this.applicationContext = SpringApplication.run(JobConfiguration.class , + this.applicationContext = SpringApplication.run(JobConfiguration.class, "--spring.cloud.task.batch.listener.enable=false --spring.cloud.task.batch.listener.enabled=false"); validateContext(); } @Test public void testAutoConfigurationEnable() { - this.applicationContext = SpringApplication.run(JobConfiguration.class , + this.applicationContext = SpringApplication.run(JobConfiguration.class, "--spring.cloud.task.batch.listener.enable=true"); validateContext(); } @Test public void testAutoConfigurationEnabled() { - this.applicationContext = SpringApplication.run(JobConfiguration.class , + this.applicationContext = SpringApplication.run(JobConfiguration.class, "--spring.cloud.task.batch.listener.enabled=true"); validateContext(); } @@ -132,26 +132,34 @@ public class TaskBatchExecutionListenerTests { 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()); - assertEquals(1, jobExecutionIds.size()); - assertEquals(1, taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()).getExecutionId()); + assertThat(jobExecutionIds.size()).isEqualTo(1); + assertThat(taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()) + .getExecutionId()).isEqualTo(1); } + @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()); - assertEquals(1, jobExecutionIds.size()); - assertEquals(1, taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()).getExecutionId()); + assertThat(jobExecutionIds.size()).isEqualTo(1); + assertThat(taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()) + .getExecutionId()).isEqualTo(1); } @Test @@ -160,11 +168,13 @@ 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()); - assertEquals(0, jobExecutionIds.size()); + assertThat(jobExecutionIds.size()).isEqualTo(0); } @Test @@ -173,28 +183,39 @@ 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()); - assertEquals(1, jobExecutionIds.size()); - assertEquals(1, (long) taskExplorer.getTaskExecutionIdByJobExecutionId(jobExecutionIds.iterator().next())); + assertThat(jobExecutionIds.size()).isEqualTo(1); + assertThat((long) taskExplorer + .getTaskExecutionIdByJobExecutionId(jobExecutionIds.iterator().next())) + .isEqualTo(1); } @Test public void testMultipleJobs() { - this.applicationContext = SpringApplication.run(MultipleJobConfiguration.class, ARGS); + this.applicationContext = SpringApplication.run(MultipleJobConfiguration.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()); - assertEquals(2, jobExecutionIds.size()); + assertThat(jobExecutionIds.size()).isEqualTo(2); Iterator jobExecutionIdsIterator = jobExecutionIds.iterator(); - assertEquals(1, (long) taskExplorer.getTaskExecutionIdByJobExecutionId(jobExecutionIdsIterator.next())); - assertEquals(1, (long) taskExplorer.getTaskExecutionIdByJobExecutionId(jobExecutionIdsIterator.next())); + assertThat((long) taskExplorer + .getTaskExecutionIdByJobExecutionId(jobExecutionIdsIterator.next())) + .isEqualTo(1); + assertThat((long) taskExplorer + .getTaskExecutionIdByJobExecutionId(jobExecutionIdsIterator.next())) + .isEqualTo(1); } @Test @@ -204,27 +225,26 @@ 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"); - assertEquals(testObject,bean); + 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"); - assertEquals(testObject,bean); + SimpleJob bean = (SimpleJob) beanPostProcessor + .postProcessBeforeInitialization(testObject, "TESTOBJECT"); + assertThat(bean).isEqualTo(testObject); } - @Test(expected = IllegalArgumentException.class) public void testBatchExecutionListenerBeanPostProcessorNullJobNames() { beanPostProcessor(null); @@ -232,16 +252,14 @@ 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, + 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.getBean( - TaskBatchExecutionListenerBeanPostProcessor.class); + TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor = this.applicationContext + .getBean(TaskBatchExecutionListenerBeanPostProcessor.class); beanPostProcessor.setJobNames(jobNames); return beanPostProcessor; @@ -269,16 +287,17 @@ public class TaskBatchExecutionListenerTests { @Bean public Job job() { - return jobBuilderFactory.get("job") - .start(stepBuilderFactory.get("step1").tasklet(new Tasklet() { + return this.jobBuilderFactory.get("job") + .start(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; } - }).build()) - .build(); + }).build()).build(); } + } @EnableBatchProcessing @@ -298,14 +317,18 @@ public class TaskBatchExecutionListenerTests { return new FactoryBean() { @Override public Job getObject() throws Exception { - 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()) + return JobFactoryBeanConfiguration.this.jobBuilderFactory.get("job") + .start(JobFactoryBeanConfiguration.this.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(); } @@ -320,6 +343,7 @@ public class TaskBatchExecutionListenerTests { } }; } + } @EnableBatchProcessing @@ -336,34 +360,31 @@ public class TaskBatchExecutionListenerTests { @Bean public Job job() { - return jobBuilderFactory.get("job") - .start(stepBuilderFactory.get("step1").tasklet(new Tasklet() { + return this.jobBuilderFactory.get("job") + .start(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; } - }).build()) - .build(); + }).build()).build(); } @Bean @Primary public DataSource myDataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.H2) - .setName("myDataSource"); + .setType(EmbeddedDatabaseType.H2).setName("myDataSource"); return builder.build(); } @Bean public DataSource incorrectDataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.H2) - .setName("incorrectDataSource"); + .setType(EmbeddedDatabaseType.H2).setName("incorrectDataSource"); return builder.build(); } - @Bean public TaskConfigurer taskConfigurer() { @@ -374,6 +395,7 @@ public class TaskBatchExecutionListenerTests { public DefaultBatchConfigurer batchConfigurer() { return new DefaultBatchConfigurer(myDataSource()); } + } @EnableBatchProcessing @@ -390,28 +412,30 @@ public class TaskBatchExecutionListenerTests { @Bean public Job job1() { - return jobBuilderFactory.get("job1") - .start(stepBuilderFactory.get("job1step1").tasklet(new Tasklet() { + return this.jobBuilderFactory.get("job1").start( + this.stepBuilderFactory.get("job1step1").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 job1"); return RepeatStatus.FINISHED; } - }).build()) - .build(); + }).build()).build(); } @Bean public Job job2() { - return jobBuilderFactory.get("job2") - .start(stepBuilderFactory.get("job2step1").tasklet(new Tasklet() { + return this.jobBuilderFactory.get("job2").start( + this.stepBuilderFactory.get("job2step1").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 job2"); return RepeatStatus.FINISHED; } - }).build()) - .build(); + }).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 298e3821..6a047eef 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import java.util.ArrayList; @@ -50,9 +51,7 @@ import org.springframework.core.env.Environment; import org.springframework.core.io.Resource; import org.springframework.mock.env.MockEnvironment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -64,6 +63,9 @@ import static org.mockito.Mockito.when; */ public class DeployerPartitionHandlerTests { + @Captor + ArgumentCaptor appDeploymentRequestArgumentCaptor; + @Mock private TaskLauncher taskLauncher; @@ -81,8 +83,6 @@ public class DeployerPartitionHandlerTests { private Environment environment; - @Captor ArgumentCaptor appDeploymentRequestArgumentCaptor; - @Before public void setUp() { MockitoAnnotations.initMocks(this); @@ -91,27 +91,33 @@ public class DeployerPartitionHandlerTests { @Test public void testConstructorValidation() { - validateConstructorValidation(null, null, null, null, "A taskLauncher is required"); - validateConstructorValidation(this.taskLauncher, null, null, null, "A jobExplorer is required"); - validateConstructorValidation(this.taskLauncher, this.jobExplorer, null, null, "A resource is required"); - validateConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, null, "A step name is required"); + validateConstructorValidation(null, null, null, null, + "A taskLauncher is required"); + validateConstructorValidation(this.taskLauncher, null, null, null, + "A jobExplorer is required"); + validateConstructorValidation(this.taskLauncher, this.jobExplorer, null, null, + "A resource is required"); + validateConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, + null, "A step name is required"); - new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, this.resource, "step-name"); + new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, this.resource, + "step-name"); } @Test public void testNoPartitions() throws Exception { - DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, this.resource, "step1"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); handler.setEnvironment(this.environment); StepExecution stepExecution = new StepExecution("step1", new JobExecution(1L)); - when(this.splitter.split(stepExecution, 1)).thenReturn(new HashSet()); + when(this.splitter.split(stepExecution, 1)).thenReturn(new HashSet<>()); Collection results = handler.handle(this.splitter, stepExecution); verify(this.taskLauncher, never()).launch((AppDeploymentRequest) any()); - assertTrue(results.isEmpty()); + assertThat(results.isEmpty()).isTrue(); } @Test @@ -121,9 +127,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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); handler.setEnvironment(this.environment); TaskExecution taskExecution = new TaskExecution(); @@ -133,32 +141,40 @@ 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(); - assertEquals(this.resource, request.getResource()); - assertEquals(0, request.getDeploymentProperties().size()); + assertThat(request.getResource()).isEqualTo(this.resource); + assertThat(request.getDeploymentProperties().size()).isEqualTo(0); AppDefinition appDefinition = request.getDefinition(); - assertEquals("partitionedJobTask", appDefinition.getName()); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))); + 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(); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); StepExecution resultStepExecution = results.iterator().next(); - assertEquals(BatchStatus.COMPLETED, resultStepExecution.getStatus()); - assertEquals("step1:partition1", resultStepExecution.getStepName()); + assertThat(resultStepExecution.getStatus()).isEqualTo(BatchStatus.COMPLETED); + assertThat(resultStepExecution.getStepName()).isEqualTo("step1:partition1"); } @Test @@ -168,49 +184,64 @@ 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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); 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(); - assertEquals(this.resource, request.getResource()); - assertEquals(0, request.getDeploymentProperties().size()); + assertThat(request.getResource()).isEqualTo(this.resource); + assertThat(request.getDeploymentProperties().size()).isEqualTo(0); AppDefinition appDefinition = request.getDefinition(); - assertEquals("partitionedJobTask", appDefinition.getName()); - assertTrue(request.getCommandlineArguments().isEmpty()); - assertEquals("1", request.getDefinition().getProperties().get(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)); - assertEquals("4", request.getDefinition().getProperties().get(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)); - assertEquals("step1", request.getDefinition().getProperties().get(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)); - assertEquals("partitionedJobTask_partitionedJob_step1:partition1", request.getDefinition().getProperties().get(DeployerPartitionHandler.SPRING_CLOUD_TASK_NAME)); - assertEquals("55", request.getDefinition().getProperties().get(DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID)); + assertThat(appDefinition.getName()).isEqualTo("partitionedJobTask"); + assertThat(request.getCommandlineArguments().isEmpty()).isTrue(); + assertThat(request.getDefinition().getProperties() + .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)) + .isEqualTo("1"); + assertThat(request.getDefinition().getProperties() + .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_PARENT_EXECUTION_ID)) + .isEqualTo("55"); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); StepExecution resultStepExecution = results.iterator().next(); - assertEquals(BatchStatus.COMPLETED, resultStepExecution.getStatus()); - assertEquals("step1:partition1", resultStepExecution.getStepName()); + assertThat(resultStepExecution.getStatus()).isEqualTo(BatchStatus.COMPLETED); + assertThat(resultStepExecution.getStepName()).isEqualTo("step1:partition1"); } @Test @@ -220,13 +251,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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); 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"); @@ -234,7 +267,8 @@ 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(); @@ -242,10 +276,13 @@ 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(); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID, "55"))); + assertThat(request.getCommandlineArguments().contains(formatArgs( + DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID, "55"))) + .isTrue(); } @Test @@ -255,15 +292,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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); handler.setEnvironment(this.environment); TaskExecution taskExecution = new TaskExecution(); @@ -277,18 +318,24 @@ 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); @@ -302,15 +349,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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); handler.setEnvironment(this.environment); handler.setMaxWorkers(2); @@ -325,18 +376,24 @@ 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); @@ -350,15 +407,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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); handler.setEnvironment(this.environment); handler.setMaxWorkers(2); @@ -373,18 +434,24 @@ 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); @@ -395,13 +462,13 @@ public class DeployerPartitionHandlerTests { StepExecution curResult = resultsIterator.next(); if (curResult.getStepName().equals("step1:partition2")) { - assertEquals(BatchStatus.FAILED, curResult.getStatus()); + assertThat(curResult.getStatus()).isEqualTo(BatchStatus.FAILED); } else { - assertEquals(BatchStatus.COMPLETED, curResult.getStatus()); + assertThat(curResult.getStatus()).isEqualTo(BatchStatus.COMPLETED); } - assertTrue(!names.contains(curResult.getStepName())); + assertThat(!names.contains(curResult.getStepName())).isTrue(); names.add(curResult.getStepName()); } } @@ -413,15 +480,18 @@ 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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); Map environmentParameters = new HashMap<>(2); environmentParameters.put("foo", "bar"); environmentParameters.put("baz", "qux"); - SimpleEnvironmentVariablesProvider environmentVariablesProvider = new SimpleEnvironmentVariablesProvider(this.environment); + SimpleEnvironmentVariablesProvider environmentVariablesProvider = new SimpleEnvironmentVariablesProvider( + this.environment); environmentVariablesProvider.setEnvironmentProperties(environmentParameters); handler.setEnvironmentVariablesProvider(environmentVariablesProvider); @@ -432,33 +502,41 @@ 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(); - assertEquals(this.resource, request.getResource()); - assertEquals(2, request.getDefinition().getProperties().size()); - assertEquals("bar", request.getDefinition().getProperties().get("foo")); - assertEquals("qux", request.getDefinition().getProperties().get("baz")); + assertThat(request.getResource()).isEqualTo(this.resource); + assertThat(request.getDefinition().getProperties().size()).isEqualTo(2); + assertThat(request.getDefinition().getProperties().get("foo")).isEqualTo("bar"); + assertThat(request.getDefinition().getProperties().get("baz")).isEqualTo("qux"); AppDefinition appDefinition = request.getDefinition(); - assertEquals("partitionedJobTask", appDefinition.getName()); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))); + 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(); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); StepExecution resultStepExecution = results.iterator().next(); - assertEquals(BatchStatus.COMPLETED, resultStepExecution.getStatus()); - assertEquals("step1:partition1", resultStepExecution.getStepName()); + assertThat(resultStepExecution.getStatus()).isEqualTo(BatchStatus.COMPLETED); + assertThat(resultStepExecution.getStepName()).isEqualTo("step1:partition1"); } @Test @@ -471,16 +549,19 @@ 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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); handler.setEnvironment(this.environment); Map environmentParameters = new HashMap<>(2); environmentParameters.put("foo", "bar"); environmentParameters.put("baz", "qux"); - SimpleEnvironmentVariablesProvider environmentVariablesProvider = new SimpleEnvironmentVariablesProvider(this.environment); + SimpleEnvironmentVariablesProvider environmentVariablesProvider = new SimpleEnvironmentVariablesProvider( + this.environment); environmentVariablesProvider.setEnvironmentProperties(environmentParameters); handler.setEnvironmentVariablesProvider(environmentVariablesProvider); @@ -491,34 +572,43 @@ 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(); - assertEquals(this.resource, request.getResource()); - assertEquals(3, request.getDefinition().getProperties().size()); - assertEquals("bar", request.getDefinition().getProperties().get("foo")); - assertEquals("qux", request.getDefinition().getProperties().get("baz")); - assertEquals("batch", request.getDefinition().getProperties().get("task")); + assertThat(request.getResource()).isEqualTo(this.resource); + 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"); AppDefinition appDefinition = request.getDefinition(); - assertEquals("partitionedJobTask", appDefinition.getName()); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))); + 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(); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); StepExecution resultStepExecution = results.iterator().next(); - assertEquals(BatchStatus.COMPLETED, resultStepExecution.getStatus()); - assertEquals("step1:partition1", resultStepExecution.getStepName()); + assertThat(resultStepExecution.getStatus()).isEqualTo(BatchStatus.COMPLETED); + assertThat(resultStepExecution.getStepName()).isEqualTo("step1:partition1"); } @Test @@ -528,12 +618,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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); handler.setEnvironment(this.environment); handler.setPollInterval(20000L); @@ -547,26 +640,33 @@ 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); - assertTrue("Time difference was too small: " + (endTime.getTime() - startTime.getTime()), - endTime.getTime() - startTime.getTime() >= 19999); + assertThat(endTime.getTime() - startTime.getTime() >= 19999) + .as("Time difference was too small: " + + (endTime.getTime() - startTime.getTime())) + .isTrue(); } @Test(expected = TimeoutException.class) @@ -576,12 +676,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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); handler.setEnvironment(this.environment); handler.setPollInterval(20000L); @@ -596,8 +699,10 @@ 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(); @@ -613,12 +718,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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); handler.setEnvironment(this.environment); handler.setGridSize(2); @@ -631,18 +739,23 @@ 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); @@ -656,9 +769,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"); + DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, + this.jobExplorer, this.resource, "step1"); handler.setEnvironment(this.environment); Map deploymentProperties = new HashMap<>(2); @@ -674,48 +789,59 @@ 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(); - assertEquals(this.resource, request.getResource()); - assertEquals(2, request.getDeploymentProperties().size()); - assertEquals("bar", request.getDeploymentProperties().get("foo")); - assertEquals("qux", request.getDeploymentProperties().get("baz")); + assertThat(request.getResource()).isEqualTo(this.resource); + assertThat(request.getDeploymentProperties().size()).isEqualTo(2); + assertThat(request.getDeploymentProperties().get("foo")).isEqualTo("bar"); + assertThat(request.getDeploymentProperties().get("baz")).isEqualTo("qux"); AppDefinition appDefinition = request.getDefinition(); - assertEquals("partitionedJobTask", appDefinition.getName()); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))); + 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(); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); StepExecution resultStepExecution = results.iterator().next(); - assertEquals(BatchStatus.COMPLETED, resultStepExecution.getStatus()); - assertEquals("step1:partition1", resultStepExecution.getStepName()); + assertThat(resultStepExecution.getStatus()).isEqualTo(BatchStatus.COMPLETED); + assertThat(resultStepExecution.getStepName()).isEqualTo("step1:partition1"); } private String formatArgs(String key, String value) { 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; } @@ -738,14 +864,15 @@ public class DeployerPartitionHandlerTests { while (resultsIterator.hasNext()) { StepExecution curResult = resultsIterator.next(); - assertEquals(BatchStatus.COMPLETED, curResult.getStatus()); + assertThat(curResult.getStatus()).isEqualTo(BatchStatus.COMPLETED); - assertTrue(!names.contains(curResult.getStepName())); + assertThat(!names.contains(curResult.getStepName())).isTrue(); names.add(curResult.getStepName()); } } - 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) { @@ -753,7 +880,8 @@ 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; } @@ -763,7 +891,8 @@ 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; } @@ -775,23 +904,33 @@ public class DeployerPartitionHandlerTests { for (int i = 4; i < (numberOfPartitions + 4); i++) { AppDeploymentRequest request = allRequests.get(i - 4); - assertEquals(this.resource, request.getResource()); - assertEquals(0, request.getDeploymentProperties().size()); + assertThat(request.getResource()).isEqualTo(this.resource); + assertThat(request.getDeploymentProperties().size()).isEqualTo(0); AppDefinition appDefinition = request.getDefinition(); - assertEquals("partitionedJobTask", appDefinition.getName()); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, String.valueOf(i)))); - assertTrue(request.getCommandlineArguments().contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))); + 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, + String.valueOf(i)))).isTrue(); + assertThat(request.getCommandlineArguments().contains(formatArgs( + DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))) + .isTrue(); } } - private void validateConstructorValidation(TaskLauncher taskLauncher, JobExplorer jobExplorer, Resource resource, String stepName, String expectedMessage) { + private void validateConstructorValidation(TaskLauncher taskLauncher, + JobExplorer jobExplorer, Resource resource, String stepName, + String expectedMessage) { try { new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, stepName); } catch (IllegalArgumentException iae) { - assertEquals(expectedMessage, iae.getMessage()); + 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 41fd97a6..15e5a170 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import org.junit.Before; @@ -35,7 +36,7 @@ import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.core.env.Environment; import org.springframework.test.util.ReflectionTestUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -70,7 +71,8 @@ public class DeployerStepExecutionHandlerTests { public void setUp() { MockitoAnnotations.initMocks(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); } @@ -78,69 +80,116 @@ 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 name is required", new String[] {DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_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, + 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) { - assertEquals("The step requested cannot be found in the provided BeanFactory", iae.getMessage()); + 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) { - assertEquals("No StepExecution could be located for step execution id 2 within job execution 1", nsse.getMessage()); + 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); - handler.run(); + this.handler.run(); verify(this.step).execute(workerStep); verifyZeroInteractions(this.jobRepository); @@ -148,51 +197,87 @@ 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); - handler.run(); + this.handler.run(); verify(this.jobRepository).update(this.stepExecutionArgumentCaptor.capture()); - assertEquals(BatchStatus.STOPPED, this.stepExecutionArgumentCaptor.getValue().getStatus()); + 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); - handler.run(); + this.handler.run(); verify(this.jobRepository).update(this.stepExecutionArgumentCaptor.capture()); - assertEquals(BatchStatus.FAILED, this.stepExecutionArgumentCaptor.getValue().getStatus()); + 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); @@ -202,17 +287,18 @@ public class DeployerStepExecutionHandlerTests { this.handler.run(); } catch (IllegalArgumentException iae) { - assertEquals(errorMessage, iae.getMessage()); + assertThat(iae.getMessage()).isEqualTo(errorMessage); } } - - 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); } catch (IllegalArgumentException iae) { - assertEquals(message, iae.getMessage()); + assertThat(iae.getMessage()).isEqualTo(message); } } + } 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 65e695db..27020d96 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import java.util.Map; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michael Minella @@ -35,11 +37,14 @@ public class NoOpEnvironmentVariablesProviderTests { @Test public void test() { - Map environmentVariables = this.provider.getEnvironmentVariables(null); - assertNotNull(environmentVariables); - assertTrue(environmentVariables.isEmpty()); + Map environmentVariables = this.provider + .getEnvironmentVariables(null); + assertThat(environmentVariables).isNotNull(); + assertThat(environmentVariables.isEmpty()).isTrue(); - Map environmentVariables2 = this.provider.getEnvironmentVariables(null); - assertTrue(environmentVariables == environmentVariables2); + 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/PassThroughCommandLineArgsProviderTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/PassThroughCommandLineArgsProviderTests.java index aeb38b9f..a5e53e8e 100644 --- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/PassThroughCommandLineArgsProviderTests.java +++ b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/PassThroughCommandLineArgsProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import java.util.Arrays; import java.util.List; import org.junit.Test; -import static org.junit.Assert.*; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michael Minella @@ -39,8 +41,9 @@ public class PassThroughCommandLineArgsProviderTests { List commandLineArgs = provider.getCommandLineArgs(null); - assertEquals("foo", commandLineArgs.get(0)); - assertEquals("bar", commandLineArgs.get(1)); - assertEquals("baz", commandLineArgs.get(2)); + assertThat(commandLineArgs.get(0)).isEqualTo("foo"); + assertThat(commandLineArgs.get(1)).isEqualTo("bar"); + assertThat(commandLineArgs.get(2)).isEqualTo("baz"); } + } 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 4855db57..738fa1dd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.partition; import java.util.ArrayList; @@ -23,7 +24,7 @@ import org.junit.Test; import org.springframework.cloud.task.repository.TaskExecution; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michael Minella @@ -35,13 +36,14 @@ 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); - assertEquals("foo", commandLineArgs.get(0)); - assertEquals("bar", commandLineArgs.get(1)); - assertEquals("baz", commandLineArgs.get(2)); + assertThat(commandLineArgs.get(0)).isEqualTo("foo"); + assertThat(commandLineArgs.get(1)).isEqualTo("bar"); + assertThat(commandLineArgs.get(2)).isEqualTo("baz"); } @Test @@ -54,17 +56,18 @@ 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); - assertEquals("foo", commandLineArgs.get(0)); - assertEquals("bar", commandLineArgs.get(1)); - assertEquals("baz", commandLineArgs.get(2)); - assertEquals("one", commandLineArgs.get(3)); - assertEquals("two", commandLineArgs.get(4)); - assertEquals("three", commandLineArgs.get(5)); + assertThat(commandLineArgs.get(0)).isEqualTo("foo"); + assertThat(commandLineArgs.get(1)).isEqualTo("bar"); + assertThat(commandLineArgs.get(2)).isEqualTo("baz"); + assertThat(commandLineArgs.get(3)).isEqualTo("one"); + assertThat(commandLineArgs.get(4)).isEqualTo("two"); + assertThat(commandLineArgs.get(5)).isEqualTo("three"); } @Test @@ -73,14 +76,16 @@ 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); - assertEquals(3, commandLineArgs.size()); - assertEquals("foo", commandLineArgs.get(0)); - assertEquals("bar", commandLineArgs.get(1)); - assertEquals("baz", commandLineArgs.get(2)); + assertThat(commandLineArgs.size()).isEqualTo(3); + assertThat(commandLineArgs.get(0)).isEqualTo("foo"); + assertThat(commandLineArgs.get(1)).isEqualTo("bar"); + assertThat(commandLineArgs.get(2)).isEqualTo("baz"); } + } diff --git a/spring-cloud-task-core/pom.xml b/spring-cloud-task-core/pom.xml index 8b40b38e..803e8629 100755 --- a/spring-cloud-task-core/pom.xml +++ b/spring-cloud-task-core/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 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 f95465b3..65e2d62a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,13 +36,14 @@ import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.transaction.PlatformTransactionManager; /** - * Default implementation of the TaskConfigurer interface. If no {@link TaskConfigurer} - * implementation is present, then this configuration will be used. - * The following defaults will be used: + * Default implementation of the TaskConfigurer interface. If no {@link TaskConfigurer} + * implementation is present, then this configuration will be used. The following defaults + * will be used: *
    - *
  • {@link SimpleTaskRepository} is the default {@link TaskRepository} returned. - * If a data source is present then a data will be stored in the database {@link JdbcTaskExecutionDao} else it will - * be stored in a map {@link MapTaskExecutionDao}. + *
  • {@link SimpleTaskRepository} is the default {@link TaskRepository} returned. If a + * data source is present then a data will be stored in the database + * {@link JdbcTaskExecutionDao} else it will be stored in a map + * {@link MapTaskExecutionDao}. *
* * @author Glenn Renfro @@ -67,12 +68,11 @@ public class DefaultTaskConfigurer implements TaskConfigurer { } /** - * Initializes the DefaultTaskConfigurer and sets the default table prefix - * to {@link TaskProperties#DEFAULT_TABLE_PREFIX}. - * + * Initializes the DefaultTaskConfigurer and sets the default table prefix to + * {@link TaskProperties#DEFAULT_TABLE_PREFIX}. * @param dataSource references the {@link DataSource} to be used as the Task - * repository. If none is provided, a Map will be used (not recommended for - * production use. + * repository. If none is provided, a Map will be used (not recommended for production + * use. */ public DefaultTaskConfigurer(DataSource dataSource) { this(dataSource, TaskProperties.DEFAULT_TABLE_PREFIX, null); @@ -80,9 +80,8 @@ public class DefaultTaskConfigurer implements TaskConfigurer { /** * Initializes the DefaultTaskConfigurer. - * - * @param tablePrefix the prefix to apply to the task table names used by - * task infrastructure. + * @param tablePrefix the prefix to apply to the task table names used by task + * infrastructure. */ public DefaultTaskConfigurer(String tablePrefix) { this(null, tablePrefix, null); @@ -90,23 +89,23 @@ public class DefaultTaskConfigurer implements TaskConfigurer { /** * Initializes the DefaultTaskConfigurer. - * * @param dataSource references the {@link DataSource} to be used as the Task - * repository. If none is provided, a Map will be used (not recommended for - * production use. - * @param tablePrefix the prefix to apply to the task table names used by - * task infrastructure. + * repository. If none is provided, a Map will be used (not recommended for production + * use. + * @param tablePrefix the prefix to apply to the task table names used by task + * 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); + if (this.dataSource != null) { + taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(this.dataSource, + tablePrefix); } else { taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(); @@ -137,22 +136,27 @@ 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(); } } @@ -163,4 +167,5 @@ public class DefaultTaskConfigurer implements TaskConfigurer { private boolean isDataSourceAvailable() { return this.dataSource != null; } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/EnableTask.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/EnableTask.java index 11e43db6..75478835 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/EnableTask.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/EnableTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,13 +23,12 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.springframework.cloud.task.repository.TaskRepository; import org.springframework.context.annotation.Import; /** *

- * Enables the {@link org.springframework.cloud.task.listener.TaskLifecycleListener} - * so that the features of Spring Cloud Task will be applied. + * Enables the {@link org.springframework.cloud.task.listener.TaskLifecycleListener} so + * that the features of Spring Cloud Task will be applied. * *

  * @Configuration
@@ -39,13 +38,14 @@ import org.springframework.context.annotation.Import;
  * 	@Bean
  * 	public MyCommandLineRunner myCommandLineRunner() {
  * 		return new MyCommandLineRunner()
- * 	}
+ *    }
  * }
  * 
* - * Note that only one of your configuration classes needs to have the @EnableTask - * annotation. Once you have an @EnableTask class in your configuration - * the task will have the Spring Cloud Task features available. + * Note that only one of your configuration classes needs to have the + * @EnableTask annotation. Once you have an + * @EnableTask class in your configuration the task will have the Spring + * Cloud Task features available. * * @author Glenn Renfro * @@ -56,4 +56,5 @@ import org.springframework.context.annotation.Import; @Inherited @Import(TaskLifecycleConfiguration.class) public @interface EnableTask { + } 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 fdf4c945..c4fe1fc6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,10 +54,13 @@ import org.springframework.util.CollectionUtils; @Configuration @EnableTransactionManagement @EnableConfigurationProperties(TaskProperties.class) +// @checkstyle:off @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; @@ -80,7 +83,7 @@ public class SimpleTaskAutoConfiguration { private TaskExplorer taskExplorer; @Bean - public TaskRepository taskRepository(){ + public TaskRepository taskRepository() { return this.taskRepository; } @@ -104,7 +107,7 @@ public class SimpleTaskAutoConfiguration { public TaskRepositoryInitializer taskRepositoryInitializer() { TaskRepositoryInitializer taskRepositoryInitializer = new TaskRepositoryInitializer(); DataSource initializerDataSource = getDefaultConfigurer().getTaskDataSource(); - if(initializerDataSource != null) { + if (initializerDataSource != null) { taskRepositoryInitializer.setDataSource(initializerDataSource); } @@ -116,7 +119,7 @@ public class SimpleTaskAutoConfiguration { */ @PostConstruct protected void initialize() { - if (initialized) { + if (this.initialized) { return; } @@ -128,7 +131,7 @@ public class SimpleTaskAutoConfiguration { this.taskRepository = taskConfigurer.getTaskRepository(); this.platformTransactionManager = taskConfigurer.getTransactionManager(); this.taskExplorer = taskConfigurer.getTaskExplorer(); - initialized = true; + this.initialized = true; } private TaskConfigurer getDefaultConfigurer() { @@ -138,36 +141,44 @@ public class SimpleTaskAutoConfiguration { if (configurers < 1) { TaskConfigurer taskConfigurer; - if(!CollectionUtils.isEmpty(this.dataSources) && this.dataSources.size() == 1) { + if (!CollectionUtils.isEmpty(this.dataSources) + && this.dataSources.size() == 1) { taskConfigurer = new DefaultTaskConfigurer( this.dataSources.iterator().next(), - taskProperties.getTablePrefix(), context); + this.taskProperties.getTablePrefix(), this.context); } else { - taskConfigurer = new DefaultTaskConfigurer(taskProperties.getTablePrefix()); + taskConfigurer = new DefaultTaskConfigurer( + this.taskProperties.getTablePrefix()); } - this.context.getBeanFactory().registerSingleton("taskConfigurer", taskConfigurer); + this.context.getBeanFactory().registerSingleton("taskConfigurer", + taskConfigurer); return taskConfigurer; } else { - if(configurers == 1) { + if (configurers == 1) { 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); } } } private void verifyEnvironment() { 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)) + // retrieve the count of dataSources (without instantiating them) excluding + // DataSource proxy beans + 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); + if (configurers == 0 && dataSources > 1) { + 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 b2b155d3..23e1afa4 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 @@ -1,17 +1,17 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.configuration; @@ -39,10 +39,10 @@ import org.springframework.integration.support.leader.LockRegistryLeaderInitiato import org.springframework.integration.support.locks.LockRegistry; /** - * When spring.cloud.task.single-instance-enabled is set to true this listener will create a lock for the task - * based on the spring.cloud.task.name. If a lock already exists this Listener will throw - * a TaskExecutionException. If this listener is added manually, then it should - * be added as the first listener in the chain. + * When spring.cloud.task.single-instance-enabled is set to true this listener will create + * a lock for the task based on the spring.cloud.task.name. If a lock already exists this + * Listener will throw a TaskExecutionException. If this listener is added manually, then + * it should be added as the first listener in the chain. * * @author Glenn Renfro * @since 2.0.0 @@ -68,19 +68,18 @@ public class SingleInstanceTaskListener implements ApplicationListenerTaskConfigurer directly unless they are using it to supply the implementations - * for Spring Beans. + * Provides a strategy interface for providing configuration customization to the task + * system. Users should not directly use getter methods from a TaskConfigurer + * directly unless they are using it to supply the implementations for Spring Beans. * * @author Glenn Renfro */ @@ -34,7 +33,6 @@ public interface TaskConfigurer { /** * Create a {@link TaskRepository} for the Task. - * * @return A TaskRepository */ TaskRepository getTaskRepository(); @@ -42,23 +40,22 @@ public interface TaskConfigurer { /** * Create a {@link PlatformTransactionManager} for use with the * TaskRepository. - * * @return A PlatformTransactionManager */ PlatformTransactionManager getTransactionManager(); /** * Create a {@link TaskExplorer} for the task. - * * @return a TaskExplorer */ TaskExplorer getTaskExplorer(); /** - * Retrieves the {@link DataSource} that will be used for task operations. If a - * DataSource is not being used for the implemented TaskConfigurer this - * method will return null. + * Retrieves the {@link DataSource} that will be used for task operations. If a + * DataSource is not being used for the implemented TaskConfigurer this method will + * return null. * @return {@link DataSource} that will be used for task operations. */ DataSource getTaskDataSource(); + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskLifecycleConfiguration.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskLifecycleConfiguration.java index df49c67c..e6cdcfd2 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskLifecycleConfiguration.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskLifecycleConfiguration.java @@ -1,17 +1,17 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.configuration; @@ -43,7 +43,8 @@ import org.springframework.context.annotation.Configuration; @Configuration public class TaskLifecycleConfiguration { - protected static final Log logger = LogFactory.getLog(TaskLifecycleConfiguration.class); + protected static final Log logger = LogFactory + .getLog(TaskLifecycleConfiguration.class); private TaskProperties taskProperties; @@ -63,10 +64,8 @@ public class TaskLifecycleConfiguration { @Autowired public TaskLifecycleConfiguration(TaskProperties taskProperties, - ConfigurableApplicationContext context, - TaskRepository taskRepository, - TaskExplorer taskExplorer, - TaskNameResolver taskNameResolver, + ConfigurableApplicationContext context, TaskRepository taskRepository, + TaskExplorer taskExplorer, TaskNameResolver taskNameResolver, ObjectProvider applicationArguments) { this.taskProperties = taskProperties; @@ -88,15 +87,13 @@ 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(context)); + this.taskLifecycleListener = new TaskLifecycleListener(this.taskRepository, + this.taskNameResolver, this.applicationArguments, this.taskExplorer, + this.taskProperties, + new TaskListenerExecutorObjectFactory(this.context)); this.initialized = true; } } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskProperties.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskProperties.java index efd7d4ce..e956f31f 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskProperties.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/TaskProperties.java @@ -1,22 +1,21 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.configuration; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -32,11 +31,14 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "spring.cloud.task") public class TaskProperties { + /** + * Default table prefix for Spring Cloud Task. + */ + public static final String DEFAULT_TABLE_PREFIX = "TASK_"; + private static final int DEFAULT_CHECK_INTERVAL = 500; private static final Log logger = LogFactory.getLog(TaskProperties.class); - - public static final String DEFAULT_TABLE_PREFIX = "TASK_"; /** * An id that can be associated with a task. @@ -49,8 +51,8 @@ public class TaskProperties { private Long executionid; /** - * The id of the parent task execution id that launched this task execution. - * Defaults to null if task execution had no parent. + * The id of the parent task execution id that launched this task execution. Defaults + * to null if task execution had no parent. */ private Long parentExecutionId; @@ -60,35 +62,34 @@ public class TaskProperties { private String tablePrefix = DEFAULT_TABLE_PREFIX; /** - * When set to true the context is closed at the end of the task. Else - * the context remains open. + * When set to true the context is closed at the end of the task. Else the context + * remains open. */ private Boolean closecontextEnabled = false; /** - * When set to true it - * will check to see if a task execution with the same task name is already - * running. If a task is still running then it will throw a - * {@link org.springframework.cloud.task.listener.TaskExecutionException}. - * When task execution ends the lock is released. + * When set to true it will check to see if a task execution with the same task name + * is already running. If a task is still running then it will throw a + * {@link org.springframework.cloud.task.listener.TaskExecutionException}. When task + * execution ends the lock is released. */ private boolean singleInstanceEnabled = false; /** - * Declares the maximum amount of time (in millis) that a task execution can - * hold a lock to prevent another task from executing with a specific task - * name when the single-instance-enabled is set to true. Default time is: Integer.MAX_VALUE. + * Declares the maximum amount of time (in millis) that a task execution can hold a + * lock to prevent another task from executing with a specific task name when the + * single-instance-enabled is set to true. Default time is: Integer.MAX_VALUE. */ private int singleInstanceLockTtl = Integer.MAX_VALUE; /** - * Declares the time (in millis) that a task execution will wait between - * checks. Default time is: 500 millis. + * Declares the time (in millis) that a task execution will wait between checks. + * Default time is: 500 millis. */ private int singleInstanceLockCheckInterval = DEFAULT_CHECK_INTERVAL; public String getExternalExecutionId() { - return externalExecutionId; + return this.externalExecutionId; } public void setExternalExecutionId(String externalExecutionId) { @@ -96,7 +97,7 @@ public class TaskProperties { } public Long getExecutionid() { - return executionid; + return this.executionid; } public void setExecutionid(Long executionid) { @@ -104,7 +105,7 @@ public class TaskProperties { } public Boolean getClosecontextEnabled() { - return closecontextEnabled; + return this.closecontextEnabled; } public void setClosecontextEnabled(Boolean closecontextEnabled) { @@ -112,7 +113,7 @@ public class TaskProperties { } public String getTablePrefix() { - return tablePrefix; + return this.tablePrefix; } public void setTablePrefix(String tablePrefix) { @@ -120,7 +121,7 @@ public class TaskProperties { } public Long getParentExecutionId() { - return parentExecutionId; + return this.parentExecutionId; } public void setParentExecutionId(Long parentExecutionId) { @@ -128,7 +129,7 @@ public class TaskProperties { } public boolean getSingleInstanceEnabled() { - return singleInstanceEnabled; + return this.singleInstanceEnabled; } public void setSingleInstanceEnabled(boolean singleInstanceEnabled) { @@ -136,7 +137,7 @@ public class TaskProperties { } public int getSingleInstanceLockTtl() { - return singleInstanceLockTtl; + return this.singleInstanceLockTtl; } public void setSingleInstanceLockTtl(int singleInstanceLockTtl) { @@ -144,10 +145,11 @@ public class TaskProperties { } public int getSingleInstanceLockCheckInterval() { - return singleInstanceLockCheckInterval; + return this.singleInstanceLockCheckInterval; } public void setSingleInstanceLockCheckInterval(int singleInstanceLockCheckInterval) { this.singleInstanceLockCheckInterval = singleInstanceLockCheckInterval; } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/package-info.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/package-info.java index 8bbdd330..cb39e626 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/package-info.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/configuration/package-info.java @@ -1,3 +1,19 @@ +/* + * Copyright 2015-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** * Interfaces for configuring Spring Cloud Task and a default implementations. */ diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskException.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskException.java index e83e5284..8db88097 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskException.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskException.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,15 +18,16 @@ package org.springframework.cloud.task.listener; /** * Base Exception for any Task issues. + * * @author Glenn Renfro */ public class TaskException extends RuntimeException { - public TaskException(String message, Throwable e){ + public TaskException(String message, Throwable e) { super(message, e); } - public TaskException(String message){ + public TaskException(String message) { super(message); } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionException.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionException.java index c4737986..82f5410c 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionException.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionException.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,11 +23,12 @@ package org.springframework.cloud.task.listener; */ public class TaskExecutionException extends TaskException { - public TaskExecutionException(String message){ + public TaskExecutionException(String message) { super(message); } - public TaskExecutionException(String message, Throwable throwable){ + public TaskExecutionException(String message, Throwable throwable) { super(message, throwable); } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionListener.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionListener.java index 637a9be6..79148d31 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionListener.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/TaskExecutionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,29 +21,32 @@ import org.springframework.cloud.task.repository.TaskRepository; /** * The listener interface for receiving task execution events. + * * @author Glenn Renfro */ public interface TaskExecutionListener { /** - * Invoked after the {@link TaskExecution} has been stored in the {@link TaskRepository}. + * Invoked after the {@link TaskExecution} has been stored in the + * {@link TaskRepository}. * @param taskExecution instance containing the information about the current task. */ void onTaskStartup(TaskExecution taskExecution); /** - * Invoked before the {@link TaskExecution} has been updated in the {@link TaskRepository} - * upon task end. + * Invoked before the {@link TaskExecution} has been updated in the + * {@link TaskRepository} upon task end. * @param taskExecution instance containing the information about the current task. */ void onTaskEnd(TaskExecution taskExecution); /** - * Invoked if an uncaught exception occurs during a task execution. This invocation - * will occur before the {@link TaskExecution} has been updated in the {@link TaskRepository} - * and before the onTaskEnd is called. + * Invoked if an uncaught exception occurs during a task execution. This invocation + * will occur before the {@link TaskExecution} has been updated in the + * {@link TaskRepository} and before the onTaskEnd is called. * @param taskExecution instance containing the information about the current task. * @param throwable the uncaught exception that was thrown during task execution. */ void onTaskFailed(TaskExecution taskExecution, Throwable throwable); + } 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 16dabcd1..e5cfd9cb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.listener; import org.springframework.cloud.task.repository.TaskExecution; @@ -25,6 +26,7 @@ import org.springframework.cloud.task.repository.TaskExecution; * @since 1.2 */ public class TaskExecutionListenerSupport implements TaskExecutionListener { + @Override public void onTaskStartup(TaskExecution taskExecution) { @@ -39,4 +41,5 @@ public class TaskExecutionListenerSupport implements TaskExecutionListener { public void onTaskFailed(TaskExecution taskExecution, Throwable throwable) { } + } 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 5578555e..6f12eff1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.listener; import java.io.PrintWriter; @@ -49,33 +50,42 @@ import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; /** - * Monitors the lifecycle of a task. This listener will record both the start and end of - * a task in the registered {@link TaskRepository}. + * Monitors the lifecycle of a task. This listener will record both the start and end of a + * task in the registered {@link TaskRepository}. * * The following events are used to identify the start and end of a task: * *
    - *
  • {@link SmartLifecycle#start()} - Used to identify the start of a task. A task - * is expected to contain a single application context.
  • - *
  • {@link ApplicationReadyEvent} - Used to identify the successful end of a task.
  • - *
  • {@link ApplicationFailedEvent} - Used to identify the failure of a task.
  • - *
  • {@link SmartLifecycle#stop()} - Used to identify the end of a task, - * if the {@link ApplicationReadyEvent} or {@link ApplicationFailedEvent} - * is not emitted. This can occur if an error occurs while executing a BeforeTask. - *
  • + *
  • {@link SmartLifecycle#start()} - Used to identify the start of a task. A task is + * expected to contain a single application context.
  • + *
  • {@link ApplicationReadyEvent} - Used to identify the successful end of a task.
  • + *
  • {@link ApplicationFailedEvent} - Used to identify the failure of a task.
  • + *
  • {@link SmartLifecycle#stop()} - Used to identify the end of a task, if the + * {@link ApplicationReadyEvent} or {@link ApplicationFailedEvent} is not emitted. This + * can occur if an error occurs while executing a BeforeTask.
  • *
* - * Note: By default, the context will close at the completion of the task unless other non-daemon - * threads keep it running. Programatic closing of the context can be configured via the - * property spring.cloud.task.closecontext.enabled (defaults to false). - * If the spring.cloud.task.closecontext.enabled is set to true, - * then the context will be closed upon task completion regardless if non-daemon threads are still running. - * Also if the context did not start, the FailedTask and TaskEnd may not have all the dependencies met. + * Note: By default, the context will close at the completion of the task unless + * other non-daemon threads keep it running. Programatic closing of the context can be + * configured via the property spring.cloud.task.closecontext.enabled + * (defaults to false). If the spring.cloud.task.closecontext.enabled is set + * to true, then the context will be closed upon task completion regardless if non-daemon + * threads are still running. Also if the context did not start, the FailedTask and + * TaskEnd may not have all the dependencies met. * * @author Michael Minella * @author Glenn Renfro */ -public class TaskLifecycleListener implements ApplicationListener, SmartLifecycle, DisposableBean { +public class TaskLifecycleListener + implements ApplicationListener, SmartLifecycle, DisposableBean { + + private static final Log logger = LogFactory.getLog(TaskLifecycleListener.class); + + private final TaskRepository taskRepository; + + private final TaskExplorer taskExplorer; + + private final TaskListenerExecutorObjectFactory taskListenerExecutorObjectFactory; @Autowired private ConfigurableApplicationContext context; @@ -85,14 +95,6 @@ public class TaskLifecycleListener implements ApplicationListener taskExecutionListeners; - private static final Log logger = LogFactory.getLog(TaskLifecycleListener.class); - - private final TaskRepository taskRepository; - - private final TaskExplorer taskExplorer; - - private final TaskListenerExecutorObjectFactory taskListenerExecutorObjectFactory; - private TaskExecution taskExecution; private TaskProperties taskProperties; @@ -115,22 +117,25 @@ public class TaskLifecycleListener implements ApplicationListener - *
  • {@link ApplicationReadyEvent} - Successful end of a task
  • - *
  • {@link ApplicationFailedEvent} - Failure of a task
  • + *
  • {@link ApplicationReadyEvent} - Successful end of a task
  • + *
  • {@link ApplicationFailedEvent} - Failure of a task
  • * - * * @param applicationEvent The application being listened for. */ @Override public void onApplicationEvent(ApplicationEvent applicationEvent) { - if(applicationEvent instanceof ApplicationFailedEvent) { - this.applicationFailedException = ((ApplicationFailedEvent) applicationEvent).getException(); + if (applicationEvent instanceof ApplicationFailedEvent) { + this.applicationFailedException = ((ApplicationFailedEvent) applicationEvent) + .getException(); doTaskEnd(); } - else if(applicationEvent instanceof ExitCodeEvent){ + else if (applicationEvent instanceof ExitCodeEvent) { this.exitCodeEvent = (ExitCodeEvent) applicationEvent; } - else if(applicationEvent instanceof ApplicationReadyEvent) { + else if (applicationEvent instanceof ApplicationReadyEvent) { doTaskEnd(); } } @@ -174,37 +179,41 @@ public class TaskLifecycleListener implements ApplicationListener(); this.taskListenerExecutorObjectFactory.getObject(); - if(!CollectionUtils.isEmpty(this.taskExecutionListenersFromContext)) { - this.taskExecutionListeners.addAll(this.taskExecutionListenersFromContext); + if (!CollectionUtils.isEmpty(this.taskExecutionListenersFromContext)) { + this.taskExecutionListeners + .addAll(this.taskExecutionListenersFromContext); } - this.taskExecutionListeners.add(this.taskListenerExecutorObjectFactory.getObject()); + this.taskExecutionListeners + .add(this.taskListenerExecutorObjectFactory.getObject()); List args = new ArrayList<>(0); - if(this.applicationArguments != null) { + if (this.applicationArguments != null) { args = Arrays.asList(this.applicationArguments.getSourceArgs()); } - if(this.taskProperties.getExecutionid() != null) { - TaskExecution taskExecution = this.taskExplorer.getTaskExecution(this.taskProperties.getExecutionid()); - Assert.notNull(taskExecution, String.format("Invalid TaskExecution, ID %s not found", this.taskProperties.getExecutionid())); + if (this.taskProperties.getExecutionid() != null) { + TaskExecution taskExecution = this.taskExplorer + .getTaskExecution(this.taskProperties.getExecutionid()); + Assert.notNull(taskExecution, + String.format("Invalid TaskExecution, ID %s not found", + this.taskProperties.getExecutionid())); Assert.isNull(taskExecution.getEndTime(), String.format( - "Invalid TaskExecution, ID %s task is already complete", this.taskProperties.getExecutionid())); - this.taskExecution = this.taskRepository.startTaskExecution(this.taskProperties.getExecutionid(), + "Invalid TaskExecution, ID %s task is already complete", + this.taskProperties.getExecutionid())); + this.taskExecution = this.taskRepository.startTaskExecution( + this.taskProperties.getExecutionid(), this.taskNameResolver.getTaskName(), new Date(), args, this.taskProperties.getExternalExecutionId(), this.taskProperties.getParentExecutionId()); @@ -268,15 +286,18 @@ public class TaskLifecycleListener implements ApplicationListener startupListenerList = new ArrayList<>(this.taskExecutionListeners); + List startupListenerList = new ArrayList<>( + this.taskExecutionListeners); if (!CollectionUtils.isEmpty(startupListenerList)) { try { Collections.reverse(startupListenerList); @@ -310,7 +332,7 @@ 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; @@ -62,7 +63,7 @@ public class TaskListenerExecutorObjectFactory implements ObjectFactory failedTaskInstances; - public TaskListenerExecutorObjectFactory(ConfigurableApplicationContext context){ + public TaskListenerExecutorObjectFactory(ConfigurableApplicationContext context) { this.context = context; } @@ -72,12 +73,13 @@ public class TaskListenerExecutorObjectFactory implements ObjectFactory(); this.failedTaskInstances = new HashMap<>(); initializeExecutor(); - return new TaskListenerExecutor(beforeTaskInstances, afterTaskInstances, failedTaskInstances); + return new TaskListenerExecutor(this.beforeTaskInstances, this.afterTaskInstances, + this.failedTaskInstances); } - private void initializeExecutor( ) { - ConfigurableListableBeanFactory factory = context.getBeanFactory(); - for( String beanName : context.getBeanDefinitionNames()) { + private void initializeExecutor() { + ConfigurableListableBeanFactory factory = this.context.getBeanFactory(); + for (String beanName : this.context.getBeanDefinitionNames()) { if (!ScopedProxyUtils.isScopedTarget(beanName)) { Class type = null; @@ -85,9 +87,11 @@ public class TaskListenerExecutorObjectFactory implements ObjectFactory type){ + 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); return; } - if(!beforeTaskMethods.isEmpty()) { - for(Method beforeTaskMethod : beforeTaskMethods.keySet()) { - this.beforeTaskInstances.put(beforeTaskMethod, context.getBean(beanName)); + if (!beforeTaskMethods.isEmpty()) { + for (Method beforeTaskMethod : beforeTaskMethods.keySet()) { + this.beforeTaskInstances.put(beforeTaskMethod, + this.context.getBean(beanName)); } } - if(!afterTaskMethods.isEmpty()){ - for(Method afterTaskMethod : afterTaskMethods.keySet()) { - this.afterTaskInstances.put(afterTaskMethod, context.getBean(beanName)); + if (!afterTaskMethods.isEmpty()) { + for (Method afterTaskMethod : afterTaskMethods.keySet()) { + this.afterTaskInstances.put(afterTaskMethod, + this.context.getBean(beanName)); } } - if(!failedTaskMethods.isEmpty()){ - for(Method failedTaskMethod : failedTaskMethods.keySet()) { - this.failedTaskInstances.put(failedTaskMethod, context.getBean(beanName)); + if (!failedTaskMethods.isEmpty()) { + for (Method failedTaskMethod : failedTaskMethods.keySet()) { + this.failedTaskInstances.put(failedTaskMethod, + this.context.getBean(beanName)); } } } } 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/annotation/AfterTask.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/AfterTask.java index 546cd7f6..7d623092 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/AfterTask.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/AfterTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,22 +27,22 @@ import org.springframework.cloud.task.repository.TaskExecution; /** *

    - * {@link TaskExecutionListener#onTaskEnd(TaskExecution)} + * {@link TaskExecutionListener#onTaskEnd(TaskExecution)}. *

    * *
      * public class MyListener {
    -
      * 	@AfterTask
      * 	public void  doSomething(TaskExecution taskExecution) {
    - * 	}
    + *    }
      * }
      * 
    * * @author Glenn Renfro */ -@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) +@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface AfterTask { + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/BeforeTask.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/BeforeTask.java index 3180ded2..3a11fb58 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/BeforeTask.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/BeforeTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,22 +27,22 @@ import org.springframework.cloud.task.repository.TaskExecution; /** *

    - * {@link TaskExecutionListener#onTaskStartup(TaskExecution)} + * {@link TaskExecutionListener#onTaskStartup(TaskExecution)}. *

    * *
      * public class MyListener {
    -
      * 	@BeforeTask
      * 	public void  doSomething(TaskExecution taskExecution) {
    - * 	}
    + *    }
      * }
      * 
    * * @author Glenn Renfro */ -@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) +@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface BeforeTask { + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/FailedTask.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/FailedTask.java index 62b7534f..75cc86f9 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/FailedTask.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/listener/annotation/FailedTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,22 +27,22 @@ import org.springframework.cloud.task.repository.TaskExecution; /** *

    - * {@link TaskExecutionListener#onTaskFailed(TaskExecution, Throwable)} + * {@link TaskExecutionListener#onTaskFailed(TaskExecution, Throwable)}. *

    * *
      * public class MyListener {
    -
      * 	@FailedTask
      * 	public void  doSomething(TaskExecution taskExecution, Throwable throwable) {
    - * 	}
    + *    }
      * }
      * 
    * * @author Glenn Renfro */ -@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) +@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FailedTask { + } 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 4cec5ce5..cee9db8b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import org.springframework.cloud.task.repository.TaskExecution; * * @author Glenn Renfro */ -public class TaskListenerExecutor implements TaskExecutionListener{ +public class TaskListenerExecutor implements TaskExecutionListener { private Map beforeTaskInstances; @@ -42,7 +42,7 @@ public class TaskListenerExecutor implements TaskExecutionListener{ public TaskListenerExecutor(Map beforeTaskInstances, Map afterTaskInstances, - Map failedTaskInstances){ + Map failedTaskInstances) { this.beforeTaskInstances = beforeTaskInstances; this.afterTaskInstances = afterTaskInstances; @@ -50,66 +50,77 @@ public class TaskListenerExecutor implements TaskExecutionListener{ } /** - * Executes all the methods that have been annotated with @BeforeTask. + * Executes all the methods that have been annotated with @BeforeTask. * @param taskExecution associated with the event. */ @Override public void onTaskStartup(TaskExecution taskExecution) { - executeTaskListener(taskExecution, beforeTaskInstances.keySet(), beforeTaskInstances); + executeTaskListener(taskExecution, this.beforeTaskInstances.keySet(), + this.beforeTaskInstances); } /** - * Executes all the methods that have been annotated with @AfterTask. + * Executes all the methods that have been annotated with @AfterTask. * @param taskExecution associated with the event. */ @Override public void onTaskEnd(TaskExecution taskExecution) { - executeTaskListener(taskExecution, afterTaskInstances.keySet(), afterTaskInstances); + executeTaskListener(taskExecution, this.afterTaskInstances.keySet(), + this.afterTaskInstances); } /** - * Executes all the methods that have been annotated with @FailedTask. + * Executes all the methods that have been annotated with @FailedTask. * @param throwable that was not caught for the task execution. * @param taskExecution associated with the event. */ @Override public void onTaskFailed(TaskExecution taskExecution, Throwable throwable) { executeTaskListenerWithThrowable(taskExecution, throwable, - failedTaskInstances.keySet(),failedTaskInstances); + this.failedTaskInstances.keySet(), this.failedTaskInstances); } - private void executeTaskListener(TaskExecution taskExecution, Set methods, Map instances){ + private void executeTaskListener(TaskExecution taskExecution, Set methods, + Map instances) { for (Method method : methods) { try { - method.invoke(instances.get(method),taskExecution); + method.invoke(instances.get(method), 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", e); + catch (IllegalArgumentException e) { + throw new TaskExecutionException("taskExecution parameter " + + "is required for @BeforeTask and @AfterTask annotated methods", + e); } } } private void executeTaskListenerWithThrowable(TaskExecution taskExecution, - Throwable throwable, Set methods, Map instances){ + Throwable throwable, Set methods, Map instances) { for (Method method : methods) { try { - method.invoke(instances.get(method),taskExecution, throwable); + method.invoke(instances.get(method), 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){ + catch (IllegalArgumentException 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/package-info.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/package-info.java index 235956ad..55d679f7 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/package-info.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/package-info.java @@ -1,3 +1,19 @@ +/* + * Copyright 2015-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** * Base package for spring cloud task. */ 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 97a35de1..69e1f129 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ import org.springframework.util.Assert; public class TaskExecution { /** - * The unique id associated with the task execution. + * The unique id associated with the task execution. */ private long executionId; @@ -75,7 +75,7 @@ public class TaskExecution { private String externalExecutionId; /** - * Error information available upon the failure of a task + * Error information available upon the failure of a task. * * @since 1.1.0 */ @@ -87,14 +87,12 @@ public class TaskExecution { private List arguments; public TaskExecution() { - arguments = new ArrayList<>(); + 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) { + 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; @@ -102,24 +100,23 @@ public class TaskExecution { this.taskName = taskName; this.exitMessage = exitMessage; this.arguments = new ArrayList<>(arguments); - this.startTime = (startTime != null) ? (Date)startTime.clone() : null; - this.endTime = (endTime != null) ? (Date)endTime.clone() : null; + this.startTime = (startTime != null) ? (Date) startTime.clone() : null; + this.endTime = (endTime != null) ? (Date) endTime.clone() : null; this.errorMessage = errorMessage; this.externalExecutionId = externalExecutionId; this.parentExecutionId = parentExecutionId; } public TaskExecution(long executionId, Integer exitCode, String taskName, - Date startTime, Date endTime, - String exitMessage, List arguments, + 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() { - return executionId; + return this.executionId; } public Integer getExitCode() { @@ -131,7 +128,7 @@ public class TaskExecution { } public String getTaskName() { - return taskName; + return this.taskName; } public void setTaskName(String taskName) { @@ -139,23 +136,23 @@ public class TaskExecution { } public Date getStartTime() { - return (startTime != null) ? (Date)startTime.clone() : null; + return (this.startTime != null) ? (Date) this.startTime.clone() : null; } public void setStartTime(Date startTime) { - this.startTime = (startTime != null) ? (Date)startTime.clone() : null; + this.startTime = (startTime != null) ? (Date) startTime.clone() : null; } public Date getEndTime() { - return (endTime != null) ? (Date)endTime.clone() : null; + return (this.endTime != null) ? (Date) this.endTime.clone() : null; } public void setEndTime(Date endTime) { - this.endTime = (endTime != null) ? (Date)endTime.clone() : null; + this.endTime = (endTime != null) ? (Date) endTime.clone() : null; } public String getExitMessage() { - return exitMessage; + return this.exitMessage; } public void setExitMessage(String exitMessage) { @@ -163,15 +160,15 @@ public class TaskExecution { } public List getArguments() { - return arguments; + return this.arguments; } public void setArguments(List arguments) { - this.arguments = new ArrayList<> (arguments); + this.arguments = new ArrayList<>(arguments); } public String getErrorMessage() { - return errorMessage; + return this.errorMessage; } public void setErrorMessage(String errorMessage) { @@ -179,7 +176,7 @@ public class TaskExecution { } public String getExternalExecutionId() { - return externalExecutionId; + return this.externalExecutionId; } public void setExternalExecutionId(String externalExecutionId) { @@ -187,7 +184,7 @@ public class TaskExecution { } public Long getParentExecutionId() { - return parentExecutionId; + return this.parentExecutionId; } public void setParentExecutionId(Long parentExecutionId) { @@ -196,17 +193,13 @@ public class TaskExecution { @Override public String toString() { - return "TaskExecution{" + - "executionId=" + executionId + - ", parentExecutionId=" + parentExecutionId + - ", exitCode=" + exitCode + - ", taskName='" + taskName + '\'' + - ", startTime=" + startTime + - ", endTime=" + endTime + - ", exitMessage='" + exitMessage + '\'' + - ", externalExecutionId='" + externalExecutionId + '\'' + - ", errorMessage='" + errorMessage + '\'' + - ", arguments=" + arguments + - '}'; + 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/TaskExplorer.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskExplorer.java index 3fa4ef82..8f0d3319 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskExplorer.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskExplorer.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,16 +33,13 @@ public interface TaskExplorer { /** * Retrieve a {@link TaskExecution} by its id. - * * @param executionId the task execution id * @return the {@link TaskExecution} with this id, or null if not found */ TaskExecution getTaskExecution(long executionId); - /** * Retrieve a collection of taskExecutions that have the task name provided. - * * @param taskName the name of the task * @param pageable the constraints for the search * @return the set of running executions for tasks with the specified name @@ -51,14 +48,12 @@ public interface TaskExplorer { /** * Retrieve a list of available task names. - * * @return the set of task names that have been executed */ List getTaskNames(); /** * Get number of executions for a taskName. - * * @param taskName the name of the task to be searched * @return the number of running tasks that have the taskname specified */ @@ -66,21 +61,18 @@ public interface TaskExplorer { /** * Retrieves current number of task executions. - * * @return current number of task executions. */ long getTaskExecutionCount(); /** * Retrieves current number of running task executions. - * * @return current number of running task executions. */ long getRunningTaskExecutionCount(); /** - * Get a collection/page of executions - * + * Get a collection/page of executions. * @param taskName the name of the task to be searched * @param pageable the constraints for the search * @return list of task executions @@ -88,9 +80,8 @@ public interface TaskExplorer { Page findTaskExecutionsByName(String taskName, Pageable pageable); /** - * Retrieves all the task executions within the pageable constraints sorted by - * start date descending, taskExecution id descending. - * + * Retrieves all the task executions within the pageable constraints sorted by start + * date descending, taskExecution id descending. * @param pageable the constraints for the search * @return page containing the results from the search */ @@ -98,8 +89,7 @@ public interface TaskExplorer { /** * Returns the id of the TaskExecution that the requested Spring Batch job execution - * was executed within the context of. Returns null if none were found. - * + * was executed within the context of. Returns null if none were found. * @param jobExecutionId the id of the JobExecution * @return the id of the {@link TaskExecution} */ @@ -108,39 +98,39 @@ public interface TaskExplorer { /** * Returns a Set of JobExecution ids for the jobs that were executed within the scope * of the requested task. - * * @param taskExecutionId id of the {@link TaskExecution} - * @return a Set of the ids of the job executions executed within the task. + * @return a Set of the ids of the job executions executed within the + * task. */ Set getJobExecutionIdsByTaskExecutionId(long taskExecutionId); /** - * Returns a {@link List} of the latest {@link TaskExecution} for 1 or more task names. + * Returns a {@link List} of the latest {@link TaskExecution} for 1 or more task + * names. * - * Latest is defined by the most recent start time. A {@link TaskExecution} does not have to be finished - * (The results may including pending {@link TaskExecution}s). + * Latest is defined by the most recent start time. A {@link TaskExecution} does not + * have to be finished (The results may including pending {@link TaskExecution}s). * - * It is theoretically possible that a {@link TaskExecution} with the same name to have more than 1 - * {@link TaskExecution} for the exact same start time. In that case the {@link TaskExecution} with the - * highest Task Execution ID is returned. - * - * This method will not consider end times in its calculations. Thus, when a task execution {@code A} starts - * after task execution {@code B} but finishes BEFORE task execution {@code A}, then task execution {@code B} - * is being returned. + * It is theoretically possible that a {@link TaskExecution} with the same name to + * have more than 1 {@link TaskExecution} for the exact same start time. In that case + * the {@link TaskExecution} with the highest Task Execution ID is returned. * + * This method will not consider end times in its calculations. Thus, when a task + * execution {@code A} starts after task execution {@code B} but finishes BEFORE task + * execution {@code A}, then task execution {@code B} is being returned. * @param taskNames At least 1 task name must be provided * @return List of TaskExecutions. May be empty but never null. */ List getLatestTaskExecutionsByTaskNames(String... taskNames); - /** - * Returns the latest task execution for a given task name. Will ultimately apply the same algorithm underneath - * as {@link #getLatestTaskExecutionsByTaskNames(String...)} but will only return a single result. - * + * Returns the latest task execution for a given task name. Will ultimately apply the + * same algorithm underneath as {@link #getLatestTaskExecutionsByTaskNames(String...)} + * but will only return a single result. * @param taskName Must not be null or empty * @return The latest Task Execution or null * @see #getLatestTaskExecutionsByTaskNames(String...) */ TaskExecution getLatestTaskExecutionForTaskName(String taskName); + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskNameResolver.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskNameResolver.java index 5f92d0e7..752216fa 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskNameResolver.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/TaskNameResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.repository; /** @@ -26,4 +27,5 @@ public interface TaskNameResolver { * @return the name of the task being executed within this context. */ String getTaskName(); + } 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 de47572b..721c797b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,6 @@ public interface TaskRepository { /** * Notifies the repository that a taskExecution has completed. - * * @param executionId to the task execution to be updated. * @param exitCode to be stored for this task. * @param endTime designated when the task completed. @@ -40,11 +39,10 @@ public interface TaskRepository { */ @Transactional TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, - String exitMessage); + String exitMessage); /** * Notifies the repository that a taskExecution has completed. - * * @param executionId to the task execution to be updated. * @param exitCode to be stored for this task execution. * @param endTime designated when the task completed. @@ -55,30 +53,26 @@ public interface TaskRepository { */ @Transactional TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, - String exitMessage, String errorMessage); + String exitMessage, String errorMessage); /** * Notifies the repository that a taskExecution needs to be created. - * - * @param taskExecution a TaskExecution instance containing the startTime, - * arguments and externalExecutionId that will be stored in the repository. - * Only the values enumerated above will be stored for this + * @param taskExecution a TaskExecution instance containing the startTime, arguments + * and externalExecutionId that will be stored in the repository. Only the values + * enumerated above will be stored for this TaskExecution. + * @return the {@link TaskExecution} that was stored in the repository. The + * TaskExecution's taskExecutionId will also contain the id that was used to store the * TaskExecution. - * @return the {@link TaskExecution} that was stored in the repository. The - * TaskExecution's taskExecutionId will also contain the id that was used - * to store the TaskExecution. */ @Transactional TaskExecution createTaskExecution(TaskExecution taskExecution); /** - * Creates an empty TaskExecution with just an id and name provided. This is intended to be - * utilized in systems where the request of launching a task is separate from the - * actual start of a task (the underlying system may need to deploy the task prior to - * launching, etc). - * + * Creates an empty TaskExecution with just an id and name provided. This is intended + * to be utilized in systems where the request of launching a task is separate from + * the actual start of a task (the underlying system may need to deploy the task prior + * to launching, etc). * @param name task name to be associated with the task execution. - * * @return the initial {@link TaskExecution} */ @Transactional @@ -89,7 +83,6 @@ public interface TaskRepository { * utilized in systems where the request of launching a task is separate from the * actual start of a task (the underlying system may need to deploy the task prior to * launching, etc). - * * @return the initial {@link TaskExecution} */ @Transactional @@ -97,43 +90,38 @@ public interface TaskRepository { /** * Notifies the repository that a taskExecution has has started. - * - * @param executionid to the task execution to be updated. - * @param taskName the name that associated with the task execution. - * @param startTime the time task began. - * @param arguments list of key/value pairs that configure the task. + * @param executionid to the task execution to be updated. + * @param taskName the name that associated with the task execution. + * @param startTime the time task began. + * @param arguments list of key/value pairs that configure the task. * @param externalExecutionId id assigned to the task by the platform. * @return TaskExecution created based on the parameters. */ @Transactional - 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. - * - * @param executionid to the task execution to be updated. + * @param executionid to the task execution to be updated. * @param externalExecutionId id assigned to the task by the platform. */ @Transactional - void updateExternalExecutionId(long executionid, - String externalExecutionId); + void updateExternalExecutionId(long executionid, String externalExecutionId); /** * Notifies the repository that a taskExecution has has started. - * @param executionid to the task execution to be updated. + * @param executionid to the task execution to be updated. * @param taskName the name that associated with the task execution. * @param startTime the time task began. * @param arguments list of key/value pairs that configure the task. * @param externalExecutionId id assigned to the task by the platform. * @param parentExecutionId the parent task execution id. - - * @return A TaskExecution that contains the information available at the - * beginning of a TaskExecution. + * @return A TaskExecution that contains the information available at the beginning of + * a TaskExecution. */ @Transactional - 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 672aef21..f099c43f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,22 +61,33 @@ import org.springframework.util.StringUtils; */ 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 "; + /** + * FROM clause for task execution. + */ public static final String FROM_CLAUSE = "%PREFIX%EXECUTION"; - public static final String RUNNING_TASK_WHERE_CLAUSE = - "where TASK_NAME = :taskName AND END_TIME IS NULL "; + /** + * WHERE clause for running task. + */ + public static final String RUNNING_TASK_WHERE_CLAUSE = "where TASK_NAME = :taskName AND END_TIME IS NULL "; + /** + * WHERE clause for task name. + */ public static final String TASK_NAME_WHERE_CLAUSE = "where TASK_NAME = :taskName "; private static final String SAVE_TASK_EXECUTION = "INSERT into %PREFIX%EXECUTION" + "(TASK_EXECUTION_ID, EXIT_CODE, START_TIME, TASK_NAME, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID)" - + "values (:taskExecutionId, :exitCode, :startTime, :taskName, :lastUpdated, :externalExecutionId, :parentExecutionId)"; + + "values (:taskExecutionId, :exitCode, :startTime, " + + ":taskName, :lastUpdated, :externalExecutionId, :parentExecutionId)"; private static final String CREATE_TASK_ARGUMENT = "INSERT into " + "%PREFIX%EXECUTION_PARAMS(TASK_EXECUTION_ID, TASK_PARAM ) values (:taskExecutionId, :taskParam)"; @@ -85,9 +96,11 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { + "START_TIME = :startTime, TASK_NAME = :taskName, LAST_UPDATED = :lastUpdated"; private static final String START_TASK_EXECUTION_EXTERNAL_ID_SUFFIX = ", " - + "EXTERNAL_EXECUTION_ID = :externalExecutionId, PARENT_EXECUTION_ID = :parentExecutionId where TASK_EXECUTION_ID = :taskExecutionId"; + + "EXTERNAL_EXECUTION_ID = :externalExecutionId, PARENT_EXECUTION_ID = :parentExecutionId " + + "where TASK_EXECUTION_ID = :taskExecutionId"; - private static final String START_TASK_EXECUTION_SUFFIX = ", PARENT_EXECUTION_ID = :parentExecutionId where TASK_EXECUTION_ID = :taskExecutionId"; + private static final String START_TASK_EXECUTION_SUFFIX = ", PARENT_EXECUTION_ID = :parentExecutionId " + + "where TASK_EXECUTION_ID = :taskExecutionId"; private static final String CHECK_TASK_EXECUTION_EXISTS = "SELECT COUNT(*) FROM " + "%PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = :taskExecutionId"; @@ -99,8 +112,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { private static final String UPDATE_TASK_EXECUTION_EXTERNAL_EXECUTION_ID = "UPDATE %PREFIX%EXECUTION set " + "EXTERNAL_EXECUTION_ID = :externalExecutionId where TASK_EXECUTION_ID = :taskExecutionId"; - private static final String GET_EXECUTION_BY_ID = "SELECT TASK_EXECUTION_ID, " + - "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, " + 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 " + "from %PREFIX%EXECUTION where TASK_EXECUTION_ID = :taskExecutionId"; @@ -108,41 +121,40 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { 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"; + private static final String TASK_EXECUTION_COUNT_BY_NAME = "SELECT COUNT(*) FROM " + + "%PREFIX%EXECUTION where TASK_NAME = :taskName"; - private static final String RUNNING_TASK_EXECUTION_COUNT_BY_NAME = "SELECT COUNT(*) FROM " + - "%PREFIX%EXECUTION where TASK_NAME = :taskName AND END_TIME IS NULL "; + private static final String RUNNING_TASK_EXECUTION_COUNT_BY_NAME = "SELECT COUNT(*) FROM " + + "%PREFIX%EXECUTION where TASK_NAME = :taskName AND END_TIME IS NULL "; - private static final String RUNNING_TASK_EXECUTION_COUNT = "SELECT COUNT(*) FROM " + - "%PREFIX%EXECUTION where END_TIME IS NULL "; + private static final String RUNNING_TASK_EXECUTION_COUNT = "SELECT COUNT(*) FROM " + + "%PREFIX%EXECUTION where END_TIME IS NULL "; - 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 " + - "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 " + - "order by TE2.START_TIME DESC, TE2.TASK_EXECUTION_ID DESC"; + 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 " + + "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 " + + "order by TE2.START_TIME DESC, TE2.TASK_EXECUTION_ID DESC"; private static final String FIND_TASK_NAMES = "SELECT distinct TASK_NAME from %PREFIX%EXECUTION order by TASK_NAME"; - private static final String FIND_TASK_EXECUTION_BY_JOB_EXECUTION_ID = "SELECT TASK_EXECUTION_ID FROM %PREFIX%TASK_BATCH WHERE JOB_EXECUTION_ID = :jobExecutionId"; + private static final String FIND_TASK_EXECUTION_BY_JOB_EXECUTION_ID = "SELECT TASK_EXECUTION_ID FROM " + + "%PREFIX%TASK_BATCH WHERE JOB_EXECUTION_ID = :jobExecutionId"; - 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 String tablePrefix = TaskProperties.DEFAULT_TABLE_PREFIX; + 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 final NamedParameterJdbcTemplate jdbcTemplate; + private String tablePrefix = TaskProperties.DEFAULT_TABLE_PREFIX; + private DataSource dataSource; private LinkedHashMap orderMap; @@ -169,120 +181,119 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { Assert.notNull(dataSource, "The dataSource must not be null."); this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource); this.dataSource = dataSource; - orderMap = new LinkedHashMap<>(); - orderMap.put("START_TIME", Order.DESCENDING); - orderMap.put("TASK_EXECUTION_ID", Order.DESCENDING); - } - - @Override - public TaskExecution createTaskExecution(String taskName, - Date startTime, List arguments, String externalExecutionId) { - return createTaskExecution(taskName, startTime, arguments, - externalExecutionId, null); + this.orderMap = new LinkedHashMap<>(); + this.orderMap.put("START_TIME", Order.DESCENDING); + this.orderMap.put("TASK_EXECUTION_ID", Order.DESCENDING); } @Override public TaskExecution createTaskExecution(String taskName, Date startTime, - List arguments, String externalExecutionId, - Long parentExecutionId) { + 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) { long nextExecutionId = getNextExecutionId(); 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("lastUpdated", new Date(), Types.TIMESTAMP) - .addValue("externalExecutionId", externalExecutionId, Types.VARCHAR) - .addValue("parentExecutionId", parentExecutionId, Types.BIGINT); + .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); - jdbcTemplate.update( - getQuery(SAVE_TASK_EXECUTION), - queryParameters); + this.jdbcTemplate.update(getQuery(SAVE_TASK_EXECUTION), queryParameters); insertTaskArguments(nextExecutionId, arguments); return taskExecution; } @Override public TaskExecution startTaskExecution(long executionId, String taskName, - Date startTime, List arguments, - String externalExecutionId) { + 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) { + Date startTime, List arguments, String externalExecutionId, + Long parentExecutionId) { TaskExecution taskExecution = new TaskExecution(executionId, null, taskName, - startTime, null, null, arguments,null, externalExecutionId, parentExecutionId); + 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("parentExecutionId", parentExecutionId, Types.BIGINT) - .addValue("taskExecutionId", executionId, Types.BIGINT); + .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); String updateString = START_TASK_EXECUTION_PREFIX; - if(externalExecutionId == null) { + if (externalExecutionId == null) { updateString += START_TASK_EXECUTION_SUFFIX; } else { updateString += START_TASK_EXECUTION_EXTERNAL_ID_SUFFIX; - queryParameters.addValue("externalExecutionId", externalExecutionId, Types.VARCHAR); + queryParameters.addValue("externalExecutionId", externalExecutionId, + Types.VARCHAR); } - jdbcTemplate.update(getQuery(updateString), queryParameters); + this.jdbcTemplate.update(getQuery(updateString), queryParameters); insertTaskArguments(executionId, arguments); return taskExecution; } @Override - public void completeTaskExecution(long taskExecutionId, Integer exitCode, Date endTime, - String exitMessage, String errorMessage) { + public void completeTaskExecution(long taskExecutionId, Integer exitCode, + Date endTime, String exitMessage, String errorMessage) { final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("taskExecutionId", taskExecutionId, Types.BIGINT); + .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 (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("exitMessage", exitMessage, Types.VARCHAR) - .addValue("errorMessage", errorMessage, Types.VARCHAR) - .addValue("lastUpdated", new Date(), Types.TIMESTAMP) - .addValue("taskExecutionId", taskExecutionId, Types.BIGINT); + .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) + .addValue("taskExecutionId", taskExecutionId, Types.BIGINT); - jdbcTemplate.update( - getQuery(UPDATE_TASK_EXECUTION), - parameters); + this.jdbcTemplate.update(getQuery(UPDATE_TASK_EXECUTION), parameters); } @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); + .addValue("taskExecutionId", executionId, Types.BIGINT); try { - TaskExecution taskExecution = 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; } @@ -295,11 +306,11 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { public long getTaskExecutionCountByTaskName(String taskName) { final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("taskName", taskName, Types.VARCHAR); + .addValue("taskName", taskName, Types.VARCHAR); try { - return 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; @@ -309,11 +320,12 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { @Override public long getRunningTaskExecutionCountByTaskName(String taskName) { final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("taskName", taskName, Types.VARCHAR); + .addValue("taskName", taskName, Types.VARCHAR); try { - return jdbcTemplate.queryForObject( - getQuery(RUNNING_TASK_EXECUTION_COUNT_BY_NAME), queryParameters, Long.class); + return this.jdbcTemplate.queryForObject( + getQuery(RUNNING_TASK_EXECUTION_COUNT_BY_NAME), queryParameters, + Long.class); } catch (EmptyResultDataAccessException e) { return 0; @@ -325,8 +337,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { try { final MapSqlParameterSource queryParameters = new MapSqlParameterSource(); - return 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; @@ -345,14 +357,15 @@ 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(); @@ -362,7 +375,8 @@ 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; } @@ -370,7 +384,9 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { return taskExecutions.get(0); } else { - throw new IllegalStateException("Only expected a single TaskExecution but received " + taskExecutions.size()); + throw new IllegalStateException( + "Only expected a single TaskExecution but received " + + taskExecutions.size()); } } @@ -378,8 +394,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { public long getTaskExecutionCount() { try { - return 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; @@ -387,14 +403,17 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { } @Override - public Page findRunningTaskExecutions(String taskName, Pageable pageable) { + public Page findRunningTaskExecutions(String taskName, + Pageable pageable) { return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, - RUNNING_TASK_WHERE_CLAUSE, new MapSqlParameterSource("taskName", taskName), + RUNNING_TASK_WHERE_CLAUSE, + new MapSqlParameterSource("taskName", taskName), getRunningTaskExecutionCountByTaskName(taskName)); } @Override - public Page findTaskExecutionsByName(String taskName, Pageable pageable) { + public Page findTaskExecutionsByName(String taskName, + Pageable pageable) { return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, TASK_NAME_WHERE_CLAUSE, new MapSqlParameterSource("taskName", taskName), getTaskExecutionCountByTaskName(taskName)); @@ -402,7 +421,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { @Override public List getTaskNames() { - return jdbcTemplate.queryForList(getQuery(FIND_TASK_NAMES), new MapSqlParameterSource(), String.class); + return this.jdbcTemplate.queryForList(getQuery(FIND_TASK_NAMES), + new MapSqlParameterSource(), String.class); } @Override @@ -415,19 +435,18 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { this.taskIncrementer = taskIncrementer; } - public long getNextExecutionId(){ - return taskIncrementer.nextLongValue(); + public long getNextExecutionId() { + return this.taskIncrementer.nextLongValue(); } @Override public Long getTaskExecutionIdByJobExecutionId(long jobExecutionId) { final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("jobExecutionId", jobExecutionId, Types.BIGINT); + .addValue("jobExecutionId", jobExecutionId, Types.BIGINT); try { - return 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) { @@ -438,19 +457,20 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { @Override public Set getJobExecutionIdsByTaskExecutionId(long taskExecutionId) { final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("taskExecutionId", taskExecutionId, Types.BIGINT); + .addValue("taskExecutionId", taskExecutionId, Types.BIGINT); try { - return 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")); + while (resultSet.next()) { + jobExecutionIds + .add(resultSet.getLong("JOB_EXECUTION_ID")); } return jobExecutionIds; @@ -463,29 +483,27 @@ 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); + .addValue("externalExecutionId", externalExecutionId, Types.VARCHAR) + .addValue("taskExecutionId", taskExecutionId, Types.BIGINT); - if (jdbcTemplate.update( + if (this.jdbcTemplate.update( getQuery(UPDATE_TASK_EXECUTION_EXTERNAL_EXECUTION_ID), queryParameters) != 1) { - throw new IllegalStateException("Invalid TaskExecution, ID " - + taskExecutionId + " not found."); + throw new IllegalStateException( + "Invalid TaskExecution, ID " + taskExecutionId + " not found."); } } private Page queryForPageableResults(Pageable pageable, - String selectClause, - String fromClause, - String whereClause, - MapSqlParameterSource queryParameters, - long totalCount){ + String selectClause, String fromClause, String whereClause, + MapSqlParameterSource queryParameters, long totalCount) { SqlPagingQueryProviderFactoryBean factoryBean = new SqlPagingQueryProviderFactoryBean(); factoryBean.setSelectClause(selectClause); factoryBean.setFromClause(fromClause); - if(StringUtils.hasText(whereClause)){ + if (StringUtils.hasText(whereClause)) { factoryBean.setWhereClause(whereClause); } final Sort sort = pageable.getSort(); @@ -493,7 +511,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { if (sort != null) { for (Sort.Order sortOrder : sort) { - sortOrderMap.put(sortOrder.getProperty(), sortOrder.isAscending() ? Order.ASCENDING : Order.DESCENDING); + sortOrderMap.put(sortOrder.getProperty(), + sortOrder.isAscending() ? Order.ASCENDING : Order.DESCENDING); } } @@ -508,29 +527,25 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { PagingQueryProvider pagingQueryProvider; try { pagingQueryProvider = factoryBean.getObject(); - pagingQueryProvider.init(dataSource); + pagingQueryProvider.init(this.dataSource); } catch (Exception e) { throw new IllegalStateException(e); } String query = pagingQueryProvider.getPageQuery(pageable); - List resultList = jdbcTemplate.query( - getQuery(query), - queryParameters, - new TaskExecutionRowMapper()); + List resultList = this.jdbcTemplate.query(getQuery(query), + queryParameters, new TaskExecutionRowMapper()); return new PageImpl<>(resultList, pageable, totalCount); } private String getQuery(String base) { - return StringUtils.replace(base, "%PREFIX%", tablePrefix); + return StringUtils.replace(base, "%PREFIX%", this.tablePrefix); } /** - * Convenience method that inserts all arguments from the provided - * task arguments. - * - * @param executionId The executionId to which the arguments are associated. - * @param taskArguments The arguments to be stored. + * Convenience method that inserts all arguments from the provided task arguments. + * @param executionId The executionId to which the arguments are associated. + * @param taskArguments The arguments to be stored. */ private void insertTaskArguments(long executionId, List taskArguments) { for (String args : taskArguments) { @@ -541,26 +556,29 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { /** * Convenience method that inserts an individual records into the * TASK_EXECUTION_PARAMS table. + * @param taskExecutionId id of a task execution + * @param taskParam task parameters */ private void insertArgument(long taskExecutionId, String taskParam) { final MapSqlParameterSource queryParameters = new MapSqlParameterSource() - .addValue("taskExecutionId", taskExecutionId, Types.BIGINT) - .addValue("taskParam", taskParam, Types.VARCHAR); - jdbcTemplate.update(getQuery(CREATE_TASK_ARGUMENT), queryParameters); + .addValue("taskExecutionId", taskExecutionId, Types.BIGINT) + .addValue("taskParam", taskParam, Types.VARCHAR); + this.jdbcTemplate.update(getQuery(CREATE_TASK_ARGUMENT), queryParameters); } - private List getTaskArguments(long taskExecutionId){ - final List params= new ArrayList<>(); + private List getTaskArguments(long taskExecutionId) { + final List params = new ArrayList<>(); RowCallbackHandler handler = new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { params.add(rs.getString(2)); } }; - jdbcTemplate.query(getQuery(FIND_ARGUMENT_FROM_ID), new MapSqlParameterSource("taskExecutionId", taskExecutionId), - handler); + this.jdbcTemplate.query(getQuery(FIND_ARGUMENT_FROM_ID), + new MapSqlParameterSource("taskExecutionId", taskExecutionId), handler); return params; } + /** * Re-usable mapper for {@link TaskExecution} instances. * @@ -572,26 +590,23 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao { @Override public TaskExecution mapRow(ResultSet rs, int rowNum) throws SQLException { - long id = rs.getLong("TASK_EXECUTION_ID"); + long id = rs.getLong("TASK_EXECUTION_ID"); Long parentExecutionId = rs.getLong("PARENT_EXECUTION_ID"); - if(rs.wasNull()) { + 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 { int exitCode = rs.getInt("EXIT_CODE"); return !rs.wasNull() ? exitCode : null; } + } + } 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 e4f28b8d..3cd7b0bb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,36 +46,38 @@ import org.springframework.util.StringUtils; */ public class MapTaskExecutionDao implements TaskExecutionDao { + private final AtomicLong currentId = new AtomicLong(0L); + private ConcurrentMap taskExecutions; private ConcurrentMap> batchJobAssociations; - private final AtomicLong currentId = new AtomicLong(0L); - public MapTaskExecutionDao() { - taskExecutions = new ConcurrentHashMap<>(); - batchJobAssociations = new ConcurrentHashMap<>(); + this.taskExecutions = new ConcurrentHashMap<>(); + this.batchJobAssociations = new ConcurrentHashMap<>(); } @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); - taskExecutions.put(taskExecutionId, taskExecution); + 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) { + public TaskExecution startTaskExecution(long executionId, String taskName, + Date startTime, List arguments, String externalExecutionid) { return startTaskExecution(executionId, taskName, startTime, arguments, externalExecutionid, null); } @@ -84,24 +86,26 @@ public class MapTaskExecutionDao implements TaskExecutionDao { public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List arguments, String externalExecutionid, Long parentExecutionId) { - TaskExecution taskExecution= taskExecutions.get(executionId); + TaskExecution taskExecution = this.taskExecutions.get(executionId); taskExecution.setTaskName(taskName); taskExecution.setStartTime(startTime); taskExecution.setArguments(arguments); taskExecution.setParentExecutionId(parentExecutionId); - if(externalExecutionid != null) { + if (externalExecutionid != null) { taskExecution.setExternalExecutionId(externalExecutionid); } return taskExecution; } @Override - 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."); + 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."); } - TaskExecution taskExecution= taskExecutions.get(executionId); + TaskExecution taskExecution = this.taskExecutions.get(executionId); taskExecution.setEndTime(endTime); taskExecution.setExitCode(exitCode); taskExecution.setExitMessage(exitMessage); @@ -109,19 +113,20 @@ 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); } @Override public TaskExecution getTaskExecution(long executionId) { - return taskExecutions.get(executionId); + return this.taskExecutions.get(executionId); } @Override public long getTaskExecutionCountByTaskName(String taskName) { int count = 0; - for (Map.Entry entry : taskExecutions.entrySet()) { + for (Map.Entry entry : this.taskExecutions.entrySet()) { if (entry.getValue().getTaskName().equals(taskName)) { count++; } @@ -132,9 +137,9 @@ public class MapTaskExecutionDao implements TaskExecutionDao { @Override public long getRunningTaskExecutionCountByTaskName(String taskName) { int count = 0; - for (Map.Entry entry : taskExecutions.entrySet()) { - if (entry.getValue().getTaskName().equals(taskName) && - entry.getValue().getEndTime() == null) { + for (Map.Entry entry : this.taskExecutions.entrySet()) { + if (entry.getValue().getTaskName().equals(taskName) + && entry.getValue().getEndTime() == null) { count++; } } @@ -144,8 +149,8 @@ public class MapTaskExecutionDao implements TaskExecutionDao { @Override public long getRunningTaskExecutionCount() { long count = 0; - for (Map.Entry entry : taskExecutions.entrySet()) { - if ( entry.getValue().getEndTime() == null) { + for (Map.Entry entry : this.taskExecutions.entrySet()) { + if (entry.getValue().getEndTime() == null) { count++; } } @@ -154,15 +159,16 @@ public class MapTaskExecutionDao implements TaskExecutionDao { @Override public long getTaskExecutionCount() { - return taskExecutions.size(); + return this.taskExecutions.size(); } @Override - public Page findRunningTaskExecutions(String taskName, Pageable pageable) { + public Page findRunningTaskExecutions(String taskName, + Pageable pageable) { Set result = getTaskExecutionTreeSet(); - for (Map.Entry entry : taskExecutions.entrySet()) { - if (entry.getValue().getTaskName().equals(taskName) && - entry.getValue().getEndTime() == null) { + for (Map.Entry entry : this.taskExecutions.entrySet()) { + if (entry.getValue().getTaskName().equals(taskName) + && entry.getValue().getEndTime() == null) { result.add(entry.getValue()); } } @@ -171,9 +177,10 @@ public class MapTaskExecutionDao implements TaskExecutionDao { } @Override - public Page findTaskExecutionsByName(String taskName, Pageable pageable) { + public Page findTaskExecutionsByName(String taskName, + Pageable pageable) { Set filteredSet = getTaskExecutionTreeSet(); - for (Map.Entry entry : taskExecutions.entrySet()) { + for (Map.Entry entry : this.taskExecutions.entrySet()) { if (entry.getValue().getTaskName().equals(taskName)) { filteredSet.add(entry.getValue()); } @@ -185,7 +192,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao { @Override public List getTaskNames() { Set result = new TreeSet<>(); - for (Map.Entry entry : taskExecutions.entrySet()) { + for (Map.Entry entry : this.taskExecutions.entrySet()) { result.add(entry.getValue().getTaskName()); } return new ArrayList<>(result); @@ -194,17 +201,17 @@ public class MapTaskExecutionDao implements TaskExecutionDao { @Override public Page findAll(Pageable pageable) { TreeSet sortedSet = getTaskExecutionTreeSet(); - sortedSet.addAll(taskExecutions.values()); + sortedSet.addAll(this.taskExecutions.values()); List result = new ArrayList<>(sortedSet.descendingSet()); return getPageFromList(result, pageable, getTaskExecutionCount()); } public Map getTaskExecutions() { - return Collections.unmodifiableMap(taskExecutions); + return Collections.unmodifiableMap(this.taskExecutions); } - public long getNextExecutionId(){ - return currentId.getAndIncrement(); + public long getNextExecutionId() { + return this.currentId.getAndIncrement(); } @Override @@ -213,9 +220,10 @@ public class MapTaskExecutionDao implements TaskExecutionDao { found: - for (Map.Entry> association : batchJobAssociations.entrySet()) { + for (Map.Entry> association : this.batchJobAssociations + .entrySet()) { for (Long curJobExecutionId : association.getValue()) { - if(curJobExecutionId.equals(jobExecutionId)) { + if (curJobExecutionId.equals(jobExecutionId)) { taskId = association.getKey(); break found; } @@ -227,8 +235,9 @@ public class MapTaskExecutionDao implements TaskExecutionDao { @Override public Set getJobExecutionIdsByTaskExecutionId(long taskExecutionId) { - if(batchJobAssociations.containsKey(taskExecutionId)) { - return Collections.unmodifiableSet(batchJobAssociations.get(taskExecutionId)); + if (this.batchJobAssociations.containsKey(taskExecutionId)) { + return Collections + .unmodifiableSet(this.batchJobAssociations.get(taskExecutionId)); } else { return new TreeSet<>(); @@ -236,15 +245,16 @@ public class MapTaskExecutionDao implements TaskExecutionDao { } @Override - public void updateExternalExecutionId(long taskExecutionId, String externalExecutionId) { - TaskExecution taskExecution = taskExecutions.get(taskExecutionId); - Assert.notNull(taskExecution, "Invalid TaskExecution, ID " - + taskExecutionId + " not found."); + public void updateExternalExecutionId(long taskExecutionId, + String externalExecutionId) { + TaskExecution taskExecution = this.taskExecutions.get(taskExecutionId); + Assert.notNull(taskExecution, + "Invalid TaskExecution, ID " + taskExecutionId + " not found."); taskExecution.setExternalExecutionId(externalExecutionId); } public ConcurrentMap> getBatchJobAssociations() { - return batchJobAssociations; + return this.batchJobAssociations; } private TreeSet getTaskExecutionTreeSet() { @@ -252,19 +262,22 @@ public class MapTaskExecutionDao implements TaskExecutionDao { @Override 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()); + if (result == 0) { + 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(); + 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), + executionList.subList((int) pageable.getOffset(), (int) toIndex), pageable, maxSize); } @@ -281,29 +294,34 @@ 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()); + 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() - ) - ) { - tempTaskExecutions.put(taskExecutionMapEntry.getValue().getTaskName(), taskExecutionMapEntry.getValue()); + || 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; } @@ -311,7 +329,8 @@ 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; } @@ -319,20 +338,29 @@ public class MapTaskExecutionDao implements TaskExecutionDao { return taskExecutions.get(0); } else { - throw new IllegalStateException("Only expected a single TaskExecution but received " + taskExecutions.size()); + throw new IllegalStateException( + "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 a90bff95..a1838e7f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,19 +36,17 @@ public interface TaskExecutionDao { /** * Save a new {@link TaskExecution}. - * * @param taskName the name that associated with the task execution. * @param startTime the time task began. * @param arguments list of key/value pairs that configure the task. * @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}. - * * @param taskName the name that associated with the task execution. * @param startTime the time task began. * @param arguments list of key/value pairs that configure the task. @@ -57,65 +55,62 @@ 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. - * - * @param executionId the id of the taskExecution to be updated. + * @param executionId the id of the taskExecution to be updated. * @param taskName the name that associated with the task execution. * @param startTime the time task began. * @param arguments list of key/value pairs that configure the task. * @param externalExecutionId id assigned to the task by the platform - * @return A TaskExecution containing the information available at task execution start. + * @return A TaskExecution containing the information available at task execution + * 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. - * - * @param executionId the id of the taskExecution to be updated. + * @param executionId the id of the taskExecution to be updated. * @param taskName the name that associated with the task execution. * @param startTime the time task began. * @param arguments list of key/value pairs that configure the task. * @param externalExecutionId id assigned to the task by the platform * @param parentExecutionId the parent task execution id. - * @return A TaskExecution containing the information available at task execution start. + * @return A TaskExecution containing the information available at task execution + * 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. - * - * @param executionId the id of the taskExecution to be updated. + * @param executionId the id of the taskExecution to be updated. * @param exitCode the status of the task upon completion. * @param endTime the time the task completed. * @param exitMessage the message assigned to the task upon completion. * @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}. - * - * @param executionId the id of the taskExecution to be updated. + * @param executionId the id of the taskExecution to be updated. * @param exitCode the status of the task upon completion. * @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. - * * @param executionId the id associated with the task execution. * @return a fully qualified TaskExecution instance. */ @@ -123,16 +118,14 @@ public interface TaskExecutionDao { /** * Retrieves current number of task executions for a taskName. - * * @param taskName the name of the task to search for in the repository. * @return current number of task executions for the taskName. */ long getTaskExecutionCountByTaskName(String taskName); - /** - * Retrieves current number of task executions for a taskName and with an endTime of null. - * + * Retrieves current number of task executions for a taskName and with an endTime of + * null. * @param taskName the name of the task to search for in the repository. * @return current number of task executions for the taskName. */ @@ -140,15 +133,12 @@ public interface TaskExecutionDao { /** * Retrieves current number of task executions with an endTime of null. - * * @return current number of task executions. */ long getRunningTaskExecutionCount(); - /** * Retrieves current number of task executions. - * * @return current number of task executions. */ long getTaskExecutionCount(); @@ -159,7 +149,7 @@ public interface TaskExecutionDao { * @param pageable the constraints for the search. * @return set of running task executions. */ - Page findRunningTaskExecutions(String taskName, Pageable pageable); + Page findRunningTaskExecutions(String taskName, Pageable pageable); /** * Retrieves a subset of task executions by task name, start location and size. @@ -172,7 +162,6 @@ public interface TaskExecutionDao { /** * Retrieves a sorted list of distinct task names for the task executions. - * * @return a list of distinct task names from the task repository.. */ List getTaskNames(); @@ -193,8 +182,7 @@ public interface TaskExecutionDao { /** * Returns the id of the TaskExecution that the requested Spring Batch job execution - * was executed within the context of. Returns null if non were found. - * + * was executed within the context of. Returns null if non were found. * @param jobExecutionId the id of the JobExecution * @return the id of the {@link TaskExecution} */ @@ -203,7 +191,8 @@ public interface TaskExecutionDao { /** * Returns the job execution ids associated with a task execution id. * @param taskExecutionId id of the {@link TaskExecution} - * @return a Set of the ids of the job executions executed within the task. + * @return a Set of the ids of the job executions executed within the + * task. */ Set getJobExecutionIdsByTaskExecutionId(long taskExecutionId); @@ -212,35 +201,35 @@ public interface TaskExecutionDao { * @param taskExecutionId the execution id for the task to be updated. * @param externalExecutionId the new externalExecutionId. */ - void updateExternalExecutionId(long taskExecutionId, - String externalExecutionId); + void updateExternalExecutionId(long taskExecutionId, String externalExecutionId); /** - * Returns a {@link List} of the latest {@link TaskExecution} for 1 or more task names. + * Returns a {@link List} of the latest {@link TaskExecution} for 1 or more task + * names. * - * Latest is defined by the most recent start time. A {@link TaskExecution} does not have to be finished - * (The results may including pending {@link TaskExecution}s). + * Latest is defined by the most recent start time. A {@link TaskExecution} does not + * have to be finished (The results may including pending {@link TaskExecution}s). * - * It is theoretically possible that a {@link TaskExecution} with the same name to have more than 1 - * {@link TaskExecution} for the exact same start time. In that case the {@link TaskExecution} with the - * highest Task Execution ID is returned. - * - * This method will not consider end times in its calculations. Thus, when a task execution {@code A} starts - * after task execution {@code B} but finishes BEFORE task execution {@code A}, then task execution {@code B} - * is being returned. + * It is theoretically possible that a {@link TaskExecution} with the same name to + * have more than 1 {@link TaskExecution} for the exact same start time. In that case + * the {@link TaskExecution} with the highest Task Execution ID is returned. * + * This method will not consider end times in its calculations. Thus, when a task + * execution {@code A} starts after task execution {@code B} but finishes BEFORE task + * execution {@code A}, then task execution {@code B} is being returned. * @param taskNames At least 1 task name must be provided * @return List of TaskExecutions. May be empty but never null. */ List getLatestTaskExecutionsByTaskNames(String... taskNames); /** - * Returns the latest task execution for a given task name. Will ultimately apply the same algorithm underneath - * as {@link #getLatestTaskExecutionsByTaskNames(String...)} but will only return a single result. - * + * Returns the latest task execution for a given task name. Will ultimately apply the + * same algorithm underneath as {@link #getLatestTaskExecutionsByTaskNames(String...)} + * but will only return a single result. * @param taskName Must not be null or empty * @return The latest Task Execution or null * @see #getLatestTaskExecutionsByTaskNames(String...) */ TaskExecution getLatestTaskExecutionForTaskName(String taskName); + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/package-info.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/package-info.java index e7bbc5ba..15a40d8b 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/package-info.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/package-info.java @@ -1,3 +1,19 @@ +/* + * Copyright 2015-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** * Interface DAO and default implementations for storing and retrieving data for tasks * from a repository. diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/PagingQueryProvider.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/PagingQueryProvider.java index f748feb4..a05b39dc 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/PagingQueryProvider.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/PagingQueryProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,35 +25,33 @@ import org.springframework.data.domain.Pageable; /** * Interface defining the functionality to be provided for generating paging queries. + * * @author Glenn Renfro */ public interface PagingQueryProvider { /** * Initialize the query provider using the provided {@link DataSource} if necessary. - * * @param dataSource DataSource to use for any initialization * @throws Exception throws {@link Exception} if query provider initialize fails. */ void init(DataSource dataSource) throws Exception; /** - * The number of parameters that are declared in the query + * The number of parameters that are declared in the query. * @return number of parameters */ int getParameterCount(); /** * Indicate whether the generated queries use named parameter syntax. - * * @return true if named parameter syntax is used */ boolean isUsingNamedParameters(); /** - * The sort keys. A Map of the columns that make up the key and a Boolean indicating ascending or descending - * (ascending = true). - * + * The sort keys. A Map of the columns that make up the key and a Boolean indicating + * ascending or descending (ascending = true). * @return the sort keys used to order the query */ Map getSortKeys(); @@ -61,9 +59,9 @@ public interface PagingQueryProvider { /** * * Generate the query that will provide the jump to item query. - * * @param pageable the coordinates to pull the next page from the datasource * @return the generated query */ String getPageQuery(Pageable pageable); + } 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 08928f34..9bf25902 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,15 +31,15 @@ import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** - * Abstract SQL Paging Query Provider to serve as a base class for all provided - * SQL paging query providers. + * Abstract SQL Paging Query Provider to serve as a base class for all provided SQL paging + * query providers. * - * Any implementation must provide a way to specify the select clause, from - * clause and optionally a where clause. It is recommended that there should be an index for - * the sort key to provide better performance. + * Any implementation must provide a way to specify the select clause, from clause and + * optionally a where clause. It is recommended that there should be an index for the sort + * key to provide better performance. * - * Provides properties and preparation for the mandatory "selectClause" and - * "fromClause" as well as for the optional "whereClause". + * Provides properties and preparation for the mandatory "selectClause" and "fromClause" + * as well as for the optional "whereClause". * * @author Glenn Renfro */ @@ -51,12 +51,19 @@ public abstract class AbstractSqlPagingQueryProvider implements PagingQueryProvi private String whereClause; - private Map sortKeys = new LinkedHashMap(); + private Map sortKeys = new LinkedHashMap<>(); private int parameterCount; private boolean usingNamedParameters; + /** + * @return SQL SELECT clause part of SQL query string + */ + protected String getSelectClause() { + return this.selectClause; + } + /** * @param selectClause SELECT clause part of SQL query string */ @@ -65,11 +72,10 @@ public abstract class AbstractSqlPagingQueryProvider implements PagingQueryProvi } /** - * - * @return SQL SELECT clause part of SQL query string + * @return SQL FROM clause part of SQL query string */ - protected String getSelectClause() { - return selectClause; + protected String getFromClause() { + return this.fromClause; } /** @@ -80,11 +86,10 @@ public abstract class AbstractSqlPagingQueryProvider implements PagingQueryProvi } /** - * - * @return SQL FROM clause part of SQL query string + * @return SQL WHERE clause part of SQL query string */ - protected String getFromClause() { - return fromClause; + protected String getWhereClause() { + return this.whereClause; } /** @@ -100,11 +105,13 @@ public abstract class AbstractSqlPagingQueryProvider implements PagingQueryProvi } /** - * - * @return SQL WHERE clause part of SQL query string + * A Map<String, Order> of sort columns as the key and {@link Order} for + * ascending/descending. + * @return sortKey key to use to sort and limit page content */ - protected String getWhereClause() { - return whereClause; + @Override + public Map getSortKeys() { + return this.sortKeys; } /** @@ -114,56 +121,51 @@ public abstract class AbstractSqlPagingQueryProvider implements PagingQueryProvi this.sortKeys = sortKeys; } - /** - * A Map<String, Order> of sort columns as the key and {@link Order} for ascending/descending. - * - * @return sortKey key to use to sort and limit page content - */ - @Override - public Map getSortKeys() { - return sortKeys; - } - @Override public int getParameterCount() { - return parameterCount; + return this.parameterCount; } @Override public boolean isUsingNamedParameters() { - return usingNamedParameters; + return this.usingNamedParameters; } @Override public void init(DataSource dataSource) throws Exception { Assert.notNull(dataSource, "DataSource must not be null"); - Assert.hasLength(selectClause, "selectClause must be specified"); - Assert.hasLength(fromClause, "fromClause must be specified"); - Assert.notEmpty(sortKeys, "sortKey must be specified"); + Assert.hasLength(this.selectClause, "selectClause must be specified"); + Assert.hasLength(this.fromClause, "fromClause must be specified"); + Assert.notEmpty(this.sortKeys, "sortKey must be specified"); StringBuilder sql = new StringBuilder(); - sql.append("SELECT ").append(selectClause); - sql.append(" FROM ").append(fromClause); - if (whereClause != null) { - sql.append(" WHERE ").append(whereClause); + sql.append("SELECT ").append(this.selectClause); + sql.append(" FROM ").append(this.fromClause); + if (this.whereClause != null) { + sql.append(" WHERE ").append(this.whereClause); } - List namedParameters = new ArrayList(); - parameterCount = JdbcParameterUtils.countParameterPlaceholders(sql.toString(), namedParameters); + List namedParameters = new ArrayList<>(); + this.parameterCount = JdbcParameterUtils + .countParameterPlaceholders(sql.toString(), namedParameters); if (namedParameters.size() > 0) { - if (parameterCount != namedParameters.size()) { + 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); } - usingNamedParameters = true; + this.usingNamedParameters = true; } } + 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 { return temp; } } + } 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 917f8d7f..125b3b99 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,10 @@ package org.springframework.cloud.task.repository.database.support; import org.springframework.data.domain.Pageable; /** - * IBM DB2 implementation of a {@link org.springframework.cloud.task.repository.database.PagingQueryProvider} using database - * specific features. - * + * IBM DB2 implementation of a + * {@link org.springframework.cloud.task.repository.database.PagingQueryProvider} using + * database specific features. + * * @author Thomas Schuettel */ public class Db2PagingQueryProvider extends AbstractSqlPagingQueryProvider { @@ -30,15 +31,18 @@ public class Db2PagingQueryProvider extends AbstractSqlPagingQueryProvider { public String getPageQuery(Pageable pageable) { long offset = pageable.getOffset() + 1; return generateRowNumSqlQueryWithNesting(getSelectClause(), false, - "TMP_ROW_NUM BETWEEN " + offset + " AND " + (offset + pageable.getPageSize())); + "TMP_ROW_NUM BETWEEN " + offset + " AND " + + (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 c6f2098e..67e48317 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ public class H2PagingQueryProvider extends AbstractSqlPagingQueryProvider { @Override public String getPageQuery(Pageable pageable) { String topClause = new StringBuilder().append("LIMIT ") - .append(pageable.getOffset()).append(" ") - .append(pageable.getPageSize()).toString(); + .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/HsqlPagingQueryProvider.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/database/support/HsqlPagingQueryProvider.java index 92ee5ee4..66ecc209 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,8 @@ import org.springframework.cloud.task.repository.database.PagingQueryProvider; import org.springframework.data.domain.Pageable; /** - * HSQLDB implementation of a {@link PagingQueryProvider} using database specific features. + * HSQLDB implementation of a {@link PagingQueryProvider} using database specific + * features. * * @author Glenn Renfro */ @@ -29,8 +30,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(); + .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 2852ae2f..2eba4c2c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,11 +25,12 @@ import org.springframework.data.domain.Pageable; * @author Glenn Renfro */ 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(); + .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 5ab1c9dc..09ab7aa7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,8 @@ import org.springframework.cloud.task.repository.database.PagingQueryProvider; import org.springframework.data.domain.Pageable; /** - * Oracle implementation of a {@link PagingQueryProvider} using database specific features. + * Oracle implementation of a {@link PagingQueryProvider} using database specific + * features. * * @author Glenn Renfro */ @@ -28,22 +29,24 @@ public class OraclePagingQueryProvider extends AbstractSqlPagingQueryProvider { @Override 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())); + long offset = pageable.getOffset() + 1; + return generateRowNumSqlQueryWithNesting(getSelectClause(), false, + "TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " + + (offset + pageable.getPageSize())); } private String generateRowNumSqlQueryWithNesting(String selectClause, - boolean remainingPageQuery, - String rowNumClause) { + 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); return sql.toString(); } + } 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 18a16c8b..3a34d3e2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,8 @@ import org.springframework.cloud.task.repository.database.PagingQueryProvider; import org.springframework.data.domain.Pageable; /** - * Postgres implementation of a {@link PagingQueryProvider} using database specific features. + * Postgres implementation of a {@link PagingQueryProvider} using database specific + * features. * * @author Glenn Renfro */ @@ -28,9 +29,10 @@ public class PostgresPagingQueryProvider extends AbstractSqlPagingQueryProvider @Override public String getPageQuery(Pageable pageable) { - String limitClause = new StringBuilder().append("LIMIT "). - append(pageable.getPageSize()).append(" OFFSET "). - append(pageable.getOffset()).toString(); + 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 b9282dc9..7a508a04 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,6 @@ package org.springframework.cloud.task.repository.database.support; -import static org.springframework.cloud.task.repository.support.DatabaseType.DB2; -import static org.springframework.cloud.task.repository.support.DatabaseType.DB2AS400; -import static org.springframework.cloud.task.repository.support.DatabaseType.DB2VSE; -import static org.springframework.cloud.task.repository.support.DatabaseType.DB2ZOS; -import static org.springframework.cloud.task.repository.support.DatabaseType.HSQL; -import static org.springframework.cloud.task.repository.support.DatabaseType.H2; -import static org.springframework.cloud.task.repository.support.DatabaseType.MYSQL; -import static org.springframework.cloud.task.repository.support.DatabaseType.ORACLE; -import static org.springframework.cloud.task.repository.support.DatabaseType.POSTGRES; -import static org.springframework.cloud.task.repository.support.DatabaseType.SQLSERVER; - import java.util.HashMap; import java.util.Map; @@ -40,14 +29,26 @@ import org.springframework.jdbc.support.MetaDataAccessException; import org.springframework.util.Assert; import org.springframework.util.StringUtils; +import static org.springframework.cloud.task.repository.support.DatabaseType.DB2; +import static org.springframework.cloud.task.repository.support.DatabaseType.DB2AS400; +import static org.springframework.cloud.task.repository.support.DatabaseType.DB2VSE; +import static org.springframework.cloud.task.repository.support.DatabaseType.DB2ZOS; +import static org.springframework.cloud.task.repository.support.DatabaseType.H2; +import static org.springframework.cloud.task.repository.support.DatabaseType.HSQL; +import static org.springframework.cloud.task.repository.support.DatabaseType.MYSQL; +import static org.springframework.cloud.task.repository.support.DatabaseType.ORACLE; +import static org.springframework.cloud.task.repository.support.DatabaseType.POSTGRES; +import static org.springframework.cloud.task.repository.support.DatabaseType.SQLSERVER; + /** - * Factory bean for {@link PagingQueryProvider} interface. The database type - * will be determined from the data source if not provided explicitly. Valid - * types are given by the {@link DatabaseType} enum. + * Factory bean for {@link PagingQueryProvider} interface. The database type will be + * determined from the data source if not provided explicitly. Valid types are given by + * the {@link DatabaseType} enum. * * @author Glenn Renfro */ -public class SqlPagingQueryProviderFactoryBean implements FactoryBean { +public class SqlPagingQueryProviderFactoryBean + implements FactoryBean { private DataSource dataSource; @@ -61,20 +62,19 @@ public class SqlPagingQueryProviderFactoryBean implements FactoryBean sortKeys; - private Map providers = new HashMap(); - + private Map providers = new HashMap<>(); { - providers.put(HSQL, new HsqlPagingQueryProvider()); - providers.put(H2, new H2PagingQueryProvider()); - providers.put(MYSQL, new MySqlPagingQueryProvider()); - providers.put(POSTGRES, new PostgresPagingQueryProvider()); - providers.put(ORACLE, new OraclePagingQueryProvider()); - providers.put(SQLSERVER, new SqlServerPagingQueryProvider()); - providers.put(DB2, new Db2PagingQueryProvider()); - providers.put(DB2VSE, new Db2PagingQueryProvider()); - providers.put(DB2ZOS, new Db2PagingQueryProvider()); - providers.put(DB2AS400, new Db2PagingQueryProvider()); + this.providers.put(HSQL, new HsqlPagingQueryProvider()); + this.providers.put(H2, new H2PagingQueryProvider()); + this.providers.put(MYSQL, new MySqlPagingQueryProvider()); + this.providers.put(POSTGRES, new PostgresPagingQueryProvider()); + this.providers.put(ORACLE, new OraclePagingQueryProvider()); + this.providers.put(SQLSERVER, new SqlServerPagingQueryProvider()); + this.providers.put(DB2, new Db2PagingQueryProvider()); + this.providers.put(DB2VSE, new Db2PagingQueryProvider()); + this.providers.put(DB2ZOS, new Db2PagingQueryProvider()); + this.providers.put(DB2AS400, new Db2PagingQueryProvider()); } /** @@ -124,8 +124,8 @@ public class SqlPagingQueryProviderFactoryBean implements FactoryBean= " - + offset + " AND TMP_ROW_NUM < " + (offset+pageable.getPageSize())); + long offset = pageable.getOffset() + 1; + return generateRowNumSqlQueryWithNesting(getSelectClause(), false, + "TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " + + (offset + pageable.getPageSize())); } private String generateRowNumSqlQueryWithNesting(String selectClause, - boolean remainingPageQuery, - String rowNumClause) { + 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 ") + 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()); + .append(") AS TMP_ROW_NUM ").append(" FROM ").append(getFromClause()); SqlPagingQueryUtils.buildWhereClause(this, remainingPageQuery, sql); sql.append(") TASK_EXECUTION_PAGE "); sql.append(" WHERE ").append(rowNumClause); sql.append(" ORDER BY ").append(SqlPagingQueryUtils.buildSortClause(this)); return sql.toString(); } + } 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 90403d6b..11d113d8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,63 +25,107 @@ import org.springframework.jdbc.support.JdbcUtils; import org.springframework.jdbc.support.MetaDataAccessException; import org.springframework.util.StringUtils; - /** - * Enum representing a database type, such as DB2 or oracle. The type also - * contains a product name, which is expected to be the same as the product name - * provided by the database driver's metadata. + * Enum representing a database type, such as DB2 or oracle. The type also contains a + * product name, which is expected to be the same as the product name provided by the + * database driver's metadata. * * @author Glenn Renfro */ public enum DatabaseType { + /** + * HSQL DB. + */ HSQL("HSQL Database Engine"), + + /** + * H2 DB. + */ H2("H2"), + + /** + * Oracle DB. + */ ORACLE("Oracle"), + + /** + * MySQL DB. + */ MYSQL("MySQL"), + + /** + * PostgreSQL DB. + */ POSTGRES("PostgreSQL"), + + /** + * Microsoft SQL Server DB. + */ SQLSERVER("Microsoft SQL Server"), + + /** + * DB2 DB. + */ DB2("DB2"), + + /** + * DB2VSE DB. + */ DB2VSE("DB2VSE"), + + /** + * DB2ZOS DB. + */ DB2ZOS("DB2ZOS"), + + /** + * DB2AS400 DB. + */ DB2AS400("DB2AS400"); private static final Map dbNameMap; + static { + dbNameMap = new HashMap<>(); + for (DatabaseType type : values()) { + dbNameMap.put(type.getProductName(), type); + } + } + private final String productName; DatabaseType(String productName) { this.productName = productName; } - static{ - dbNameMap = new HashMap(); - for(DatabaseType type: values()){ - dbNameMap.put(type.getProductName(), type); - } - } - /** - * Convenience method that pulls a database product name from the DataSource's metadata. - * + * Convenience method that pulls a database product name from the DataSource's + * metadata. * @param dataSource the datasource used to extact metadata. * @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 MetaDataAccessException { - String databaseProductName = - JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName").toString(); - if (StringUtils.hasText(databaseProductName) && !databaseProductName.equals("DB2/Linux") && databaseProductName.startsWith("DB2")) { - String databaseProductVersion = - JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductVersion").toString(); + public static DatabaseType fromMetaData(DataSource dataSource) + throws MetaDataAccessException { + String databaseProductName = JdbcUtils + .extractDatabaseMetaData(dataSource, "getDatabaseProductName").toString(); + if (StringUtils.hasText(databaseProductName) + && !databaseProductName.equals("DB2/Linux") + && databaseProductName.startsWith("DB2")) { + String databaseProductVersion = JdbcUtils + .extractDatabaseMetaData(dataSource, "getDatabaseProductVersion") + .toString(); if (databaseProductVersion.startsWith("ARI")) { databaseProductName = "DB2VSE"; } else if (databaseProductVersion.startsWith("DSN")) { databaseProductName = "DB2ZOS"; } - else if (databaseProductName.indexOf("AS") != -1 && (databaseProductVersion.startsWith("QSQ") || - databaseProductVersion.substring(databaseProductVersion.indexOf('V')).matches("V\\dR\\d[mM]\\d"))) { + else if (databaseProductName.indexOf("AS") != -1 + && (databaseProductVersion.startsWith("QSQ") || databaseProductVersion + .substring(databaseProductVersion.indexOf('V')) + .matches("V\\dR\\d[mM]\\d"))) { databaseProductName = "DB2AS400"; } else { @@ -96,23 +140,22 @@ public enum DatabaseType { /** * Static method to obtain a DatabaseType from the provided product name. - * * @param productName the name of the database. * @return DatabaseType for given product name. * @throws IllegalArgumentException if none is found. */ - public static DatabaseType fromProductName(String productName){ - if(!dbNameMap.containsKey(productName)){ - throw new IllegalArgumentException("DatabaseType not found for product name: [" + - productName + "]"); + public static DatabaseType fromProductName(String productName) { + if (!dbNameMap.containsKey(productName)) { + throw new IllegalArgumentException( + "DatabaseType not found for product name: [" + productName + "]"); } - else{ + else { return dbNameMap.get(productName); } } private String getProductName() { - return productName; + return this.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 3f66dfe6..9f8d72b1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,8 @@ 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(); @@ -51,62 +52,64 @@ public class SimpleTaskExplorer implements TaskExplorer { @Override public TaskExecution getTaskExecution(long executionId) { - return taskExecutionDao.getTaskExecution(executionId); + return this.taskExecutionDao.getTaskExecution(executionId); } @Override - public Page findRunningTaskExecutions(String taskName, Pageable pageable) { - return taskExecutionDao.findRunningTaskExecutions(taskName, pageable); + public Page findRunningTaskExecutions(String taskName, + Pageable pageable) { + return this.taskExecutionDao.findRunningTaskExecutions(taskName, pageable); } @Override public List getTaskNames() { - return taskExecutionDao.getTaskNames(); + return this.taskExecutionDao.getTaskNames(); } @Override public long getTaskExecutionCountByTaskName(String taskName) { - return taskExecutionDao.getTaskExecutionCountByTaskName(taskName); + return this.taskExecutionDao.getTaskExecutionCountByTaskName(taskName); } @Override public long getTaskExecutionCount() { - return taskExecutionDao.getTaskExecutionCount(); + return this.taskExecutionDao.getTaskExecutionCount(); } @Override public long getRunningTaskExecutionCount() { - return taskExecutionDao.getRunningTaskExecutionCount(); + return this.taskExecutionDao.getRunningTaskExecutionCount(); } @Override - public Page findTaskExecutionsByName(String taskName, Pageable pageable) { - return taskExecutionDao.findTaskExecutionsByName(taskName, pageable); + public Page findTaskExecutionsByName(String taskName, + Pageable pageable) { + return this.taskExecutionDao.findTaskExecutionsByName(taskName, pageable); } @Override public Page findAll(Pageable pageable) { - return taskExecutionDao.findAll(pageable); + return this.taskExecutionDao.findAll(pageable); } @Override public Long getTaskExecutionIdByJobExecutionId(long jobExecutionId) { - return taskExecutionDao.getTaskExecutionIdByJobExecutionId(jobExecutionId); + return this.taskExecutionDao.getTaskExecutionIdByJobExecutionId(jobExecutionId); } @Override public Set getJobExecutionIdsByTaskExecutionId(long taskExecutionId) { - return taskExecutionDao.getJobExecutionIdsByTaskExecutionId(taskExecutionId); + return this.taskExecutionDao.getJobExecutionIdsByTaskExecutionId(taskExecutionId); } @Override public List getLatestTaskExecutionsByTaskNames(String... taskNames) { - return taskExecutionDao.getLatestTaskExecutionsByTaskNames(taskNames); + return this.taskExecutionDao.getLatestTaskExecutionsByTaskNames(taskNames); } @Override public TaskExecution getLatestTaskExecutionForTaskName(String taskName) { - return taskExecutionDao.getLatestTaskExecutionForTaskName(taskName); + return this.taskExecutionDao.getLatestTaskExecutionForTaskName(taskName); } } 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 00dd08ab..1ff9846b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.repository.support; import org.springframework.beans.BeansException; @@ -23,11 +24,11 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.util.StringUtils; /** - * Simple implementation of the {@link TaskNameResolver} interface. Names the task based + * Simple implementation of the {@link TaskNameResolver} interface. Names the task based * on the following order of precidence: *
      - *
    1. A configured property spring.cloud.task.name
    2. - *
    3. The {@link ApplicationContext}'s id.
    4. + *
    5. A configured property spring.cloud.task.name
    6. + *
    7. The {@link ApplicationContext}'s id.
    8. *
    * * @author Michael Minella @@ -45,17 +46,19 @@ public class SimpleTaskNameResolver implements TaskNameResolver, ApplicationCont } @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { this.context = applicationContext; } @Override public String getTaskName() { - if(StringUtils.hasText(configuredName)) { - return configuredName; + if (StringUtils.hasText(this.configuredName)) { + return this.configuredName; } else { - return context.getId().replace(":", "_"); + return this.context.getId().replace(":", "_"); } } + } 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 78a8cc75..b9b10aa9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,15 +31,27 @@ import org.springframework.util.Assert; /** * Records the task execution information to the log and to TaskExecutionDao provided. + * * @author Glenn Renfro */ public class SimpleTaskRepository implements TaskRepository { + /** + * Max exit message size. + */ public static final int MAX_EXIT_MESSAGE_SIZE = 2500; + + /** + * Max task name size. + */ public static final int MAX_TASK_NAME_SIZE = 100; + + /** + * Max error message size. + */ public static final int MAX_ERROR_MESSAGE_SIZE = 2500; - private static final Log logger = LogFactory.getLog(SimpleTaskRepository.class); + private static final Log logger = LogFactory.getLog(SimpleTaskRepository.class); private TaskExecutionDao taskExecutionDao; @@ -53,63 +65,63 @@ 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"); - if(maxTaskNameSize != null) { + 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; } - if(maxExitMessageSize != null) { + if (maxExitMessageSize != null) { this.maxExitMessageSize = maxExitMessageSize; } - if(maxErrorMessageSize != null) { + if (maxErrorMessageSize != null) { this.maxErrorMessageSize = maxErrorMessageSize; } this.taskExecutionDaoFactoryBean = taskExecutionDaoFactoryBean; } @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); - 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 + '\'' - + '}'); + 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 taskExecutionDao.getTaskExecution(executionId); + return this.taskExecutionDao.getTaskExecution(executionId); } @Override public TaskExecution createTaskExecution(TaskExecution taskExecution) { initialize(); validateCreateInformation(taskExecution); - TaskExecution daoTaskExecution = - taskExecutionDao.createTaskExecution( - taskExecution.getTaskName(), - taskExecution.getStartTime(), - taskExecution.getArguments(), - taskExecution.getExternalExecutionId(), - taskExecution.getParentExecutionId()); + TaskExecution daoTaskExecution = this.taskExecutionDao.createTaskExecution( + taskExecution.getTaskName(), taskExecution.getStartTime(), + taskExecution.getArguments(), taskExecution.getExternalExecutionId(), + taskExecution.getParentExecutionId()); logger.debug("Creating: " + taskExecution.toString()); return daoTaskExecution; } @@ -117,21 +129,20 @@ public class SimpleTaskRepository implements TaskRepository { @Override public TaskExecution createTaskExecution(String name) { initialize(); - TaskExecution taskExecution = - taskExecutionDao.createTaskExecution(name, null, - Collections.emptyList(), null); + TaskExecution taskExecution = this.taskExecutionDao.createTaskExecution(name, + null, Collections.emptyList(), null); logger.debug("Creating: " + taskExecution.toString()); return taskExecution; } @Override public TaskExecution createTaskExecution() { - return createTaskExecution((String)null); + return createTaskExecution((String) null); } @Override - public TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, List arguments, - String externalExecutionId) { + public TaskExecution startTaskExecution(long executionid, String taskName, + Date startTime, List arguments, String externalExecutionId) { return startTaskExecution(executionid, taskName, startTime, arguments, externalExecutionId, null); } @@ -139,7 +150,7 @@ public class SimpleTaskRepository implements TaskRepository { @Override public void updateExternalExecutionId(long executionid, String externalExecutionId) { initialize(); - taskExecutionDao.updateExternalExecutionId(executionid, externalExecutionId); + this.taskExecutionDao.updateExternalExecutionId(executionid, externalExecutionId); } @Override @@ -147,10 +158,9 @@ public class SimpleTaskRepository implements TaskRepository { Date startTime, List arguments, String externalExecutionId, Long parentExecutionId) { initialize(); - TaskExecution taskExecution = - 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; } @@ -161,44 +171,47 @@ public class SimpleTaskRepository implements TaskRepository { */ public TaskExecutionDao getTaskExecutionDao() { initialize(); - return taskExecutionDao; + return this.taskExecutionDao; } private void initialize() { - if(!initialized) { + if (!this.initialized) { try { this.taskExecutionDao = this.taskExecutionDaoFactoryBean.getObject(); this.initialized = true; } catch (Exception e) { - throw new IllegalStateException("Unable to create the TaskExecutionDao", e); + throw new IllegalStateException("Unable to create the TaskExecutionDao", + e); } } } /** * Validate startTime and taskName are valid. + * @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."); } - private String trimMessage(String exitMessage, int maxSize){ + private String trimMessage(String exitMessage, int maxSize) { String result = exitMessage; - if(exitMessage != null && - exitMessage.length() > maxSize) { + if (exitMessage != null && exitMessage.length() > maxSize) { result = exitMessage.substring(0, maxSize); } return result; @@ -215,4 +228,5 @@ public class SimpleTaskRepository implements TaskRepository { public void setMaxErrorMessageSize(int maxErrorMessageSize) { this.maxErrorMessageSize = maxErrorMessageSize; } + } 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 f45f843c..319ebbb2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.repository.support; import javax.sql.DataSource; @@ -43,7 +44,7 @@ public class TaskExecutionDaoFactoryBean implements FactoryBeanThis is only + * Default constructor will result in a Map based TaskExecutionDao. This is only * intended for testing purposes. */ public TaskExecutionDaoFactoryBean() { @@ -51,7 +52,6 @@ public class TaskExecutionDaoFactoryBean implements FactoryBeanspring.cloud.task.initialize.enable to false. @@ -67,7 +67,7 @@ public final class TaskRepositoryInitializer implements InitializingBean { @Value("${spring.cloud.task.tablePrefix:#{null}}") private String tablePrefix; - public TaskRepositoryInitializer(){ + public TaskRepositoryInitializer() { } public void setDataSource(DataSource dataSource) { @@ -81,7 +81,9 @@ public final class TaskRepositoryInitializer implements InitializingBean { private String getDatabaseType(DataSource dataSource) { try { - return JdbcUtils.commonDatabaseName(DatabaseType.fromMetaData(dataSource).toString()).toLowerCase(); + return JdbcUtils + .commonDatabaseName(DatabaseType.fromMetaData(dataSource).toString()) + .toLowerCase(); } catch (MetaDataAccessException ex) { throw new IllegalStateException("Unable to detect database type", ex); @@ -90,10 +92,9 @@ public final class TaskRepositoryInitializer implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { - if (dataSource != null && - taskInitializationEnable && - !StringUtils.hasText(this.tablePrefix)) { - String platform = getDatabaseType(dataSource); + if (this.dataSource != null && this.taskInitializationEnable + && !StringUtils.hasText(this.tablePrefix)) { + String platform = getDatabaseType(this.dataSource); if ("hsql".equals(platform)) { platform = "hsqldb"; } @@ -106,17 +107,18 @@ public final class TaskRepositoryInitializer implements InitializingBean { if ("mysql".equals(platform)) { platform = "mysql"; } - if ("sqlserver".equals(platform)){ + if ("sqlserver".equals(platform)) { platform = "sqlserver"; } ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); String schemaLocation = schema; schemaLocation = schemaLocation.replace("@@platform@@", platform); - populator.addScript(resourceLoader.getResource(schemaLocation)); + populator.addScript(this.resourceLoader.getResource(schemaLocation)); populator.setContinueOnError(true); - logger.debug(String.format("Initializing task schema for %s database", - platform)); - DatabasePopulatorUtils.execute(populator, dataSource); + logger.debug( + String.format("Initializing task schema for %s database", platform)); + DatabasePopulatorUtils.execute(populator, this.dataSource); } } + } diff --git a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/package-info.java b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/package-info.java index 95223cf3..b4d887f8 100644 --- a/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/package-info.java +++ b/spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/support/package-info.java @@ -1,3 +1,19 @@ +/* + * Copyright 2015-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** * Classes used for setting up and supporting a task repositories. */ diff --git a/spring-cloud-task-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-task-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 72459a6b..27751d19 100644 --- a/spring-cloud-task-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/spring-cloud-task-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -1,10 +1,10 @@ { - "properties": [ - { - "defaultValue": false, - "name": "spring.cloud.task.single-instance-enabled", - "description": "This property is used to determine if a task will execute if another task with the same app name is running.", - "type": "java.lang.Boolean" - } - ] + "properties": [ + { + "defaultValue": false, + "name": "spring.cloud.task.single-instance-enabled", + "description": "This property is used to determine if a task will execute if another task with the same app name is running.", + "type": "java.lang.Boolean" + } + ] } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleSingleTaskAutoConfigurationTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleSingleTaskAutoConfigurationTests.java index 4660ccf5..c29d408c 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleSingleTaskAutoConfigurationTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/SimpleSingleTaskAutoConfigurationTests.java @@ -1,17 +1,17 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task; @@ -25,8 +25,7 @@ import org.springframework.cloud.task.configuration.SimpleTaskAutoConfiguration; import org.springframework.cloud.task.configuration.SingleInstanceTaskListener; import org.springframework.cloud.task.configuration.SingleTaskConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Verifies that the beans created by the SimpleSingleTaskAutoConfigurationConfiguration @@ -43,15 +42,18 @@ public class SimpleSingleTaskAutoConfigurationTests { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of( PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.class)) + SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) .withPropertyValues("spring.cloud.task.singleInstanceEnabled=true"); applicationContextRunner.run((context) -> { - SingleInstanceTaskListener singleInstanceTaskListener = context.getBean(SingleInstanceTaskListener.class); + SingleInstanceTaskListener singleInstanceTaskListener = context + .getBean(SingleInstanceTaskListener.class); - assertNotNull("singleInstanceTaskListener should not be null", singleInstanceTaskListener); + assertThat(singleInstanceTaskListener) + .as("singleInstanceTaskListener should not be null").isNotNull(); - assertEquals(singleInstanceTaskListener.getClass(), SingleInstanceTaskListener.class); }); + 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 257cc5b9..61865cdc 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 @@ -1,17 +1,17 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task; @@ -26,8 +26,7 @@ import org.springframework.cloud.task.configuration.SimpleTaskAutoConfiguration; import org.springframework.cloud.task.configuration.SingleInstanceTaskListener; import org.springframework.cloud.task.configuration.SingleTaskConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Verifies that the beans created by the SimpleSingleTaskAutoConfigurationConfiguration @@ -44,16 +43,19 @@ public class SimpleSingleTaskAutoConfigurationWithDataSourceTests { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of( PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.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); - assertNotNull("singleInstanceTaskListener should not be null", singleInstanceTaskListener); + assertThat(singleInstanceTaskListener) + .as("singleInstanceTaskListener should not be null").isNotNull(); - assertEquals(singleInstanceTaskListener.getClass(), SingleInstanceTaskListener.class); + 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 ea01e0f7..64b9ed88 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; /** @@ -71,10 +71,10 @@ 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); @@ -89,50 +89,50 @@ public class SimpleTaskAutoConfigurationTests { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of( PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.class)) + SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) .withPropertyValues("spring.cloud.task.autoconfiguration.enabled=false"); Executable executable = () -> { applicationContextRunner.run((context) -> { 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, + .withConfiguration(AutoConfigurations.of( + EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.class)) + SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) .withUserConfiguration(TaskLifecycleListenerConfiguration.class); applicationContextRunner.run((context) -> { TaskExplorer taskExplorer = context.getBean(TaskExplorer.class); - assertThat(taskExplorer.getTaskExecutionCount()).isEqualTo(1l); + assertThat(taskExplorer.getTaskExecutionCount()).isEqualTo(1L); }); } @Test public void testRepositoryNotInitialized() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EmbeddedDataSourceConfiguration.class, + .withConfiguration(AutoConfigurations.of( + EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.class)) + SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) .withUserConfiguration(TaskLifecycleListenerConfiguration.class) .withPropertyValues("spring.cloud.task.tablePrefix=foobarless"); - verifyExceptionThrownDefaultExecutable(ApplicationContextException.class, "Failed to start " + - "bean 'taskLifecycleListener'; nested exception is " + - "org.springframework.dao.DataAccessResourceFailureException: " + - "Could not obtain sequence value; nested exception is org.h2.jdbc.JdbcSQLException: " + - "Syntax error in SQL statement \"SELECT FOOBARLESSSEQ.NEXTVAL FROM[*] DUAL \"; " + - "expected \"identifier\"; SQL statement:\n" + - "select foobarlessSEQ.nextval from dual [42001-197]", applicationContextRunner); + verifyExceptionThrownDefaultExecutable(ApplicationContextException.class, + "Failed to start " + "bean 'taskLifecycleListener'; nested exception is " + + "org.springframework.dao.DataAccessResourceFailureException: " + + "Could not obtain sequence value; nested exception is org.h2.jdbc.JdbcSQLException: " + + "Syntax error in SQL statement \"SELECT FOOBARLESSSEQ.NEXTVAL FROM[*] DUAL \"; " + + "expected \"identifier\"; SQL statement:\n" + + "select foobarlessSEQ.nextval from dual [42001-197]", + applicationContextRunner); } @Test @@ -140,29 +140,32 @@ public class SimpleTaskAutoConfigurationTests { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of( PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.class)) + SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) .withUserConfiguration(MultipleConfigurers.class); - verifyExceptionThrownDefaultExecutable(BeanCreationException.class, "Error creating bean " + - "with name 'simpleTaskAutoConfiguration': Invocation of init " + - "method failed; nested exception is java.lang.IllegalStateException:" + - " Expected one TaskConfigurer but found 2", applicationContextRunner); + verifyExceptionThrownDefaultExecutable(BeanCreationException.class, + "Error creating bean " + + "with name 'simpleTaskAutoConfiguration': Invocation of init " + + "method failed; nested exception is java.lang.IllegalStateException:" + + " Expected one TaskConfigurer but found 2", + applicationContextRunner); } @Test public void testMultipleDataSources() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.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; nested exception is java.lang.IllegalStateException: To use " + - "the default TaskConfigurer the context must contain no more than " + - "one DataSource, found 2", applicationContextRunner); + verifyExceptionThrownDefaultExecutable(BeanCreationException.class, + "Error creating bean " + + "with name 'simpleTaskAutoConfiguration': Invocation of init method " + + "failed; nested exception is java.lang.IllegalStateException: To use " + + "the default TaskConfigurer the context must contain no more than " + + "one DataSource, found 2", + applicationContextRunner); } @@ -178,14 +181,15 @@ public class SimpleTaskAutoConfigurationTests { verifyExceptionThrown(classToCheck, message, executable); } - public void verifyExceptionThrown(Class classToCheck, String message, Executable executable) { - Throwable exception = assertThrows(classToCheck, executable); - assertThat(exception.getMessage()).isEqualTo(message); + public void verifyExceptionThrown(Class classToCheck, String message, + Executable executable) { + assertThatExceptionOfType(classToCheck).isThrownBy(executable::execute) + .withMessage(message); } /** - * Verify that the verifyEnvironment method skips DataSource Proxy Beans when determining - * the number of available dataSources. + * Verify that the verifyEnvironment method skips DataSource Proxy Beans when + * determining the number of available dataSources. */ @Test public void testWithDataSourceProxy() { @@ -193,12 +197,12 @@ public class SimpleTaskAutoConfigurationTests { .withConfiguration(AutoConfigurations.of( EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.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(); }); @@ -216,6 +220,7 @@ public class SimpleTaskAutoConfigurationTests { public TaskConfigurer taskConfigurer2() { return new DefaultTaskConfigurer((DataSource) null); } + } @Configuration @@ -243,9 +248,10 @@ 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 528530a1..4ad66b9a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import org.springframework.context.ApplicationContextException; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Verifies core behavior for Tasks. @@ -41,42 +41,49 @@ import static org.junit.Assert.assertTrue; public class TaskCoreTests { private static final String TASK_NAME = "taskEventTest"; - private static final String EXCEPTION_MESSAGE = "FOO EXCEPTION"; - private static final String CREATE_TASK_MESSAGE = "Creating: TaskExecution{executionId="; - private static final String UPDATE_TASK_MESSAGE = "Updating: TaskExecution with executionId="; - private static final String SUCCESS_EXIT_CODE_MESSAGE = "with the following {exitCode=0"; - private static final String EXCEPTION_EXIT_CODE_MESSAGE = "with the following {exitCode=1"; - private static final String EXCEPTION_INVALID_TASK_EXECUTION_ID = - "java.lang.IllegalArgumentException: Invalid TaskExecution, ID 55 not found"; - private static final String ERROR_MESSAGE = - "errorMessage='java.lang.IllegalStateException: Failed to execute CommandLineRunner"; - private ConfigurableApplicationContext applicationContext; + private static final String EXCEPTION_MESSAGE = "FOO EXCEPTION"; + + private static final String CREATE_TASK_MESSAGE = "Creating: TaskExecution{executionId="; + + private static final String UPDATE_TASK_MESSAGE = "Updating: TaskExecution with executionId="; + + private static final String SUCCESS_EXIT_CODE_MESSAGE = "with the following {exitCode=0"; + + private static final String EXCEPTION_EXIT_CODE_MESSAGE = "with the following {exitCode=1"; + + private static final String EXCEPTION_INVALID_TASK_EXECUTION_ID = "java.lang.IllegalArgumentException: " + + "Invalid TaskExecution, ID 55 not found"; + + private static final String ERROR_MESSAGE = "errorMessage='java.lang.IllegalStateException: " + + "Failed to execute CommandLineRunner"; @Rule public OutputCapture outputCapture = new OutputCapture(); + private ConfigurableApplicationContext applicationContext; + @After public void teardown() { - if (applicationContext != null && applicationContext.isActive()) { - applicationContext.close(); + if (this.applicationContext != null && this.applicationContext.isActive()) { + this.applicationContext.close(); } } @Test public void successfulTaskTest() { - this.applicationContext = SpringApplication.run( TaskConfiguration.class, + this.applicationContext = SpringApplication.run(TaskConfiguration.class, "--spring.cloud.task.closecontext.enable=false", "--spring.cloud.task.name=" + TASK_NAME, "--spring.main.web-environment=false"); String output = this.outputCapture.toString(); - assertTrue("Test results do not show create task message: " + output, - output.contains(CREATE_TASK_MESSAGE)); - assertTrue("Test results do not show success message: " + output, - output.contains(UPDATE_TASK_MESSAGE)); - assertTrue("Test results have incorrect exit code: " + output, - output.contains(SUCCESS_EXIT_CODE_MESSAGE)); + 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(); } /** @@ -84,25 +91,27 @@ public class TaskCoreTests { */ @Test public void successfulTaskTestWithAnnotation() { - this.applicationContext = SpringApplication.run( TaskConfigurationWithAnotation.class, + 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 = this.outputCapture.toString(); - assertTrue("Test results do not show create task message: " + output, - output.contains(CREATE_TASK_MESSAGE)); - assertTrue("Test results do not show success message: " + output, - output.contains(UPDATE_TASK_MESSAGE)); - assertTrue("Test results have incorrect exit code: " + output, - output.contains(SUCCESS_EXIT_CODE_MESSAGE)); + 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() { boolean exceptionFired = false; try { - this.applicationContext = SpringApplication.run( TaskExceptionConfiguration.class, + this.applicationContext = SpringApplication.run( + TaskExceptionConfiguration.class, "--spring.cloud.task.closecontext.enable=false", "--spring.cloud.task.name=" + TASK_NAME, "--spring.main.web-environment=false"); @@ -110,19 +119,20 @@ public class TaskCoreTests { catch (IllegalStateException exception) { exceptionFired = true; } - assertTrue("An IllegalStateException should have been thrown", exceptionFired); + assertThat(exceptionFired).as("An IllegalStateException should have been thrown") + .isTrue(); String output = this.outputCapture.toString(); - assertTrue("Test results do not show create task message: " + output, - output.contains(CREATE_TASK_MESSAGE)); - assertTrue("Test results do not show success message: " + output, - output.contains(UPDATE_TASK_MESSAGE)); - assertTrue("Test results have incorrect exit code: " + output, - output.contains(EXCEPTION_EXIT_CODE_MESSAGE)); - assertTrue("Test results have incorrect exit message: " + output, - output.contains(ERROR_MESSAGE)); - assertTrue("Test results have exception message: " + output, - output.contains(EXCEPTION_MESSAGE)); + 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 @@ -130,7 +140,8 @@ public class TaskCoreTests { boolean exceptionFired = false; try { this.applicationContext = SpringApplication.run( - TaskExceptionConfiguration.class, "--spring.cloud.task.closecontext.enable=false", + TaskExceptionConfiguration.class, + "--spring.cloud.task.closecontext.enable=false", "--spring.cloud.task.name=" + TASK_NAME, "--spring.main.web-environment=false", "--spring.cloud.task.executionid=55"); @@ -138,15 +149,18 @@ public class TaskCoreTests { catch (ApplicationContextException exception) { exceptionFired = true; } - assertTrue("An ApplicationContextException should have been thrown", exceptionFired); + assertThat(exceptionFired) + .as("An ApplicationContextException should have been thrown").isTrue(); String output = this.outputCapture.toString(); - assertTrue("Test results do not show the correct exception message: " + output, - output.contains(EXCEPTION_INVALID_TASK_EXECUTION_ID)); + assertThat(output.contains(EXCEPTION_INVALID_TASK_EXECUTION_ID)) + .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 @@ -157,10 +171,12 @@ public class TaskCoreTests { } }; } + } @EnableTask - @ImportAutoConfiguration({SimpleTaskAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class}) + @ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) public static class TaskConfigurationWithAnotation { @Bean @@ -171,10 +187,12 @@ public class TaskCoreTests { } }; } + } @EnableTask - @ImportAutoConfiguration({SimpleTaskAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class}) + @ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) public static class TaskExceptionConfiguration { @Bean @@ -186,5 +204,7 @@ public class TaskCoreTests { } }; } + } + } 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 97b516e4..f515e0a5 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 @@ -1,17 +1,17 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task; @@ -36,15 +36,15 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; /** - * Verifies that TaskRepositoryInitializer creates tables if a {@link TaskConfigurer} - * has a {@link DataSource}. + * Verifies that TaskRepositoryInitializer creates tables if a {@link TaskConfigurer} has + * a {@link DataSource}. * * @author Glenn Renfro * @since 2.0.0 */ @RunWith(SpringRunner.class) -@ContextConfiguration(classes = {SimpleTaskAutoConfiguration.class, - EmbeddedDataSourceConfiguration.class}) +@ContextConfiguration(classes = { SimpleTaskAutoConfiguration.class, + EmbeddedDataSourceConfiguration.class }) @DirtiesContext public class TaskRepositoryInitializerDefaultTaskConfigurerTests { @@ -53,8 +53,9 @@ public class TaskRepositoryInitializerDefaultTaskConfigurerTests { @Test public void testTablesCreated() { - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); - List> rows= jdbcTemplate.queryForList("SHOW TABLES"); + JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource); + List> rows = jdbcTemplate.queryForList("SHOW TABLES"); assertThat(rows.size()).isEqualTo(4); } + } 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 3495e1ed..d245274b 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 @@ -1,17 +1,17 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task; @@ -37,16 +37,16 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; /** - * Verifies that TaskRepositoryInitializer does not create tables if a {@link TaskConfigurer} - * has no {@link DataSource}. + * Verifies that TaskRepositoryInitializer does not create tables if a + * {@link TaskConfigurer} has no {@link DataSource}. * * @author Glenn Renfro * @since 2.0.0 */ @RunWith(SpringRunner.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 @@ -54,8 +54,9 @@ public class TaskRepositoryInitializerNoDataSourceTaskConfigurerTests { @Test public void testNoTablesCreated() { - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); - List> rows= jdbcTemplate.queryForList("SHOW TABLES"); + JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource); + List> rows = jdbcTemplate.queryForList("SHOW TABLES"); assertThat(rows.size()).isEqualTo(0); } + } 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 722aa142..55d0fb8c 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 @@ -1,17 +1,17 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.configuration; @@ -31,11 +31,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.core.IsNull.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -54,64 +50,80 @@ public class DefaultTaskConfigurerTests { @Test public void resourcelessTransactionManagerTest() { DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(); - assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName(), - is("org.springframework.batch.support.transaction.ResourcelessTransactionManager")); + assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName()) + .isEqualTo( + "org.springframework.batch.support.transaction.ResourcelessTransactionManager"); defaultTaskConfigurer = new DefaultTaskConfigurer("foo"); - assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName(), - is("org.springframework.batch.support.transaction.ResourcelessTransactionManager")); + assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName()) + .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(dataSource, TaskProperties.DEFAULT_TABLE_PREFIX, localContext); - assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName(), is(equalTo("org.springframework.orm.jpa.JpaTransactionManager"))); + DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer( + this.dataSource, TaskProperties.DEFAULT_TABLE_PREFIX, localContext); + assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName()) + .isEqualTo("org.springframework.orm.jpa.JpaTransactionManager"); } @Test public void dataSourceTransactionManagerTest() { - DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(dataSource); - assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName(), - is("org.springframework.jdbc.datasource.DataSourceTransactionManager")); - defaultTaskConfigurer = new DefaultTaskConfigurer(dataSource, "FOO", null); - assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName(), - is("org.springframework.jdbc.datasource.DataSourceTransactionManager")); - defaultTaskConfigurer = new DefaultTaskConfigurer(dataSource, "FOO", context); - assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName(), - is("org.springframework.jdbc.datasource.DataSourceTransactionManager")); + DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer( + this.dataSource); + assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName()) + .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); + assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName()) + .isEqualTo( + "org.springframework.jdbc.datasource.DataSourceTransactionManager"); } @Test public void taskExplorerTest() { - DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(dataSource); - assertThat(defaultTaskConfigurer.getTaskExplorer(), is(notNullValue())); + DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer( + this.dataSource); + assertThat(defaultTaskConfigurer.getTaskExplorer()).isNotNull(); defaultTaskConfigurer = new DefaultTaskConfigurer(); - assertThat(defaultTaskConfigurer.getTaskExplorer(), is(notNullValue())); + assertThat(defaultTaskConfigurer.getTaskExplorer()).isNotNull(); } @Test public void taskRepositoryTest() { - DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(dataSource); - assertThat(defaultTaskConfigurer.getTaskRepository(), is(notNullValue())); + DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer( + this.dataSource); + assertThat(defaultTaskConfigurer.getTaskRepository()).isNotNull(); defaultTaskConfigurer = new DefaultTaskConfigurer(); - assertThat(defaultTaskConfigurer.getTaskRepository(), is(notNullValue())); + assertThat(defaultTaskConfigurer.getTaskRepository()).isNotNull(); } @Test public void taskDataSource() { - DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(dataSource); - assertThat(defaultTaskConfigurer.getTaskDataSource(), is(notNullValue())); + DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer( + this.dataSource); + assertThat(defaultTaskConfigurer.getTaskDataSource()).isNotNull(); defaultTaskConfigurer = new DefaultTaskConfigurer(); - assertThat(defaultTaskConfigurer.getTaskDataSource(), is(nullValue())); + assertThat(defaultTaskConfigurer.getTaskDataSource()).isNull(); } @Configuration public static class EntityManagerConfiguration { + @Bean public EntityManager entityManager() { return mock(EntityManager.class); } + } + } 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 b8b1aa72..f19b9f71 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 @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,36 +27,37 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - +import static org.assertj.core.api.Assertions.assertThat; @RunWith(Suite.class) -@SuiteClasses({ - TaskPropertiesTests.CloseContextEnabledTest.class - +@SuiteClasses({ TaskPropertiesTests.CloseContextEnabledTest.class + }) @DirtiesContext public class TaskPropertiesTests { + @Autowired TaskProperties taskProperties; @Test public void test() { - assertThat(taskProperties.getClosecontextEnabled(), is(false)); + assertThat(this.taskProperties.getClosecontextEnabled()).isFalse(); } @RunWith(SpringRunner.class) - @SpringBootTest(classes={TaskPropertiesTests.Config.class, - SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class}, - properties = { "spring.cloud.task.closecontextEnabled=false" }) + @SpringBootTest(classes = { TaskPropertiesTests.Config.class, + SimpleTaskAutoConfiguration.class, + SingleTaskConfiguration.class }, properties = { + "spring.cloud.task.closecontextEnabled=false" }) @DirtiesContext - public static class CloseContextEnabledTest extends TaskPropertiesTests {} - - + public static class CloseContextEnabledTest extends TaskPropertiesTests { + + } + @Configuration public static class Config { } + } 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 bad33af1..4fb10ef2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.configuration; import javax.sql.DataSource; @@ -63,27 +64,29 @@ public class TestConfiguration implements InitializingBean { } @Bean - public TaskRepository taskRepository(){ + public TaskRepository taskRepository() { return new SimpleTaskRepository(this.taskExecutionDaoFactoryBean); } @Bean public PlatformTransactionManager transactionManager() { - if(dataSource == null) { + if (this.dataSource == null) { return new ResourcelessTransactionManager(); } else { - return new DataSourceTransactionManager(dataSource); + return new DataSourceTransactionManager(this.dataSource); } } @Override public void afterPropertiesSet() throws Exception { - if(this.dataSource != null) { - this.taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(this.dataSource); + if (this.dataSource != null) { + 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/listener/TaskExceptionTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/listener/TaskExceptionTests.java index e25dca81..25aefc59 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 @@ -1,25 +1,24 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.listener; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro @@ -31,24 +30,25 @@ public class TaskExceptionTests { @Test public void testTaskException() { TaskException taskException = new TaskException(ERROR_MESSAGE); - assertEquals(ERROR_MESSAGE, taskException.getMessage()); + assertThat(taskException.getMessage()).isEqualTo(ERROR_MESSAGE); taskException = new TaskException(ERROR_MESSAGE, new IllegalStateException(ERROR_MESSAGE)); - assertEquals(ERROR_MESSAGE, taskException.getMessage()); - assertNotNull(taskException.getCause()); - assertEquals(ERROR_MESSAGE, taskException.getCause().getMessage()); + assertThat(taskException.getMessage()).isEqualTo(ERROR_MESSAGE); + assertThat(taskException.getCause()).isNotNull(); + assertThat(taskException.getCause().getMessage()).isEqualTo(ERROR_MESSAGE); } @Test public void testTaskExecutionException() { TaskExecutionException taskException = new TaskExecutionException(ERROR_MESSAGE); - assertEquals(ERROR_MESSAGE, taskException.getMessage()); + assertThat(taskException.getMessage()).isEqualTo(ERROR_MESSAGE); taskException = new TaskExecutionException(ERROR_MESSAGE, new IllegalStateException(ERROR_MESSAGE)); - assertEquals(ERROR_MESSAGE, taskException.getMessage()); - assertNotNull(taskException.getCause()); - assertEquals(ERROR_MESSAGE, taskException.getCause().getMessage()); + 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 e04f0116..391936e5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,10 +37,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Verifies that the TaskExecutionListener invocations occur at the appropriate task @@ -49,14 +46,17 @@ import static org.junit.Assert.assertTrue; * @author Glenn Renfro */ public class TaskExecutionListenerTests { - private AnnotationConfigApplicationContext context; private static final String EXCEPTION_MESSAGE = "This was expected"; private static boolean beforeTaskDidFireOnError = false; + private static boolean endTaskDidFireOnError = false; + private static boolean failedTaskDidFireOnError = false; + private AnnotationConfigApplicationContext context; + @BeforeTask public void setup() { beforeTaskDidFireOnError = false; @@ -66,27 +66,29 @@ public class TaskExecutionListenerTests { @After public void tearDown() { - if(context != null && context.isActive()) { - context.close(); + if (this.context != null && this.context.isActive()) { + this.context.close(); } } /** - * Verify that if a TaskExecutionListener Bean is present that the onTaskStartup method - * is called. + * Verify that if a TaskExecutionListener Bean is present that the onTaskStartup + * method is called. */ @Test public void testTaskCreate() { setupContextForTaskExecutionListener(); - DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = - context.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); + 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); + verifyListenerResults(false, false, taskExecution, taskExecutionListener); } /** - * Verify that if a LifecycleProcessor executes all TaskExecutionListeners if BeforeTask throws exception. + * Verify that if a LifecycleProcessor executes all TaskExecutionListeners if + * BeforeTask throws exception. */ @Test public void testBeforeTaskErrorCreate() { @@ -97,14 +99,18 @@ public class TaskExecutionListenerTests { catch (Exception exception) { exceptionFired = true; } - assertTrue("Exception should have fired", exceptionFired); - assertTrue("BeforeTask Listener should have executed", beforeTaskDidFireOnError); - assertTrue("EndTask Listener should have executed", endTaskDidFireOnError); - assertTrue("FailedTask Listener should have executed", failedTaskDidFireOnError); + 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(); } /** - * Verify that if a LifecycleProcessor executes AfterTask TaskExecutionListeners if FailedTask throws exception. + * Verify that if a LifecycleProcessor executes AfterTask TaskExecutionListeners if + * FailedTask throws exception. */ @Test public void testFailedTaskErrorCreate() { @@ -115,42 +121,52 @@ public class TaskExecutionListenerTests { catch (Exception exception) { exceptionFired = true; } - assertTrue("Exception should have fired", exceptionFired); - assertTrue("EndTask Listener should have executed", endTaskDidFireOnError); - assertTrue("FailedTask Listener should not have executed", failedTaskDidFireOnError); + 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(); } /** - * Verify that if a LifecycleProcessor stores the correct exit code if AfterTask listener fails. + * Verify that if a LifecycleProcessor stores the correct exit code if AfterTask + * listener fails. */ @Test public void testAfterTaskErrorCreate() { setupContextForAfterTaskErrorAnnotatedListener(); - AfterTaskErrorAnnotationConfiguration.AnnotatedTaskListener taskExecutionListener = - context.getBean(AfterTaskErrorAnnotationConfiguration.AnnotatedTaskListener.class); - context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], context)); + AfterTaskErrorAnnotationConfiguration.AnnotatedTaskListener taskExecutionListener = this.context + .getBean( + AfterTaskErrorAnnotationConfiguration.AnnotatedTaskListener.class); + this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), + new String[0], this.context)); - assertTrue(taskExecutionListener.isTaskStartup()); - assertTrue(taskExecutionListener.isTaskEnd()); - assertEquals(TestListener.END_MESSAGE, taskExecutionListener.getTaskExecution().getExitMessage()); - assertTrue(taskExecutionListener.getTaskExecution().getErrorMessage().contains("Failed to process @BeforeTask or @AfterTask annotation because: AfterTaskFailure")); - assertNull(taskExecutionListener.getThrowable()); + 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.getThrowable()).isNull(); } /** - * Verify that if a TaskExecutionListener Bean is present that the onTaskEnd method - * is called. + * Verify that if a TaskExecutionListener Bean is present that the onTaskEnd method is + * called. */ @Test public void testTaskUpdate() { setupContextForTaskExecutionListener(); - DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = - context.getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class); - context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], context)); + DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context + .getBean( + DefaultTaskListenerConfiguration.TestTaskExecutionListener.class); + this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), + new String[0], this.context)); - TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", - new Date(), new Date(), null, new ArrayList<>(), null, null); - verifyListenerResults(true, false, taskExecution,taskExecutionListener); + TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(), + new Date(), null, new ArrayList<>(), null, null); + verifyListenerResults(true, false, taskExecution, taskExecutionListener); } /** @@ -162,14 +178,17 @@ public class TaskExecutionListenerTests { RuntimeException exception = new RuntimeException(EXCEPTION_MESSAGE); setupContextForTaskExecutionListener(); SpringApplication application = new SpringApplication(); - DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = - context.getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class); - context.publishEvent(new ApplicationFailedEvent(application, new String[0], context, exception)); - context.publishEvent(new ApplicationReadyEvent(application, new String[0], context)); + DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context + .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)); TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(), new Date(), null, new ArrayList<>(), null, null); - verifyListenerResults(true, true, taskExecution,taskExecutionListener); + verifyListenerResults(true, true, taskExecution, taskExecutionListener); } /** @@ -179,11 +198,11 @@ public class TaskExecutionListenerTests { @Test public void testAnnotationCreate() { setupContextForAnnotatedListener(); - DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener = - context.getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class); - TaskExecution taskExecution = new TaskExecution(0, null, "wombat", - new Date(), new Date(), null, new ArrayList<>(), null, null); - verifyListenerResults(false, false, taskExecution,annotatedListener); + 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); + verifyListenerResults(false, false, taskExecution, annotatedListener); } /** @@ -193,13 +212,14 @@ public class TaskExecutionListenerTests { @Test public void testAnnotationUpdate() { setupContextForAnnotatedListener(); - DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener = - context.getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class); - context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], context)); + DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener = this.context + .getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class); + this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), + new String[0], this.context)); - TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", - new Date(), new Date(), null, new ArrayList<>(), null, null); - verifyListenerResults(true, false, taskExecution,annotatedListener); + TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(), + new Date(), null, new ArrayList<>(), null, null); + verifyListenerResults(true, false, taskExecution, annotatedListener); } /** @@ -211,73 +231,91 @@ public class TaskExecutionListenerTests { RuntimeException exception = new RuntimeException(EXCEPTION_MESSAGE); setupContextForAnnotatedListener(); SpringApplication application = new SpringApplication(); - DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener = - context.getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class); - context.publishEvent(new ApplicationFailedEvent(application, new String[0], context, exception)); - context.publishEvent(new ApplicationReadyEvent(application, new String[0], context)); + 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 ApplicationReadyEvent(application, new String[0], this.context)); TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(), new Date(), null, new ArrayList<>(), null, null); - verifyListenerResults(true, true, taskExecution,annotatedListener); + verifyListenerResults(true, true, taskExecution, annotatedListener); } - private void verifyListenerResults(boolean isTaskEnd, - boolean isTaskFailed, TaskExecution taskExecution, - TestListener actualListener){ - assertTrue(actualListener.isTaskStartup()); - assertEquals(isTaskEnd,actualListener.isTaskEnd()); - assertEquals(isTaskFailed,actualListener.isTaskFailed()); - if(isTaskFailed){ - assertEquals(TestListener.END_MESSAGE, actualListener.getTaskExecution().getExitMessage()); - assertNotNull(actualListener.getThrowable()); - assertTrue(actualListener.getThrowable() instanceof RuntimeException); - assertTrue(actualListener.getTaskExecution().getErrorMessage().startsWith("java.lang.RuntimeException: This was expected")); + 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.getThrowable()).isNotNull(); + assertThat(actualListener.getThrowable() instanceof RuntimeException) + .isTrue(); + assertThat(actualListener.getTaskExecution().getErrorMessage() + .startsWith("java.lang.RuntimeException: This was expected")) + .isTrue(); } - else if(isTaskEnd){ - assertEquals(TestListener.END_MESSAGE, actualListener.getTaskExecution().getExitMessage()); - assertEquals(taskExecution.getErrorMessage(), actualListener.getTaskExecution().getErrorMessage()); - assertNull(actualListener.getThrowable()); + else if (isTaskEnd) { + assertThat(actualListener.getTaskExecution().getExitMessage()) + .isEqualTo(TestListener.END_MESSAGE); + assertThat(actualListener.getTaskExecution().getErrorMessage()) + .isEqualTo(taskExecution.getErrorMessage()); + assertThat(actualListener.getThrowable()).isNull(); } else { - assertEquals(TestListener.START_MESSAGE, actualListener.getTaskExecution().getExitMessage()); - assertNull(actualListener.getTaskExecution().getErrorMessage()); - assertNull(actualListener.getThrowable()); + assertThat(actualListener.getTaskExecution().getExitMessage()) + .isEqualTo(TestListener.START_MESSAGE); + assertThat(actualListener.getTaskExecution().getErrorMessage()).isNull(); + assertThat(actualListener.getThrowable()).isNull(); } - assertEquals(taskExecution.getExecutionId(), actualListener.getTaskExecution().getExecutionId()); - assertEquals(taskExecution.getExitCode(), actualListener.getTaskExecution().getExitCode()); - assertEquals(taskExecution.getExternalExecutionId(), actualListener.getTaskExecution().getExternalExecutionId()); + assertThat(actualListener.getTaskExecution().getExecutionId()) + .isEqualTo(taskExecution.getExecutionId()); + assertThat(actualListener.getTaskExecution().getExitCode()) + .isEqualTo(taskExecution.getExitCode()); + assertThat(actualListener.getTaskExecution().getExternalExecutionId()) + .isEqualTo(taskExecution.getExternalExecutionId()); } - private void setupContextForTaskExecutionListener(){ - context = new AnnotationConfigApplicationContext(DefaultTaskListenerConfiguration.class, + private void setupContextForTaskExecutionListener() { + 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.setId("annotatedTask"); + } + + private void setupContextForBeforeTaskErrorAnnotatedListener() { + this.context = new AnnotationConfigApplicationContext( TestDefaultConfiguration.class, + BeforeTaskErrorAnnotationConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - context.setId("testTask"); + this.context.setId("beforeTaskAnnotatedTask"); } - private void setupContextForAnnotatedListener(){ - context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class, DefaultAnnotationConfiguration.class, + private void setupContextForFailedTaskErrorAnnotatedListener() { + this.context = new AnnotationConfigApplicationContext( + TestDefaultConfiguration.class, + FailedTaskErrorAnnotationConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - context.setId("annotatedTask"); + this.context.setId("failedTaskAnnotatedTask"); } - private void setupContextForBeforeTaskErrorAnnotatedListener(){ - context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class, BeforeTaskErrorAnnotationConfiguration.class, + private void setupContextForAfterTaskErrorAnnotatedListener() { + this.context = new AnnotationConfigApplicationContext( + TestDefaultConfiguration.class, + AfterTaskErrorAnnotationConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - context.setId("beforeTaskAnnotatedTask"); - } - - private void setupContextForFailedTaskErrorAnnotatedListener(){ - context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class, FailedTaskErrorAnnotationConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - context.setId("failedTaskAnnotatedTask"); - } - - private void setupContextForAfterTaskErrorAnnotatedListener(){ - context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class, AfterTaskErrorAnnotationConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - context.setId("afterTaskAnnotatedTask"); + this.context.setId("afterTaskAnnotatedTask"); } @Configuration @@ -292,14 +330,14 @@ public class TaskExecutionListenerTests { @BeforeTask public void methodA(TaskExecution taskExecution) { - isTaskStartup = true; + this.isTaskStartup = true; this.taskExecution = taskExecution; this.taskExecution.setExitMessage(START_MESSAGE); } @AfterTask public void methodB(TaskExecution taskExecution) { - isTaskEnd = true; + this.isTaskEnd = true; this.taskExecution = taskExecution; this.taskExecution.setExitMessage(END_MESSAGE); @@ -307,12 +345,14 @@ public class TaskExecutionListenerTests { @FailedTask public void methodC(TaskExecution taskExecution, Throwable throwable) { - isTaskFailed = true; + this.isTaskFailed = true; this.taskExecution = taskExecution; this.throwable = throwable; this.taskExecution.setExitMessage(ERROR_MESSAGE); } + } + } @Configuration @@ -345,7 +385,9 @@ public class TaskExecutionListenerTests { public void methodC(TaskExecution taskExecution, Throwable throwable) { failedTaskDidFireOnError = true; } + } + } @Configuration @@ -356,7 +398,6 @@ public class TaskExecutionListenerTests { return new AnnotatedTaskListener(); } - public static class AnnotatedTaskListener { @BeforeTask @@ -375,7 +416,9 @@ public class TaskExecutionListenerTests { failedTaskDidFireOnError = true; throw new TaskExecutionException("FailedTaskFailure"); } + } + } @Configuration @@ -386,21 +429,23 @@ public class TaskExecutionListenerTests { return new AnnotatedTaskListener(); } - public static class AnnotatedTaskListener extends TestListener{ + public static class AnnotatedTaskListener extends TestListener { @BeforeTask public void methodA(TaskExecution taskExecution) { - isTaskStartup = true; + this.isTaskStartup = true; } @AfterTask public void methodB(TaskExecution taskExecution) { - isTaskEnd = true; + this.isTaskEnd = true; this.taskExecution = taskExecution; this.taskExecution.setExitMessage(END_MESSAGE); throw new TaskExecutionException("AfterTaskFailure"); } + } + } @Configuration @@ -411,31 +456,33 @@ 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) { - isTaskStartup = true; + this.isTaskStartup = true; this.taskExecution = taskExecution; this.taskExecution.setExitMessage(START_MESSAGE); } @Override public void onTaskEnd(TaskExecution taskExecution) { - isTaskEnd = true; + this.isTaskEnd = true; this.taskExecution = taskExecution; this.taskExecution.setExitMessage(END_MESSAGE); } @Override public void onTaskFailed(TaskExecution taskExecution, Throwable throwable) { - isTaskFailed = true; + this.isTaskFailed = true; this.taskExecution = taskExecution; this.throwable = throwable; this.taskExecution.setExitMessage(ERROR_MESSAGE); } + } + } } - 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 75e1a80e..e67f3c23 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,32 +51,30 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** - * Verifies that the TaskLifecycleListener Methods record the appropriate log header entries and - * result codes. + * Verifies that the TaskLifecycleListener Methods record the appropriate log header + * entries and result codes. * * @author Glenn Renfro * @author Michael Minella */ public class TaskLifecycleListenerTests { + @Rule + public OutputCapture outputCapture = new OutputCapture(); + private AnnotationConfigApplicationContext context; private TaskExplorer taskExplorer; - @Rule - public OutputCapture outputCapture = new OutputCapture(); - @Before public void setUp() { - context = new AnnotationConfigApplicationContext(); - context.setId("testTask"); - context.register(TestDefaultConfiguration.class, PropertyPlaceholderAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(); + this.context.setId("testTask"); + this.context.register(TestDefaultConfiguration.class, + PropertyPlaceholderAutoConfiguration.class); TestListener.getStartupOrderList().clear(); TestListener.getFailOrderList().clear(); TestListener.getEndOrderList().clear(); @@ -85,44 +83,47 @@ public class TaskLifecycleListenerTests { @After public void tearDown() { - if(context != null && context.isActive()) { - context.close(); + if (this.context != null && this.context.isActive()) { + this.context.close(); } } @Test public void testTaskCreate() { - context.refresh(); - this.taskExplorer = context.getBean(TaskExplorer.class); + this.context.refresh(); + this.taskExplorer = this.context.getBean(TaskExplorer.class); verifyTaskExecution(0, false); } @Test public void testTaskCreateWithArgs() { - context.register(ArgsConfiguration.class); - context.refresh(); - this.taskExplorer = context.getBean(TaskExplorer.class); + this.context.register(ArgsConfiguration.class); + this.context.refresh(); + this.taskExplorer = this.context.getBean(TaskExplorer.class); verifyTaskExecution(2, false); } @Test public void testTaskUpdate() { - context.refresh(); - this.taskExplorer = context.getBean(TaskExplorer.class); + this.context.refresh(); + this.taskExplorer = this.context.getBean(TaskExplorer.class); - context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], context)); + this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), + new String[0], this.context)); verifyTaskExecution(0, true, 0); } @Test public void testTaskFailedUpdate() { - context.refresh(); + this.context.refresh(); RuntimeException exception = new RuntimeException("This was expected"); SpringApplication application = new SpringApplication(); - this.taskExplorer = context.getBean(TaskExplorer.class); - context.publishEvent(new ApplicationFailedEvent(application, new String[0], context, exception)); - context.publishEvent(new ApplicationReadyEvent(application, new String[0], context)); + this.taskExplorer = this.context.getBean(TaskExplorer.class); + this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], + this.context, exception)); + this.context.publishEvent( + new ApplicationReadyEvent(application, new String[0], this.context)); verifyTaskExecution(0, true, 1, exception, null); } @@ -130,38 +131,44 @@ public class TaskLifecycleListenerTests { @Test public void testTaskFailedWithExitCodeEvent() { final int exitCode = 10; - context.register(TestListener.class); - context.register(TestListener2.class); + this.context.register(TestListener.class); + this.context.register(TestListener2.class); - context.refresh(); + this.context.refresh(); RuntimeException exception = new RuntimeException("This was expected"); SpringApplication application = new SpringApplication(); - this.taskExplorer = context.getBean(TaskExplorer.class); - context.publishEvent(new ExitCodeEvent(context, exitCode)); - context.publishEvent(new ApplicationFailedEvent(application, new String[0], context, exception)); - context.publishEvent(new ApplicationReadyEvent(application, new String[0], context)); + 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 ApplicationReadyEvent(application, new String[0], this.context)); verifyTaskExecution(0, true, exitCode, exception, null); - assertEquals(2, TestListener.getStartupOrderList().size()); - assertEquals(Integer.valueOf(2), TestListener.getStartupOrderList().get(0)); - assertEquals(Integer.valueOf(1), TestListener.getStartupOrderList().get(1)); + assertThat(TestListener.getStartupOrderList().size()).isEqualTo(2); + assertThat(TestListener.getStartupOrderList().get(0)) + .isEqualTo(Integer.valueOf(2)); + assertThat(TestListener.getStartupOrderList().get(1)) + .isEqualTo(Integer.valueOf(1)); - assertEquals(2, TestListener.getEndOrderList().size()); - assertEquals(Integer.valueOf(1), TestListener.getEndOrderList().get(0)); - assertEquals(Integer.valueOf(2), TestListener.getEndOrderList().get(1)); + assertThat(TestListener.getEndOrderList().size()).isEqualTo(2); + assertThat(TestListener.getEndOrderList().get(0)).isEqualTo(Integer.valueOf(1)); + assertThat(TestListener.getEndOrderList().get(1)).isEqualTo(Integer.valueOf(2)); - assertEquals(2, TestListener.getFailOrderList().size()); - assertEquals(Integer.valueOf(1), TestListener.getFailOrderList().get(0)); - assertEquals(Integer.valueOf(2), TestListener.getFailOrderList().get(1)); + assertThat(TestListener.getFailOrderList().size()).isEqualTo(2); + assertThat(TestListener.getFailOrderList().get(0)).isEqualTo(Integer.valueOf(1)); + assertThat(TestListener.getFailOrderList().get(1)).isEqualTo(Integer.valueOf(2)); } @Test public void testNoClosingOfContext() { - try (ConfigurableApplicationContext applicationContext = SpringApplication.run(new Class[] {TestDefaultConfiguration.class, PropertyPlaceholderAutoConfiguration.class}, - new String[] {"--spring.cloud.task.closecontext_enabled=false"})) { - assertTrue(applicationContext.isActive()); + try (ConfigurableApplicationContext applicationContext = SpringApplication.run( + new Class[] { TestDefaultConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }, + new String[] { "--spring.cloud.task.closecontext_enabled=false" })) { + assertThat(applicationContext.isActive()).isTrue(); } } @@ -171,20 +178,21 @@ public class TaskLifecycleListenerTests { MutablePropertySources propertySources = environment.getPropertySources(); Map myMap = new HashMap<>(); myMap.put("spring.cloud.task.executionid", "55"); - propertySources.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); - context.setEnvironment(environment); - context.refresh(); + propertySources + .addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); + this.context.setEnvironment(environment); + this.context.refresh(); } @Test public void testRestartExistingTask() { - context.refresh(); - TaskLifecycleListener taskLifecycleListener = - context.getBean(TaskLifecycleListener.class); + this.context.refresh(); + TaskLifecycleListener taskLifecycleListener = this.context + .getBean(TaskLifecycleListener.class); taskLifecycleListener.start(); String output = this.outputCapture.toString(); - assertTrue("Test results do not show error message: " + output, - output.contains("Multiple start events have been received")); + assertThat(output.contains("Multiple start events have been received")) + .as("Test results do not show error message: " + output).isTrue(); } @Test @@ -193,10 +201,11 @@ 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)); - context.setEnvironment(environment); - context.refresh(); - this.taskExplorer = context.getBean(TaskExplorer.class); + propertySources + .addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); + this.context.setEnvironment(environment); + this.context.refresh(); + this.taskExplorer = this.context.getBean(TaskExplorer.class); verifyTaskExecution(0, false, null, null, "myid"); } @@ -207,15 +216,17 @@ public class TaskLifecycleListenerTests { MutablePropertySources propertySources = environment.getPropertySources(); Map myMap = new HashMap<>(); myMap.put("spring.cloud.task.parentExecutionId", 789); - propertySources.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); - context.setEnvironment(environment); - context.refresh(); - this.taskExplorer = context.getBean(TaskExplorer.class); + propertySources + .addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap)); + this.context.setEnvironment(environment); + this.context.refresh(); + this.taskExplorer = this.context.getBean(TaskExplorer.class); 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); } @@ -223,47 +234,48 @@ public class TaskLifecycleListenerTests { verifyTaskExecution(numberOfParams, update, null, null, null); } - private void verifyTaskExecution(int numberOfParams, boolean update, - Integer exitCode, Throwable exception, String externalExecutionId) { + 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); - assertTrue(taskExecutionsByName.iterator().hasNext()); + Page taskExecutionsByName = this.taskExplorer + .findTaskExecutionsByName("testTask", request); + assertThat(taskExecutionsByName.iterator().hasNext()).isTrue(); TaskExecution taskExecution = taskExecutionsByName.iterator().next(); - assertEquals(numberOfParams, taskExecution.getArguments().size()); - assertEquals(exitCode, taskExecution.getExitCode()); - assertEquals(externalExecutionId, taskExecution.getExternalExecutionId()); - assertEquals(parentExecutionId, taskExecution.getParentExecutionId()); + assertThat(taskExecution.getArguments().size()).isEqualTo(numberOfParams); + assertThat(taskExecution.getExitCode()).isEqualTo(exitCode); + assertThat(taskExecution.getExternalExecutionId()).isEqualTo(externalExecutionId); + assertThat(taskExecution.getParentExecutionId()).isEqualTo(parentExecutionId); - if(exception != null) { - assertTrue(taskExecution.getErrorMessage().length() > exception.getStackTrace().length); + if (exception != null) { + assertThat(taskExecution.getErrorMessage() + .length() > exception.getStackTrace().length).isTrue(); } else { - assertNull(taskExecution.getExitMessage()); + assertThat(taskExecution.getExitMessage()).isNull(); } - if(update) { - assertTrue(taskExecution.getEndTime().getTime() >= taskExecution.getStartTime().getTime()); - assertNotNull(taskExecution.getExitCode()); + if (update) { + assertThat(taskExecution.getEndTime().getTime() >= taskExecution + .getStartTime().getTime()).isTrue(); + assertThat(taskExecution.getExitCode()).isNotNull(); } else { - assertNull(taskExecution.getEndTime()); - assertTrue(taskExecution.getExitCode() == null); + assertThat(taskExecution.getEndTime()).isNull(); + assertThat(taskExecution.getExitCode() == null).isTrue(); } - assertEquals("testTask", taskExecution.getTaskName()); + assertThat(taskExecution.getTaskName()).isEqualTo("testTask"); } @Configuration @@ -278,23 +290,25 @@ public class TaskLifecycleListenerTests { return new SimpleApplicationArgs(args); } + } private static class SimpleApplicationArgs implements ApplicationArguments { private Map args; - public SimpleApplicationArgs(Map args) { + SimpleApplicationArgs(Map args) { this.args = args; } @Override public String[] getSourceArgs() { - String [] sourceArgs = new String[this.args.size()]; + String[] sourceArgs = new String[this.args.size()]; int i = 0; - for (Map.Entry stringStringEntry : args.entrySet()) { - sourceArgs[i] = "--" + stringStringEntry.getKey() + "=" + stringStringEntry.getValue(); + for (Map.Entry stringStringEntry : this.args.entrySet()) { + sourceArgs[i] = "--" + stringStringEntry.getKey() + "=" + + stringStringEntry.getValue(); i++; } @@ -320,6 +334,7 @@ public class TaskLifecycleListenerTests { public List getNonOptionArgs() { throw new UnsupportedOperationException("Not supported at this time."); } + } private static class TestListener2 extends TestListener { @@ -328,34 +343,17 @@ public class TaskLifecycleListenerTests { private static class TestListener implements TaskExecutionListener { + static List startupOrderList = new ArrayList<>(); + static List endOrderList = new ArrayList<>(); + static List failOrderList = new ArrayList<>(); + private static int currentCount = 0; private int id = 0; - static List startupOrderList = new ArrayList<>(); - - static List endOrderList = new ArrayList<>(); - - static List failOrderList = new ArrayList<>(); - - public TestListener() { + TestListener() { currentCount++; - id = currentCount; - } - - @Override - public void onTaskStartup(TaskExecution taskExecution) { - startupOrderList.add(id); - } - - @Override - public void onTaskEnd(TaskExecution taskExecution) { - endOrderList.add(id); - } - - @Override - public void onTaskFailed(TaskExecution taskExecution, Throwable throwable) { - failOrderList.add(id); + this.id = currentCount; } public static List getStartupOrderList() { @@ -369,5 +367,22 @@ public class TaskLifecycleListenerTests { public static List getFailOrderList() { return failOrderList; } + + @Override + public void onTaskStartup(TaskExecution taskExecution) { + startupOrderList.add(this.id); + } + + @Override + public void onTaskEnd(TaskExecution taskExecution) { + endOrderList.add(this.id); + } + + @Override + public void onTaskFailed(TaskExecution taskExecution, Throwable throwable) { + failOrderList.add(this.id); + } + } + } 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 17dba895..f322b36e 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 @@ -1,17 +1,17 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.listener; @@ -46,7 +46,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @since 2.1.0 */ @RunWith(SpringRunner.class) -@ContextConfiguration(classes = { TaskListenerExecutorObjectFactoryTests.TaskExecutionListenerConfiguration.class }) +@ContextConfiguration(classes = { + TaskListenerExecutorObjectFactoryTests.TaskExecutionListenerConfiguration.class }) @DirtiesContext public class TaskListenerExecutorObjectFactoryTests { @@ -68,13 +69,15 @@ public class TaskListenerExecutorObjectFactoryTests { @Before public void setup() { taskExecutionListenerResults.clear(); - this.taskListenerExecutorObjectFactory = new TaskListenerExecutorObjectFactory(this.context); + this.taskListenerExecutorObjectFactory = new TaskListenerExecutorObjectFactory( + this.context); this.taskListenerExecutor = this.taskListenerExecutorObjectFactory.getObject(); } @Test public void verifyTaskStartupListener() { - this.taskListenerExecutor.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); + this.taskListenerExecutor + .onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); validateSingleEntry(BEFORE_LISTENER); } @@ -93,14 +96,18 @@ public class TaskListenerExecutorObjectFactoryTests { @Test public void verifyAllListener() { - this.taskListenerExecutor.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); + this.taskListenerExecutor + .onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER)); this.taskListenerExecutor.onTaskFailed(createSampleTaskExecution(FAIL_LISTENER), new IllegalStateException("oops")); 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); } private TaskExecution createSampleTaskExecution(String taskName) { @@ -121,23 +128,29 @@ public class TaskListenerExecutorObjectFactoryTests { public TaskRunComponent taskRunComponent() { 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/repository/dao/BaseTaskExecutionDaoTestCases.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/dao/BaseTaskExecutionDaoTestCases.java index 26d3233d..b1674c03 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 @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,22 +18,20 @@ package org.springframework.cloud.task.repository.dao; import java.util.Calendar; import java.util.Date; -import java.util.GregorianCalendar; import java.util.List; import java.util.TimeZone; import org.junit.Test; + import org.springframework.cloud.task.repository.TaskExecution; import org.springframework.test.annotation.DirtiesContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** - * Defines test cases that shall be shared between {@link JdbcTaskExecutionDaoTests} and {@link MapTaskExecutionDaoTests}. + * Defines test cases that shall be shared between {@link JdbcTaskExecutionDaoTests} and + * {@link MapTaskExecutionDaoTests}. * * @author Gunnar Hillert */ @@ -43,12 +41,13 @@ public class BaseTaskExecutionDaoTestCases { @Test @DirtiesContext - public void getLatestTaskExecutionsByTaskNamesWithNullParameter() { + public void getLatestTaskExecutionsByTaskNamesWithNullParameter() { try { - dao.getLatestTaskExecutionsByTaskNames(null); + this.dao.getLatestTaskExecutionsByTaskNames(null); } catch (IllegalArgumentException e) { - assertEquals("At least 1 task name must be provided.", e.getMessage()); + assertThat(e.getMessage()) + .isEqualTo("At least 1 task name must be provided."); return; } fail("Expected an IllegalArgumentException to be thrown."); @@ -56,12 +55,13 @@ public class BaseTaskExecutionDaoTestCases { @Test @DirtiesContext - public void getLatestTaskExecutionsByTaskNamesWithEmptyArrayParameter() { + public void getLatestTaskExecutionsByTaskNamesWithEmptyArrayParameter() { try { - dao.getLatestTaskExecutionsByTaskNames(new String[0]); + this.dao.getLatestTaskExecutionsByTaskNames(new String[0]); } catch (IllegalArgumentException e) { - assertEquals("At least 1 task name must be provided.", e.getMessage()); + assertThat(e.getMessage()) + .isEqualTo("At least 1 task name must be provided."); return; } fail("Expected an IllegalArgumentException to be thrown."); @@ -69,12 +69,13 @@ public class BaseTaskExecutionDaoTestCases { @Test @DirtiesContext - public void getLatestTaskExecutionsByTaskNamesWithArrayParametersContainingNullAndEmptyValues() { + public void getLatestTaskExecutionsByTaskNamesWithArrayParametersContainingNullAndEmptyValues() { try { - dao.getLatestTaskExecutionsByTaskNames("foo", null, "bar", " "); + this.dao.getLatestTaskExecutionsByTaskNames("foo", null, "bar", " "); } catch (IllegalArgumentException e) { - assertEquals("Task names must not contain any empty elements but 2 of 4 were empty or null.", e.getMessage()); + 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."); @@ -82,95 +83,105 @@ public class BaseTaskExecutionDaoTestCases { @Test @DirtiesContext - public void getLatestTaskExecutionsByTaskNamesWithSingleTaskName() { + public void getLatestTaskExecutionsByTaskNamesWithSingleTaskName() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final List latestTaskExecutions = dao.getLatestTaskExecutionsByTaskNames("FOO1"); - assertTrue("Expected only 1 taskExecution but got " + latestTaskExecutions.size(), latestTaskExecutions.size() == 1); + 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); - assertEquals("FOO1", lastTaskExecution.getTaskName()); + assertThat(lastTaskExecution.getTaskName()).isEqualTo("FOO1"); final Calendar dateTime = Calendar.getInstance(TimeZone.getTimeZone("UTC")); dateTime.setTime(lastTaskExecution.getStartTime()); - assertEquals(2015, dateTime.get(Calendar.YEAR)); - assertEquals(2, dateTime.get(Calendar.MONTH) + 1); - assertEquals(22, dateTime.get(Calendar.DAY_OF_MONTH)); - assertEquals(23, dateTime.get(Calendar.HOUR_OF_DAY)); - assertEquals(59, dateTime.get(Calendar.MINUTE)); - assertEquals(0, dateTime.get(Calendar.SECOND)); + assertThat(dateTime.get(Calendar.YEAR)).isEqualTo(2015); + assertThat(dateTime.get(Calendar.MONTH) + 1).isEqualTo(2); + assertThat(dateTime.get(Calendar.DAY_OF_MONTH)).isEqualTo(22); + assertThat(dateTime.get(Calendar.HOUR_OF_DAY)).isEqualTo(23); + assertThat(dateTime.get(Calendar.MINUTE)).isEqualTo(59); + assertThat(dateTime.get(Calendar.SECOND)).isEqualTo(0); } @Test @DirtiesContext - public void getLatestTaskExecutionsByTaskNamesWithMultipleTaskNames() { + public void getLatestTaskExecutionsByTaskNamesWithMultipleTaskNames() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final List latestTaskExecutions = dao.getLatestTaskExecutionsByTaskNames("FOO1", "FOO3", "FOO4"); - assertTrue("Expected 3 taskExecutions but got " + latestTaskExecutions.size(), latestTaskExecutions.size() == 3); + final List latestTaskExecutions = this.dao + .getLatestTaskExecutionsByTaskNames("FOO1", "FOO3", "FOO4"); + assertThat(latestTaskExecutions.size() == 3) + .as("Expected 3 taskExecutions but got " + latestTaskExecutions.size()) + .isTrue(); final Calendar dateTimeFoo3 = Calendar.getInstance(TimeZone.getTimeZone("UTC")); dateTimeFoo3.setTime(latestTaskExecutions.get(0).getStartTime()); - assertEquals(2016, dateTimeFoo3.get(Calendar.YEAR)); - assertEquals(8, dateTimeFoo3.get(Calendar.MONTH) + 1); - assertEquals(20, dateTimeFoo3.get(Calendar.DAY_OF_MONTH)); - assertEquals(14, dateTimeFoo3.get(Calendar.HOUR_OF_DAY)); - assertEquals(45, dateTimeFoo3.get(Calendar.MINUTE)); - assertEquals(0, dateTimeFoo3.get(Calendar.SECOND)); + assertThat(dateTimeFoo3.get(Calendar.YEAR)).isEqualTo(2016); + assertThat(dateTimeFoo3.get(Calendar.MONTH) + 1).isEqualTo(8); + assertThat(dateTimeFoo3.get(Calendar.DAY_OF_MONTH)).isEqualTo(20); + assertThat(dateTimeFoo3.get(Calendar.HOUR_OF_DAY)).isEqualTo(14); + assertThat(dateTimeFoo3.get(Calendar.MINUTE)).isEqualTo(45); + assertThat(dateTimeFoo3.get(Calendar.SECOND)).isEqualTo(0); final Calendar dateTimeFoo1 = Calendar.getInstance(TimeZone.getTimeZone("UTC")); dateTimeFoo1.setTime(latestTaskExecutions.get(1).getStartTime()); - assertEquals(2015, dateTimeFoo1.get(Calendar.YEAR)); - assertEquals(2, dateTimeFoo1.get(Calendar.MONTH) + 1); - assertEquals(22, dateTimeFoo1.get(Calendar.DAY_OF_MONTH)); - assertEquals(23, dateTimeFoo1.get(Calendar.HOUR_OF_DAY)); - assertEquals(59, dateTimeFoo1.get(Calendar.MINUTE)); - assertEquals(0, dateTimeFoo1.get(Calendar.SECOND)); + assertThat(dateTimeFoo1.get(Calendar.YEAR)).isEqualTo(2015); + assertThat(dateTimeFoo1.get(Calendar.MONTH) + 1).isEqualTo(2); + assertThat(dateTimeFoo1.get(Calendar.DAY_OF_MONTH)).isEqualTo(22); + assertThat(dateTimeFoo1.get(Calendar.HOUR_OF_DAY)).isEqualTo(23); + assertThat(dateTimeFoo1.get(Calendar.MINUTE)).isEqualTo(59); + assertThat(dateTimeFoo1.get(Calendar.SECOND)).isEqualTo(0); final Calendar dateTimeFoo4 = Calendar.getInstance(TimeZone.getTimeZone("UTC")); dateTimeFoo4.setTime(latestTaskExecutions.get(2).getStartTime()); - assertEquals(2015, dateTimeFoo4.get(Calendar.YEAR)); - assertEquals(2, dateTimeFoo4.get(Calendar.MONTH) + 1); - assertEquals(20, dateTimeFoo4.get(Calendar.DAY_OF_MONTH)); - assertEquals(14, dateTimeFoo4.get(Calendar.HOUR_OF_DAY)); - assertEquals(45, dateTimeFoo4.get(Calendar.MINUTE)); - assertEquals(0, dateTimeFoo4.get(Calendar.SECOND)); + assertThat(dateTimeFoo4.get(Calendar.YEAR)).isEqualTo(2015); + assertThat(dateTimeFoo4.get(Calendar.MONTH) + 1).isEqualTo(2); + assertThat(dateTimeFoo4.get(Calendar.DAY_OF_MONTH)).isEqualTo(20); + assertThat(dateTimeFoo4.get(Calendar.HOUR_OF_DAY)).isEqualTo(14); + assertThat(dateTimeFoo4.get(Calendar.MINUTE)).isEqualTo(45); + assertThat(dateTimeFoo4.get(Calendar.SECOND)).isEqualTo(0); } /** - * This test is a special use-case. While not common, it is theoretically possible, that a task may have - * executed with the exact same start time multiple times. In that case we should still only get 1 returned - * {@link TaskExecution}. + * This test is a special use-case. While not common, it is theoretically possible, + * that a task may have executed with the exact same start time multiple times. In + * that case we should still only get 1 returned {@link TaskExecution}. */ @Test @DirtiesContext - public void getLatestTaskExecutionsByTaskNamesWithIdenticalTaskExecutions() { + public void getLatestTaskExecutionsByTaskNamesWithIdenticalTaskExecutions() { long executionIdOffset = initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final List latestTaskExecutions = dao.getLatestTaskExecutionsByTaskNames("FOO5"); - assertTrue("Expected only 1 taskExecution but got " + latestTaskExecutions.size(), latestTaskExecutions.size() == 1); + 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()); - assertEquals(2015, dateTime.get(Calendar.YEAR)); - assertEquals(2, dateTime.get(Calendar.MONTH) + 1); - assertEquals(22, dateTime.get(Calendar.DAY_OF_MONTH)); - assertEquals(23, dateTime.get(Calendar.HOUR_OF_DAY)); - assertEquals(59, dateTime.get(Calendar.MINUTE)); - assertEquals(0, dateTime.get(Calendar.SECOND)); - assertEquals(9 + executionIdOffset, latestTaskExecutions.get(0).getExecutionId()); + assertThat(dateTime.get(Calendar.YEAR)).isEqualTo(2015); + assertThat(dateTime.get(Calendar.MONTH) + 1).isEqualTo(2); + assertThat(dateTime.get(Calendar.DAY_OF_MONTH)).isEqualTo(22); + 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); } @Test @DirtiesContext - public void getLatestTaskExecutionForTaskNameWithNullParameter() { + public void getLatestTaskExecutionForTaskNameWithNullParameter() { try { - dao.getLatestTaskExecutionForTaskName(null); + this.dao.getLatestTaskExecutionForTaskName(null); } catch (IllegalArgumentException e) { - assertEquals("The task name must not be empty.", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("The task name must not be empty."); return; } fail("Expected an IllegalArgumentException to be thrown."); @@ -178,12 +189,12 @@ public class BaseTaskExecutionDaoTestCases { @Test @DirtiesContext - public void getLatestTaskExecutionForTaskNameWithEmptyStringParameter() { + public void getLatestTaskExecutionForTaskNameWithEmptyStringParameter() { try { - dao.getLatestTaskExecutionForTaskName(""); + this.dao.getLatestTaskExecutionForTaskName(""); } catch (IllegalArgumentException e) { - assertEquals("The task name must not be empty.", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("The task name must not be empty."); return; } fail("Expected an IllegalArgumentException to be thrown."); @@ -191,61 +202,71 @@ public class BaseTaskExecutionDaoTestCases { @Test @DirtiesContext - public void getLatestTaskExecutionForNonExistingTaskName() { + public void getLatestTaskExecutionForNonExistingTaskName() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final TaskExecution latestTaskExecution = dao.getLatestTaskExecutionForTaskName("Bar5"); - assertNull("Expected the latestTaskExecution to be null but got" + latestTaskExecution, latestTaskExecution); + final TaskExecution latestTaskExecution = this.dao + .getLatestTaskExecutionForTaskName("Bar5"); + assertThat(latestTaskExecution) + .as("Expected the latestTaskExecution to be null but got" + + latestTaskExecution) + .isNull(); } @Test @DirtiesContext - public void getLatestTaskExecutionForExistingTaskName() { + public void getLatestTaskExecutionForExistingTaskName() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final TaskExecution latestTaskExecution = dao.getLatestTaskExecutionForTaskName("FOO1"); - assertNotNull("Expected the latestTaskExecution not to be null", latestTaskExecution); + 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()); - assertEquals(2015, dateTime.get(Calendar.YEAR)); - assertEquals(2, dateTime.get(Calendar.MONTH) + 1); - assertEquals(22, dateTime.get(Calendar.DAY_OF_MONTH)); - assertEquals(23, dateTime.get(Calendar.HOUR_OF_DAY)); - assertEquals(59, dateTime.get(Calendar.MINUTE)); - assertEquals(0, dateTime.get(Calendar.SECOND)); + assertThat(dateTime.get(Calendar.YEAR)).isEqualTo(2015); + assertThat(dateTime.get(Calendar.MONTH) + 1).isEqualTo(2); + assertThat(dateTime.get(Calendar.DAY_OF_MONTH)).isEqualTo(22); + assertThat(dateTime.get(Calendar.HOUR_OF_DAY)).isEqualTo(23); + assertThat(dateTime.get(Calendar.MINUTE)).isEqualTo(59); + assertThat(dateTime.get(Calendar.SECOND)).isEqualTo(0); } /** - * This test is a special use-case. While not common, it is theoretically possible, that a task may have - * executed with the exact same start time multiple times. In that case we should still only get 1 returned - * {@link TaskExecution}. + * This test is a special use-case. While not common, it is theoretically possible, + * that a task may have executed with the exact same start time multiple times. In + * that case we should still only get 1 returned {@link TaskExecution}. */ @Test @DirtiesContext - public void getLatestTaskExecutionForTaskNameWithIdenticalTaskExecutions() { + public void getLatestTaskExecutionForTaskNameWithIdenticalTaskExecutions() { long executionIdOffset = initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - final TaskExecution latestTaskExecution = dao.getLatestTaskExecutionForTaskName("FOO5"); - assertNotNull("Expected the latestTaskExecution not to be null", latestTaskExecution); + 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()); - assertEquals(2015, dateTime.get(Calendar.YEAR)); - assertEquals(2, dateTime.get(Calendar.MONTH) + 1); - assertEquals(22, dateTime.get(Calendar.DAY_OF_MONTH)); - assertEquals(23, dateTime.get(Calendar.HOUR_OF_DAY)); - assertEquals(59, dateTime.get(Calendar.MINUTE)); - assertEquals(0, dateTime.get(Calendar.SECOND)); - assertEquals(9 + executionIdOffset, latestTaskExecution.getExecutionId()); + assertThat(dateTime.get(Calendar.YEAR)).isEqualTo(2015); + assertThat(dateTime.get(Calendar.MONTH) + 1).isEqualTo(2); + assertThat(dateTime.get(Calendar.DAY_OF_MONTH)).isEqualTo(22); + assertThat(dateTime.get(Calendar.HOUR_OF_DAY)).isEqualTo(23); + assertThat(dateTime.get(Calendar.MINUTE)).isEqualTo(59); + assertThat(dateTime.get(Calendar.SECOND)).isEqualTo(0); + assertThat(latestTaskExecution.getExecutionId()).isEqualTo(9 + executionIdOffset); } @Test @DirtiesContext public void getRunningTaskExecutions() { initializeRepositoryNotInOrderWithMultipleTaskExecutions(); - assertEquals(dao.getTaskExecutionCount(), dao.getRunningTaskExecutionCount()); - dao.completeTaskExecution(1, 0, new Date(), "c'est fini!" ); - assertEquals(dao.getTaskExecutionCount() - 1, dao.getRunningTaskExecutionCount()); + 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); } protected long initializeRepositoryNotInOrderWithMultipleTaskExecutions() { @@ -304,7 +325,8 @@ public class BaseTaskExecutionDaoTestCases { } private long createTaskExecution(TaskExecution te) { - return 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, @@ -315,4 +337,5 @@ public class BaseTaskExecutionDaoTestCases { taskExecution.setStartTime(new Date()); return taskExecution; } + } 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 b83c084a..e557e26d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Executes unit tests on JdbcTaskExecutionDao. @@ -53,83 +53,95 @@ import static org.junit.Assert.assertEquals; * @author Gunnar Hillert */ @RunWith(SpringRunner.class) -@ContextConfiguration(classes = {TestConfiguration.class, +@ContextConfiguration(classes = { TestConfiguration.class, EmbeddedDataSourceConfiguration.class, - PropertyPlaceholderAutoConfiguration.class}) + PropertyPlaceholderAutoConfiguration.class }) public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { - @Autowired - private DataSource dataSource; - @Autowired TaskRepository repository; + @Autowired + private DataSource dataSource; + @Before - public void setup(){ - final JdbcTaskExecutionDao dao = new JdbcTaskExecutionDao(dataSource); - dao.setTaskIncrementer(TestDBUtils.getIncrementer(dataSource)); + public void setup() { + final JdbcTaskExecutionDao dao = new JdbcTaskExecutionDao(this.dataSource); + dao.setTaskIncrementer(TestDBUtils.getIncrementer(this.dataSource)); super.dao = dao; } @Test @DirtiesContext public void testStartTaskExecution() { - TaskExecution expectedTaskExecution = 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()); - 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(dataSource, expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, + expectedTaskExecution.getExecutionId())); } @Test @DirtiesContext public void createTaskExecution() { - TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); - expectedTaskExecution = dao.createTaskExecution(expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); + TaskExecution expectedTaskExecution = TestVerifierUtils + .createSampleTaskExecutionNoArg(); + expectedTaskExecution = this.dao.createTaskExecution( + expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), + expectedTaskExecution.getArguments(), + expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(dataSource, expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, + expectedTaskExecution.getExecutionId())); } @Test @DirtiesContext public void createEmptyTaskExecution() { - TaskExecution expectedTaskExecution = dao.createTaskExecution(null, null, - new ArrayList(0), null); + TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, + new ArrayList<>(0), null); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(dataSource, expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, + expectedTaskExecution.getExecutionId())); } @Test @DirtiesContext public void completeTaskExecution() { - TaskExecution expectedTaskExecution = TestVerifierUtils.endSampleTaskExecutionNoArg(); - expectedTaskExecution = dao.createTaskExecution(expectedTaskExecution.getTaskName(), - expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), + TaskExecution expectedTaskExecution = TestVerifierUtils + .endSampleTaskExecutionNoArg(); + expectedTaskExecution = this.dao.createTaskExecution( + expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), + expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); - dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), + this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(dataSource, expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, + expectedTaskExecution.getExecutionId())); } @Test(expected = IllegalStateException.class) @DirtiesContext public void completeTaskExecutionWithNoCreate() { - JdbcTaskExecutionDao dao = new JdbcTaskExecutionDao(dataSource); + JdbcTaskExecutionDao dao = new JdbcTaskExecutionDao(this.dataSource); - TaskExecution expectedTaskExecution = TestVerifierUtils.endSampleTaskExecutionNoArg(); + TaskExecution expectedTaskExecution = TestVerifierUtils + .endSampleTaskExecutionNoArg(); dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage()); @@ -137,89 +149,90 @@ public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { @Test @DirtiesContext - public void testFindAllPageableSort() { + public void testFindAllPageableSort() { initializeRepositoryNotInOrder(); - Sort sort = Sort.by(new Sort.Order(Sort.Direction.ASC, - "EXTERNAL_EXECUTION_ID")); + Sort sort = Sort.by(new Sort.Order(Sort.Direction.ASC, "EXTERNAL_EXECUTION_ID")); Iterator iter = getPageIterator(0, 2, sort); TaskExecution taskExecution = iter.next(); - assertEquals("FOO2", taskExecution.getTaskName()); + assertThat(taskExecution.getTaskName()).isEqualTo("FOO2"); taskExecution = iter.next(); - assertEquals("FOO3", taskExecution.getTaskName()); + assertThat(taskExecution.getTaskName()).isEqualTo("FOO3"); iter = getPageIterator(1, 2, sort); taskExecution = iter.next(); - assertEquals("FOO1", taskExecution.getTaskName()); + assertThat(taskExecution.getTaskName()).isEqualTo("FOO1"); } @Test @DirtiesContext - public void testFindAllDefaultSort() { + public void testFindAllDefaultSort() { initializeRepository(); Iterator iter = getPageIterator(0, 2, null); TaskExecution taskExecution = iter.next(); - assertEquals("FOO1", taskExecution.getTaskName()); + assertThat(taskExecution.getTaskName()).isEqualTo("FOO1"); taskExecution = iter.next(); - assertEquals("FOO2", taskExecution.getTaskName()); + assertThat(taskExecution.getTaskName()).isEqualTo("FOO2"); iter = getPageIterator(1, 2, null); taskExecution = iter.next(); - assertEquals("FOO3", taskExecution.getTaskName()); + assertThat(taskExecution.getTaskName()).isEqualTo("FOO3"); } @Test @DirtiesContext public void testStartExecutionWithNullExternalExecutionIdExisting() { - TaskExecution expectedTaskExecution = - initializeTaskExecutionWithExternalExecutionId(); + TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId(); - 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(dataSource, expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, + expectedTaskExecution.getExecutionId())); } @Test @DirtiesContext public void testStartExecutionWithNullExternalExecutionIdNonExisting() { - TaskExecution expectedTaskExecution = - initializeTaskExecutionWithExternalExecutionId(); + TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId(); - 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(dataSource, expectedTaskExecution.getExecutionId())); + TestDBUtils.getTaskExecutionFromDB(this.dataSource, + expectedTaskExecution.getExecutionId())); } private TaskExecution initializeTaskExecutionWithExternalExecutionId() { - TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); + TaskExecution expectedTaskExecution = TestVerifierUtils + .createSampleTaskExecutionNoArg(); return this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), - expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), - "FOO1"); + expectedTaskExecution.getStartTime(), + expectedTaskExecution.getArguments(), "FOO1"); } - private Iterator getPageIterator(int pageNum, int pageSize, Sort sort) { - Pageable pageable = (sort == null) ? - PageRequest.of(pageNum, pageSize) : - PageRequest.of(pageNum, pageSize, sort); - Page page = dao.findAll(pageable); - assertEquals(3, page.getTotalElements()); - assertEquals(2, page.getTotalPages()); + 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); + assertThat(page.getTotalElements()).isEqualTo(3); + assertThat(page.getTotalPages()).isEqualTo(2); return page.iterator(); } private void initializeRepository() { - repository.createTaskExecution(getTaskExecution("FOO3", "externalA")); - repository.createTaskExecution(getTaskExecution("FOO2", "externalB")); - repository.createTaskExecution(getTaskExecution("FOO1", "externalC")); + this.repository.createTaskExecution(getTaskExecution("FOO3", "externalA")); + this.repository.createTaskExecution(getTaskExecution("FOO2", "externalB")); + this.repository.createTaskExecution(getTaskExecution("FOO1", "externalC")); } private void initializeRepositoryNotInOrder() { - repository.createTaskExecution(getTaskExecution("FOO1", "externalC")); - repository.createTaskExecution(getTaskExecution("FOO2", "externalA")); - repository.createTaskExecution(getTaskExecution("FOO3", "externalB")); + this.repository.createTaskExecution(getTaskExecution("FOO1", "externalC")); + this.repository.createTaskExecution(getTaskExecution("FOO2", "externalA")); + this.repository.createTaskExecution(getTaskExecution("FOO3", "externalB")); } + } 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 f1c7a742..d589d492 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,12 +27,11 @@ import java.util.UUID; import org.junit.Before; import org.junit.Test; + import org.springframework.cloud.task.repository.TaskExecution; import org.springframework.cloud.task.util.TestVerifierUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Executes unit tests on MapTaskExecutionDaoTests. @@ -40,7 +39,7 @@ import static org.junit.Assert.assertNull; * @author Glenn Renfro * @author Gunnar Hillert */ -public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases{ +public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases { private MapTaskExecutionDao mapTaskExecutionDao; @@ -52,122 +51,138 @@ 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(); - assertNotNull("taskExecutionMap must not be null", taskExecutionMap); + Map taskExecutionMap = this.mapTaskExecutionDao + .getTaskExecutions(); + assertThat(taskExecutionMap).as("taskExecutionMap must not be null").isNotNull(); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, taskExecutionMap.get(expectedTaskExecution.getExecutionId())); } @Test public void createEmptyTaskExecution() { - TaskExecution expectedTaskExecution = 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(expected = IllegalStateException.class) public void completeTaskExecutionWithNoCreate() { - TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); + TaskExecution expectedTaskExecution = TestVerifierUtils + .createSampleTaskExecutionNoArg(); 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(), + public void saveTaskExecution() { + TaskExecution expectedTaskExecution = TestVerifierUtils + .createSampleTaskExecutionNoArg(); + expectedTaskExecution = this.dao.createTaskExecution( + expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), + expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); - Map taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions(); - assertNotNull("taskExecutionMap must not be null", taskExecutionMap); + Map taskExecutionMap = this.mapTaskExecutionDao + .getTaskExecutions(); + assertThat(taskExecutionMap).as("taskExecutionMap must not be null").isNotNull(); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, taskExecutionMap.get(expectedTaskExecution.getExecutionId())); } @Test - public void completeTaskExecution(){ - TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); - expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), - expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), + public void completeTaskExecution() { + 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(); - assertNotNull("taskExecutionMap must not be null", taskExecutionMap); + Map taskExecutionMap = this.mapTaskExecutionDao + .getTaskExecutions(); + assertThat(taskExecutionMap).as("taskExecutionMap must not be null").isNotNull(); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, taskExecutionMap.get(expectedTaskExecution.getExecutionId())); } @Test - public void testJobQueries(){ + public void testJobQueries() { List expectedTaskExecutionList = new ArrayList<>(2); expectedTaskExecutionList.add(TestVerifierUtils.createSampleTaskExecutionNoArg()); 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.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); - assertEquals(Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId()), - this.dao.getTaskExecutionIdByJobExecutionId(123L)); - assertEquals(Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId()), - this.dao.getTaskExecutionIdByJobExecutionId(456L)); - assertNull(this.dao.getTaskExecutionIdByJobExecutionId(789L)); + 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); + public void testStartExecutionWithNullExternalExecutionIdExisting() { + TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId(); + Map taskExecutionMap = this.mapTaskExecutionDao + .getTaskExecutions(); + this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), + expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), + expectedTaskExecution.getArguments(), null); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, taskExecutionMap.get(expectedTaskExecution.getExecutionId())); } @Test - public void testStartExecutionWithNullExternalExecutionIdNonExisting(){ - TaskExecution expectedTaskExecution = - initializeTaskExecutionWithExternalExecutionId(); - Map taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions(); - this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), - expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), - "BAR"); + public void testStartExecutionWithNullExternalExecutionIdNonExisting() { + TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId(); + 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(); + TaskExecution expectedTaskExecution = TestVerifierUtils + .createSampleTaskExecutionNoArg(); return this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), - expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), - "FOO1"); + 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 96a96774..e2e666d2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import org.springframework.cloud.task.util.TestDBUtils; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro @@ -36,13 +36,22 @@ import static org.junit.Assert.assertEquals; public class FindAllPagingQueryProviderTests { private String databaseProductName; + private String expectedQuery; + private Pageable pageable = PageRequest.of(0, 10); + public FindAllPagingQueryProviderTests(String databaseProductName, + String expectedQuery) { + this.databaseProductName = databaseProductName; + this.expectedQuery = expectedQuery; + } + + // @checkstyle:off @Parameterized.Parameters public static Collection data() { - return Arrays.asList(new Object[][]{ - {"Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + 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 " @@ -50,41 +59,39 @@ public class FindAllPagingQueryProviderTests { + "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, " + + "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 " - + "START_TIME DESC, TASK_EXECUTION_ID DESC"}, - {"PostgreSQL","SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, " + + "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 ORDER BY START_TIME DESC, " - + "TASK_EXECUTION_ID DESC LIMIT 10 OFFSET 0"}, - {"MySQL","SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + + "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"} - }); - } - - public FindAllPagingQueryProviderTests(String databaseProductName, String expectedQuery) { - this.databaseProductName = databaseProductName; - this.expectedQuery = expectedQuery; + + "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" } }); } + // @checkstyle:on @Test - public void testGeneratedQuery() throws Exception{ - String actualQuery = TestDBUtils.getPagingQueryProvider(databaseProductName).getPageQuery(pageable); - assertEquals(String.format( - "the generated query for %s, was not the expected query", - databaseProductName), expectedQuery, actualQuery); + public void testGeneratedQuery() throws Exception { + String actualQuery = TestDBUtils.getPagingQueryProvider(this.databaseProductName) + .getPageQuery(this.pageable); + assertThat(actualQuery).as( + String.format("the generated query for %s, was not the expected query", + this.databaseProductName)) + .isEqualTo(this.expectedQuery); } } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/InvalidPagingQueryProviderTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/InvalidPagingQueryProviderTests.java index 45e761f9..03737b36 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/InvalidPagingQueryProviderTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/InvalidPagingQueryProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.cloud.task.repository.database.support; import org.junit.Test; + import org.springframework.cloud.task.util.TestDBUtils; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; @@ -27,8 +28,9 @@ import org.springframework.data.domain.Pageable; public class InvalidPagingQueryProviderTests { @Test(expected = IllegalStateException.class) - public void testInvalidDatabase() throws Exception{ + public void testInvalidDatabase() throws Exception { Pageable pageable = PageRequest.of(0, 10); TestDBUtils.getPagingQueryProvider("Invalid").getPageQuery(pageable); } + } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryProviderFactoryBeanTests.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryProviderFactoryBeanTests.java index 10bdba06..968810b3 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryProviderFactoryBeanTests.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/repository/database/support/SqlPagingQueryProviderFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,19 @@ package org.springframework.cloud.task.repository.database.support; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - import java.util.Map; import java.util.TreeMap; import org.junit.Before; import org.junit.Test; + import org.springframework.batch.item.database.Order; import org.springframework.cloud.task.repository.dao.JdbcTaskExecutionDao; import org.springframework.cloud.task.repository.database.PagingQueryProvider; import org.springframework.cloud.task.util.TestDBUtils; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Glenn Renfro */ @@ -38,28 +37,28 @@ public class SqlPagingQueryProviderFactoryBeanTests { private SqlPagingQueryProviderFactoryBean factoryBean; @Before - public void setup() throws Exception{ - factoryBean = new SqlPagingQueryProviderFactoryBean(); - factoryBean.setDataSource(TestDBUtils.getMockDataSource("MySQL")); - factoryBean.setDatabaseType("Oracle"); - factoryBean.setSelectClause(JdbcTaskExecutionDao.SELECT_CLAUSE); - factoryBean.setFromClause(JdbcTaskExecutionDao.FROM_CLAUSE); + public void setup() throws Exception { + this.factoryBean = new SqlPagingQueryProviderFactoryBean(); + this.factoryBean.setDataSource(TestDBUtils.getMockDataSource("MySQL")); + this.factoryBean.setDatabaseType("Oracle"); + this.factoryBean.setSelectClause(JdbcTaskExecutionDao.SELECT_CLAUSE); + this.factoryBean.setFromClause(JdbcTaskExecutionDao.FROM_CLAUSE); Map orderMap = new TreeMap<>(); orderMap.put("START_TIME", Order.DESCENDING); orderMap.put("TASK_EXECUTION_ID", Order.DESCENDING); - factoryBean.setSortKeys(orderMap); + this.factoryBean.setSortKeys(orderMap); } @Test - public void testDatabaseType() throws Exception{ - PagingQueryProvider pagingQueryProvider = factoryBean.getObject(); - assertThat(pagingQueryProvider, instanceOf(OraclePagingQueryProvider.class)); + public void testDatabaseType() throws Exception { + PagingQueryProvider pagingQueryProvider = this.factoryBean.getObject(); + assertThat(pagingQueryProvider).isInstanceOf(OraclePagingQueryProvider.class); } @Test - public void testIsSingleton(){ - assertTrue(factoryBean.isSingleton()); + public void testIsSingleton() { + assertThat(this.factoryBean.isSingleton()).isTrue(); } } 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 73b38667..4a900a77 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ import org.springframework.cloud.task.util.TestDBUtils; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro @@ -37,13 +37,22 @@ import static org.junit.Assert.assertEquals; public class WhereClausePagingQueryProviderTests { private String databaseProductName; + private String expectedQuery; + private Pageable pageable = PageRequest.of(0, 10); + public WhereClausePagingQueryProviderTests(String databaseProductName, + String expectedQuery) { + this.databaseProductName = databaseProductName; + this.expectedQuery = expectedQuery; + } + + // @checkstyle:off @Parameterized.Parameters public static Collection data() { - return Arrays.asList(new Object[][]{ - {"Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + 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 " @@ -52,46 +61,43 @@ public class WhereClausePagingQueryProviderTests { + "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, " + + "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"}, - {"PostgreSQL","SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, " + + "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, " - + "TASK_EXECUTION_ID DESC LIMIT 10 OFFSET 0"}, - {"MySQL","SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, " + + "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, " - + "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"} - }); - } - - public WhereClausePagingQueryProviderTests(String databaseProductName, String expectedQuery) { - this.databaseProductName = databaseProductName; - this.expectedQuery = expectedQuery; + + "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" } }); } + // @checkstyle:on @Test - public void testGeneratedQuery() throws Exception{ - PagingQueryProvider pagingQueryProvider = - TestDBUtils.getPagingQueryProvider(databaseProductName, - "TASK_EXECUTION_ID = '0000'"); - String actualQuery = pagingQueryProvider.getPageQuery(pageable); - assertEquals(String.format( - "the generated query for %s, was not the expected query", - databaseProductName), expectedQuery, actualQuery); + public void testGeneratedQuery() throws Exception { + PagingQueryProvider pagingQueryProvider = TestDBUtils.getPagingQueryProvider( + this.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", + this.databaseProductName)) + .isEqualTo(this.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 b122113b..0e30851b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,20 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.repository.support; -import static org.junit.Assert.assertEquals; +import javax.sql.DataSource; + +import org.junit.Test; + +import org.springframework.cloud.task.util.TestDBUtils; + +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.cloud.task.repository.support.DatabaseType.HSQL; import static org.springframework.cloud.task.repository.support.DatabaseType.MYSQL; import static org.springframework.cloud.task.repository.support.DatabaseType.ORACLE; import static org.springframework.cloud.task.repository.support.DatabaseType.POSTGRES; import static org.springframework.cloud.task.repository.support.DatabaseType.fromProductName; -import javax.sql.DataSource; - -import org.junit.Test; -import org.springframework.cloud.task.util.TestDBUtils; - /** * Tests that the correct database names are selected from datasource metadata. * @@ -39,10 +41,10 @@ public class DatabaseTypeTests { @Test public void testFromProductName() { - assertEquals(HSQL, fromProductName("HSQL Database Engine")); - assertEquals(ORACLE, fromProductName("Oracle")); - assertEquals(POSTGRES, fromProductName("PostgreSQL")); - assertEquals(MYSQL, fromProductName("MySQL")); + assertThat(fromProductName("HSQL Database Engine")).isEqualTo(HSQL); + assertThat(fromProductName("Oracle")).isEqualTo(ORACLE); + assertThat(fromProductName("PostgreSQL")).isEqualTo(POSTGRES); + assertThat(fromProductName("MySQL")).isEqualTo(MYSQL); } @Test(expected = IllegalArgumentException.class) @@ -53,25 +55,25 @@ public class DatabaseTypeTests { @Test public void testFromMetaDataForHsql() throws Exception { DataSource ds = TestDBUtils.getMockDataSource("HSQL Database Engine"); - assertEquals(HSQL, DatabaseType.fromMetaData(ds)); + assertThat(DatabaseType.fromMetaData(ds)).isEqualTo(HSQL); } @Test public void testFromMetaDataForOracle() throws Exception { DataSource ds = TestDBUtils.getMockDataSource("Oracle"); - assertEquals(ORACLE, DatabaseType.fromMetaData(ds)); + assertThat(DatabaseType.fromMetaData(ds)).isEqualTo(ORACLE); } @Test public void testFromMetaDataForPostgres() throws Exception { DataSource ds = TestDBUtils.getMockDataSource("PostgreSQL"); - assertEquals(POSTGRES, DatabaseType.fromMetaData(ds)); + assertThat(DatabaseType.fromMetaData(ds)).isEqualTo(POSTGRES); } @Test public void testFromMetaDataForMySQL() throws Exception { DataSource ds = TestDBUtils.getMockDataSource("MySQL"); - assertEquals(MYSQL, DatabaseType.fromMetaData(ds)); + assertThat(DatabaseType.fromMetaData(ds)).isEqualTo(MYSQL); } } 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 c309bed1..1500ae67 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,6 @@ package org.springframework.cloud.task.repository.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -41,6 +36,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; @@ -56,6 +52,8 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Glenn Renfro * @author Gunnar Hillert @@ -67,6 +65,9 @@ public class SimpleTaskExplorerTests { private final static String EXTERNAL_EXECUTION_ID = "123ABC"; + @Rule + public ExpectedException expected = ExpectedException.none(); + private AnnotationConfigApplicationContext context; @Autowired @@ -77,18 +78,14 @@ public class SimpleTaskExplorerTests { private DaoType testType; - @Parameterized.Parameters - public static Collection data() { - return Arrays.asList(new Object[]{ - DaoType.jdbc, DaoType.map }); - } - public SimpleTaskExplorerTests(DaoType testType) { this.testType = testType; } - @Rule - public ExpectedException expected = ExpectedException.none(); + @Parameterized.Parameters + public static Collection data() { + return Arrays.asList(new Object[] { DaoType.jdbc, DaoType.map }); + } @Before public void testDefaultContext() throws Exception { @@ -112,11 +109,11 @@ public class SimpleTaskExplorerTests { public void getTaskExecution() { Map expectedResults = createSampleDataSet(5); for (Long taskExecutionId : expectedResults.keySet()) { - TaskExecution actualTaskExecution = - taskExplorer.getTaskExecution(taskExecutionId); - assertNotNull(String.format( - "expected a taskExecution but got null for test type %s", testType), - actualTaskExecution); + TaskExecution actualTaskExecution = this.taskExplorer + .getTaskExecution(taskExecutionId); + assertThat(actualTaskExecution).as(String.format( + "expected a taskExecution but got null for test type %s", + this.testType)).isNotNull(); TestVerifierUtils.verifyTaskExecution(expectedResults.get(taskExecutionId), actualTaskExecution); } @@ -126,11 +123,10 @@ public class SimpleTaskExplorerTests { public void taskExecutionNotFound() { createSampleDataSet(5); - TaskExecution actualTaskExecution = - taskExplorer.getTaskExecution(-5); - assertNull(String.format( - "expected null for actualTaskExecution %s", testType), - actualTaskExecution); + TaskExecution actualTaskExecution = this.taskExplorer.getTaskExecution(-5); + assertThat(actualTaskExecution).as( + String.format("expected null for actualTaskExecution %s", this.testType)) + .isNull(); } @Test @@ -138,29 +134,30 @@ public class SimpleTaskExplorerTests { Map expectedResults = createSampleDataSet(5); for (Map.Entry entry : expectedResults.entrySet()) { String taskName = entry.getValue().getTaskName(); - assertEquals(String.format( - "task count for task name did not match expected result for testType %s", - testType), - 1, taskExplorer.getTaskExecutionCountByTaskName(taskName)); + assertThat(this.taskExplorer.getTaskExecutionCountByTaskName(taskName)) + .as(String.format( + "task count for task name did not match expected result for testType %s", + this.testType)) + .isEqualTo(1); } } @Test public void getTaskCount() { createSampleDataSet(33); - assertEquals(String.format( - "task count did not match expected result for test Type %s", - testType), - 33, taskExplorer.getTaskExecutionCount()); + assertThat(this.taskExplorer.getTaskExecutionCount()).as( + String.format("task count did not match expected result for test Type %s", + this.testType)) + .isEqualTo(33); } @Test public void getRunningTaskCount() { createSampleDataSet(33); - assertEquals(String.format( - "task count did not match expected result for test Type %s", - testType), - 33, taskExplorer.getRunningTaskExecutionCount()); + assertThat(this.taskExplorer.getRunningTaskExecutionCount()).as( + String.format("task count did not match expected result for test Type %s", + this.testType)) + .isEqualTo(33); } @Test @@ -169,31 +166,34 @@ public class SimpleTaskExplorerTests { final int COMPLETE_COUNT = 5; Map expectedResults = new HashMap<>(); - //Store completed jobs + // Store completed jobs int i = 0; for (; i < COMPLETE_COUNT; i++) { createAndSaveTaskExecution(i); } 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 = taskExplorer.findRunningTaskExecutions(TASK_NAME, pageable); - assertEquals(String.format( + 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), TEST_COUNT, actualResults.getNumberOfElements()); + this.testType)).isEqualTo(TEST_COUNT); for (TaskExecution result : actualResults) { - assertTrue(String.format( - "result returned from repo %s not expected for testType %s", - result.getExecutionId(), testType), - expectedResults.containsKey(result.getExecutionId())); - assertNull(String.format("result had non null for endTime for the testType %s", - testType), result.getEndTime()); + assertThat(expectedResults.containsKey(result.getExecutionId())).as(String + .format("result returned from repo %s not expected for testType %s", + result.getExecutionId(), this.testType)) + .isTrue(); + assertThat(result.getEndTime()).as(String.format( + "result had non null for endTime for the testType %s", this.testType)) + .isNull(); } } @@ -203,30 +203,33 @@ public class SimpleTaskExplorerTests { final int COMPLETE_COUNT = 7; Map expectedResults = new HashMap<>(); - //Store completed jobs + // Store completed jobs for (int i = 0; i < COMPLETE_COUNT; i++) { createAndSaveTaskExecution(i); } 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 = taskExplorer.findTaskExecutionsByName(TASK_NAME, pageable); - assertEquals(String.format( + 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), TEST_COUNT, resultSet.getNumberOfElements()); + this.testType)).isEqualTo(TEST_COUNT); for (TaskExecution result : resultSet) { - assertTrue(String.format("result returned from %s repo %s not expected", - testType, result.getExecutionId()), - expectedResults.containsKey(result.getExecutionId())); - assertEquals( - String.format("taskName for taskExecution is incorrect for testType %s", - testType), TASK_NAME, result.getTaskName()); + assertThat(expectedResults.containsKey(result.getExecutionId())) + .as(String.format("result returned from %s repo %s not expected", + this.testType, result.getExecutionId())) + .isTrue(); + assertThat(result.getTaskName()).as(String.format( + "taskName for taskExecution is incorrect for testType %s", + this.testType)).isEqualTo(TASK_NAME); } } @@ -238,10 +241,12 @@ public class SimpleTaskExplorerTests { TaskExecution expectedTaskExecution = createAndSaveTaskExecution(i); expectedResults.add(expectedTaskExecution.getTaskName()); } - List actualTaskNames = taskExplorer.getTaskNames(); + List actualTaskNames = this.taskExplorer.getTaskNames(); for (String taskName : actualTaskNames) { - assertTrue(String.format("taskName was not in expected results for testType %s", - testType), expectedResults.contains(taskName)); + assertThat(expectedResults.contains(taskName)).as( + String.format("taskName was not in expected results for testType %s", + this.testType)) + .isTrue(); } } @@ -271,23 +276,26 @@ public class SimpleTaskExplorerTests { @Test public void findTasksForInvalidJob() { - assertNull(taskExplorer.getTaskExecutionIdByJobExecutionId(55555L)); + assertThat(this.taskExplorer.getTaskExecutionIdByJobExecutionId(55555L)).isNull(); } @Test - public void findJobsExecutionIdsForInvalidTask () { - assertEquals(0, taskExplorer.getJobExecutionIdsByTaskExecutionId(555555L).size()); + public void findJobsExecutionIdsForInvalidTask() { + assertThat(this.taskExplorer.getJobExecutionIdsByTaskExecutionId(555555L).size()) + .isEqualTo(0); } @Test public void getLatestTaskExecutionForTaskName() { Map expectedResults = createSampleDataSet(5); - for (Map.Entry taskExecutionMapEntry: expectedResults.entrySet()) { - TaskExecution latestTaskExecution = - taskExplorer.getLatestTaskExecutionForTaskName(taskExecutionMapEntry.getValue().getTaskName()); - assertNotNull(String.format( - "expected a taskExecution but got null for test type %s", testType), - latestTaskExecution); + 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", + this.testType)).isNotNull(); TestVerifierUtils.verifyTaskExecution( expectedResults.get(latestTaskExecution.getExecutionId()), latestTaskExecution); @@ -304,13 +312,14 @@ public class SimpleTaskExplorerTests { taskNamesAsList.add(taskExecution.getTaskName()); } - final List latestTaskExecutions = taskExplorer.getLatestTaskExecutionsByTaskNames( - taskNamesAsList.toArray(new String[taskNamesAsList.size()])); + final List latestTaskExecutions = this.taskExplorer + .getLatestTaskExecutionsByTaskNames( + taskNamesAsList.toArray(new String[taskNamesAsList.size()])); for (TaskExecution latestTaskExecution : latestTaskExecutions) { - assertNotNull(String.format( - "expected a taskExecution but got null for test type %s", testType), - latestTaskExecution); + assertThat(latestTaskExecution).as(String.format( + "expected a taskExecution but got null for test type %s", + this.testType)).isNotNull(); TestVerifierUtils.verifyTaskExecution( expectedResults.get(latestTaskExecution.getExecutionId()), latestTaskExecution); @@ -318,38 +327,42 @@ public class SimpleTaskExplorerTests { } 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 = taskExplorer.findAll(pageable); - int pagesExpected = (int) Math.ceil(totalNumberOfExecs / ((double) pageable.getPageSize())); - assertEquals("actual page count return was not the expected total", - pagesExpected, - taskPage.getTotalPages()); - assertEquals("actual element count was not the expected count", totalNumberOfExecs, - taskPage.getTotalElements()); + // 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") + .isEqualTo(pagesExpected); + assertThat(taskPage.getTotalElements()) + .as("actual element count was not the expected count") + .isEqualTo(totalNumberOfExecs); - //Verify pagination + // Verify pagination Pageable actualPageable = PageRequest.of(0, pageable.getPageSize()); boolean hasMorePages = taskPage.hasContent(); int pageNumber = 0; int elementCount = 0; while (hasMorePages) { - taskPage = taskExplorer.findAll(actualPageable); + taskPage = this.taskExplorer.findAll(actualPageable); hasMorePages = taskPage.hasNext(); List actualTaskExecutions = taskPage.getContent(); int expectedPageSize = pageable.getPageSize(); if (!hasMorePages && pageable.getPageSize() != actualTaskExecutions.size()) { expectedPageSize = totalNumberOfExecs % pageable.getPageSize(); } - assertEquals( - String.format("Element count on page did not match on the %n page", - pageNumber), expectedPageSize, actualTaskExecutions.size()); + assertThat(actualTaskExecutions.size()).as(String.format( + "Element count on page did not match on the %n page", pageNumber)) + .isEqualTo(expectedPageSize); for (TaskExecution actualExecution : actualTaskExecutions) { - assertEquals(String.format("Element on page %n did not match expected", - pageNumber), (long)expectedTaskExecutionIter.next(), - actualExecution.getExecutionId()); + assertThat(actualExecution.getExecutionId()) + .as(String.format("Element on page %n did not match expected", + pageNumber)) + .isEqualTo((long) expectedTaskExecutionIter.next()); TestVerifierUtils.verifyTaskExecution( expectedResults.get(actualExecution.getExecutionId()), actualExecution); @@ -358,9 +371,11 @@ public class SimpleTaskExplorerTests { actualPageable = taskPage.nextPageable(); pageNumber++; } - //Verify actual totals - assertEquals("Pages processed did not equal expected", pagesExpected, pageNumber); - assertEquals("Elements processed did not equal expected,", totalNumberOfExecs, elementCount); + // 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); } private TaskExecution createAndSaveTaskExecution(int i) { @@ -376,7 +391,7 @@ public class SimpleTaskExplorerTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - context.getAutowireCapableBeanFactory().autowireBeanProperties(this, + this.context.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); } @@ -386,11 +401,11 @@ public class SimpleTaskExplorerTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - context.getAutowireCapableBeanFactory().autowireBeanProperties(this, + this.context.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); } - private Map createSampleDataSet(int count){ + private Map createSampleDataSet(int count) { Map expectedResults = new HashMap<>(); for (int i = 0; i < count; i++) { TaskExecution expectedTaskExecution = createAndSaveTaskExecution(i); @@ -400,24 +415,25 @@ public class SimpleTaskExplorerTests { return expectedResults; } - private List getSortedOfTaskExecIds(Map taskExecutionMap){ + private List getSortedOfTaskExecIds(Map taskExecutionMap) { List sortedExecIds = new ArrayList<>(taskExecutionMap.size()); TreeSet sortedSet = getTreeSet(); sortedSet.addAll(taskExecutionMap.values()); - Iterator iterator = sortedSet.descendingIterator(); - while(iterator.hasNext()){ + Iterator iterator = sortedSet.descendingIterator(); + while (iterator.hasNext()) { sortedExecIds.add(iterator.next().getExecutionId()); } return sortedExecIds; } - private TreeSet getTreeSet(){ - return new TreeSet(new Comparator() { + private TreeSet getTreeSet() { + return new TreeSet<>(new Comparator() { @Override 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()); + if (result == 0) { + result = Long.valueOf(e1.getExecutionId()) + .compareTo(e2.getExecutionId()); } return result; } @@ -432,11 +448,20 @@ public class SimpleTaskExplorerTests { return taskExecution; } - private enum DaoType{jdbc, map} + private enum DaoType { + + jdbc, map + + } @Configuration - public static class DataSourceConfiguration{} + public static class DataSourceConfiguration { + + } @Configuration - public static class EmptyConfiguration{} + public static class EmptyConfiguration { + + } + } 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 25e9b6df..e661027b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.repository.support; import org.junit.Test; import org.springframework.context.support.GenericApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michael Minella @@ -34,7 +34,9 @@ public class SimpleTaskNameResolverTests { SimpleTaskNameResolver taskNameResolver = new SimpleTaskNameResolver(); taskNameResolver.setApplicationContext(context); - assertTrue(taskNameResolver.getTaskName().startsWith("org.springframework.context.support.GenericApplicationContext")); + assertThat(taskNameResolver.getTaskName().startsWith( + "org.springframework.context.support.GenericApplicationContext")) + .isTrue(); } @Test @@ -45,7 +47,7 @@ public class SimpleTaskNameResolverTests { SimpleTaskNameResolver taskNameResolver = new SimpleTaskNameResolver(); taskNameResolver.setApplicationContext(context); - assertTrue(taskNameResolver.getTaskName().startsWith("foo_bar")); + assertThat(taskNameResolver.getTaskName().startsWith("foo_bar")).isTrue(); } @Test @@ -56,7 +58,7 @@ public class SimpleTaskNameResolverTests { SimpleTaskNameResolver taskNameResolver = new SimpleTaskNameResolver(); taskNameResolver.setApplicationContext(context); - assertEquals("foo", taskNameResolver.getTaskName()); + assertThat(taskNameResolver.getTaskName()).isEqualTo("foo"); } @Test @@ -69,6 +71,7 @@ public class SimpleTaskNameResolverTests { taskNameResolver.setConfiguredName("bar"); - assertEquals("bar", taskNameResolver.getTaskName()); + assertThat(taskNameResolver.getTaskName()).isEqualTo("bar"); } + } 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 3d97c9f1..9e9dfc81 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for the SimpleTaskRepository that uses JDBC as a datastore. @@ -48,9 +48,8 @@ import static org.junit.Assert.assertEquals; * @author Ilayaperumal Gopinathan */ @RunWith(SpringRunner.class) -@ContextConfiguration(classes = {EmbeddedDataSourceConfiguration.class, - SimpleTaskAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class}) +@ContextConfiguration(classes = { EmbeddedDataSourceConfiguration.class, + SimpleTaskAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @DirtiesContext public class SimpleTaskRepositoryJdbcTests { @@ -63,47 +62,49 @@ public class SimpleTaskRepositoryJdbcTests { @Test @DirtiesContext public void testCreateEmptyExecution() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository); - TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(dataSource, - expectedTaskExecution.getExecutionId()); - TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - actualTaskExecution); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreEmptyTaskExecution(this.taskRepository); + TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB( + this.dataSource, expectedTaskExecution.getExecutionId()); + TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @Test @DirtiesContext public void testCreateTaskExecutionNoParam() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); - TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(dataSource, - expectedTaskExecution.getExecutionId()); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); + TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB( + this.dataSource, expectedTaskExecution.getExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @Test @DirtiesContext public void testCreateTaskExecutionWithParam() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionWithParams(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionWithParams(this.taskRepository); TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB( - dataSource, expectedTaskExecution.getExecutionId()); + this.dataSource, expectedTaskExecution.getExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @Test @DirtiesContext public void startTaskExecutionWithParam() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository); + 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(), + TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); + expectedTaskExecution.getArguments(), + expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @@ -111,66 +112,68 @@ public class SimpleTaskRepositoryJdbcTests { @Test @DirtiesContext public void startTaskExecutionWithNoParam() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreEmptyTaskExecution(this.taskRepository); expectedTaskExecution.setStartTime(new Date()); expectedTaskExecution.setTaskName(UUID.randomUUID().toString()); - TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(expectedTaskExecution.getExecutionId(), + TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); + expectedTaskExecution.getArguments(), + expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @Test public void testUpdateExternalExecutionId() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(UUID.randomUUID().toString()); - taskRepository.updateExternalExecutionId( + this.taskRepository.updateExternalExecutionId( expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(dataSource, + TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId())); } @Test public void testUpdateNullExternalExecutionId() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(null); - taskRepository.updateExternalExecutionId( + this.taskRepository.updateExternalExecutionId( expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - TestDBUtils.getTaskExecutionFromDB(dataSource, + TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId())); } @Test(expected = IllegalStateException.class) public void testInvalidExecutionIdForExternalExecutionIdUpdate() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(null); - taskRepository.updateExternalExecutionId( - -1, + this.taskRepository.updateExternalExecutionId(-1, expectedTaskExecution.getExternalExecutionId()); } @Test @DirtiesContext public void startTaskExecutionWithParent() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreEmptyTaskExecution(this.taskRepository); expectedTaskExecution.setStartTime(new Date()); expectedTaskExecution.setTaskName(UUID.randomUUID().toString()); expectedTaskExecution.setParentExecutionId(12345L); - TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(expectedTaskExecution.getExecutionId(), + TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId(), @@ -182,62 +185,79 @@ public class SimpleTaskRepositoryJdbcTests { @Test @DirtiesContext public void testCompleteTaskExecution() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(77); expectedTaskExecution.setExitMessage(UUID.randomUUID().toString()); - TaskExecution actualTaskExecution = TaskExecutionCreator.completeExecution(taskRepository, expectedTaskExecution); + TaskExecution actualTaskExecution = TaskExecutionCreator + .completeExecution(this.taskRepository, expectedTaskExecution); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @Test @DirtiesContext - public void testCreateTaskExecutionNoParamMaxExitDefaultMessageSize(){ - TaskExecution expectedTaskExecution = TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); - expectedTaskExecution.setExitMessage(new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE+1])); + public void testCreateTaskExecutionNoParamMaxExitDefaultMessageSize() { + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); + expectedTaskExecution.setExitMessage( + new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE + 1])); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(0); - TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, taskRepository); - assertEquals(SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE, actualTaskExecution.getExitMessage().length()); + TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, + this.taskRepository); + assertThat(actualTaskExecution.getExitMessage().length()) + .isEqualTo(SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE); } @Test public void testCreateTaskExecutionNoParamMaxExitMessageSize() { - SimpleTaskRepository simpleTaskRepository = new SimpleTaskRepository(new TaskExecutionDaoFactoryBean(this.dataSource)); + SimpleTaskRepository simpleTaskRepository = new SimpleTaskRepository( + new TaskExecutionDaoFactoryBean(this.dataSource)); simpleTaskRepository.setMaxExitMessageSize(5); - TaskExecution expectedTaskExecution = TaskExecutionCreator.createAndStoreTaskExecutionNoParams(simpleTaskRepository); - expectedTaskExecution.setExitMessage(new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE + 1])); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(simpleTaskRepository); + expectedTaskExecution.setExitMessage( + new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE + 1])); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(0); - TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, simpleTaskRepository); - assertEquals(5, actualTaskExecution.getExitMessage().length()); + TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, + simpleTaskRepository); + assertThat(actualTaskExecution.getExitMessage().length()).isEqualTo(5); } @Test @DirtiesContext - public void testCreateTaskExecutionNoParamMaxErrorDefaultMessageSize(){ - TaskExecution expectedTaskExecution = TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); - expectedTaskExecution.setErrorMessage(new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE+1])); + public void testCreateTaskExecutionNoParamMaxErrorDefaultMessageSize() { + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); + expectedTaskExecution.setErrorMessage( + new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE + 1])); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(0); - TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, taskRepository); - assertEquals(SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE, actualTaskExecution.getErrorMessage().length()); + TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, + this.taskRepository); + assertThat(actualTaskExecution.getErrorMessage().length()) + .isEqualTo(SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE); } @Test public void testCreateTaskExecutionNoParamMaxErrorMessageSize() { - SimpleTaskRepository simpleTaskRepository = new SimpleTaskRepository(new TaskExecutionDaoFactoryBean(this.dataSource)); + SimpleTaskRepository simpleTaskRepository = new SimpleTaskRepository( + new TaskExecutionDaoFactoryBean(this.dataSource)); simpleTaskRepository.setMaxErrorMessageSize(5); - TaskExecution expectedTaskExecution = TaskExecutionCreator.createAndStoreTaskExecutionNoParams(simpleTaskRepository); - expectedTaskExecution.setErrorMessage(new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE + 1])); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(simpleTaskRepository); + expectedTaskExecution.setErrorMessage( + new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE + 1])); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(0); - TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, simpleTaskRepository); - assertEquals(5, actualTaskExecution.getErrorMessage().length()); + TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, + simpleTaskRepository); + assertThat(actualTaskExecution.getErrorMessage().length()).isEqualTo(5); } @Test(expected = IllegalArgumentException.class) @@ -246,9 +266,10 @@ 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])); simpleTaskRepository.createTaskExecution(expectedTaskExecution); } @@ -257,8 +278,10 @@ 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])); simpleTaskRepository.createTaskExecution(expectedTaskExecution); } @@ -267,9 +290,10 @@ 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 @@ -280,54 +304,63 @@ public class SimpleTaskRepositoryJdbcTests { SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE, simpleTaskRepository); } - @Test(expected=IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) @DirtiesContext - public void testCreateTaskExecutionNoParamMaxTaskName(){ + public void testCreateTaskExecutionNoParamMaxTaskName() { TaskExecution taskExecution = new TaskExecution(); taskExecution.setTaskName( - new String(new char[SimpleTaskRepository.MAX_TASK_NAME_SIZE+1])); + new String(new char[SimpleTaskRepository.MAX_TASK_NAME_SIZE + 1])); taskExecution.setStartTime(new Date()); - taskRepository.createTaskExecution(taskExecution); + this.taskRepository.createTaskExecution(taskExecution); } - @Test(expected=IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) @DirtiesContext - public void testCreateTaskExecutionNegativeException(){ - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + public void testCreateTaskExecutionNegativeException() { + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(-1); - TaskExecution actualTaskExecution = TaskExecutionCreator.completeExecution(taskRepository, expectedTaskExecution); + TaskExecution actualTaskExecution = TaskExecutionCreator + .completeExecution(this.taskRepository, expectedTaskExecution); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } - @Test(expected=IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) @DirtiesContext - public void testCreateTaskExecutionNullEndTime(){ - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + public void testCreateTaskExecutionNullEndTime() { + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExitCode(-1); - TaskExecutionCreator.completeExecution(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(), expectedTaskExecution.getErrorMessage()); - } - - private void verifyTaskRepositoryConstructor(Integer maxExitMessage, Integer maxErrorMessage, + private TaskExecution completeTaskExecution(TaskExecution expectedTaskExecution, TaskRepository taskRepository) { - TaskExecution expectedTaskExecution = TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); - expectedTaskExecution.setErrorMessage(new String(new char[maxErrorMessage+ 1])); + 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); + 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); - assertEquals(maxErrorMessage.intValue(), actualTaskExecution.getErrorMessage().length()); - assertEquals(maxExitMessage.intValue(), actualTaskExecution.getExitMessage().length()); + 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 7c049787..9a81f64f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,72 +49,78 @@ public class SimpleTaskRepositoryMapTests { @Test public void testCreateEmptyExecution() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreEmptyTaskExecution(this.taskRepository); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId())); + getSingleTaskExecutionFromMapRepository( + expectedTaskExecution.getExecutionId())); } @Test public void testCreateTaskExecutionNoParam() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId())); + getSingleTaskExecutionFromMapRepository( + expectedTaskExecution.getExecutionId())); } @Test public void testUpdateExternalExecutionId() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(UUID.randomUUID().toString()); - taskRepository.updateExternalExecutionId( + this.taskRepository.updateExternalExecutionId( expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId())); + getSingleTaskExecutionFromMapRepository( + expectedTaskExecution.getExecutionId())); } @Test public void testUpdateNullExternalExecutionId() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(null); - taskRepository.updateExternalExecutionId( + this.taskRepository.updateExternalExecutionId( expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId())); + getSingleTaskExecutionFromMapRepository( + expectedTaskExecution.getExecutionId())); } @Test(expected = IllegalArgumentException.class) public void testInvalidExecutionIdForExternalExecutionIdUpdate() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExternalExecutionId(null); - taskRepository.updateExternalExecutionId( - -1, + this.taskRepository.updateExternalExecutionId(-1, expectedTaskExecution.getExternalExecutionId()); } @Test public void testCreateTaskExecutionWithParam() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionWithParams(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionWithParams(this.taskRepository); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, - getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId())); + getSingleTaskExecutionFromMapRepository( + expectedTaskExecution.getExecutionId())); } @Test public void startTaskExecutionWithParam() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository); + 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(), + TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId(), @@ -125,59 +131,65 @@ public class SimpleTaskRepositoryMapTests { @Test public void startTaskExecutionWithNoParam() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreEmptyTaskExecution(this.taskRepository); expectedTaskExecution.setStartTime(new Date()); expectedTaskExecution.setTaskName(UUID.randomUUID().toString()); - TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(expectedTaskExecution.getExecutionId(), + TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); + expectedTaskExecution.getArguments(), + expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } - @Test public void startTaskExecutionWithParent() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreEmptyTaskExecution(this.taskRepository); expectedTaskExecution.setStartTime(new Date()); expectedTaskExecution.setTaskName(UUID.randomUUID().toString()); expectedTaskExecution.setParentExecutionId(12345L); - TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(expectedTaskExecution.getExecutionId(), + TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution( + expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), - expectedTaskExecution.getArguments(), expectedTaskExecution.getExternalExecutionId()); + expectedTaskExecution.getArguments(), + expectedTaskExecution.getExternalExecutionId()); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } @Test public void testCompleteTaskExecution() { - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setEndTime(new Date()); expectedTaskExecution.setExitCode(0); - TaskExecution actualTaskExecution = TaskExecutionCreator.completeExecution(taskRepository, expectedTaskExecution); + TaskExecution actualTaskExecution = TaskExecutionCreator + .completeExecution(this.taskRepository, expectedTaskExecution); TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution); } - private TaskExecution getSingleTaskExecutionFromMapRepository(long taskExecutionId){ - Map taskMap = ((MapTaskExecutionDao) - ((SimpleTaskRepository)taskRepository).getTaskExecutionDao()).getTaskExecutions(); + private TaskExecution getSingleTaskExecutionFromMapRepository(long taskExecutionId) { + Map taskMap = ((MapTaskExecutionDao) ((SimpleTaskRepository) this.taskRepository) + .getTaskExecutionDao()).getTaskExecutions(); assertTrue("taskExecutionId must be in MapTaskExecutionRepository", taskMap.containsKey(taskExecutionId)); return taskMap.get(taskExecutionId); } - @Test(expected=IllegalArgumentException.class) - public void testCreateTaskExecutionNullEndTime(){ - TaskExecution expectedTaskExecution = - TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository); + @Test(expected = IllegalArgumentException.class) + public void testCreateTaskExecutionNullEndTime() { + TaskExecution expectedTaskExecution = TaskExecutionCreator + .createAndStoreTaskExecutionNoParams(this.taskRepository); expectedTaskExecution.setExitCode(-1); - TaskExecutionCreator.completeExecution(taskRepository, expectedTaskExecution); + TaskExecutionCreator.completeExecution(this.taskRepository, + expectedTaskExecution); } + } 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 728b7856..74ab4977 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,9 +33,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -44,11 +42,12 @@ import static org.mockito.Mockito.mock; * @author Glenn Renfro */ public class TaskDatabaseInitializerTests { - private AnnotationConfigApplicationContext context; @Rule public ExpectedException expected = ExpectedException.none(); + private AnnotationConfigApplicationContext context; + @After public void close() { if (this.context != null) { @@ -59,21 +58,23 @@ public class TaskDatabaseInitializerTests { @Test public void testDefaultContext() { this.context = new AnnotationConfigApplicationContext(); - this.context.register( TestConfiguration.class, + this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals(0, new JdbcTemplate(this.context.getBean(DataSource.class)) - .queryForList("select * from TASK_EXECUTION").size()); + 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(), instanceOf(MapTaskExecutionDao.class)); + SimpleTaskRepository repository = new SimpleTaskRepository( + new TaskExecutionDaoFactoryBean()); + assertThat(repository.getTaskExecutionDao()) + .isInstanceOf(MapTaskExecutionDao.class); MapTaskExecutionDao dao = (MapTaskExecutionDao) repository.getTaskExecutionDao(); - assertEquals(0, dao.getTaskExecutions().size()); + assertThat(dao.getTaskExecutions().size()).isEqualTo(0); } @Test @@ -83,20 +84,24 @@ public class TaskDatabaseInitializerTests { EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals(0, this.context.getBeanNamesForType(SimpleTaskRepository.class).length); + assertThat(this.context.getBeanNamesForType(SimpleTaskRepository.class).length) + .isEqualTo(0); } @Test(expected = BeanCreationException.class) public void testMultipleDataSourcesContext() { this.context = new AnnotationConfigApplicationContext(); - this.context.register( SimpleTaskAutoConfiguration.class, + this.context.register(SimpleTaskAutoConfiguration.class, EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class); DataSource dataSource = mock(DataSource.class); - context.getBeanFactory().registerSingleton("mockDataSource", dataSource); + this.context.getBeanFactory().registerSingleton("mockDataSource", dataSource); this.context.refresh(); } @Configuration - public static class EmptyConfiguration {} + public static class EmptyConfiguration { + + } + } 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 0794f1c4..f8a2842c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.repository.support; import javax.sql.DataSource; @@ -31,8 +32,7 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.test.util.ReflectionTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michael Minella @@ -43,19 +43,20 @@ public class TaskExecutionDaoFactoryBeanTests { @After public void tearDown() { - if(this.context != null) { + if (this.context != null) { this.context.close(); } } @Test public void testGetObjectType() { - assertEquals(new TaskExecutionDaoFactoryBean().getObjectType(), TaskExecutionDao.class); + assertThat(TaskExecutionDao.class) + .isEqualTo(new TaskExecutionDaoFactoryBean().getObjectType()); } @Test public void testIsSingleton() { - assertTrue(new TaskExecutionDaoFactoryBean().isSingleton()); + assertThat(new TaskExecutionDaoFactoryBean().isSingleton()).isTrue(); } @Test(expected = IllegalArgumentException.class) @@ -63,46 +64,49 @@ public class TaskExecutionDaoFactoryBeanTests { new TaskExecutionDaoFactoryBean(null); } - @Test public void testMapTaskExecutionDaoWithoutAppContext() throws Exception { TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean(); TaskExecutionDao taskExecutionDao = factoryBean.getObject(); - assertTrue(taskExecutionDao instanceof MapTaskExecutionDao); + assertThat(taskExecutionDao instanceof MapTaskExecutionDao).isTrue(); TaskExecutionDao taskExecutionDao2 = factoryBean.getObject(); - assertTrue(taskExecutionDao == taskExecutionDao2); + assertThat(taskExecutionDao == taskExecutionDao2).isTrue(); } @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(); - assertTrue(taskExecutionDao instanceof JdbcTaskExecutionDao); + assertThat(taskExecutionDao instanceof JdbcTaskExecutionDao).isTrue(); TaskExecutionDao taskExecutionDao2 = factoryBean.getObject(); - assertTrue(taskExecutionDao == taskExecutionDao2); + assertThat(taskExecutionDao == taskExecutionDao2).isTrue(); } - @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(); - assertEquals("foo_", ReflectionTestUtils.getField(taskExecutionDao, "tablePrefix")); + assertThat(ReflectionTestUtils.getField(taskExecutionDao, "tablePrefix")) + .isEqualTo("foo_"); } @Configuration @@ -110,8 +114,11 @@ 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 507cb487..6f3a93da 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,34 +32,35 @@ public class TaskExecutionCreator { /** * Creates a sample TaskExecution and stores it in the taskRepository. - * * @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(); } /** * Creates a sample TaskExecution and stores it in the taskRepository. - * * @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; } /** * Creates a sample TaskExecution and stores it in the taskRepository with params. - * * @param taskRepository the taskRepository where the taskExecution should be stored. * @return the taskExecution created. */ - public static TaskExecution createAndStoreTaskExecutionWithParams(TaskRepository taskRepository) { - TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg(); - List params = new ArrayList(); + public static TaskExecution createAndStoreTaskExecutionWithParams( + TaskRepository taskRepository) { + TaskExecution expectedTaskExecution = TestVerifierUtils + .createSampleTaskExecutionNoArg(); + List params = new ArrayList<>(); params.add(UUID.randomUUID().toString()); params.add(UUID.randomUUID().toString()); expectedTaskExecution.setArguments(params); @@ -69,14 +70,16 @@ public class TaskExecutionCreator { /** * Updates a sample TaskExecution in the taskRepository. - * * @param taskRepository the taskRepository where the taskExecution should be updated. * @return the taskExecution created. */ public static TaskExecution completeExecution(TaskRepository taskRepository, TaskExecution expectedTaskExecution) { - return taskRepository.completeTaskExecution(expectedTaskExecution.getExecutionId(), + 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 76205564..09ff1b4d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; + import javax.sql.DataSource; import org.springframework.batch.item.database.Order; @@ -40,7 +41,7 @@ import org.springframework.jdbc.support.MetaDataAccessException; import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -60,28 +61,29 @@ public class TestDBUtils { * @return taskExecution retrieved from the database. */ public static TaskExecution getTaskExecutionFromDB(DataSource dataSource, - long taskExecutionId) { - String sql = "SELECT * FROM TASK_EXECUTION WHERE " - + "TASK_EXECUTION_ID = '" + 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; - } - }); - assertEquals("only one row should be returned", 1, rows.size()); + 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); populateParamsToDB(dataSource, taskExecution); @@ -92,21 +94,23 @@ public class TestDBUtils { * Create a pagingQueryProvider specific database type with a findAll. * @param databaseProductName of the database. * @return a PagingQueryPovider that will return all the requested information. - * @throws Exception + * @throws Exception exception */ - public static PagingQueryProvider getPagingQueryProvider(String databaseProductName) throws Exception{ + public static PagingQueryProvider getPagingQueryProvider(String databaseProductName) + throws Exception { return getPagingQueryProvider(databaseProductName, null); } /** - * Create a pagingQueryProvider specific database type with a query containing a where clause. + * Create a pagingQueryProvider specific database type with a query containing a where + * clause. * @param databaseProductName of the database. - * @param whereClause to be applied to the query. + * @param whereClause to be applied to the query. * @return a PagingQueryProvider that will return the requested information. - * @throws Exception + * @throws Exception exception */ public static PagingQueryProvider getPagingQueryProvider(String databaseProductName, - String whereClause) throws Exception{ + String whereClause) throws Exception { DataSource dataSource = getMockDataSource(databaseProductName); Map orderMap = new TreeMap<>(); orderMap.put("START_TIME", Order.DESCENDING); @@ -114,7 +118,7 @@ public class TestDBUtils { SqlPagingQueryProviderFactoryBean factoryBean = new SqlPagingQueryProviderFactoryBean(); factoryBean.setSelectClause(JdbcTaskExecutionDao.SELECT_CLAUSE); factoryBean.setFromClause(JdbcTaskExecutionDao.FROM_CLAUSE); - if(whereClause != null){ + if (whereClause != null) { factoryBean.setWhereClause(whereClause); } factoryBean.setSortKeys(orderMap); @@ -134,9 +138,10 @@ public class TestDBUtils { * Creates a mock DataSource for use in testing. * @param databaseProductName the name of the database type to mock. * @return a mock DataSource. - * @throws Exception + * @throws Exception exception */ - 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); @@ -148,12 +153,13 @@ public class TestDBUtils { /** * Creates a incrementer for the DataSource. - * @param dataSource the datasource that the incrementer will use to record current id. + * @param dataSource the datasource that the incrementer will use to record current + * id. * @return a DataFieldMaxValueIncrementer object. */ - public static DataFieldMaxValueIncrementer getIncrementer(DataSource dataSource){ - DataFieldMaxValueIncrementerFactory incrementerFactory = - new DefaultDataFieldMaxValueIncrementerFactory(dataSource); + public static DataFieldMaxValueIncrementer getIncrementer(DataSource dataSource) { + DataFieldMaxValueIncrementerFactory incrementerFactory = new DefaultDataFieldMaxValueIncrementerFactory( + dataSource); String databaseType = null; try { databaseType = DatabaseType.fromMetaData(dataSource).name(); @@ -161,11 +167,11 @@ public class TestDBUtils { catch (MetaDataAccessException e) { throw new IllegalStateException(e); } - return incrementerFactory.getIncrementer(databaseType, - "TASK_SEQ"); + return incrementerFactory.getIncrementer(databaseType, "TASK_SEQ"); } - private static void populateParamsToDB(DataSource dataSource, TaskExecution taskExecution) { + private static void populateParamsToDB(DataSource dataSource, + TaskExecution taskExecution) { String sql = "SELECT * FROM TASK_EXECUTION_PARAMS WHERE TASK_EXECUTION_ID = '" + taskExecution.getExecutionId() + "'"; @@ -177,4 +183,5 @@ public class TestDBUtils { } taskExecution.setArguments(arguments); } + } 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 a92fb9ea..aaa05bdc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,11 +46,11 @@ import org.springframework.context.annotation.Configuration; @EnableConfigurationProperties(TaskProperties.class) public class TestDefaultConfiguration implements InitializingBean { - private TaskExecutionDaoFactoryBean factoryBean; - @Autowired TaskProperties taskProperties; + private TaskExecutionDaoFactoryBean factoryBean; + @Autowired(required = false) private ApplicationArguments applicationArguments; @@ -61,7 +61,7 @@ public class TestDefaultConfiguration implements InitializingBean { } @Bean - public TaskRepository taskRepository(){ + public TaskRepository taskRepository() { return new SimpleTaskRepository(this.factoryBean); } @@ -76,19 +76,21 @@ public class TestDefaultConfiguration implements InitializingBean { } @Bean - public TaskListenerExecutorObjectFactory taskListenerExecutorObjectProvider(ConfigurableApplicationContext context) { + public TaskListenerExecutorObjectFactory taskListenerExecutorObjectProvider( + ConfigurableApplicationContext context) { return new TaskListenerExecutorObjectFactory(context); } @Bean - public TaskLifecycleListener taskHandler(TaskExplorer taskExplorer){ + public TaskLifecycleListener taskHandler(TaskExplorer taskExplorer) { return new TaskLifecycleListener(taskRepository(), taskNameResolver(), - applicationArguments, taskExplorer, taskProperties, taskListenerExecutorObjectProvider(context)); + this.applicationArguments, taskExplorer, this.taskProperties, + taskListenerExecutorObjectProvider(this.context)); } @Override public void afterPropertiesSet() throws Exception { - if(this.context.getBeanNamesForType(DataSource.class).length == 1){ + if (this.context.getBeanNamesForType(DataSource.class).length == 1) { DataSource dataSource = this.context.getBean(DataSource.class); this.factoryBean = new TaskExecutionDaoFactoryBean(dataSource); } @@ -96,4 +98,5 @@ public class TestDefaultConfiguration implements InitializingBean { this.factoryBean = new TaskExecutionDaoFactoryBean(); } } + } diff --git a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestListener.java b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestListener.java index 8062026f..76e53cb2 100644 --- a/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestListener.java +++ b/spring-cloud-task-core/src/test/java/org/springframework/cloud/task/util/TestListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,20 +19,26 @@ package org.springframework.cloud.task.util; import org.springframework.cloud.task.repository.TaskExecution; /** - * Provides the basic infrastructure for evaluating if task listener performed - * properly. + * Provides the basic infrastructure for evaluating if task listener performed properly. * * @author Glenn Renfro */ public abstract class TestListener { + public static final String START_MESSAGE = "FOO"; + public static final String ERROR_MESSAGE = "BAR"; + public static final String END_MESSAGE = "BAZ"; protected boolean isTaskStartup; + protected boolean isTaskEnd; + protected boolean isTaskFailed; + protected TaskExecution taskExecution; + protected Throwable throwable; /** @@ -40,15 +46,15 @@ public abstract class TestListener { * @return true if task listener was called during task creation, else false. */ public boolean isTaskStartup() { - return isTaskStartup; + return this.isTaskStartup; } /** * Indicates if the task listener was called during task end. - * @return true if the task listener was called during task end, else false. + * @return true if the task listener was called during task end, else false. */ public boolean isTaskEnd() { - return isTaskEnd; + return this.isTaskEnd; } /** @@ -56,20 +62,21 @@ public abstract class TestListener { * @return true if task listener was called during task failure, else false. */ public boolean isTaskFailed() { - return isTaskFailed; + return this.isTaskFailed; } /** * Task Execution that was updated during listener call. */ public TaskExecution getTaskExecution() { - return taskExecution; + return this.taskExecution; } /** * The throwable that was sent with the task if task failed. */ public Throwable getThrowable() { - return throwable; + return this.throwable; } + } 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 c6424daf..a6267e35 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,17 +31,14 @@ import org.slf4j.LoggerFactory; import org.springframework.cloud.task.repository.TaskExecution; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** - * Offers utils to test the results produced by the code being tested. + * Offers utils to test the results produced by the code being tested. * * @author Glenn Renfro */ @@ -51,11 +48,11 @@ public class TestVerifierUtils { /** * Creates a mock {@link Appender} to be added to the root logger. - * * @return reference to the mock appender. */ public static Appender getMockAppender() { - ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory + .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); final Appender mockAppender = mock(Appender.class); when(mockAppender.getName()).thenReturn("MOCK"); root.addAppender(mockAppender); @@ -63,24 +60,24 @@ public class TestVerifierUtils { } /** - * Verifies that the log sample is contained within the content that was written - * to the mock appender. - * + * Verifies that the log sample is contained within the content that was written to + * the mock appender. * @param mockAppender The appender that is associated with the test. - * @param logSample The string to search for in the log entry. + * @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); } })); } /** * Creates a fully populated TaskExecution (except args) for testing. - * * @return */ public static TaskExecution createSampleTaskExecutionNoArg() { @@ -89,13 +86,12 @@ public 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); } /** * Creates a fully populated TaskExecution (except args) for testing. - * * @return */ public static TaskExecution endSampleTaskExecutionNoArg() { @@ -107,13 +103,12 @@ public 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); } /** * Creates a fully populated TaskExecution for testing. - * * @return */ public static TaskExecution createSampleTaskExecution(long executionId) { @@ -121,66 +116,65 @@ public class TestVerifierUtils { String taskName = UUID.randomUUID().toString(); String externalExecutionId = UUID.randomUUID().toString(); List args = new ArrayList<>(ARG_SIZE); - for (int i = 0; i < ARG_SIZE; i++){ + 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); } /** * Verifies that all the fields in between the expected and actual are the same; - * * @param expectedTaskExecution The expected value for the task execution. - * @param actualTaskExecution The actual value for the task execution. + * @param actualTaskExecution The actual value for the task execution. */ public static void verifyTaskExecution(TaskExecution expectedTaskExecution, - TaskExecution actualTaskExecution) { - assertEquals("taskExecutionId must be equal", expectedTaskExecution.getExecutionId(), - actualTaskExecution.getExecutionId()); - assertEquals("startTime must be equal", - expectedTaskExecution.getStartTime(), - actualTaskExecution.getStartTime()); - assertEquals("endTime must be equal", - expectedTaskExecution.getEndTime(), - actualTaskExecution.getEndTime()); - assertEquals("exitCode must be equal", - expectedTaskExecution.getExitCode(), - actualTaskExecution.getExitCode()); - assertEquals("taskName must be equal", - expectedTaskExecution.getTaskName(), - actualTaskExecution.getTaskName()); - assertEquals("exitMessage must be equal", - expectedTaskExecution.getExitMessage(), - actualTaskExecution.getExitMessage()); - assertEquals("errorMessage must be equal", - expectedTaskExecution.getErrorMessage(), - actualTaskExecution.getErrorMessage()); - assertEquals("externalExecutionId must be equal", - expectedTaskExecution.getExternalExecutionId(), - actualTaskExecution.getExternalExecutionId()); - assertEquals("parentExecutionId must be equal", - expectedTaskExecution.getParentExecutionId(), - actualTaskExecution.getParentExecutionId()); + 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") + .hasSameTimeAs(expectedTaskExecution.getStartTime()); + } + if (actualTaskExecution.getEndTime() != null) { + assertThat(actualTaskExecution.getEndTime()).as("endTime must be equal") + .hasSameTimeAs(expectedTaskExecution.getEndTime()); + } + assertThat(actualTaskExecution.getExitCode()).as("exitCode must be equal") + .isEqualTo(expectedTaskExecution.getExitCode()); + assertThat(actualTaskExecution.getTaskName()).as("taskName must be equal") + .isEqualTo(expectedTaskExecution.getTaskName()); + assertThat(actualTaskExecution.getExitMessage()).as("exitMessage must be equal") + .isEqualTo(expectedTaskExecution.getExitMessage()); + assertThat(actualTaskExecution.getErrorMessage()).as("errorMessage must be equal") + .isEqualTo(expectedTaskExecution.getErrorMessage()); + assertThat(actualTaskExecution.getExternalExecutionId()) + .as("externalExecutionId must be equal") + .isEqualTo(expectedTaskExecution.getExternalExecutionId()); + assertThat(actualTaskExecution.getParentExecutionId()) + .as("parentExecutionId must be equal") + .isEqualTo(expectedTaskExecution.getParentExecutionId()); if (expectedTaskExecution.getArguments() != null) { - assertNotNull("arguments should not be null", - actualTaskExecution.getArguments()); - assertEquals("arguments result set count should match expected count", - expectedTaskExecution.getArguments().size(), - actualTaskExecution.getArguments().size()); + 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 { - assertNull("arguments should be null", actualTaskExecution.getArguments()); + assertThat(actualTaskExecution.getArguments()).as("arguments should be null") + .isNull(); } - Set args = new HashSet(); + Set args = new HashSet<>(); for (String param : expectedTaskExecution.getArguments()) { args.add(param); } for (String arg : actualTaskExecution.getArguments()) { - assertTrue("arg must exist in the repository", args.contains(arg)); + assertThat(args.contains(arg)).as("arg must exist in the repository") + .isTrue(); } } - } diff --git a/spring-cloud-task-dependencies/pom.xml b/spring-cloud-task-dependencies/pom.xml index 8bd543a1..543ec9e4 100644 --- a/spring-cloud-task-dependencies/pom.xml +++ b/spring-cloud-task-dependencies/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 spring-cloud-task-dependencies 2.1.0.BUILD-SNAPSHOT @@ -11,7 +13,7 @@ spring-cloud-dependencies-parent org.springframework.cloud 2.1.1.RELEASE - + diff --git a/spring-cloud-task-docs/pom.xml b/spring-cloud-task-docs/pom.xml index 8eaf32b3..3dbd17bf 100644 --- a/spring-cloud-task-docs/pom.xml +++ b/spring-cloud-task-docs/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 org.springframework.cloud @@ -33,14 +35,19 @@ - ${project.build.directory}/external-resources - src/main/xslt/dependencyVersions.xsl + ${project.build.directory}/external-resources + + src/main/xslt/dependencyVersions.xsl + - + .adoc - ${project.build.directory}/generated-resources + + ${project.build.directory}/generated-resources + @@ -71,11 +78,17 @@ book true - ${project.version} - ${project.version} - ${spring-boot-repo} - ${spring.version} - ${spring-security.version} + ${project.version} + + ${project.version} + + ${spring-boot-repo} + + ${spring.version} + + + ${spring-security.version} + true ${github-tag} @@ -88,14 +101,18 @@ docbkx-maven-plugin 2.0.15 - ${basedir}/target/generated-docs + ${basedir}/target/generated-docs + index.xml true false - ${basedir}/src/main/docbook/xsl/pdf.xsl + ${basedir}/src/main/docbook/xsl/pdf.xsl + 1 1 - ${basedir}/src/main/docbook/xsl/xslthl-config.xml + + ${basedir}/src/main/docbook/xsl/xslthl-config.xml + @@ -120,20 +137,27 @@ prepare-package - ${basedir}/src/main/docbook/xsl/html-singlepage.xsl - ${basedir}/target/docbook/htmlsingle + + ${basedir}/src/main/docbook/xsl/html-singlepage.xsl + + + ${basedir}/target/docbook/htmlsingle + - - - + + + - + - - - - + + + + @@ -146,21 +170,26 @@ prepare-package - ${basedir}/src/main/docbook/xsl/html-multipage.xsl - ${basedir}/target/docbook/html + + ${basedir}/src/main/docbook/xsl/html-multipage.xsl + + ${basedir}/target/docbook/html + true - + - + - + - - - - + + + + @@ -173,15 +202,21 @@ prepare-package - ${basedir}/src/main/docbook/xsl/pdf.xsl - ${basedir}/target/docbook/pdf + + ${basedir}/src/main/docbook/xsl/pdf.xsl + + ${basedir}/target/docbook/pdf + - + - + - + @@ -192,15 +227,21 @@ prepare-package - ${basedir}/src/main/docbook/xsl/epub.xsl - ${basedir}/target/docbook/epub + + ${basedir}/src/main/docbook/xsl/epub.xsl + + ${basedir}/target/docbook/epub + - + - + - + @@ -241,8 +282,10 @@ - - + + @@ -256,18 +299,42 @@ true - - - - - - - - - + + + + + + + + + - - + + @@ -282,7 +349,8 @@ false - src/main/assembly/assemble.xml + src/main/assembly/assemble.xml + false @@ -304,8 +372,11 @@ - ${project.build.directory}/${project.artifactId}-${project.version}.zip - zip;zip.type=docs;zip.deployed=false + + ${project.build.directory}/${project.artifactId}-${project.version}.zip + + zip;zip.type=docs;zip.deployed=false + diff --git a/spring-cloud-task-docs/src/main/asciidoc/Guardfile b/spring-cloud-task-docs/src/main/asciidoc/Guardfile index bdd4d729..bf9950e4 100644 --- a/spring-cloud-task-docs/src/main/asciidoc/Guardfile +++ b/spring-cloud-task-docs/src/main/asciidoc/Guardfile @@ -4,14 +4,14 @@ require 'erb' guard 'shell' do watch(/.*\.adoc$/) {|m| Asciidoctor.render_file('index.adoc', \ - :in_place => true, \ - :safe => Asciidoctor::SafeMode::UNSAFE, \ - :attributes=> { \ - 'source-highlighter' => 'prettify', \ - 'icons' => 'font', \ - 'linkcss'=> 'true', \ - 'copycss' => 'true', \ - 'doctype' => 'book'}) + :in_place => true, \ + :safe => Asciidoctor::SafeMode::UNSAFE, \ + :attributes => {\ + 'source-highlighter' => 'prettify', \ + 'icons' => 'font', \ + 'linkcss' => 'true', \ + 'copycss' => 'true', \ + 'doctype' => 'book'}) } end diff --git a/spring-cloud-task-docs/src/main/asciidoc/index-docinfo.xml b/spring-cloud-task-docs/src/main/asciidoc/index-docinfo.xml index 1fe15d99..45d96981 100644 --- a/spring-cloud-task-docs/src/main/asciidoc/index-docinfo.xml +++ b/spring-cloud-task-docs/src/main/asciidoc/index-docinfo.xml @@ -1,14 +1,14 @@ Spring Cloud Task {spring-boot-version} - 2015-2017 - Pivotal Software, Inc. +2015-2019 +Pivotal Software, Inc. - - Copies of this document may be made for your own use and for distribution to - others, provided that you do not charge any fee for such copies and further - provided that each copy contains this Copyright Notice, whether distributed in - print or electronically. - + + Copies of this document may be made for your own use and for distribution to + others, provided that you do not charge any fee for such copies and further + provided that each copy contains this Copyright Notice, whether distributed in + print or electronically. + diff --git a/spring-cloud-task-docs/src/main/docbook/css/highlight.css b/spring-cloud-task-docs/src/main/docbook/css/highlight.css index ffefef72..1acf9c44 100644 --- a/spring-cloud-task-docs/src/main/docbook/css/highlight.css +++ b/spring-cloud-task-docs/src/main/docbook/css/highlight.css @@ -4,32 +4,32 @@ */ .hl-keyword { - color: #7F0055; - font-weight: bold; + color: #7F0055; + font-weight: bold; } .hl-comment { - color: #3F5F5F; - font-style: italic; + color: #3F5F5F; + font-style: italic; } .hl-multiline-comment { - color: #3F5FBF; - font-style: italic; + color: #3F5FBF; + font-style: italic; } .hl-tag { - color: #3F7F7F; + color: #3F7F7F; } .hl-attribute { - color: #7F007F; + color: #7F007F; } .hl-value { - color: #2A00FF; + color: #2A00FF; } .hl-string { - color: #2A00FF; -} \ No newline at end of file + color: #2A00FF; +} diff --git a/spring-cloud-task-docs/src/main/docbook/css/manual-multipage.css b/spring-cloud-task-docs/src/main/docbook/css/manual-multipage.css index 0c484531..8e5281d5 100644 --- a/spring-cloud-task-docs/src/main/docbook/css/manual-multipage.css +++ b/spring-cloud-task-docs/src/main/docbook/css/manual-multipage.css @@ -5,5 +5,5 @@ body.firstpage { } div.part h1 { - border-top: none; + border-top: none; } diff --git a/spring-cloud-task-docs/src/main/docbook/css/manual.css b/spring-cloud-task-docs/src/main/docbook/css/manual.css index 0ecbe2e8..7a1fe13a 100644 --- a/spring-cloud-task-docs/src/main/docbook/css/manual.css +++ b/spring-cloud-task-docs/src/main/docbook/css/manual.css @@ -18,11 +18,11 @@ code { font-family: Consolas, "Liberation Mono", Courier, monospace; } -:not(a)>code { +:not(a) > code { color: #6D180B; } -:not(pre)>code { +:not(pre) > code { background-color: #F2F2F2; border: 1px solid #CCCCCC; border-radius: 4px; @@ -31,7 +31,7 @@ code { white-space: nowrap; } -body>*:first-child { +body > *:first-child { margin-top: 0 !important; } @@ -44,7 +44,7 @@ hr { background: #CCCCCC; } -h1,h2,h3,h4,h5,h6 { +h1, h2, h3, h4, h5, h6 { color: #000000; cursor: text; font-weight: bold; @@ -52,7 +52,7 @@ h1,h2,h3,h4,h5,h6 { padding: 0; } -h1,h2,h3 { +h1, h2, h3 { margin: 40px 0 10px; } @@ -65,23 +65,23 @@ div.part h1 { border-top: 1px dotted #CCCCCC; } -h1,h1 code { +h1, h1 code { font-size: 32px; } -h2,h2 code { +h2, h2 code { font-size: 24px; } -h3,h3 code { +h3, h3 code { font-size: 20px; } -h4,h1 code,h5,h5 code,h6,h6 code { +h4, h1 code, h5, h5 code, h6, h6 code { font-size: 18px; } -div.book,div.chapter,div.appendix,div.part,div.preface { +div.book, div.chapter, div.appendix, div.part, div.preface { min-width: 300px; max-width: 1200px; margin: 0 auto; @@ -108,7 +108,7 @@ p.copyright { line-height: 1; } -div.titlepage+p,div.titlepage+p { +div.titlepage + p, div.titlepage + p { margin-top: 0; } @@ -127,7 +127,7 @@ p { text-align: left; } -ul,ol { +ul, ol { padding-left: 30px; } @@ -141,7 +141,7 @@ div.table { text-align: center; } -div.table table,div.informaltable table { +div.table table, div.informaltable table { display: table; width: 100%; } @@ -163,7 +163,7 @@ div.table td { color: #6D180B; } -pre.programlisting,pre.screen { +pre.programlisting, pre.screen { font-size: 15px; padding: 6px 10px; background-color: #F8F8F8; @@ -197,7 +197,7 @@ table th { font-weight: bold; } -table th,table td { +table th, table td { border: none !important; padding: 6px 13px; } @@ -214,19 +214,18 @@ div.table-contents td p { margin: 0; } -div.important *,div.note *,div.tip *,div.warning *,div.navheader *,div.navfooter *,div.calloutlist * - { +div.important *, div.note *, div.tip *, div.warning *, div.navheader *, div.navfooter *, div.calloutlist * { border: none !important; background: none !important; margin: 0; } -div.important p,div.note p,div.tip p,div.warning p { +div.important p, div.note p, div.tip p, div.warning p { color: #6F6F6F; line-height: 1.6; } -div.important code,div.note code,div.tip code,div.warning code { +div.important code, div.note code, div.tip code, div.warning code { background-color: #F2F2F2 !important; border: 1px solid #CCCCCC !important; border-radius: 4px !important; @@ -235,27 +234,26 @@ div.important code,div.note code,div.tip code,div.warning code { white-space: nowrap !important; } -.note th,.tip th,.warning th { +.note th, .tip th, .warning th { display: none; } -.note tr:first-child td,.tip tr:first-child td,.warning tr:first-child td - { +.note tr:first-child td, .tip tr:first-child td, .warning tr:first-child td { border-right: 1px solid #CCCCCC !important; padding-top: 10px; } -div.calloutlist p,div.calloutlist td { +div.calloutlist p, div.calloutlist td { padding: 0; margin: 0; } -div.calloutlist>table>tbody>tr>td:first-child { +div.calloutlist > table > tbody > tr > td:first-child { padding-left: 10px; width: 30px !important; } -div.important,div.note,div.tip,div.warning { +div.important, div.note, div.tip, div.warning { margin-left: 0px !important; margin-right: 20px !important; margin-top: 20px; @@ -268,26 +266,26 @@ div.toc { line-height: 1.2; } -dl,dt { +dl, dt { margin-top: 1px; margin-bottom: 0; } -div.toc>dl>dt { +div.toc > dl > dt { font-size: 32px; font-weight: bold; margin: 30px 0 10px 0; display: block; } -div.toc>dl>dd>dl>dt { +div.toc > dl > dd > dl > dt { font-size: 24px; font-weight: bold; margin: 20px 0 10px 0; display: block; } -div.toc>dl>dd>dl>dd>dl>dt { +div.toc > dl > dd > dl > dd > dl > dt { font-weight: bold; font-size: 20px; margin: 10px 0 0 0; @@ -320,7 +318,7 @@ div.navfooter { padding-left: 1em; } -.title>a { +.title > a { position: absolute; visibility: hidden; display: block; @@ -331,14 +329,14 @@ div.navfooter { color: black; } -.title>a:before { +.title > a:before { content: "\00A7"; } -.title:hover>a,.title>a:hover,.title:hover>a:hover { +.title:hover > a, .title > a:hover, .title:hover > a:hover { visibility: visible; } -.title:focus>a,.title>a:focus,.title:focus>a:focus { +.title:focus > a, .title > a:focus, .title:focus > a:focus { outline: 0; } diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/common.xsl b/spring-cloud-task-docs/src/main/docbook/xsl/common.xsl index 157bf9d8..c921d3c3 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/common.xsl +++ b/spring-cloud-task-docs/src/main/docbook/xsl/common.xsl @@ -20,10 +20,10 @@ --> + xmlns:xslthl="http://xslthl.sf.net" + xmlns:d="http://docbook.org/ns/docbook" + exclude-result-prefixes="xslthl d" + version='1.0'> 1 diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/epub.xsl b/spring-cloud-task-docs/src/main/docbook/xsl/epub.xsl index 031406ca..c83cbf95 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/epub.xsl +++ b/spring-cloud-task-docs/src/main/docbook/xsl/epub.xsl @@ -20,10 +20,10 @@ under the License. --> + xmlns:xslthl="http://xslthl.sf.net" + xmlns:d="http://docbook.org/ns/docbook" + exclude-result-prefixes="xslthl d" + version='1.0'> diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/html-multipage.xsl b/spring-cloud-task-docs/src/main/docbook/xsl/html-multipage.xsl index be9cc52d..2fe13e12 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/html-multipage.xsl +++ b/spring-cloud-task-docs/src/main/docbook/xsl/html-multipage.xsl @@ -39,12 +39,12 @@ under the License. - + - - + + diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/html.xsl b/spring-cloud-task-docs/src/main/docbook/xsl/html.xsl index fd96f9a7..a1ac81d6 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/html.xsl +++ b/spring-cloud-task-docs/src/main/docbook/xsl/html.xsl @@ -20,10 +20,10 @@ under the License. --> + xmlns:xslthl="http://xslthl.sf.net" + xmlns:d="http://docbook.org/ns/docbook" + exclude-result-prefixes="xslthl" + version='1.0'> @@ -35,7 +35,7 @@ under the License. 1 - + 120 images/callouts/ .png @@ -68,35 +68,51 @@ under the License. - + + + - + + + - + + + - + + + - + + + - + + + - + + + - + + + diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/pdf.xsl b/spring-cloud-task-docs/src/main/docbook/xsl/pdf.xsl index a543bf19..0c67c81f 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/pdf.xsl +++ b/spring-cloud-task-docs/src/main/docbook/xsl/pdf.xsl @@ -68,33 +68,41 @@ under the License. - - + - + - + - + - + , @@ -103,15 +111,19 @@ under the License. - + - - Copyright © + + Copyright © - + @@ -236,11 +248,13 @@ under the License. - + - + @@ -248,11 +262,13 @@ under the License. - + - + @@ -308,9 +324,9 @@ under the License. Let's remove it, so this sucker can use our attribute-set only... --> + xsl:use-attribute-sets="chapter.titlepage.recto.style"> - + @@ -455,7 +471,8 @@ under the License. - + normal italic @@ -524,7 +541,7 @@ under the License. 1.5em - + 10pt bold false @@ -545,38 +562,51 @@ under the License. - + - - - + + + - + + + - + + + - + + + - + + + - + + + - + + + diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl-config.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl-config.xml index e4d677fc..1dce4071 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl-config.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl-config.xml @@ -1,23 +1,23 @@ - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/asciidoc-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/asciidoc-hl.xml index 5478b1d6..959434e1 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/asciidoc-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/asciidoc-hl.xml @@ -5,37 +5,37 @@ Syntax highlighting definition for AsciiDoc files --> - - //// - //// - - - // - - - - ^(={1,6} .+)$ - - MULTILINE - - - ^(\.[^\.\s].+)$ - - MULTILINE - - - ^(:!?\w.*?:) - - MULTILINE - - - ^(-|\*{1,5}|\d*\.{1,5})(?= .+$) - - MULTILINE - - - ^(\[.+\])$ - - MULTILINE - + + //// + //// + + + // + + + + ^(={1,6} .+)$ + + MULTILINE + + + ^(\.[^\.\s].+)$ + + MULTILINE + + + ^(:!?\w.*?:) + + MULTILINE + + + ^(-|\*{1,5}|\d*\.{1,5})(?= .+$) + + MULTILINE + + + ^(\[.+\])$ + + MULTILINE + diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/bourne-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/bourne-hl.xml index e2cd98d8..518fdb86 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/bourne-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/bourne-hl.xml @@ -31,8 +31,8 @@ freely, subject to the following restrictions: ' " - - - + + " @@ -41,16 +41,16 @@ freely, subject to the following restrictions: ' \ - + 0x - + . - - + + diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/c-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/c-hl.xml index 176cc379..0c994db7 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/c-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/c-hl.xml @@ -46,7 +46,7 @@ Michiel Hendriks # \ - + " @@ -62,18 +62,18 @@ Michiel Hendriks lu u l - + . - + e ul lu u f l - + auto diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/cpp-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/cpp-hl.xml index ef83c4f5..a9f7d0de 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/cpp-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/cpp-hl.xml @@ -64,18 +64,18 @@ Michiel Hendriks lu u l - + . - + e ul lu u f l - + diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/csharp-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/csharp-hl.xml index d57e6310..e21a1258 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/csharp-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/csharp-hl.xml @@ -62,7 +62,7 @@ Michiel Hendriks @" " \ - + " @@ -78,11 +78,11 @@ Michiel Hendriks lu u l - + . - + e ul lu @@ -91,7 +91,7 @@ Michiel Hendriks d m l - + abstract diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/css-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/css-hl.xml index 164c48c3..1d261f4e 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/css-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/css-hl.xml @@ -5,7 +5,7 @@ Syntax highlighting definition for CSS files xslthl - XSLT Syntax Highlighting http://sourceforge.net/projects/xslthl/ -Copyright (C) 2011-2012 Martin Hujer, Michiel Hendriks +Copyright (C) 2015-2019 Martin Hujer, Michiel Hendriks This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -30,147 +30,147 @@ Reference: http://www.w3.org/TR/CSS21/propidx.html --> - - /* - */ - - + + /* + */ + + " - \ - - - + \ + + + ' \ - - - - . - - - - @charset - @import - @media - @page - - - - - - azimuth - background-attachment - background-color - background-image - background-position - background-repeat - background - border-collapse - border-color - border-spacing - border-style - border-top - border-right - border-bottom - border-left - border-top-color - border-right-color - border-bottom-color - border-left-color - border-top-style - border-right-style - border-bottom-style - border-left-style - border-top-width - border-right-width - border-bottom-width - border-left-width - border-width - border - bottom - caption-side - clear - clip - color - content - counter-increment - counter-reset - cue-after - cue-before - cue - cursor - direction - display - elevation - empty-cells - float - font-family - font-size - font-style - font-variant - font-weight - font - height - left - letter-spacing - line-height - list-style-image - list-style-position - list-style-type - list-style - margin-right - margin-left - margin-top - margin-bottom - margin - max-height - max-width - min-height - min-width - orphans - outline-color - outline-style - outline-width - outline - overflow - padding-top - padding-right - padding-bottom - padding-left - padding - page-break-after - page-break-before - page-break-inside - pause-after - pause-before - pause - pitch-range - pitch - play-during - position - quotes - richness - right - speak-header - speak-numeral - speak-punctuation - speak - speech-rate - stress - table-layout - text-align - text-decoration - text-indent - text-transform - top - unicode-bidi - vertical-align - visibility - voice-family - volume - white-space - widows - width - word-spacing - z-index - + + + + . + + + + @charset + @import + @media + @page + + + + - + azimuth + background-attachment + background-color + background-image + background-position + background-repeat + background + border-collapse + border-color + border-spacing + border-style + border-top + border-right + border-bottom + border-left + border-top-color + border-right-color + border-bottom-color + border-left-color + border-top-style + border-right-style + border-bottom-style + border-left-style + border-top-width + border-right-width + border-bottom-width + border-left-width + border-width + border + bottom + caption-side + clear + clip + color + content + counter-increment + counter-reset + cue-after + cue-before + cue + cursor + direction + display + elevation + empty-cells + float + font-family + font-size + font-style + font-variant + font-weight + font + height + left + letter-spacing + line-height + list-style-image + list-style-position + list-style-type + list-style + margin-right + margin-left + margin-top + margin-bottom + margin + max-height + max-width + min-height + min-width + orphans + outline-color + outline-style + outline-width + outline + overflow + padding-top + padding-right + padding-bottom + padding-left + padding + page-break-after + page-break-before + page-break-inside + pause-after + pause-before + pause + pitch-range + pitch + play-during + position + quotes + richness + right + speak-header + speak-numeral + speak-punctuation + speak + speech-rate + stress + table-layout + text-align + text-decoration + text-indent + text-transform + top + unicode-bidi + vertical-align + visibility + voice-family + volume + white-space + widows + width + word-spacing + z-index + diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/html-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/html-hl.xml index 5b6761ba..fd48f118 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/html-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/html-hl.xml @@ -10,113 +10,113 @@ This file has been customized for the Asciidoctor project (http://asciidoctor.org). --> - - - - a - abbr - address - area - article - aside - audio - b - base - bdi - blockquote - body - br - button - caption - canvas - cite - code - command - col - colgroup - dd - del - dialog - div - dl - dt - em - embed - fieldset - figcaption - figure - font - form - footer - h1 - h2 - h3 - h4 - h5 - h6 - head - header - hr - html - i - iframe - img - input - ins - kbd - label - legend - li - link - map - mark - menu - menu - meta - nav - noscript - object - ol - optgroup - option - p - param - pre - q - samp - script - section - select - small - source - span - strong - style - sub - summary - sup - table - tbody - td - textarea - tfoot - th - thead - time - title - tr - track - u - ul - var - video - wbr - xmp - - - - - xsl: - - + + + + a + abbr + address + area + article + aside + audio + b + base + bdi + blockquote + body + br + button + caption + canvas + cite + code + command + col + colgroup + dd + del + dialog + div + dl + dt + em + embed + fieldset + figcaption + figure + font + form + footer + h1 + h2 + h3 + h4 + h5 + h6 + head + header + hr + html + i + iframe + img + input + ins + kbd + label + legend + li + link + map + mark + menu + menu + meta + nav + noscript + object + ol + optgroup + option + p + param + pre + q + samp + script + section + select + small + source + span + strong + style + sub + summary + sup + table + tbody + td + textarea + tfoot + th + thead + time + title + tr + track + u + ul + var + video + wbr + xmp + + + + + xsl: + + diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/java-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/java-hl.xml index f7bb1641..96ef3da7 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/java-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/java-hl.xml @@ -54,7 +54,7 @@ Michiel Hendriks 0x - + . @@ -62,7 +62,7 @@ Michiel Hendriks f d l - + abstract diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/javascript-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/javascript-hl.xml index 99b8a71e..f74807f3 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/javascript-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/javascript-hl.xml @@ -44,12 +44,12 @@ Michiel Hendriks 0x - + . e - + break diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/json-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/json-hl.xml index 59b9c481..c13923c2 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/json-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/json-hl.xml @@ -20,7 +20,7 @@ f d l - + true diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/perl-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/perl-hl.xml index 73d71cc0..adf7b094 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/perl-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/perl-hl.xml @@ -47,12 +47,12 @@ Michiel Hendriks 0x - + . - - + + if diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/php-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/php-hl.xml index 1da25b8c..1060ae4d 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/php-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/php-hl.xml @@ -47,24 +47,24 @@ Michiel Hendriks " \ - + ' \ - + <<< 0x - + . e - + and @@ -142,7 +142,7 @@ Michiel Hendriks __NAMESPACE__ goto __DIR__ - + diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/python-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/python-hl.xml index a4674432..fd6db57b 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/python-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/python-hl.xml @@ -38,11 +38,11 @@ Michiel Hendriks # """ - + ''' - + " @@ -55,14 +55,14 @@ Michiel Hendriks 0x l - + . - + e l - + and diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/ruby-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/ruby-hl.xml index d105640e..5bf3473d 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/ruby-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/ruby-hl.xml @@ -59,12 +59,12 @@ Michiel Hendriks 0x - + . e - + alias diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/sql2003-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/sql2003-hl.xml index ac1d5d04..bb561c64 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/sql2003-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/sql2003-hl.xml @@ -32,36 +32,36 @@ freely, subject to the following restrictions: ' - + U' ' - + B' ' - + N' ' - + X' ' - + . - + e - + - + A ABS diff --git a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/yaml-hl.xml b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/yaml-hl.xml index a28008ec..e678bad6 100644 --- a/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/yaml-hl.xml +++ b/spring-cloud-task-docs/src/main/docbook/xsl/xslthl/yaml-hl.xml @@ -20,7 +20,7 @@ f d l - + true diff --git a/spring-cloud-task-docs/src/main/javadoc/spring-javadoc.css b/spring-cloud-task-docs/src/main/javadoc/spring-javadoc.css index 06ad4227..17ec45f5 100644 --- a/spring-cloud-task-docs/src/main/javadoc/spring-javadoc.css +++ b/spring-cloud-task-docs/src/main/javadoc/spring-javadoc.css @@ -2,385 +2,456 @@ /* Overall document style */ - @import url('resources/fonts/dejavu.css'); body { - background-color:#ffffff; - color:#353833; - font-family:'DejaVu Sans', Arial, Helvetica, sans-serif; - font-size:14px; - margin:0; + background-color: #ffffff; + color: #353833; + font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; + font-size: 14px; + margin: 0; } + a:link, a:visited { - text-decoration:none; - color:#4A6782; + text-decoration: none; + color: #4A6782; } + a:hover, a:focus { - text-decoration:none; - color:#bb7a2a; + text-decoration: none; + color: #bb7a2a; } + a:active { - text-decoration:none; - color:#4A6782; + text-decoration: none; + color: #4A6782; } + a[name] { - color:#353833; + color: #353833; } + a[name]:hover { - text-decoration:none; - color:#353833; + text-decoration: none; + color: #353833; } + pre { - font-family:'DejaVu Sans Mono', monospace; - font-size:14px; + font-family: 'DejaVu Sans Mono', monospace; + font-size: 14px; } + h1 { - font-size:20px; + font-size: 20px; } + h2 { - font-size:18px; + font-size: 18px; } + h3 { - font-size:16px; - font-style:italic; + font-size: 16px; + font-style: italic; } + h4 { - font-size:13px; + font-size: 13px; } + h5 { - font-size:12px; + font-size: 12px; } + h6 { - font-size:11px; + font-size: 11px; } + ul { - list-style-type:disc; + list-style-type: disc; } + code, tt { - font-family:'DejaVu Sans Mono', monospace; - font-size:14px; - padding-top:4px; - margin-top:8px; - line-height:1.4em; + font-family: 'DejaVu Sans Mono', monospace; + font-size: 14px; + padding-top: 4px; + margin-top: 8px; + line-height: 1.4em; } + dt code { - font-family:'DejaVu Sans Mono', monospace; - font-size:14px; - padding-top:4px; + font-family: 'DejaVu Sans Mono', monospace; + font-size: 14px; + padding-top: 4px; } + table tr td dt code { - font-family:'DejaVu Sans Mono', monospace; - font-size:14px; - vertical-align:top; - padding-top:4px; + font-family: 'DejaVu Sans Mono', monospace; + font-size: 14px; + vertical-align: top; + padding-top: 4px; } + sup { - font-size:8px; + font-size: 8px; } + /* Document title and Copyright styles */ .clear { - clear:both; - height:0px; - overflow:hidden; + clear: both; + height: 0px; + overflow: hidden; } + .aboutLanguage { - float:right; - padding:0px 21px; - font-size:11px; - z-index:200; - margin-top:-9px; + float: right; + padding: 0px 21px; + font-size: 11px; + z-index: 200; + margin-top: -9px; } + .legalCopy { - margin-left:.5em; + margin-left: .5em; } + .bar a, .bar a:link, .bar a:visited, .bar a:active { - color:#FFFFFF; - text-decoration:none; + color: #FFFFFF; + text-decoration: none; } + .bar a:hover, .bar a:focus { - color:#bb7a2a; + color: #bb7a2a; } + .tab { - background-color:#0066FF; - color:#ffffff; - padding:8px; - width:5em; - font-weight:bold; + background-color: #0066FF; + color: #ffffff; + padding: 8px; + width: 5em; + font-weight: bold; } + /* Navigation bar styles */ .bar { - background-color:#4D7A97; - color:#FFFFFF; - padding:.8em .5em .4em .8em; - height:auto;/*height:1.8em;*/ - font-size:11px; - margin:0; + background-color: #4D7A97; + color: #FFFFFF; + padding: .8em .5em .4em .8em; + height: auto; /*height:1.8em;*/ + font-size: 11px; + margin: 0; } + .topNav { - background-color:#4D7A97; - color:#FFFFFF; - float:left; - padding:0; - width:100%; - clear:right; - height:2.8em; - padding-top:10px; - overflow:hidden; - font-size:12px; + background-color: #4D7A97; + color: #FFFFFF; + float: left; + padding: 0; + width: 100%; + clear: right; + height: 2.8em; + padding-top: 10px; + overflow: hidden; + font-size: 12px; } + .bottomNav { - margin-top:10px; - background-color:#4D7A97; - color:#FFFFFF; - float:left; - padding:0; - width:100%; - clear:right; - height:2.8em; - padding-top:10px; - overflow:hidden; - font-size:12px; + margin-top: 10px; + background-color: #4D7A97; + color: #FFFFFF; + float: left; + padding: 0; + width: 100%; + clear: right; + height: 2.8em; + padding-top: 10px; + overflow: hidden; + font-size: 12px; } + .subNav { - background-color:#dee3e9; - float:left; - width:100%; - overflow:hidden; - font-size:12px; + background-color: #dee3e9; + float: left; + width: 100%; + overflow: hidden; + font-size: 12px; } + .subNav div { - clear:left; - float:left; - padding:0 0 5px 6px; - text-transform:uppercase; + clear: left; + float: left; + padding: 0 0 5px 6px; + text-transform: uppercase; } + ul.navList, ul.subNavList { - float:left; - margin:0 25px 0 0; - padding:0; + float: left; + margin: 0 25px 0 0; + padding: 0; } -ul.navList li{ - list-style:none; - float:left; - padding: 5px 6px; - text-transform:uppercase; + +ul.navList li { + list-style: none; + float: left; + padding: 5px 6px; + text-transform: uppercase; } -ul.subNavList li{ - list-style:none; - float:left; + +ul.subNavList li { + list-style: none; + float: left; } + .topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited { - color:#FFFFFF; - text-decoration:none; - text-transform:uppercase; + color: #FFFFFF; + text-decoration: none; + text-transform: uppercase; } + .topNav a:hover, .bottomNav a:hover { - text-decoration:none; - color:#bb7a2a; - text-transform:uppercase; + text-decoration: none; + color: #bb7a2a; + text-transform: uppercase; } + .navBarCell1Rev { - background-color:#F8981D; - color:#253441; - margin: auto 5px; + background-color: #F8981D; + color: #253441; + margin: auto 5px; } + .skipNav { - position:absolute; - top:auto; - left:-9999px; - overflow:hidden; + position: absolute; + top: auto; + left: -9999px; + overflow: hidden; } + /* Page header and footer styles */ .header, .footer { - clear:both; - margin:0 20px; - padding:5px 0 0 0; + clear: both; + margin: 0 20px; + padding: 5px 0 0 0; } + .indexHeader { - margin:10px; - position:relative; + margin: 10px; + position: relative; } -.indexHeader span{ - margin-right:15px; + +.indexHeader span { + margin-right: 15px; } + .indexHeader h1 { - font-size:13px; + font-size: 13px; } + .title { - color:#2c4557; - margin:10px 0; + color: #2c4557; + margin: 10px 0; } + .subTitle { - margin:5px 0 0 0; + margin: 5px 0 0 0; } + .header ul { - margin:0 0 15px 0; - padding:0; + margin: 0 0 15px 0; + padding: 0; } + .footer ul { - margin:20px 0 5px 0; + margin: 20px 0 5px 0; } + .header ul li, .footer ul li { - list-style:none; - font-size:13px; + list-style: none; + font-size: 13px; } + /* Heading styles */ div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 { - background-color:#dee3e9; - border:1px solid #d0d9e0; - margin:0 0 6px -8px; - padding:7px 5px; + background-color: #dee3e9; + border: 1px solid #d0d9e0; + margin: 0 0 6px -8px; + padding: 7px 5px; } + ul.blockList ul.blockList ul.blockList li.blockList h3 { - background-color:#dee3e9; - border:1px solid #d0d9e0; - margin:0 0 6px -8px; - padding:7px 5px; + background-color: #dee3e9; + border: 1px solid #d0d9e0; + margin: 0 0 6px -8px; + padding: 7px 5px; } + ul.blockList ul.blockList li.blockList h3 { - padding:0; - margin:15px 0; + padding: 0; + margin: 15px 0; } + ul.blockList li.blockList h2 { - padding:0px 0 20px 0; + padding: 0px 0 20px 0; } + /* Page layout container styles */ .contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer { - clear:both; - padding:10px 20px; - position:relative; + clear: both; + padding: 10px 20px; + position: relative; } + .indexContainer { - margin:10px; - position:relative; - font-size:12px; + margin: 10px; + position: relative; + font-size: 12px; } + .indexContainer h2 { - font-size:13px; - padding:0 0 3px 0; + font-size: 13px; + padding: 0 0 3px 0; } + .indexContainer ul { - margin:0; - padding:0; + margin: 0; + padding: 0; } + .indexContainer ul li { - list-style:none; - padding-top:2px; + list-style: none; + padding-top: 2px; } + .contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt { - font-size:12px; - font-weight:bold; - margin:10px 0 0 0; - color:#4E4E4E; + font-size: 12px; + font-weight: bold; + margin: 10px 0 0 0; + color: #4E4E4E; } + .contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd { - margin:5px 0 10px 0px; - font-size:14px; - font-family:'DejaVu Sans Mono',monospace; + margin: 5px 0 10px 0px; + font-size: 14px; + font-family: 'DejaVu Sans Mono', monospace; } + .serializedFormContainer dl.nameValue dt { - margin-left:1px; - font-size:1.1em; - display:inline; - font-weight:bold; + margin-left: 1px; + font-size: 1.1em; + display: inline; + font-weight: bold; } + .serializedFormContainer dl.nameValue dd { - margin:0 0 0 1px; - font-size:1.1em; - display:inline; + margin: 0 0 0 1px; + font-size: 1.1em; + display: inline; } + /* List styles */ ul.horizontal li { - display:inline; - font-size:0.9em; + display: inline; + font-size: 0.9em; } + ul.inheritance { - margin:0; - padding:0; + margin: 0; + padding: 0; } + ul.inheritance li { - display:inline; - list-style:none; + display: inline; + list-style: none; } + ul.inheritance li ul.inheritance { - margin-left:15px; - padding-left:15px; - padding-top:1px; + margin-left: 15px; + padding-left: 15px; + padding-top: 1px; } + ul.blockList, ul.blockListLast { - margin:10px 0 10px 0; - padding:0; + margin: 10px 0 10px 0; + padding: 0; } + ul.blockList li.blockList, ul.blockListLast li.blockList { - list-style:none; - margin-bottom:15px; - line-height:1.4; + list-style: none; + margin-bottom: 15px; + line-height: 1.4; } + ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList { - padding:0px 20px 5px 10px; - border:1px solid #ededed; - background-color:#f8f8f8; + padding: 0px 20px 5px 10px; + border: 1px solid #ededed; + background-color: #f8f8f8; } + ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList { - padding:0 0 5px 8px; - background-color:#ffffff; - border:none; + padding: 0 0 5px 8px; + background-color: #ffffff; + border: none; } + ul.blockList ul.blockList ul.blockList ul.blockList li.blockList { - margin-left:0; - padding-left:0; - padding-bottom:15px; - border:none; + margin-left: 0; + padding-left: 0; + padding-bottom: 15px; + border: none; } + ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast { - list-style:none; - border-bottom:none; - padding-bottom:0; + list-style: none; + border-bottom: none; + padding-bottom: 0; } + table tr td dl, table tr td dl dt, table tr td dl dd { - margin-top:0; - margin-bottom:1px; + margin-top: 0; + margin-bottom: 1px; } + /* Table styles */ .overviewSummary, .memberSummary, .typeSummary, .useSummary, .constantsSummary, .deprecatedSummary { - width:100%; - border-left:1px solid #EEE; - border-right:1px solid #EEE; - border-bottom:1px solid #EEE; + width: 100%; + border-left: 1px solid #EEE; + border-right: 1px solid #EEE; + border-bottom: 1px solid #EEE; } -.overviewSummary, .memberSummary { - padding:0px; + +.overviewSummary, .memberSummary { + padding: 0px; } + .overviewSummary caption, .memberSummary caption, .typeSummary caption, .useSummary caption, .constantsSummary caption, .deprecatedSummary caption { - position:relative; - text-align:left; - background-repeat:no-repeat; - color:#253441; - font-weight:bold; - clear:none; - overflow:hidden; - padding:0px; - padding-top:10px; - padding-left:1px; - margin:0px; - white-space:pre; + position: relative; + text-align: left; + background-repeat: no-repeat; + color: #253441; + font-weight: bold; + clear: none; + overflow: hidden; + padding: 0px; + padding-top: 10px; + padding-left: 1px; + margin: 0px; + white-space: pre; } + .overviewSummary caption a:link, .memberSummary caption a:link, .typeSummary caption a:link, .useSummary caption a:link, .constantsSummary caption a:link, .deprecatedSummary caption a:link, .overviewSummary caption a:hover, .memberSummary caption a:hover, .typeSummary caption a:hover, @@ -389,211 +460,236 @@ Table styles .useSummary caption a:active, .constantsSummary caption a:active, .deprecatedSummary caption a:active, .overviewSummary caption a:visited, .memberSummary caption a:visited, .typeSummary caption a:visited, .useSummary caption a:visited, .constantsSummary caption a:visited, .deprecatedSummary caption a:visited { - color:#FFFFFF; + color: #FFFFFF; } + .overviewSummary caption span, .memberSummary caption span, .typeSummary caption span, .useSummary caption span, .constantsSummary caption span, .deprecatedSummary caption span { - white-space:nowrap; - padding-top:5px; - padding-left:12px; - padding-right:12px; - padding-bottom:7px; - display:inline-block; - float:left; - background-color:#F8981D; - border: none; - height:16px; + white-space: nowrap; + padding-top: 5px; + padding-left: 12px; + padding-right: 12px; + padding-bottom: 7px; + display: inline-block; + float: left; + background-color: #F8981D; + border: none; + height: 16px; } + .memberSummary caption span.activeTableTab span { - white-space:nowrap; - padding-top:5px; - padding-left:12px; - padding-right:12px; - margin-right:3px; - display:inline-block; - float:left; - background-color:#F8981D; - height:16px; + white-space: nowrap; + padding-top: 5px; + padding-left: 12px; + padding-right: 12px; + margin-right: 3px; + display: inline-block; + float: left; + background-color: #F8981D; + height: 16px; } + .memberSummary caption span.tableTab span { - white-space:nowrap; - padding-top:5px; - padding-left:12px; - padding-right:12px; - margin-right:3px; - display:inline-block; - float:left; - background-color:#4D7A97; - height:16px; + white-space: nowrap; + padding-top: 5px; + padding-left: 12px; + padding-right: 12px; + margin-right: 3px; + display: inline-block; + float: left; + background-color: #4D7A97; + height: 16px; } + .memberSummary caption span.tableTab, .memberSummary caption span.activeTableTab { - padding-top:0px; - padding-left:0px; - padding-right:0px; - background-image:none; - float:none; - display:inline; + padding-top: 0px; + padding-left: 0px; + padding-right: 0px; + background-image: none; + float: none; + display: inline; } + .overviewSummary .tabEnd, .memberSummary .tabEnd, .typeSummary .tabEnd, .useSummary .tabEnd, .constantsSummary .tabEnd, .deprecatedSummary .tabEnd { - display:none; - width:5px; - position:relative; - float:left; - background-color:#F8981D; + display: none; + width: 5px; + position: relative; + float: left; + background-color: #F8981D; } + .memberSummary .activeTableTab .tabEnd { - display:none; - width:5px; - margin-right:3px; - position:relative; - float:left; - background-color:#F8981D; + display: none; + width: 5px; + margin-right: 3px; + position: relative; + float: left; + background-color: #F8981D; } + .memberSummary .tableTab .tabEnd { - display:none; - width:5px; - margin-right:3px; - position:relative; - background-color:#4D7A97; - float:left; + display: none; + width: 5px; + margin-right: 3px; + position: relative; + background-color: #4D7A97; + float: left; } + .overviewSummary td, .memberSummary td, .typeSummary td, .useSummary td, .constantsSummary td, .deprecatedSummary td { - text-align:left; - padding:0px 0px 12px 10px; - width:100%; + text-align: left; + padding: 0px 0px 12px 10px; + width: 100%; } + th.colOne, th.colFirst, th.colLast, .useSummary th, .constantsSummary th, -td.colOne, td.colFirst, td.colLast, .useSummary td, .constantsSummary td{ - vertical-align:top; - padding-right:0px; - padding-top:8px; - padding-bottom:3px; +td.colOne, td.colFirst, td.colLast, .useSummary td, .constantsSummary td { + vertical-align: top; + padding-right: 0px; + padding-top: 8px; + padding-bottom: 3px; } + th.colFirst, th.colLast, th.colOne, .constantsSummary th { - background:#dee3e9; - text-align:left; - padding:8px 3px 3px 7px; + background: #dee3e9; + text-align: left; + padding: 8px 3px 3px 7px; } + td.colFirst, th.colFirst { - white-space:nowrap; - font-size:13px; + white-space: nowrap; + font-size: 13px; } + td.colLast, th.colLast { - font-size:13px; + font-size: 13px; } + td.colOne, th.colOne { - font-size:13px; + font-size: 13px; } + .overviewSummary td.colFirst, .overviewSummary th.colFirst, .overviewSummary td.colOne, .overviewSummary th.colOne, .memberSummary td.colFirst, .memberSummary th.colFirst, .memberSummary td.colOne, .memberSummary th.colOne, -.typeSummary td.colFirst{ - width:25%; - vertical-align:top; +.typeSummary td.colFirst { + width: 25%; + vertical-align: top; } + td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover { - font-weight:bold; + font-weight: bold; } + .tableSubHeadingColor { - background-color:#EEEEFF; + background-color: #EEEEFF; } + .altColor { - background-color:#FFFFFF; + background-color: #FFFFFF; } + .rowColor { - background-color:#EEEEEF; + background-color: #EEEEEF; } + /* Content styles */ .description pre { - margin-top:0; + margin-top: 0; } + .deprecatedContent { - margin:0; - padding:10px 0; + margin: 0; + padding: 10px 0; } + .docSummary { - padding:0; + padding: 0; } ul.blockList ul.blockList ul.blockList li.blockList h3 { - font-style:normal; + font-style: normal; } div.block { - font-size:14px; - font-family:'DejaVu Serif', Georgia, "Times New Roman", Times, serif; + font-size: 14px; + font-family: 'DejaVu Serif', Georgia, "Times New Roman", Times, serif; } td.colLast div { - padding-top:0px; + padding-top: 0px; } td.colLast a { - padding-bottom:3px; + padding-bottom: 3px; } + /* Formatting effect styles */ .sourceLineNo { - color:green; - padding:0 30px 0 0; + color: green; + padding: 0 30px 0 0; } + h1.hidden { - visibility:hidden; - overflow:hidden; - font-size:10px; + visibility: hidden; + overflow: hidden; + font-size: 10px; } + .block { - display:block; - margin:3px 10px 2px 0px; - color:#474747; + display: block; + margin: 3px 10px 2px 0px; + color: #474747; } + .deprecatedLabel, .descfrmTypeLabel, .memberNameLabel, .memberNameLink, .overrideSpecifyLabel, .packageHierarchyLabel, .paramLabel, .returnLabel, .seeLabel, .simpleTagLabel, .throwsLabel, .typeNameLabel, .typeNameLink { - font-weight:bold; + font-weight: bold; } + .deprecationComment, .emphasizedPhrase, .interfaceName { - font-style:italic; + font-style: italic; } div.block div.block span.deprecationComment, div.block div.block span.emphasizedPhrase, div.block div.block span.interfaceName { - font-style:normal; + font-style: normal; } -div.contentContainer ul.blockList li.blockList h2{ - padding-bottom:0px; +div.contentContainer ul.blockList li.blockList h2 { + padding-bottom: 0px; } - /* Spring */ pre.code { - background-color: #F8F8F8; - border: 1px solid #CCCCCC; - border-radius: 3px 3px 3px 3px; - overflow: auto; - padding: 10px; - margin: 4px 20px 2px 0px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; + overflow: auto; + padding: 10px; + margin: 4px 20px 2px 0px; } pre.code code, pre.code code * { - font-size: 1em; + font-size: 1em; } pre.code code, pre.code code * { - padding: 0 !important; - margin: 0 !important; + padding: 0 !important; + margin: 0 !important; } diff --git a/spring-cloud-task-integration-tests/pom.xml b/spring-cloud-task-integration-tests/pom.xml index ead1a69d..e6b9fdf6 100644 --- a/spring-cloud-task-integration-tests/pom.xml +++ b/spring-cloud-task-integration-tests/pom.xml @@ -1,5 +1,7 @@ - + spring-cloud-task-parent org.springframework.cloud @@ -7,7 +9,8 @@ 4.0.0 Spring Cloud Task Integration Tests - Tests the integration between Task/Batch Events and Stream Binders + Tests the integration between Task/Batch Events and Stream Binders + org.springframework.cloud spring-cloud-task-integration-tests 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 7b0af5e0..6a60ea86 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package configuration; @@ -52,16 +52,15 @@ public class JobConfiguration { @Bean public Job job() { - return jobBuilderFactory.get("job") - .start(step1()).next(step2()) - .build(); + return this.jobBuilderFactory.get("job").start(step1()).next(step2()).build(); } @Bean public Step step1() { - return stepBuilderFactory.get("step1").tasklet(new Tasklet() { + 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; } @@ -70,15 +69,15 @@ public class JobConfiguration { @Bean public Step step2() { - return 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 public String process(String item) throws Exception { return String.valueOf(Integer.parseInt(item) * -1); } - }) - .writer(new ItemWriter() { + }).writer(new ItemWriter() { @Override public void write(List items) throws Exception { for (Object item : items) { 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 dfa5e584..ed4c56ff 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package configuration; @@ -36,6 +36,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableBatchProcessing public class JobSkipConfiguration { + @Autowired private JobBuilderFactory jobBuilderFactory; @@ -44,16 +45,15 @@ public class JobSkipConfiguration { @Bean public Job job() { - return jobBuilderFactory.get("job") - .start(step1()).next(step2()) - .build(); + return this.jobBuilderFactory.get("job").start(step1()).next(step2()).build(); } @Bean public Step step1() { - return stepBuilderFactory.get("step1").tasklet(new Tasklet() { + 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; } @@ -62,15 +62,15 @@ public class JobSkipConfiguration { @Bean public Step step2() { - return stepBuilderFactory.get("step2").chunk(3).faultTolerant().skip(IllegalStateException.class).skipLimit(100) + 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); } - }) - .writer( new SkipItemWriter() ).build(); + }).writer(new SkipItemWriter()).build(); } } 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 097c2a99..cca63a3e 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package configuration; @@ -24,22 +24,25 @@ import org.springframework.batch.item.UnexpectedInputException; /** * @author Glenn Renfro */ -public class SkipItemReader implements ItemReader{ +public class SkipItemReader implements ItemReader { int failCount = 0; + boolean finished = false; @Override - public Object read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { + public Object read() throws Exception, UnexpectedInputException, ParseException, + NonTransientResourceException { String result = "1"; - if(failCount < 2) { - failCount++; + if (this.failCount < 2) { + this.failCount++; throw new IllegalStateException("Reader FOOBAR"); } - if (finished){ + if (this.finished) { result = null; } - finished = true; + this.finished = true; return result; } + } diff --git a/spring-cloud-task-integration-tests/src/test/java/configuration/SkipItemWriter.java b/spring-cloud-task-integration-tests/src/test/java/configuration/SkipItemWriter.java index c7205b5f..5f57a0f8 100644 --- a/spring-cloud-task-integration-tests/src/test/java/configuration/SkipItemWriter.java +++ b/spring-cloud-task-integration-tests/src/test/java/configuration/SkipItemWriter.java @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package configuration; @@ -29,12 +29,13 @@ public class SkipItemWriter implements ItemWriter { @Override public void write(List items) throws Exception { - if(failCount < 2) { - failCount++; + if (this.failCount < 2) { + this.failCount++; throw new IllegalStateException("Writer FOOBAR"); } for (Object item : items) { System.out.println(">> " + item); } } + } diff --git a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/executionid/TaskStartApplication.java b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/executionid/TaskStartApplication.java index bc922490..506b9bc2 100644 --- a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/executionid/TaskStartApplication.java +++ b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/executionid/TaskStartApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,9 +38,11 @@ public class TaskStartApplication { return new CommandLineRunner() { @Override public void run(String... strings) throws Exception { - for(String s : strings) + for (String s : strings) { System.out.println("Test" + s); + } } }; } + } 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 accf2bde..ef33180b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,29 +61,35 @@ import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.SocketUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = {TaskStartTests.TaskLauncherConfiguration.class}) +@SpringBootTest(classes = { TaskStartTests.TaskLauncherConfiguration.class }) public class TaskStartTests { private final static int WAIT_INTERVAL = 500; + 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 DATASOURCE_URL; + 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 final static String TASK_NAME = "TASK_LAUNCHER_SINK_TEST"; private static int randomPort; static { randomPort = SocketUtils.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; @@ -98,7 +104,7 @@ public class TaskStartTests { @After public void tearDown() { - if (this.applicationContext != null && this.applicationContext.isActive() ) { + if (this.applicationContext != null && this.applicationContext.isActive()) { this.applicationContext.close(); } } @@ -106,20 +112,22 @@ public class TaskStartTests { @Autowired public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; - TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean(dataSource); - taskExplorer = new SimpleTaskExplorer(factoryBean); - taskRepository = new SimpleTaskRepository(factoryBean); + TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean( + dataSource); + this.taskExplorer = new SimpleTaskExplorer(factoryBean); + this.taskRepository = new SimpleTaskRepository(factoryBean); } @Before public void setup() { - properties = new HashMap<>(); - properties.put("spring.datasource.url", DATASOURCE_URL); - properties.put("spring.datasource.username", DATASOURCE_USER_NAME); - properties.put("spring.datasource.password", DATASOURCE_USER_PASSWORD); - properties.put("spring.datasource.driverClassName", DATASOURCE_DRIVER_CLASS_NAME); - properties.put("spring.application.name",TASK_NAME); - properties.put("spring.cloud.task.initialize.enable", "false"); + this.properties = new HashMap<>(); + 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.application.name", TASK_NAME); + this.properties.put("spring.cloud.task.initialize.enable", "false"); JdbcTemplate template = new JdbcTemplate(this.dataSource); template.execute("DROP TABLE IF EXISTS TASK_TASK_BATCH"); @@ -140,41 +148,52 @@ public class TaskStartTests { DataSourceInitializer initializer = new DataSourceInitializer(); - initializer.setDataSource(dataSource); + 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(); } @Test public void testWithGeneratedTaskExecution() throws Exception { - taskRepository.createTaskExecution(); - assertEquals("Only one row is expected", 1, taskExplorer.getTaskExecutionCount()); + this.taskRepository.createTaskExecution(); + assertThat(this.taskExplorer.getTaskExecutionCount()) + .as("Only one row is expected").isEqualTo(1); this.applicationContext = getTaskApplication(1).run(new String[0]); - assertTrue(waitForDBToBePopulated()); + assertThat(waitForDBToBePopulated()).isTrue(); - Page taskExecutions = taskExplorer.findAll(PageRequest.of(0, 10)); + Page taskExecutions = this.taskExplorer + .findAll(PageRequest.of(0, 10)); TaskExecution te = taskExecutions.iterator().next(); - assertEquals("Only one row is expected", 1, taskExecutions.getTotalElements()); - assertEquals("return code should be 0", 0, taskExecutions.iterator().next().getExitCode().intValue()); + 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"; - taskRepository.createTaskExecution(TASK_EXECUTION_NAME); - assertEquals("Only one row is expected", 1, taskExplorer.getTaskExecutionCount()); - assertEquals(TASK_EXECUTION_NAME, taskExplorer.getTaskExecution(1).getTaskName()); + 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); this.applicationContext = getTaskApplication(1).run(new String[0]); - assertTrue(waitForDBToBePopulated()); + assertThat(waitForDBToBePopulated()).isTrue(); - Page taskExecutions = taskExplorer.findAll(PageRequest.of(0, 10)); + Page taskExecutions = this.taskExplorer + .findAll(PageRequest.of(0, 10)); TaskExecution te = taskExecutions.iterator().next(); - assertEquals("Only one row is expected", 1, taskExecutions.getTotalElements()); - assertEquals("return code should be 0", 0, taskExecutions.iterator().next().getExitCode().intValue()); - assertEquals("batchEvents", taskExplorer.getTaskExecution(1).getTaskName()); + 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(expected = ApplicationContextException.class) @@ -184,64 +203,67 @@ public class TaskStartTests { @Test(expected = ApplicationContextException.class) public void testCompletedTaskExecution() throws Exception { - taskRepository.createTaskExecution(); - assertEquals("Only one row is expected", 1, taskExplorer.getTaskExecutionCount()); - taskRepository.completeTaskExecution(1, 0, new Date(),""); + this.taskRepository.createTaskExecution(); + assertThat(this.taskExplorer.getTaskExecutionCount()) + .as("Only one row is expected").isEqualTo(1); + this.taskRepository.completeTaskExecution(1, 0, new Date(), ""); this.applicationContext = getTaskApplication(1).run(new String[0]); } @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 { - taskRepository.createTaskExecution(); - assertEquals("Only one row is expected", 1, taskExplorer.getTaskExecutionCount()); + this.taskRepository.createTaskExecution(); + assertThat(this.taskExplorer.getTaskExecutionCount()) + .as("Only one row is expected").isEqualTo(1); enableLock("foo"); getTaskApplication(1).run(params); } catch (ApplicationContextException taskException) { - assertEquals("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.", - taskException.getMessage()); + 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."); testFailed = true; } - assertTrue("Expected TaskExecutionException for because of " + - "single-instance-enabled is enabled", testFailed); + assertThat(testFailed).as("Expected TaskExecutionException for because of " + + "single-instance-enabled is enabled").isTrue(); } @Test public void testDuplicateTaskExecutionWithSingleInstanceDisabled() throws Exception { - taskRepository.createTaskExecution(); - TaskExecution execution = taskRepository.createTaskExecution(); - taskRepository.startTaskExecution(execution.getExecutionId(), "bar", + this.taskRepository.createTaskExecution(); + TaskExecution execution = this.taskRepository.createTaskExecution(); + this.taskRepository.startTaskExecution(execution.getExecutionId(), "bar", new Date(), new ArrayList<>(), ""); - String params[] = {"--spring.cloud.task.name=bar"}; + String[] params = { "--spring.cloud.task.name=bar" }; enableLock("bar"); this.applicationContext = getTaskApplication(1).run(params); - assertTrue(waitForDBToBePopulated()); + assertThat(waitForDBToBePopulated()).isTrue(); } private SpringApplication getTaskApplication(Integer executionId) { SpringApplication myapp = new SpringApplication(TaskStartApplication.class); - Map myMap = new HashMap<>(); + Map myMap = new HashMap<>(); 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; } private boolean tableExists() throws SQLException { boolean result; - try (Connection conn = dataSource.getConnection(); - ResultSet res = conn.getMetaData().getTables(null, null, "TASK_EXECUTION", - new String[]{"TABLE"})) { + try (Connection conn = this.dataSource.getConnection(); + ResultSet res = conn.getMetaData().getTables(null, null, "TASK_EXECUTION", + new String[] { "TABLE" })) { result = res.next(); } return result; @@ -251,7 +273,7 @@ public class TaskStartTests { boolean isDbPopulated = false; for (int waitTime = 0; waitTime <= MAX_WAIT_TIME; waitTime += WAIT_INTERVAL) { Thread.sleep(WAIT_INTERVAL); - if (tableExists() && taskExplorer.getTaskExecutionCount() > 0) { + if (tableExists() && this.taskExplorer.getTaskExecutionCount() > 0) { isDbPopulated = true; break; } @@ -260,9 +282,11 @@ 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()); @@ -271,13 +295,14 @@ public class TaskStartTests { @Configuration public static class TaskLauncherConfiguration { + private static Server defaultServer; - @Bean() + @Bean public Server initH2TCPServer() { Server server = null; try { - if(defaultServer == null) { + if (defaultServer == null) { server = Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort)).start(); defaultServer = server; @@ -298,6 +323,7 @@ public class TaskStartTests { dataSource.setPassword(DATASOURCE_USER_PASSWORD); return dataSource; } + } } 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 a241f864..a20806a8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; -import java.util.Properties; + import javax.sql.DataSource; import org.h2.tools.Server; @@ -55,35 +55,42 @@ import org.springframework.messaging.support.GenericMessage; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.SocketUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = {TaskLauncherSinkApplication.class, TaskLauncherSinkTests.TaskLauncherConfiguration.class}, - properties = {"maven.remote-repositories.repo1.url=https://repo.spring.io/libs-milestone"}) +@SpringBootTest(classes = { TaskLauncherSinkApplication.class, + TaskLauncherSinkTests.TaskLauncherConfiguration.class }, properties = { + "maven.remote-repositories.repo1.url=https://repo.spring.io/libs-milestone" }) public class TaskLauncherSinkTests { private final static int WAIT_INTERVAL = 500; + private final static int MAX_WAIT_TIME = 120000; + private final static String URL = "maven://org.springframework.cloud.task.app:" + "timestamp-task:2.0.0.RELEASE"; + private final static String DATASOURCE_URL; + 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 final static String TASK_NAME = "TASK_LAUNCHER_SINK_TEST"; + @ClassRule + public static RabbitTestSupport rabbitTestSupport = new RabbitTestSupport(); + private static int randomPort; static { randomPort = SocketUtils.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"; } - @ClassRule - public static RabbitTestSupport rabbitTestSupport = new RabbitTestSupport(); - @Autowired private Sink sink; @@ -96,27 +103,30 @@ public class TaskLauncherSinkTests { @Autowired public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; - taskExplorer = new SimpleTaskExplorer(new TaskExecutionDaoFactoryBean(dataSource)); + this.taskExplorer = new SimpleTaskExplorer( + new TaskExecutionDaoFactoryBean(dataSource)); } @Before public void setup() { - properties = new HashMap<>(); - properties.put("spring.datasource.url", DATASOURCE_URL); - properties.put("spring.datasource.username", DATASOURCE_USER_NAME); - properties.put("spring.datasource.password", DATASOURCE_USER_PASSWORD); - properties.put("spring.datasource.driverClassName", DATASOURCE_DRIVER_CLASS_NAME); - properties.put("spring.application.name",TASK_NAME); - properties.put("spring.cloud.task.initialize.enable", "false"); + this.properties = new HashMap<>(); + 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.application.name", TASK_NAME); + this.properties.put("spring.cloud.task.initialize.enable", "false"); JdbcTemplate template = new JdbcTemplate(this.dataSource); template.execute("DROP ALL OBJECTS"); DataSourceInitializer initializer = new DataSourceInitializer(); - initializer.setDataSource(dataSource); + 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(); @@ -125,20 +135,22 @@ public class TaskLauncherSinkTests { @Test public void testWithLocalDeployer() throws Exception { launchTask(URL); - assertTrue(waitForDBToBePopulated()); + assertThat(waitForDBToBePopulated()).isTrue(); - Page taskExecutions = taskExplorer.findAll(PageRequest.of(0, 10)); - assertEquals("Only one row is expected", 1, taskExecutions.getTotalElements()); - assertTrue(waitForTaskToComplete()); - assertEquals("return code should be 0", 0, taskExecutions.iterator().next().getExitCode().intValue()); + 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); } private boolean tableExists() throws SQLException { boolean result; - try ( - Connection conn = dataSource.getConnection(); + try (Connection conn = this.dataSource.getConnection(); ResultSet res = conn.getMetaData().getTables(null, null, "TASK_EXECUTION", - new String[]{"TABLE"})) { + new String[] { "TABLE" })) { result = res.next(); } return result; @@ -148,7 +160,7 @@ public class TaskLauncherSinkTests { boolean isDbPopulated = false; for (int waitTime = 0; waitTime <= MAX_WAIT_TIME; waitTime += WAIT_INTERVAL) { Thread.sleep(WAIT_INTERVAL); - if (tableExists() && taskExplorer.getTaskExecutionCount() > 0) { + if (tableExists() && this.taskExplorer.getTaskExecutionCount() > 0) { isDbPopulated = true; break; } @@ -156,18 +168,18 @@ public class TaskLauncherSinkTests { return isDbPopulated; } - private boolean waitForTaskToComplete() throws Exception { - boolean istTaskComplete = false; - for (int waitTime = 0; waitTime <= MAX_WAIT_TIME; waitTime += WAIT_INTERVAL) { - Thread.sleep(WAIT_INTERVAL); - TaskExecution taskExecution = taskExplorer.getTaskExecution(1); - if (taskExecution.getExitCode() != null) { - istTaskComplete = true; - break; - } + private boolean waitForTaskToComplete() throws Exception { + boolean istTaskComplete = false; + for (int waitTime = 0; waitTime <= MAX_WAIT_TIME; waitTime += WAIT_INTERVAL) { + Thread.sleep(WAIT_INTERVAL); + TaskExecution taskExecution = this.taskExplorer.getTaskExecution(1); + if (taskExecution.getExitCode() != null) { + istTaskComplete = true; + break; } - return istTaskComplete; } + return istTaskComplete; + } private void launchTask(String artifactURL) { @@ -179,6 +191,7 @@ public class TaskLauncherSinkTests { @Configuration public static class TaskLauncherConfiguration { + @Bean public TaskLauncher taskLauncher() { LocalDeployerProperties props = new LocalDeployerProperties(); @@ -209,6 +222,7 @@ public class TaskLauncherSinkTests { dataSource.setPassword(DATASOURCE_USER_PASSWORD); return dataSource; } + } } diff --git a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/launcher/util/TaskLauncherSinkApplication.java b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/launcher/util/TaskLauncherSinkApplication.java index 141d7eb3..7b8aafff 100644 --- a/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/launcher/util/TaskLauncherSinkApplication.java +++ b/spring-cloud-task-integration-tests/src/test/java/org/springframework/cloud/task/launcher/util/TaskLauncherSinkApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,4 +30,5 @@ public class TaskLauncherSinkApplication { public static void main(String[] args) { SpringApplication.run(TaskLauncherSinkApplication.class, args); } + } 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 b50a14bc..7ea7aa33 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 @@ -1,18 +1,17 @@ - /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.listener; @@ -23,6 +22,7 @@ import java.util.concurrent.TimeUnit; import configuration.JobConfiguration; import configuration.JobSkipConfiguration; +import org.assertj.core.api.Assertions; import org.junit.After; import org.junit.ClassRule; import org.junit.Test; @@ -41,14 +41,15 @@ import org.springframework.cloud.task.configuration.EnableTask; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.PropertySource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro */ public class BatchExecutionEventTests { + + private static final String TASK_NAME = "jobEventTest"; + @ClassRule public static RabbitTestSupport rabbitTestSupport = new RabbitTestSupport(); @@ -77,82 +78,135 @@ public class BatchExecutionEventTests { static int readSkipCount = 0; static int writeSkipCount = 0; - - private static final String TASK_NAME = "jobEventTest"; - private ConfigurableApplicationContext applicationContext; @After public void tearDown() { - if (applicationContext != null && applicationContext.isActive() ) { - applicationContext.close(); + if (this.applicationContext != null && this.applicationContext.isActive()) { + this.applicationContext.close(); } } @Test public void testContext() { - applicationContext = new SpringApplicationBuilder() - .sources(this.getConfigurations(BatchExecutionEventTests.ListenerBinding.class, JobConfiguration.class)) - .build().run(getCommandLineParams("--spring.cloud.stream.bindings.job-execution-events.destination=bazbar")); + this.applicationContext = new SpringApplicationBuilder() + .sources(this.getConfigurations( + BatchExecutionEventTests.ListenerBinding.class, + JobConfiguration.class)) + .build().run(getCommandLineParams( + "--spring.cloud.stream.bindings.job-execution-events.destination=bazbar")); - assertNotNull(applicationContext.getBean("jobExecutionEventsListener")); - assertNotNull(applicationContext.getBean("stepExecutionEventsListener")); - assertNotNull(applicationContext.getBean("chunkEventsListener")); - assertNotNull(applicationContext.getBean("itemReadEventsListener")); - assertNotNull(applicationContext.getBean("itemWriteEventsListener")); - assertNotNull(applicationContext.getBean("itemProcessEventsListener")); - assertNotNull(applicationContext.getBean("skipEventsListener")); - assertNotNull(applicationContext.getBean(BatchEventAutoConfiguration.BatchEventsChannels.class)); + 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("skipEventsListener")).isNotNull(); + assertThat(this.applicationContext + .getBean(BatchEventAutoConfiguration.BatchEventsChannels.class)) + .isNotNull(); } @Test public void testJobEventListener() throws Exception { - testListener("--spring.cloud.stream.bindings.job-execution-events.destination=foobar", + testListener( + "--spring.cloud.stream.bindings.job-execution-events.destination=foobar", jobExecutionLatch, BatchExecutionEventTests.ListenerBinding.class); } @Test public void testStepEventListener() throws Exception { - testListener("--spring.cloud.stream.bindings.step-execution-events.destination=step-execution-foobar", + testListener( + "--spring.cloud.stream.bindings.step-execution-events.destination=step-execution-foobar", stepExecutionLatch, BatchExecutionEventTests.StepListenerBinding.class); - assertEquals("the number of step1 events did not match", 2, stepOneCount); - assertEquals("the number of step2 events did not match", 2, stepTwoCount); + 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); } @Test public void testItemProcessEventListener() throws Exception { - testListener("--spring.cloud.stream.bindings.item-process-events.destination=item-process-foobar", - itemProcessLatch, BatchExecutionEventTests.ItemProcessListenerBinding.class); + testListener( + "--spring.cloud.stream.bindings.item-process-events.destination=item-process-foobar", + itemProcessLatch, + BatchExecutionEventTests.ItemProcessListenerBinding.class); } - @Test public void testChunkListener() throws Exception { - testListener("--spring.cloud.stream.bindings.chunk-events.destination=chunk-events-foobar", - chunkEventsLatch, BatchExecutionEventTests.ChunkEventsListenerBinding.class); + testListener( + "--spring.cloud.stream.bindings.chunk-events.destination=chunk-events-foobar", + chunkEventsLatch, + BatchExecutionEventTests.ChunkEventsListenerBinding.class); } @Test public void testItemReadListener() throws Exception { - testListener("--spring.cloud.stream.bindings.item-read-events.destination=item-read-events-foobar", - itemReadEventsLatch, BatchExecutionEventTests.ItemReadEventsListenerBinding.class); + testListener( + "--spring.cloud.stream.bindings.item-read-events.destination=item-read-events-foobar", + itemReadEventsLatch, + BatchExecutionEventTests.ItemReadEventsListenerBinding.class); } @Test public void testWriteListener() throws Exception { - testListener("--spring.cloud.stream.bindings.item-write-events.destination=item-write-events-foobar", - itemWriteEventsLatch, BatchExecutionEventTests.ItemWriteEventsListenerBinding.class); + testListener( + "--spring.cloud.stream.bindings.item-write-events.destination=item-write-events-foobar", + itemWriteEventsLatch, + BatchExecutionEventTests.ItemWriteEventsListenerBinding.class); } @Test public void testSkipEventListener() throws Exception { - testListenerSkip("--spring.cloud.stream.bindings.skip-events.destination=skip-event-foobar", - skipEventsLatch, BatchExecutionEventTests.SkipEventsListenerBinding.class); - assertEquals("read skip count did not match expected result", 2, readSkipCount); - assertEquals("write skip count did not match expected result", 1, writeSkipCount); + testListenerSkip( + "--spring.cloud.stream.bindings.skip-events.destination=skip-event-foobar", + skipEventsLatch, + BatchExecutionEventTests.SkipEventsListenerBinding.class); + assertThat(readSkipCount).as("read skip count did not match expected result") + .isEqualTo(2); + assertThat(writeSkipCount).as("write skip count did not match expected result") + .isEqualTo(1); + } + + private Class[] getConfigurations(Class sinkClazz, Class jobConfigurationClazz) { + return new Class[] { PropertyPlaceholderAutoConfiguration.class, + jobConfigurationClazz, sinkClazz }; + } + + 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", + "--spring.cloud.stream.bindings.task-events.destination=test", + "foo=" + UUID.randomUUID().toString(), sinkChannelParam }; + } + + private void testListener(String channelBinding, CountDownLatch latch, Class clazz) + throws Exception { + this.applicationContext = new SpringApplicationBuilder() + .sources(this.getConfigurations(clazz, JobConfiguration.class)).build() + .run(getCommandLineParams(channelBinding)); + + assertThat(latch.await(1, TimeUnit.SECONDS)).isTrue(); + } + + private void testListenerSkip(String channelBinding, CountDownLatch latch, + Class clazz) throws Exception { + this.applicationContext = new SpringApplicationBuilder() + .sources(this.getConfigurations(clazz, JobSkipConfiguration.class)) + .build().run(getCommandLineParams(channelBinding)); + + assertThat(latch.await(1, TimeUnit.SECONDS)).isTrue(); } @EnableBinding(Sink.class) @@ -163,9 +217,11 @@ public class BatchExecutionEventTests { @StreamListener(Sink.INPUT) public void receive(JobExecutionEvent execution) { - assertEquals("Job name should be job", "job", execution.getJobInstance().getJobName()); + Assertions.assertThat(execution.getJobInstance().getJobName()) + .isEqualTo("job").as("Job name should be job"); jobExecutionLatch.countDown(); } + } @EnableBinding(Sink.class) @@ -176,15 +232,16 @@ public class BatchExecutionEventTests { @StreamListener(Sink.INPUT) public void receive(StepExecutionEvent execution) { - if(execution.getStepName().equals("step1")) { + if (execution.getStepName().equals("step1")) { stepOneCount++; } - if(execution.getStepName().equals("step2")) { + if (execution.getStepName().equals("step2")) { stepTwoCount++; } stepExecutionLatch.countDown(); } + } @EnableBinding(Sink.class) @@ -197,6 +254,7 @@ public class BatchExecutionEventTests { public void receive(String object) { itemProcessLatch.countDown(); } + } @EnableBinding(Sink.class) @@ -209,6 +267,7 @@ public class BatchExecutionEventTests { public void receive(String message) { chunkEventsLatch.countDown(); } + } @EnableBinding(Sink.class) @@ -221,6 +280,7 @@ public class BatchExecutionEventTests { public void receive(Object itemRead) { itemReadEventsLatch.countDown(); } + } @EnableBinding(Sink.class) @@ -228,18 +288,22 @@ public class BatchExecutionEventTests { @EnableAutoConfiguration @EnableTask public static class SkipEventsListenerBinding { + private static final String SKIPPING_READ_MESSAGE = "Skipped when reading."; + private static final String SKIPPING_WRITE_CONTENT = "-1"; + @StreamListener(Sink.INPUT) public void receive(String exceptionMessage) { - if(exceptionMessage.toString().equals(SKIPPING_READ_MESSAGE)){ + if (exceptionMessage.toString().equals(SKIPPING_READ_MESSAGE)) { readSkipCount++; } - if(exceptionMessage.toString().equals(SKIPPING_WRITE_CONTENT)){ + if (exceptionMessage.toString().equals(SKIPPING_WRITE_CONTENT)) { writeSkipCount++; } skipEventsLatch.countDown(); } + } @EnableBinding(Sink.class) @@ -250,41 +314,13 @@ public class BatchExecutionEventTests { @StreamListener(Sink.INPUT) public void receive(String itemWrite) { - assertTrue("Message should start with '3 items'", itemWrite.toString().startsWith("3 items ")); - assertTrue("Message should end with ' written.'", itemWrite.toString().endsWith(" written.")); + Assertions.assertThat(itemWrite).startsWith("3 items ") + .as("Message should start with '3 items'"); + Assertions.assertThat(itemWrite).endsWith("written") + .as("Message should end with ' written.'"); itemWriteEventsLatch.countDown(); } + } - private Class[] getConfigurations(Class sinkClazz, Class jobConfigurationClazz) { - return new Class[]{PropertyPlaceholderAutoConfiguration.class, - jobConfigurationClazz, - sinkClazz }; - } - - 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", - "--spring.cloud.stream.bindings.task-events.destination=test", - "foo=" + UUID.randomUUID().toString(), - sinkChannelParam }; - } - - private void testListener(String channelBinding, CountDownLatch latch, Class clazz) throws Exception{ - applicationContext = new SpringApplicationBuilder() - .sources(this.getConfigurations(clazz, JobConfiguration.class)) - .build().run(getCommandLineParams(channelBinding)); - - assertTrue(latch.await(1, TimeUnit.SECONDS)); - } - - private void testListenerSkip(String channelBinding, CountDownLatch latch, Class clazz) throws Exception{ - applicationContext = new SpringApplicationBuilder() - .sources(this.getConfigurations(clazz, JobSkipConfiguration.class)) - .build().run(getCommandLineParams(channelBinding)); - - assertTrue(latch.await(1, TimeUnit.SECONDS)); - } } 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 1ed3179d..b1b55cea 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.listener; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import org.assertj.core.api.Assertions; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; @@ -36,37 +38,34 @@ import org.springframework.cloud.stream.config.BindingServiceConfiguration; import org.springframework.cloud.stream.messaging.Sink; import org.springframework.cloud.task.configuration.EnableTask; import org.springframework.cloud.task.configuration.SimpleTaskAutoConfiguration; -import org.springframework.cloud.task.configuration.SingleTaskConfiguration; import org.springframework.cloud.task.repository.TaskExecution; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michael Minella * @author Ilayaperumal Gopinathan */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = {TaskEventTests.ListenerBinding.class}) +@SpringBootTest(classes = { TaskEventTests.ListenerBinding.class }) public class TaskEventTests { + private static final String TASK_NAME = "taskEventTest"; + @ClassRule public static RabbitTestSupport rabbitTestSupport = new RabbitTestSupport(); // Count for two task execution events per task static CountDownLatch latch = new CountDownLatch(2); - private static final String TASK_NAME = "taskEventTest"; - @Test public void testTaskEventListener() throws Exception { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - TaskEventAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(TaskEventAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, RabbitServiceAutoConfiguration.class, SimpleTaskAutoConfiguration.class, @@ -78,15 +77,18 @@ public class TaskEventTests { "--spring.cloud.stream.defaultBinder=rabbit", "--spring.cloud.stream.bindings.task-events.destination=test"); applicationContextRunner.run((context) -> { - assertNotNull(context.getBean("taskEventListener")); - assertNotNull(context.getBean(TaskEventAutoConfiguration.TaskEventChannels.class)); + assertThat(context.getBean("taskEventListener")).isNotNull(); + assertThat( + context.getBean(TaskEventAutoConfiguration.TaskEventChannels.class)) + .isNotNull(); }); - assertTrue(latch.await(1, TimeUnit.SECONDS)); + assertThat(latch.await(1, TimeUnit.SECONDS)).isTrue(); } @EnableTask @Configuration public static class TaskEventsConfiguration { + } @EnableBinding(Sink.class) @@ -96,12 +98,13 @@ public class TaskEventTests { @StreamListener(Sink.INPUT) public void receive(TaskExecution execution) { - assertTrue(String.format("Task name should be '%s'", TASK_NAME), execution.getTaskName().equals(TASK_NAME)); + Assertions.assertThat(execution.getTaskName()).isEqualTo(TASK_NAME) + .as(String.format("Task name should be '%s'", TASK_NAME)); latch.countDown(); } @Bean - public CommandLineRunner commandLineRunner(){ + public CommandLineRunner commandLineRunner() { return new CommandLineRunner() { @Override public void run(String... args) throws Exception { @@ -109,5 +112,7 @@ public class TaskEventTests { } }; } + } + } diff --git a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/chunk-events-sink-channel.properties b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/chunk-events-sink-channel.properties index aa4a821b..730962e3 100644 --- a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/chunk-events-sink-channel.properties +++ b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/chunk-events-sink-channel.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,5 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # - spring.cloud.stream.bindings.input.destination=chunk-events-foobar diff --git a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-process-sink-channel.properties b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-process-sink-channel.properties index 7cc85130..9111e409 100644 --- a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-process-sink-channel.properties +++ b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-process-sink-channel.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,5 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # - spring.cloud.stream.bindings.input.destination=item-process-foobar diff --git a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-read-events-sink-channel.properties b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-read-events-sink-channel.properties index 95175e69..24ca4e33 100644 --- a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-read-events-sink-channel.properties +++ b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-read-events-sink-channel.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,5 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # - spring.cloud.stream.bindings.input.destination=item-read-events-foobar diff --git a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-write-events-sink-channel.properties b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-write-events-sink-channel.properties index c5906e36..24a76754 100644 --- a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-write-events-sink-channel.properties +++ b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/item-write-events-sink-channel.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,5 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # - spring.cloud.stream.bindings.input.destination=item-write-events-foobar diff --git a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/job-execution-sink-channel.properties b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/job-execution-sink-channel.properties index 2ab32e3e..8b7cdc2b 100644 --- a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/job-execution-sink-channel.properties +++ b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/job-execution-sink-channel.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,5 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # - spring.cloud.stream.bindings.input.destination=foobar diff --git a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/sink-channel.properties b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/sink-channel.properties index 47e0200c..2e8f813a 100644 --- a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/sink-channel.properties +++ b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/sink-channel.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,5 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # - spring.cloud.stream.bindings.input.destination=test diff --git a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/skip-events-sink-channel.properties b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/skip-events-sink-channel.properties index 9d518149..4014d2bc 100644 --- a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/skip-events-sink-channel.properties +++ b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/skip-events-sink-channel.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,5 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # - spring.cloud.stream.bindings.input.destination=skip-event-foobar diff --git a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/step-execution-sink-channel.properties b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/step-execution-sink-channel.properties index 4afc659b..fc95872b 100644 --- a/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/step-execution-sink-channel.properties +++ b/spring-cloud-task-integration-tests/src/test/resources/org/springframework/cloud/task/listener/step-execution-sink-channel.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,5 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # - spring.cloud.stream.bindings.input.destination=step-execution-foobar diff --git a/spring-cloud-task-samples/batch-events/pom.xml b/spring-cloud-task-samples/batch-events/pom.xml index 07a2a3d3..c79a9842 100644 --- a/spring-cloud-task-samples/batch-events/pom.xml +++ b/spring-cloud-task-samples/batch-events/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 io.spring.cloud @@ -14,7 +16,7 @@ org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE - + @@ -72,7 +74,7 @@ - + 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 d118d4cd..7858b8d4 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package io.spring.cloud; @@ -61,42 +61,42 @@ 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(); + .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); + .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); } - }) - .writer(new ItemWriter() { - @Override - public void write(List items) throws Exception { - for (String item : items) { - System.out.println(">> " + item); - } - } - }).build(); + } + }).build(); } @Bean public Job job() { return this.jobBuilderFactory.get("job") - .start(step1()) - .next(step2()) - .build(); + .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 fc834504..ba0bd99a 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package io.spring.cloud; @@ -19,7 +19,7 @@ package io.spring.cloud; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import org.junit.Assert; +import org.assertj.core.api.BDDAssertions; import org.junit.ClassRule; import org.junit.Test; @@ -32,6 +32,8 @@ import org.springframework.cloud.task.batch.listener.support.JobExecutionEvent; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; +import static org.assertj.core.api.Assertions.assertThat; + public class BatchEventsApplicationTests { @ClassRule @@ -42,13 +44,14 @@ public class BatchEventsApplicationTests { @Test public void testExecution() throws Exception { - SpringApplication.run(JobExecutionListenerBinding.class, "--spring.main.web-environment=false"); + SpringApplication + .run(JobExecutionListenerBinding.class, "--spring.main.web-environment=false"); SpringApplication.run(BatchEventsApplication.class, "--server.port=0", - "--spring.cloud.stream.bindings.output.producer.requiredGroups=testgroup", - "--spring.jmx.default-domain=fakedomain", - "--spring.main.webEnvironment=false"); - Assert.assertTrue("The latch did not count down to zero before timeout", - jobExecutionLatch.await(60, TimeUnit.SECONDS)); + "--spring.cloud.stream.bindings.output.producer.requiredGroups=testgroup", + "--spring.jmx.default-domain=fakedomain", + "--spring.main.webEnvironment=false"); + assertThat(jobExecutionLatch.await(60, TimeUnit.SECONDS)) + .as("The latch did not count down to zero before timeout").isTrue(); } @EnableBinding(Sink.class) @@ -58,7 +61,8 @@ public class BatchEventsApplicationTests { @StreamListener(Sink.INPUT) public void receive(JobExecutionEvent execution) { - Assert.assertEquals("Job name should be job", "job", execution.getJobInstance().getJobName()); + BDDAssertions.then(execution.getJobInstance().getJobName()) + .isEqualTo("job").as("Job name should be job"); jobExecutionLatch.countDown(); } } diff --git a/spring-cloud-task-samples/batch-events/src/test/resources/io/spring/task/listener/job-listener-sink-channel.properties b/spring-cloud-task-samples/batch-events/src/test/resources/io/spring/task/listener/job-listener-sink-channel.properties index 8921774b..dfc975d3 100644 --- a/spring-cloud-task-samples/batch-events/src/test/resources/io/spring/task/listener/job-listener-sink-channel.properties +++ b/spring-cloud-task-samples/batch-events/src/test/resources/io/spring/task/listener/job-listener-sink-channel.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,6 +13,5 @@ # See the License for the specific language governing permissions and # limitations under the License. # - spring.cloud.stream.bindings.input.destination=job-execution-events spring.cloud.stream.bindings.input.group=testgroup diff --git a/spring-cloud-task-samples/batch-job/pom.xml b/spring-cloud-task-samples/batch-job/pom.xml index 7f67cade..f0cdb19e 100644 --- a/spring-cloud-task-samples/batch-job/pom.xml +++ b/spring-cloud-task-samples/batch-job/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 io.spring.cloud @@ -14,7 +16,7 @@ org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE - + 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 5784904d..dc7907e8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.spring; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; 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 783e914e..653ce341 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.spring.configuration; import org.apache.commons.logging.Log; @@ -45,31 +46,31 @@ public class JobConfiguration { @Bean public Job job1() { - return jobBuilderFactory.get("job1") - .start(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(); } @Bean public Job job2() { - return jobBuilderFactory.get("job2") - .start(stepBuilderFactory.get("job2step1") - .tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { - logger.info("Job2 was run"); - return RepeatStatus.FINISHED; - } - }) - .build()) - .build(); + return this.jobBuilderFactory.get("job2") + .start(this.stepBuilderFactory.get("job2step1") + .tasklet(new Tasklet() { + @Override + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + logger.info("Job2 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 1444bddb..b2957008 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,23 +50,23 @@ public class BatchJobApplicationTests { String output = this.outputCapture.toString(); assertTrue("Unable to find the timestamp: " + output, - output.contains(JOB_RUN_MESSAGE)); + output.contains(JOB_RUN_MESSAGE)); assertTrue("Test results do not show create task message: " + output, - output.contains(CREATE_TASK_MESSAGE)); + output.contains(CREATE_TASK_MESSAGE)); assertTrue("Test results do not show success message: " + output, - output.contains(UPDATE_TASK_MESSAGE)); + output.contains(UPDATE_TASK_MESSAGE)); assertTrue("Test results do not show success message: " + output, - output.contains(EXIT_CODE_MESSAGE)); + output.contains(EXIT_CODE_MESSAGE)); int i = output.indexOf(JOB_ASSOCIATION_MESSAGE); assertTrue("Test results do not show the listener message: " + output, - i > 0); + i > 0); int j = output.indexOf(JOB_ASSOCIATION_MESSAGE, i + 1); assertTrue("Test results do not show the listener message: " + output, - j > i); + j > i); String taskTitle = "Demo Batch Job Task"; diff --git a/spring-cloud-task-samples/batch-job/src/test/resources/application.properties b/spring-cloud-task-samples/batch-job/src/test/resources/application.properties index de3e2f84..8643c881 100644 --- a/spring-cloud-task-samples/batch-job/src/test/resources/application.properties +++ b/spring-cloud-task-samples/batch-job/src/test/resources/application.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,6 +13,5 @@ # See the License for the specific language governing permissions and # limitations under the License. # - logging.level.root=DEBUG spring.application.name=Demo Batch Job Task diff --git a/spring-cloud-task-samples/jpa-sample/pom.xml b/spring-cloud-task-samples/jpa-sample/pom.xml index 11990107..885e4335 100644 --- a/spring-cloud-task-samples/jpa-sample/pom.xml +++ b/spring-cloud-task-samples/jpa-sample/pom.xml @@ -1,6 +1,6 @@ + --> + 4.0.0 io.spring.cloud @@ -28,7 +31,7 @@ org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE - + diff --git a/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/JpaApplication.java b/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/JpaApplication.java index 0dd47c1f..33636636 100644 --- a/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/JpaApplication.java +++ b/spring-cloud-task-samples/jpa-sample/src/main/java/io/spring/JpaApplication.java @@ -1,17 +1,17 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package io.spring; 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 b580ac8a..724388e7 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 @@ -1,17 +1,17 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package io.spring.configuration; @@ -29,7 +29,7 @@ import org.springframework.stereotype.Component; /** * Records an entry in the TASK_RUN_OUTPUT table on the BeforeTask event. - * + * * @author Glenn Renfro * @author Pas Apicella */ @@ -44,7 +44,7 @@ public class TaskRunComponent { @BeforeTask public void init(TaskExecution taskExecution) { String execDate = new SimpleDateFormat().format(new Date()); - taskRunRepository.save(new TaskRunOutput("Executed at " + execDate)); + 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 599ed97b..10612e81 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 @@ -1,17 +1,17 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package io.spring.configuration; @@ -24,7 +24,7 @@ import javax.persistence.Table; /** * Entity for the id and output to be written to the data store. - * + * * @author Pas Apicella * @author Glenn Renfro */ @@ -45,7 +45,7 @@ public class TaskRunOutput { } public Long getId() { - return id; + return this.id; } public void setId(Long id) { @@ -53,7 +53,7 @@ public class TaskRunOutput { } public String getOutput() { - return output; + return this.output; } public void setOutput(String output) { @@ -62,6 +62,6 @@ public class TaskRunOutput { @Override public String toString() { - return "TaskRunOutput{" + "id=" + id + ", output='" + output + '\'' + '}'; + 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 a97829bc..febee82b 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 @@ -1,17 +1,17 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package io.spring.configuration; diff --git a/spring-cloud-task-samples/jpa-sample/src/main/resources/application.yml b/spring-cloud-task-samples/jpa-sample/src/main/resources/application.yml index 10a5a504..25956e36 100644 --- a/spring-cloud-task-samples/jpa-sample/src/main/resources/application.yml +++ b/spring-cloud-task-samples/jpa-sample/src/main/resources/application.yml @@ -7,7 +7,7 @@ spring: name: Spring Cloud Task JPA Sample Application logging: level: - org: - springframework: - cloud: - task: debug + org: + springframework: + cloud: + task: debug 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 0d7d36bf..3a130f74 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 @@ -1,17 +1,17 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package io.spring; @@ -34,10 +34,7 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.util.SocketUtils; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Verifies that a JPA Application can write its data to a repository. @@ -56,16 +53,16 @@ public class JpaApplicationTests { private static int randomPort; - private ConfigurableApplicationContext context; - static { randomPort = SocketUtils.findAvailableTcpPort(); DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;" - + "DB_CLOSE_ON_EXIT=FALSE"; + + "DB_CLOSE_ON_EXIT=FALSE"; } + @Rule + public OutputCapture outputCapture = new OutputCapture(); + private ConfigurableApplicationContext context; private DataSource dataSource; - private Server server; @Before @@ -77,8 +74,10 @@ public class JpaApplicationTests { dataSource.setPassword(DATASOURCE_USER_PASSWORD); this.dataSource = dataSource; try { - this.server = Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort)) - .start(); + this.server = Server + .createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", String + .valueOf(randomPort)) + .start(); } catch (SQLException e) { throw new IllegalStateException(e); @@ -87,28 +86,29 @@ public class JpaApplicationTests { @After public void tearDown() { - if(this.context != null && this.context.isActive()) { + if (this.context != null && this.context.isActive()) { this.context.close(); } this.server.stop(); } - @Rule - public OutputCapture outputCapture = new OutputCapture(); - @Test public void testBatchJobApp() { 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 = this.outputCapture.toString(); - assertTrue("Unable to find the insert message: " + output, output.contains(INSERT_MESSAGE)); + 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"); - assertThat(result.get("ID"), is(1L)); - assertThat(((String) result.get("OUTPUT")), containsString("Executed at")); + 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/jpa-sample/src/test/resources/application.properties b/spring-cloud-task-samples/jpa-sample/src/test/resources/application.properties index b7ac0859..5604dab1 100644 --- a/spring-cloud-task-samples/jpa-sample/src/test/resources/application.properties +++ b/spring-cloud-task-samples/jpa-sample/src/test/resources/application.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,6 +13,5 @@ # See the License for the specific language governing permissions and # limitations under the License. # - logging.level.root=DEBUG spring.application.name=Spring Cloud Task JPA Sample Application diff --git a/spring-cloud-task-samples/multiple-datasources/pom.xml b/spring-cloud-task-samples/multiple-datasources/pom.xml index 260d9381..d509e222 100644 --- a/spring-cloud-task-samples/multiple-datasources/pom.xml +++ b/spring-cloud-task-samples/multiple-datasources/pom.xml @@ -1,12 +1,15 @@ - + 4.0.0 io.spring.cloud multiple-datasources jar 2.1.0.BUILD-SNAPSHOT - To show users how to enable a task with a multiple DataSources. + To show users how to enable a task with a multiple DataSources. + Spring Cloud Task Multiple DataSources Application @@ -14,7 +17,7 @@ org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE - + 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 023d6835..67284a86 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 @@ -1,17 +1,17 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package io.spring; 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 8ee6593b..209c91d6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.spring.configuration; import javax.sql.DataSource; diff --git a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/DataSourceConfiguration.java b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/DataSourceConfiguration.java index 93f8d176..6167f035 100644 --- a/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/DataSourceConfiguration.java +++ b/spring-cloud-task-samples/multiple-datasources/src/main/java/io/spring/configuration/DataSourceConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.spring.configuration; import javax.sql.DataSource; @@ -31,14 +32,14 @@ public class DataSourceConfiguration { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.HSQL) - .build(); + .setType(EmbeddedDatabaseType.HSQL) + .build(); } @Bean public DataSource secondDataSource() { return new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.H2) - .build(); + .setType(EmbeddedDatabaseType.H2) + .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 d63e4602..583de4bc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.spring.task; import java.util.List; + import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; @@ -37,7 +39,7 @@ public class SampleCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { - System.out.println("There are " + 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 d9463f13..510011b6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.spring; import org.junit.Rule; @@ -21,7 +22,7 @@ import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.test.rule.OutputCapture; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michael Minella @@ -38,11 +39,11 @@ public class MultiDataSourcesApplicationTests { String output = this.outputCapture.toString(); - assertTrue("Unable to find CommandLineRunner output: " + output, - output.contains("There are 2 DataSources within this application")); - assertTrue("Unable to find start task message: " + output, - output.contains("Creating: TaskExecution{")); - assertTrue("Unable to find update task message: " + output, - output.contains("Updating: TaskExecution")); + 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(); } } diff --git a/spring-cloud-task-samples/multiple-datasources/src/test/resources/application.properties b/spring-cloud-task-samples/multiple-datasources/src/test/resources/application.properties index 3a3d6633..eec48e4b 100644 --- a/spring-cloud-task-samples/multiple-datasources/src/test/resources/application.properties +++ b/spring-cloud-task-samples/multiple-datasources/src/test/resources/application.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,6 +13,5 @@ # See the License for the specific language governing permissions and # limitations under the License. # - spring.application.name=Demo Multiple DataSources Task logging.level.org.springframework.cloud.task=DEBUG diff --git a/spring-cloud-task-samples/partitioned-batch-job/pom.xml b/spring-cloud-task-samples/partitioned-batch-job/pom.xml index 49e18739..73224b80 100644 --- a/spring-cloud-task-samples/partitioned-batch-job/pom.xml +++ b/spring-cloud-task-samples/partitioned-batch-job/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 io.spring.cloud @@ -13,7 +15,7 @@ org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE - + @@ -159,7 +161,7 @@ - + spring-snapshots 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 cc00cb43..e134b549 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.spring; import java.util.ArrayList; @@ -58,41 +59,40 @@ import org.springframework.core.io.Resource; @Configuration 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; - private static final int GRID_SIZE = 4; - @Bean public PartitionHandler partitionHandler(TaskLauncher taskLauncher, JobExplorer jobExplorer) throws Exception { - Resource resource = resourceLoader.getResource("maven://io.spring.cloud:partitioned-batch-job:1.1.0.RELEASE"); + Resource resource = this.resourceLoader + .getResource("maven://io.spring.cloud:partitioned-batch-job:1.1.0.RELEASE"); - DeployerPartitionHandler partitionHandler = new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, "workerStep"); + DeployerPartitionHandler partitionHandler = + new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, "workerStep"); List commandLineArgs = new ArrayList<>(3); commandLineArgs.add("--spring.profiles.active=worker"); commandLineArgs.add("--spring.cloud.task.initialize.enable=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(1); partitionHandler.setApplicationName("PartitionedBatchJobTask"); @@ -107,7 +107,7 @@ public class JobConfiguration { Map partitions = new HashMap<>(gridSize); - for(int i = 0; i < GRID_SIZE; i++) { + for (int i = 0; i < GRID_SIZE; i++) { ExecutionContext context1 = new ExecutionContext(); context1.put("partitionNumber", i); @@ -128,7 +128,7 @@ public class JobConfiguration { @Bean @StepScope public Tasklet workerTasklet( - final @Value("#{stepExecutionContext['partitionNumber']}")Integer partitionNumber) { + final @Value("#{stepExecutionContext['partitionNumber']}") Integer partitionNumber) { return new Tasklet() { @Override @@ -142,26 +142,26 @@ public class JobConfiguration { @Bean public Step step1(PartitionHandler partitionHandler) throws Exception { - return 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 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 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 9af7a883..44eb8099 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 @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.spring; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; 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 ea9c7c52..e4a9fe7f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.cloud.task.partitioner; import java.sql.SQLException; + import javax.sql.DataSource; import io.spring.PartitionedBatchJobApplication; @@ -41,33 +42,31 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.SocketUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(classes = {TaskPartitionerTests.TaskLauncherConfiguration.class}) public class TaskPartitionerTests { - private static String DATASOURCE_URL; 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 TaskExplorer taskExplorer; - - @Autowired - private DataSource dataSource; - - @Autowired - public void setDataSource(DataSource dataSource) { - taskExplorer = new SimpleTaskExplorer(new TaskExecutionDaoFactoryBean(dataSource)); - } - + private static String DATASOURCE_URL; private static int randomPort; static { randomPort = SocketUtils.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; + + @Autowired + public void setDataSource(DataSource dataSource) { + this.taskExplorer = new SimpleTaskExplorer(new TaskExecutionDaoFactoryBean(dataSource)); } @Before @@ -93,16 +92,23 @@ public class TaskPartitionerTests { SpringApplication app = new SpringApplication(PartitionedBatchJobApplication.class); app.setAdditionalProfiles("master"); app.run("--server.port=0", "--spring.datasource.url=" + DATASOURCE_URL, - "--spring.datasource.username=" + DATASOURCE_USER_NAME, - "--spring.datasource.driverClassName=" + DATASOURCE_DRIVER_CLASS_NAME, - "--spring.cloud.deployer.local.use-spring-application-json=false"); + "--spring.datasource.username=" + DATASOURCE_USER_NAME, + "--spring.datasource.driverClassName=" + DATASOURCE_DRIVER_CLASS_NAME, + "--spring.cloud.deployer.local.use-spring-application-json=false"); - Page taskExecutions = taskExplorer.findAll(PageRequest.of(0, 10)); - assertEquals("Five rows are expected", 5, taskExecutions.getTotalElements()); - assertEquals("Only One master is expected", 1, taskExplorer.getTaskExecutionCountByTaskName("Partitioned Batch Job Task:master:0")); - assertEquals("4 partitions is expected", 4, taskExplorer.getTaskExecutionCountByTaskName("Partitioned Batch Job Task:worker:0")); + Page taskExecutions = this.taskExplorer + .findAll(PageRequest.of(0, 10)); + assertThat(taskExecutions.getTotalElements()).as("Five rows are expected") + .isEqualTo(5); + assertThat(this.taskExplorer + .getTaskExecutionCountByTaskName("Partitioned Batch Job Task:master:0")) + .as("Only One master is expected").isEqualTo(1); + assertThat(this.taskExplorer + .getTaskExecutionCountByTaskName("Partitioned Batch Job Task:worker:0")) + .as("4 partitions is expected").isEqualTo(4); for (TaskExecution taskExecution : taskExecutions) { - assertEquals("return code should be 0", 0, taskExecution.getExitCode().intValue()); + assertThat(taskExecution.getExitCode() + .intValue()).as("return code should be 0").isEqualTo(0); } } @@ -114,7 +120,7 @@ public class TaskPartitionerTests { Server server; try { server = Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", - String.valueOf(randomPort)).start(); + String.valueOf(randomPort)).start(); } catch (SQLException e) { throw new IllegalStateException(e); diff --git a/spring-cloud-task-samples/pom.xml b/spring-cloud-task-samples/pom.xml index 94ad8828..1d2da6d2 100644 --- a/spring-cloud-task-samples/pom.xml +++ b/spring-cloud-task-samples/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 diff --git a/spring-cloud-task-samples/task-events/pom.xml b/spring-cloud-task-samples/task-events/pom.xml index 77803557..6fab808e 100644 --- a/spring-cloud-task-samples/task-events/pom.xml +++ b/spring-cloud-task-samples/task-events/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 io.spring.cloud @@ -14,7 +16,7 @@ org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE - + @@ -52,7 +54,7 @@ test - + 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 6d087192..7b4fe9b8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.spring; import org.springframework.boot.CommandLineRunner; diff --git a/spring-cloud-task-samples/taskprocessor/pom.xml b/spring-cloud-task-samples/taskprocessor/pom.xml index 0b60e749..9ef55237 100644 --- a/spring-cloud-task-samples/taskprocessor/pom.xml +++ b/spring-cloud-task-samples/taskprocessor/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 io.spring.cloud @@ -8,13 +10,14 @@ jar Task Processor Sample Application - Task processor converts inbound message to a TaskLaunchRequest + Task processor converts inbound message to a TaskLaunchRequest + org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE - + 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 50221159..a6eca734 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,26 +43,32 @@ public class TaskProcessor { @Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT) public Object setupRequest(String message) { - Map properties = new HashMap(); - if(StringUtils.hasText(processorProperties.getDataSourceUrl())){ - properties.put("spring_datasource_url",processorProperties.getDataSourceUrl()); + Map properties = new HashMap<>(); + if (StringUtils.hasText(this.processorProperties.getDataSourceUrl())) { + properties + .put("spring_datasource_url", this.processorProperties + .getDataSourceUrl()); } - if(StringUtils.hasText(processorProperties.getDataSourceDriverClassName())){ - properties.put("spring_datasource_driverClassName",processorProperties.getDataSourceDriverClassName()); + if (StringUtils + .hasText(this.processorProperties.getDataSourceDriverClassName())) { + properties.put("spring_datasource_driverClassName", this.processorProperties + .getDataSourceDriverClassName()); } - if(StringUtils.hasText(processorProperties.getDataSourceUserName())){ - properties.put("spring_datasource_username",processorProperties.getDataSourceUserName()); + if (StringUtils.hasText(this.processorProperties.getDataSourceUserName())) { + properties.put("spring_datasource_username", this.processorProperties + .getDataSourceUserName()); } - if(StringUtils.hasText(processorProperties.getDataSourcePassword())){ - properties.put("spring_datasource_password",processorProperties.getDataSourcePassword()); + if (StringUtils.hasText(this.processorProperties.getDataSourcePassword())) { + properties.put("spring_datasource_password", this.processorProperties + .getDataSourcePassword()); } properties.put("payload", message); TaskLaunchRequest request = new TaskLaunchRequest( - processorProperties.getUri(), null, properties, null, - processorProperties.getApplicationName()); + this.processorProperties.getUri(), null, properties, null, + this.processorProperties.getApplicationName()); - return new GenericMessage(request); + return new GenericMessage<>(request); } } 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 58fbb8ef..508e8ee8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. 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 d3618cd0..3a53a4a9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +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; @@ -41,9 +41,8 @@ public class TaskProcessorProperties { private String applicationName; - public String getDataSourceUrl() { - return dataSourceUrl; + return this.dataSourceUrl; } public void setDataSourceUrl(String dataSourceUrl) { @@ -51,7 +50,7 @@ public class TaskProcessorProperties { } public String getDataSourceDriverClassName() { - return dataSourceDriverClassName; + return this.dataSourceDriverClassName; } public void setDataSourceDriverClassName(String dataSourceDriverClassName) { @@ -59,7 +58,7 @@ public class TaskProcessorProperties { } public String getDataSourceUserName() { - return dataSourceUserName; + return this.dataSourceUserName; } public void setDataSourceUserName(String dataSourceUserName) { @@ -67,7 +66,7 @@ public class TaskProcessorProperties { } public String getDataSourcePassword() { - return dataSourcePassword; + return this.dataSourcePassword; } public void setDataSourcePassword(String dataSourcePassword) { @@ -75,7 +74,7 @@ public class TaskProcessorProperties { } public String getUri() { - return uri; + return this.uri; } public void setUri(String uri) { @@ -83,7 +82,7 @@ public class TaskProcessorProperties { } public String getApplicationName() { - return applicationName; + return this.applicationName; } public void setApplicationName(String 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 16e34e57..3201d9ff 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; import org.springframework.test.context.junit4.SpringRunner; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro @@ -53,18 +52,21 @@ public class TaskProcessorApplicationTests { private ObjectMapper mapper = new ObjectMapper(); - @Test - public void test() throws InterruptedException, IOException { - channels.input().send(new GenericMessage(DEFAULT_PAYLOAD)); - 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); - Message result = (Message)collector.forChannel(channels.output()).take(); - TaskLaunchRequest tlq = mapper.readValue(result.getPayload(),TaskLaunchRequest.class); - assertThat(tlq, is(expectedRequest)); - } + @Test + public void test() throws InterruptedException, IOException { + this.channels.input().send(new GenericMessage(DEFAULT_PAYLOAD)); + 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); + Message result = (Message) this.collector + .forChannel(this.channels.output()) + .take(); + TaskLaunchRequest tlq = this.mapper + .readValue(result.getPayload(), TaskLaunchRequest.class); + assertThat(tlq).isEqualTo(expectedRequest); + } } diff --git a/spring-cloud-task-samples/tasksink/pom.xml b/spring-cloud-task-samples/tasksink/pom.xml index ef2569a8..6ca15395 100644 --- a/spring-cloud-task-samples/tasksink/pom.xml +++ b/spring-cloud-task-samples/tasksink/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 io.spring.cloud @@ -8,13 +10,15 @@ jar Task Sink Sample Application - Launches tasks based on contents of TaskLaunchRequest for local deployer + Launches tasks based on contents of TaskLaunchRequest for local + deployer + org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE - + 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 0bf0e77a..2c221b06 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. 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 2849b0fb..261db3d9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,9 +34,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.messaging.support.GenericMessage; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; /** @@ -54,29 +52,32 @@ public class TaskSinkApplicationTests { @Test public void testLaunch() throws IOException { - assertNotNull(this.sink.input()); + assertThat(this.sink.input()).isNotNull(); TaskLauncher testTaskLauncher = - context.getBean(TaskLauncher.class); + this.context.getBean(TaskLauncher.class); Map properties = new HashMap(); properties.put("server.port", "0"); TaskLaunchRequest request = new TaskLaunchRequest( - "maven://org.springframework.cloud.task.app:" + "maven://org.springframework.cloud.task.app:" + "timestamp-task:jar:1.0.1.RELEASE", null, properties, - null, null); - GenericMessage message = new GenericMessage(request); + null, null); + GenericMessage message = new GenericMessage<>(request); this.sink.input().send(message); - ArgumentCaptor deploymentRequest = ArgumentCaptor.forClass(AppDeploymentRequest.class); + ArgumentCaptor deploymentRequest = ArgumentCaptor + .forClass(AppDeploymentRequest.class); verify(testTaskLauncher).launch(deploymentRequest.capture()); AppDeploymentRequest actualRequest = deploymentRequest.getValue(); - assertTrue(actualRequest.getCommandlineArguments().isEmpty()); - assertEquals("0", actualRequest.getDefinition().getProperties().get("server.port")); - assertTrue(actualRequest.getResource().toString() - .contains("maven://org.springframework.cloud.task.app:timestamp-task:jar:1.0.1.RELEASE")); + assertThat(actualRequest.getCommandlineArguments().isEmpty()).isTrue(); + assertThat(actualRequest.getDefinition().getProperties() + .get("server.port")).isEqualTo("0"); + assertThat(actualRequest.getResource().toString() + .contains("maven://org.springframework.cloud.task.app:timestamp-task:jar:1.0.1.RELEASE")) + .isTrue(); } } diff --git a/spring-cloud-task-samples/tasksink/src/test/java/io/spring/configuration/TaskSinkConfiguration.java b/spring-cloud-task-samples/tasksink/src/test/java/io/spring/configuration/TaskSinkConfiguration.java index 38ee8add..c7d8a9a1 100644 --- a/spring-cloud-task-samples/tasksink/src/test/java/io/spring/configuration/TaskSinkConfiguration.java +++ b/spring-cloud-task-samples/tasksink/src/test/java/io/spring/configuration/TaskSinkConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-task-samples/timestamp/pom.xml b/spring-cloud-task-samples/timestamp/pom.xml index bf07b117..fc8fe2c5 100644 --- a/spring-cloud-task-samples/timestamp/pom.xml +++ b/spring-cloud-task-samples/timestamp/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 @@ -14,11 +16,12 @@ org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE - + - org.springframework.cloud.task.timestamp.TaskApplication + org.springframework.cloud.task.timestamp.TaskApplication + true 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 6689502f..491825c6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,23 +35,22 @@ import org.springframework.context.annotation.Bean; /** * Spring Boot Application that has tasks enabled. */ - @EnableTask @SpringBootApplication -@EnableConfigurationProperties({ TimestampTaskProperties.class }) +@EnableConfigurationProperties({TimestampTaskProperties.class}) public class TaskApplication { private static final Log logger = LogFactory.getLog(TaskApplication.class); + public static void main(String[] args) { + SpringApplication.run(TaskApplication.class, args); + } + @Bean public TimestampTask timeStampTask() { return new TimestampTask(); } - public static void main(String[] args) { - SpringApplication.run(TaskApplication.class, args); - } - /** * A commandline runner that prints a timestamp. */ @@ -62,7 +61,7 @@ public class TaskApplication { @Override public void run(String... strings) throws Exception { - DateFormat dateFormat = new SimpleDateFormat(config.getFormat()); + 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 a79eef7f..70b251d8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ public class TimestampTaskProperties { private String format = "yyyy-MM-dd HH:mm:ss.SSS"; public String getFormat() { - Assert.hasText(format, "format must not be empty nor null"); - return format; + Assert.hasText(this.format, "format must not be empty nor null"); + return this.format; } public void setFormat(String 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 7a47f8bf..00c6cd2d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.test.rule.OutputCapture; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Verifies that the Task Application outputs the correct task log entries. @@ -44,19 +43,19 @@ public class TaskApplicationTests { 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 = this.outputCapture.toString(); - assertTrue("Unable to find the timestamp: " + output, - output.contains(TEST_DATE_DOTS)); - assertTrue("Test results do not show create task message: " + output, - output.contains(CREATE_TASK_MESSAGE)); - assertTrue("Test results do not show success message: " + output, - output.contains(UPDATE_TASK_MESSAGE)); - assertTrue("Test results have incorrect exit code: " + output, - output.contains(EXIT_CODE_MESSAGE)); + 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); @@ -65,6 +64,7 @@ public class TaskApplicationTests { while (matcher.find()) { count++; } - assertEquals("The number of task titles did not match expected: ", 1, count); + 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 95e78ea5..18c907b9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,15 @@ package org.springframework.cloud.task.timestamp; -import static org.junit.Assert.assertEquals; - import org.junit.Test; + import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; +import static org.assertj.core.api.Assertions.assertThat; + /** * @author Glenn Renfro */ @@ -36,7 +37,8 @@ public class TimestampTaskPropertiesTests { testPropertyValues.applyTo(context); context.register(Conf.class); context.refresh(); - TimestampTaskProperties properties = context.getBean(TimestampTaskProperties.class); + TimestampTaskProperties properties = context + .getBean(TimestampTaskProperties.class); properties.getFormat(); } @@ -45,9 +47,10 @@ public class TimestampTaskPropertiesTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Conf.class); context.refresh(); - TimestampTaskProperties properties = context.getBean(TimestampTaskProperties.class); - assertEquals("result does not match default format.", "yyyy-MM-dd HH:mm:ss.SSS", - properties.getFormat()); + TimestampTaskProperties properties = context + .getBean(TimestampTaskProperties.class); + assertThat(properties.getFormat()).as("result does not match default format.") + .isEqualTo("yyyy-MM-dd HH:mm:ss.SSS"); } @Test @@ -56,10 +59,11 @@ 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); - assertEquals("result does not match established format.", FORMAT, - properties.getFormat()); + assertThat(properties.getFormat()).as("result does not match established format.") + .isEqualTo(FORMAT); } @Configuration diff --git a/spring-cloud-task-samples/timestamp/src/test/resources/application.properties b/spring-cloud-task-samples/timestamp/src/test/resources/application.properties index 575294ca..87771b4b 100644 --- a/spring-cloud-task-samples/timestamp/src/test/resources/application.properties +++ b/spring-cloud-task-samples/timestamp/src/test/resources/application.properties @@ -1,5 +1,5 @@ # -# Copyright 2016 the original author or authors. +# Copyright 2015-2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,6 +13,5 @@ # See the License for the specific language governing permissions and # limitations under the License. # - logging.level.org.springframework.cloud.task=DEBUG spring.application.name=Demo Timestamp Task diff --git a/spring-cloud-task-stream/pom.xml b/spring-cloud-task-stream/pom.xml index 9e38526c..10d7c8ff 100644 --- a/spring-cloud-task-stream/pom.xml +++ b/spring-cloud-task-stream/pom.xml @@ -1,10 +1,12 @@ - + 4.0.0 spring-cloud-task-stream jar - Spring Cloud Task Stream + Spring Cloud Task Stream Allows a Task to be a part of a stream 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 8c1cfff6..093828f1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.listener; import org.springframework.batch.core.ChunkListener; @@ -42,16 +43,17 @@ import org.springframework.context.annotation.Lazy; import org.springframework.messaging.MessageChannel; /** - * Autoconfigures Spring Batch listeners designed to emit events on the following channels: + * Autoconfigures Spring Batch listeners designed to emit events on the following + * channels. * *
      - *
    • {@link EventEmittingJobExecutionListener} - job-execution-events
    • - *
    • {@link EventEmittingStepExecutionListener} - step-execution-events
    • - *
    • {@link ChunkListener} - chunk-events
    • - *
    • {@link EventEmittingItemReadListener} - item-read-events
    • - *
    • {@link EventEmittingItemProcessListener} - item-process-events
    • - *
    • {@link EventEmittingItemWriteListener} - item-write-events
    • - *
    • {@link EventEmittingSkipListener} - skip-events
    • + *
    • {@link EventEmittingJobExecutionListener} - job-execution-events
    • + *
    • {@link EventEmittingStepExecutionListener} - step-execution-events
    • + *
    • {@link ChunkListener} - chunk-events
    • + *
    • {@link EventEmittingItemReadListener} - item-read-events
    • + *
    • {@link EventEmittingItemProcessListener} - item-process-events
    • + *
    • {@link EventEmittingItemWriteListener} - item-write-events
    • + *
    • {@link EventEmittingSkipListener} - skip-events
    • *
    * * @author Michael Minella @@ -60,17 +62,46 @@ import org.springframework.messaging.MessageChannel; */ @Configuration @ConditionalOnClass(Job.class) -@ConditionalOnBean(value = { Job.class, TaskLifecycleListener.class }) +@ConditionalOnBean({ Job.class, TaskLifecycleListener.class }) +// @checkstyle:off @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events", name = "enabled", havingValue = "true", matchIfMissing = true) +// @checkstyle:on @AutoConfigureAfter(SimpleTaskAutoConfiguration.class) public class BatchEventAutoConfiguration { + /** + * Name of the job execution events listener. + */ public static final String JOB_EXECUTION_EVENTS_LISTENER = "jobExecutionEventsListener"; + + /** + * Name of the chunk events listener. + */ public static final String CHUNK_EVENTS_LISTENER = "chunkEventsListener"; + + /** + * Name of the step execution events listener. + */ public static final String STEP_EXECUTION_EVENTS_LISTENER = "stepExecutionEventsListener"; + + /** + * Name of the item read events listener. + */ public static final String ITEM_READ_EVENTS_LISTENER = "itemReadEventsListener"; + + /** + * Name of the item write events listener. + */ public static final String ITEM_WRITE_EVENTS_LISTENER = "itemWriteEventsListener"; + + /** + * Name of the item process events listener. + */ public static final String ITEM_PROCESS_EVENTS_LISTENER = "itemProcessEventsListener"; + + /** + * Name of the skip events listener. + */ public static final String SKIP_EVENTS_LISTENER = "skipEventsListener"; @Bean @@ -79,72 +110,44 @@ public class BatchEventAutoConfiguration { return new TaskBatchEventListenerBeanPostProcessor(); } - @Configuration - @ConditionalOnClass(EnableBinding.class) - @EnableBinding(BatchEventsChannels.class) - @EnableConfigurationProperties(TaskEventProperties.class) - @ConditionalOnMissingBean(name = JOB_EXECUTION_EVENTS_LISTENER) - public static class JobExecutionListenerConfiguration { - - @Autowired - private BatchEventsChannels listenerChannels; - - @Autowired - private TaskEventProperties taskEventProperties; - - @Bean - @Lazy - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.job-execution", name = "enabled", havingValue = "true", matchIfMissing = true) - public JobExecutionListener jobExecutionEventsListener() { - return new EventEmittingJobExecutionListener(listenerChannels.jobExecutionEvents(),taskEventProperties.getJobExecutionOrder()); - } - - @Bean - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.step-execution", name = "enabled", havingValue = "true", matchIfMissing = true) - public StepExecutionListener stepExecutionEventsListener() { - return new EventEmittingStepExecutionListener(listenerChannels.stepExecutionEvents(),taskEventProperties.getStepExecutionOrder()); - } - - @Bean - @Lazy - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.chunk", name = "enabled", havingValue = "true", matchIfMissing = true) - public EventEmittingChunkListener chunkEventsListener() { - return new EventEmittingChunkListener(listenerChannels.chunkEvents(),taskEventProperties.getChunkOrder()); - } - - @Bean - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-read", name = "enabled", havingValue = "true", matchIfMissing = true) - public ItemReadListener itemReadEventsListener() { - return new EventEmittingItemReadListener(listenerChannels.itemReadEvents(),taskEventProperties.getItemReadOrder()); - } - - @Bean - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-write", name = "enabled", havingValue = "true", matchIfMissing = true) - public ItemWriteListener itemWriteEventsListener() { - return new EventEmittingItemWriteListener(listenerChannels.itemWriteEvents(),taskEventProperties.getItemWriteOrder()); - } - - @Bean - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-process", name = "enabled", havingValue = "true", matchIfMissing = true) - public ItemProcessListener itemProcessEventsListener() { - return new EventEmittingItemProcessListener(listenerChannels.itemProcessEvents(),taskEventProperties.getItemProcessOrder()); - } - - @Bean - @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.skip", name = "enabled", havingValue = "true", matchIfMissing = true) - public SkipListener skipEventsListener() { - return new EventEmittingSkipListener(listenerChannels.skipEvents(),taskEventProperties.getItemProcessOrder()); - } - } - + /** + * Name of Batch Events channels. + */ public interface BatchEventsChannels { + /** + * Name of the job execution events channel. + */ String JOB_EXECUTION_EVENTS = "job-execution-events"; + + /** + * Name of the step execution events channel. + */ String STEP_EXECUTION_EVENTS = "step-execution-events"; + + /** + * Name of the chunk execution events channel. + */ String CHUNK_EXECUTION_EVENTS = "chunk-events"; + + /** + * Name of the item read events channel. + */ String ITEM_READ_EVENTS = "item-read-events"; + + /** + * Name of the item process events channel. + */ String ITEM_PROCESS_EVENTS = "item-process-events"; + + /** + * Name of the item write events channel. + */ String ITEM_WRITE_EVENTS = "item-write-events"; + + /** + * Name of the skip events channel. + */ String SKIP_EVENTS = "skip-events"; @Output(JOB_EXECUTION_EVENTS) @@ -169,4 +172,93 @@ public class BatchEventAutoConfiguration { MessageChannel skipEvents(); } + + /** + * Configuration for Job Execution Listener. + */ + @Configuration + @ConditionalOnClass(EnableBinding.class) + @EnableBinding(BatchEventsChannels.class) + @EnableConfigurationProperties(TaskEventProperties.class) + @ConditionalOnMissingBean(name = JOB_EXECUTION_EVENTS_LISTENER) + public static class JobExecutionListenerConfiguration { + + @Autowired + private BatchEventsChannels listenerChannels; + + @Autowired + private TaskEventProperties taskEventProperties; + + // @checkstyle:off + @Bean + @Lazy + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.job-execution", name = "enabled", havingValue = "true", matchIfMissing = true) + // @checkstyle:on + public JobExecutionListener jobExecutionEventsListener() { + return new EventEmittingJobExecutionListener( + this.listenerChannels.jobExecutionEvents(), + this.taskEventProperties.getJobExecutionOrder()); + } + + // @checkstyle:off + @Bean + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.step-execution", name = "enabled", havingValue = "true", matchIfMissing = true) + // @checkstyle:on + public StepExecutionListener stepExecutionEventsListener() { + return new EventEmittingStepExecutionListener( + this.listenerChannels.stepExecutionEvents(), + this.taskEventProperties.getStepExecutionOrder()); + } + + // @checkstyle:off + @Bean + @Lazy + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.chunk", name = "enabled", havingValue = "true", matchIfMissing = true) + // @checkstyle:on + public EventEmittingChunkListener chunkEventsListener() { + return new EventEmittingChunkListener(this.listenerChannels.chunkEvents(), + this.taskEventProperties.getChunkOrder()); + } + + // @checkstyle:off + @Bean + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-read", name = "enabled", havingValue = "true", matchIfMissing = true) + // @checkstyle:on + public ItemReadListener itemReadEventsListener() { + return new EventEmittingItemReadListener( + this.listenerChannels.itemReadEvents(), + this.taskEventProperties.getItemReadOrder()); + } + + // @checkstyle:off + @Bean + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-write", name = "enabled", havingValue = "true", matchIfMissing = true) + // @checkstyle:on + public ItemWriteListener itemWriteEventsListener() { + return new EventEmittingItemWriteListener( + this.listenerChannels.itemWriteEvents(), + this.taskEventProperties.getItemWriteOrder()); + } + + // @checkstyle:off + @Bean + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.item-process", name = "enabled", havingValue = "true", matchIfMissing = true) + // @checkstyle:on + public ItemProcessListener itemProcessEventsListener() { + return new EventEmittingItemProcessListener( + this.listenerChannels.itemProcessEvents(), + this.taskEventProperties.getItemProcessOrder()); + } + + // @checkstyle:off + @Bean + @ConditionalOnProperty(prefix = "spring.cloud.task.batch.events.skip", name = "enabled", havingValue = "true", matchIfMissing = true) + // @checkstyle:on + public SkipListener skipEventsListener() { + return new EventEmittingSkipListener(this.listenerChannels.skipEvents(), + this.taskEventProperties.getItemProcessOrder()); + } + + } + } 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 34df52bb..38449ef5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.listener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.batch.core.ChunkListener; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.cloud.task.batch.listener.support.MessagePublisher; @@ -25,11 +27,12 @@ import org.springframework.messaging.MessageChannel; import org.springframework.util.Assert; /** - * Provides informational messages around the {@link org.springframework.batch.core.step.item.Chunk} of a batch job. + * Provides informational messages around the + * {@link org.springframework.batch.core.step.item.Chunk} of a batch job. * - * The {@link ChunkListener#beforeChunk(ChunkContext)} and - * {@link ChunkListener#afterChunk(ChunkContext)} are both no-ops in this implementation. - * {@link ChunkListener#afterChunkError(ChunkContext)}. + * The {@link ChunkListener#beforeChunk(ChunkContext)} and + * {@link ChunkListener#afterChunk(ChunkContext)} are both no-ops in this implementation. + * {@link ChunkListener#afterChunkError(ChunkContext)}. * * @author Ali Shahbour */ @@ -38,6 +41,7 @@ public class EventEmittingChunkListener implements ChunkListener, Ordered { private static final Log logger = LogFactory.getLog(EventEmittingChunkListener.class); private MessagePublisher messagePublisher; + private int order = Ordered.LOWEST_PRECEDENCE; public EventEmittingChunkListener(MessageChannel output) { @@ -52,12 +56,12 @@ public class EventEmittingChunkListener implements ChunkListener, Ordered { @Override public void beforeChunk(ChunkContext context) { - messagePublisher.publish("Before Chunk Processing"); + this.messagePublisher.publish("Before Chunk Processing"); } @Override public void afterChunk(ChunkContext context) { - messagePublisher.publish("After Chunk Processing"); + this.messagePublisher.publish("After Chunk Processing"); } @Override @@ -69,4 +73,5 @@ public class EventEmittingChunkListener implements ChunkListener, Ordered { public int getOrder() { return this.order; } + } 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 223a390b..eba27c70 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.listener; import org.springframework.batch.core.ItemProcessListener; @@ -40,6 +41,7 @@ import org.springframework.util.Assert; public class EventEmittingItemProcessListener implements ItemProcessListener, Ordered { private MessagePublisher messagePublisher; + private int order = Ordered.LOWEST_PRECEDENCE; public EventEmittingItemProcessListener(MessageChannel output) { @@ -59,23 +61,25 @@ public class EventEmittingItemProcessListener implements ItemProcessListener, Or @Override public void afterProcess(Object item, Object result) { if (result == null) { - messagePublisher.publish("1 item was filtered"); + this.messagePublisher.publish("1 item was filtered"); } else if (item.equals(result)) { - messagePublisher.publish("item equaled result after processing"); + this.messagePublisher.publish("item equaled result after processing"); } else { - messagePublisher.publish("item did not equal result after processing"); + this.messagePublisher.publish("item did not equal result after processing"); } } @Override public void onProcessError(Object item, Exception e) { - messagePublisher.publishWithThrowableHeader("Exception while item was being processed", e.getMessage()); + this.messagePublisher.publishWithThrowableHeader( + "Exception while item was being processed", e.getMessage()); } @Override public int getOrder() { return this.order; } + } 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 a5ae9f8a..fcf81ffb 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener; @@ -28,21 +28,23 @@ import org.springframework.messaging.MessageChannel; import org.springframework.util.Assert; /** - * Provides informational messages around the {@link ItemReader} of a batch job. + * Provides informational messages around the {@link ItemReader} of a batch job. * - * The {@link ItemReadListener#beforeRead()} and - * {@link ItemReadListener#afterRead(Object)} are both no-ops in this implementation. - * {@link ItemReadListener#onReadError(Exception)} provides the exception - * via the {@link BatchJobHeaders#BATCH_EXCEPTION} message header. + * The {@link ItemReadListener#beforeRead()} and + * {@link ItemReadListener#afterRead(Object)} are both no-ops in this implementation. + * {@link ItemReadListener#onReadError(Exception)} provides the exception via the + * {@link BatchJobHeaders#BATCH_EXCEPTION} message header. * * @author Glenn Renfro * @author Ali Shahbour */ 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 MessagePublisher messagePublisher; + private int order = Ordered.LOWEST_PRECEDENCE; public EventEmittingItemReadListener(MessageChannel output) { @@ -71,11 +73,13 @@ public class EventEmittingItemReadListener implements ItemReadListener, Ordered logger.debug("Executing onReadError: " + ex.getMessage(), ex); } - messagePublisher.publishWithThrowableHeader("Exception while item was being read", ex.getMessage()); + this.messagePublisher.publishWithThrowableHeader( + "Exception while item was being read", ex.getMessage()); } @Override public int getOrder() { return this.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 923e9f17..c4cd6f3d 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener; @@ -29,20 +29,23 @@ import org.springframework.messaging.MessageChannel; import org.springframework.util.Assert; /** - * Setups up the ItemWriteEventsListener to emit events to the spring cloud stream output channel. + * Setups up the ItemWriteEventsListener to emit events to the spring cloud stream output + * channel. * - * Each method provides an informational message. - * {@link ItemWriteListener#onWriteError(Exception, List)} provides a message as well as - * the exception's message via the {@link BatchJobHeaders#BATCH_EXCEPTION} message header. + * Each method provides an informational message. + * {@link ItemWriteListener#onWriteError(Exception, List)} provides a message as well as + * the exception's message via the {@link BatchJobHeaders#BATCH_EXCEPTION} message header. * * @author Glenn Renfro * @author Ali Shahbour */ 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 MessagePublisher messagePublisher; + private int order = Ordered.LOWEST_PRECEDENCE; public EventEmittingItemWriteListener(MessageChannel output) { @@ -73,7 +76,8 @@ 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."; + String payload = "Exception while " + items.size() + + " items are attempted to be written."; this.messagePublisher.publishWithThrowableHeader(payload, exception.getMessage()); } @@ -81,4 +85,5 @@ public class EventEmittingItemWriteListener implements ItemWriteListener, Ordere public int getOrder() { return this.order; } + } 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 8b52830c..555b279c 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 @@ -1,18 +1,19 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.cloud.task.batch.listener; import org.springframework.batch.core.JobExecution; @@ -33,6 +34,7 @@ import org.springframework.util.Assert; public class EventEmittingJobExecutionListener implements JobExecutionListener, Ordered { private MessagePublisher messagePublisher; + private int order = Ordered.LOWEST_PRECEDENCE; public EventEmittingJobExecutionListener(MessageChannel output) { @@ -59,4 +61,5 @@ public class EventEmittingJobExecutionListener implements JobExecutionListener, public int getOrder() { return this.order; } + } 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 c974ac8a..2275fa68 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener; @@ -27,10 +27,11 @@ import org.springframework.messaging.MessageChannel; import org.springframework.util.Assert; /** - * Setups up the SkipProcessListener to emit events to the spring cloud stream output channel. + * Setups up the SkipProcessListener to emit events to the spring cloud stream output + * channel. * * This listener emits the exception's message via the - * {@link BatchJobHeaders#BATCH_EXCEPTION} message header for each method. For + * {@link BatchJobHeaders#BATCH_EXCEPTION} message header for each method. For * {@link SkipListener#onSkipInProcess(Object, Throwable)} and * {@link SkipListener#onSkipInWrite(Object, Throwable)} the body of the message consists * of the item that caused the error. @@ -43,6 +44,7 @@ public class EventEmittingSkipListener implements SkipListener, Ordered { private static final Log logger = LogFactory.getLog(EventEmittingSkipListener.class); private MessagePublisher messagePublisher; + private int order = Ordered.LOWEST_PRECEDENCE; public EventEmittingSkipListener(MessageChannel output) { @@ -60,7 +62,8 @@ public class EventEmittingSkipListener implements SkipListener, Ordered { if (logger.isDebugEnabled()) { logger.debug("Executing onSkipInRead: " + t.getMessage(), t); } - messagePublisher.publishWithThrowableHeader("Skipped when reading.", t.getMessage()); + this.messagePublisher.publishWithThrowableHeader("Skipped when reading.", + t.getMessage()); } @Override @@ -68,7 +71,7 @@ public class EventEmittingSkipListener implements SkipListener, Ordered { if (logger.isDebugEnabled()) { logger.debug("Executing onSkipInWrite: " + t.getMessage(), t); } - messagePublisher.publishWithThrowableHeader(item, t.getMessage()); + this.messagePublisher.publishWithThrowableHeader(item, t.getMessage()); } @Override @@ -76,11 +79,12 @@ public class EventEmittingSkipListener implements SkipListener, Ordered { if (logger.isDebugEnabled()) { logger.debug("Executing onSkipInProcess: " + t.getMessage(), t); } - messagePublisher.publishWithThrowableHeader(item, t.getMessage()); + this.messagePublisher.publishWithThrowableHeader(item, t.getMessage()); } @Override public int getOrder() { return this.order; } + } 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 78a351a9..b32b22d7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,29 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.listener; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; -import org.springframework.cloud.task.batch.listener.support.StepExecutionEvent; import org.springframework.cloud.task.batch.listener.support.MessagePublisher; +import org.springframework.cloud.task.batch.listener.support.StepExecutionEvent; import org.springframework.core.Ordered; import org.springframework.messaging.MessageChannel; import org.springframework.util.Assert; /** * Provides a {@link StepExecutionEvent} at the start and end of each step indicating the - * step's status. The {@link StepExecutionListener#afterStep(StepExecution)} returns the + * step's status. The {@link StepExecutionListener#afterStep(StepExecution)} returns the * {@link ExitStatus} of the inputted {@link StepExecution}. * * @author Michael Minella * @author Glenn Renfro * @author Ali Shahbour */ -public class EventEmittingStepExecutionListener implements StepExecutionListener, Ordered { +public class EventEmittingStepExecutionListener + implements StepExecutionListener, Ordered { private MessagePublisher messagePublisher; + private int order = Ordered.LOWEST_PRECEDENCE; public EventEmittingStepExecutionListener(MessageChannel output) { @@ -64,4 +67,5 @@ public class EventEmittingStepExecutionListener implements StepExecutionListener public int getOrder() { return this.order; } + } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/BatchJobHeaders.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/BatchJobHeaders.java index bd3ce8f8..c198c836 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/BatchJobHeaders.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/BatchJobHeaders.java @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener.support; @@ -24,8 +24,14 @@ package org.springframework.cloud.task.batch.listener.support; */ public final class BatchJobHeaders { + /** + * Name of the batch listener event type. + */ public static final String BATCH_LISTENER_EVENT_TYPE = "batch_listener_event_type"; + /** + * Name of the batch exception. + */ public static final String BATCH_EXCEPTION = "batch_exception"; private BatchJobHeaders() { diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/ExitStatus.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/ExitStatus.java index f2dca30d..e5b71e2f 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/ExitStatus.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/ExitStatus.java @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener.support; @@ -19,8 +19,9 @@ package org.springframework.cloud.task.batch.listener.support; import org.springframework.util.Assert; /** - * ExitStatus DTO created so that {@link org.springframework.batch.core.ExitStatus} can be serialized into Json without - * having to add mixins to an ObjectMapper + * ExitStatus DTO created so that {@link org.springframework.batch.core.ExitStatus} can be + * serialized into Json without. having to add mixins to an ObjectMapper + * * @author Glenn Renfro */ public class ExitStatus { @@ -29,7 +30,7 @@ public class ExitStatus { private String exitDescription; - public ExitStatus(){ + public ExitStatus() { } public ExitStatus(org.springframework.batch.core.ExitStatus exitStatus) { @@ -40,7 +41,7 @@ public class ExitStatus { } public String getExitCode() { - return exitCode; + return this.exitCode; } public void setExitCode(String exitCode) { @@ -48,10 +49,11 @@ public class ExitStatus { } public String getExitDescription() { - return exitDescription; + return this.exitDescription; } public void setExitDescription(String exitDescription) { this.exitDescription = exitDescription; } + } 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 4379c40c..f546c3a2 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener.support; @@ -33,8 +33,10 @@ import org.springframework.batch.core.StepExecution; import org.springframework.batch.item.ExecutionContext; /** - * This is a JobEvent DTO created so that a {@link org.springframework.batch.core.JobExecution} can be serialized into - * Json without having to add mixins to an ObjectMapper. + * This is a JobEvent DTO created so that a + * {@link org.springframework.batch.core.JobExecution} can be serialized into Json without + * having to add mixins to an ObjectMapper. + * * @author Glenn Renfro */ public class JobExecutionEvent extends Entity { @@ -43,7 +45,7 @@ public class JobExecutionEvent extends Entity { private JobInstanceEvent jobInstance; - private Collection stepExecutions = new CopyOnWriteArraySet(); + private Collection stepExecutions = new CopyOnWriteArraySet<>(); private BatchStatus status = BatchStatus.STARTING; @@ -55,11 +57,12 @@ 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(); - private List failureExceptions = new CopyOnWriteArrayList(); + private List failureExceptions = new CopyOnWriteArrayList<>(); private String jobConfigurationName; @@ -69,14 +72,15 @@ public class JobExecutionEvent extends Entity { /** * Constructor for the StepExecution to initialize the DTO. - * * @param original the StepExecution to build this DTO around. */ public JobExecutionEvent(JobExecution original) { - this.jobParameters = new JobParametersEvent(original.getJobParameters().getParameters()); - this.jobInstance = new JobInstanceEvent(original.getJobInstance().getId(), original.getJobInstance().getJobName()); - for(StepExecution stepExecution : original.getStepExecutions()){ - stepExecutions.add(new StepExecutionEvent(stepExecution)); + this.jobParameters = new JobParametersEvent( + original.getJobParameters().getParameters()); + this.jobInstance = new JobInstanceEvent(original.getJobInstance().getId(), + original.getJobInstance().getJobName()); + for (StepExecution stepExecution : original.getStepExecutions()) { + this.stepExecutions.add(new StepExecutionEvent(stepExecution)); } this.status = original.getStatus(); this.startTime = original.getStartTime(); @@ -99,16 +103,12 @@ public class JobExecutionEvent extends Entity { return this.endTime; } - public void setJobInstance(JobInstanceEvent jobInstance) { - this.jobInstance = jobInstance; - } - public void setEndTime(Date endTime) { this.endTime = endTime; } public Date getStartTime() { - return startTime; + return this.startTime; } public void setStartTime(Date startTime) { @@ -121,7 +121,6 @@ public class JobExecutionEvent extends Entity { /** * Set the value of the status field. - * * @param status the status to set */ public void setStatus(BatchStatus status) { @@ -129,10 +128,9 @@ public class JobExecutionEvent extends Entity { } /** - * Upgrade the status field if the provided value is greater than the - * existing one. Clients using this method to set the status can be sure - * that they don't overwrite a failed status with an successful one. - * + * Upgrade the status field if the provided value is greater than the existing one. + * Clients using this method to set the status can be sure that they don't overwrite a + * failed status with an successful one. * @param status the new status value */ public void upgradeStatus(BatchStatus status) { @@ -142,23 +140,15 @@ public class JobExecutionEvent extends Entity { /** * Convenience getter for for the id of the enclosing job. Useful for DAO * implementations. - * * @return the id of the enclosing job */ public Long getJobId() { - if (jobInstance != null) { - return jobInstance.getId(); + if (this.jobInstance != null) { + return this.jobInstance.getId(); } return null; } - /** - * @param exitStatus the exit status for the job. - */ - public void setExitStatus(ExitStatus exitStatus) { - this.exitStatus = exitStatus; - } - /** * @return the exitCode for the job. */ @@ -166,6 +156,13 @@ public class JobExecutionEvent extends Entity { return this.exitStatus; } + /** + * @param exitStatus the exit status for the job. + */ + public void setExitStatus(ExitStatus exitStatus) { + this.exitStatus = exitStatus; + } + /** * @return the Job that is executing. */ @@ -173,9 +170,12 @@ public class JobExecutionEvent extends Entity { return this.jobInstance; } + public void setJobInstance(JobInstanceEvent jobInstance) { + this.jobInstance = jobInstance; + } + /** * Accessor for the step executions. - * * @return the step executions that were registered */ public Collection getStepExecutions() { @@ -183,24 +183,22 @@ public class JobExecutionEvent extends Entity { } /** - * Sets the {@link ExecutionContext} for this execution - * - * @param executionContext the context - */ - public void setExecutionContext(ExecutionContext executionContext) { - this.executionContext = executionContext; - } - - /** - * Returns the {@link ExecutionContext} for this execution. The content is - * expected to be persisted after each step completion (successful or not). - * + * Returns the {@link ExecutionContext} for this execution. The content is expected to + * be persisted after each step completion (successful or not). * @return the context */ public ExecutionContext getExecutionContext() { return this.executionContext; } + /** + * Sets the {@link ExecutionContext} for this execution. + * @param executionContext the context + */ + public void setExecutionContext(ExecutionContext executionContext) { + this.executionContext = executionContext; + } + /** * @return the time when this execution was created. */ @@ -220,9 +218,8 @@ public class JobExecutionEvent extends Entity { } /** - * Get the date representing the last time this JobExecution was updated in - * the JobRepository. - * + * Get the date representing the last time this JobExecution was updated in the + * JobRepository. * @return Date representing the last time this JobExecution was updated. */ public Date getLastUpdated() { @@ -231,7 +228,6 @@ public class JobExecutionEvent extends Entity { /** * Set the last time this {@link JobExecution} was updated. - * * @param lastUpdated The date the {@link JobExecution} was updated. */ public void setLastUpdated(Date lastUpdated) { @@ -244,7 +240,6 @@ public class JobExecutionEvent extends Entity { /** * Add the provided throwable to the failure exception list. - * * @param t a {@link Throwable} to be added to the exception list. */ public synchronized void addFailureException(Throwable t) { @@ -252,11 +247,10 @@ public class JobExecutionEvent extends Entity { } /** - * Return all failure causing exceptions for this JobExecution, including - * step executions. - * - * @return List<Throwable> containing all exceptions causing failure for - * this JobExecution. + * Return all failure causing exceptions for this JobExecution, including step + * executions. + * @return List<Throwable> containing all exceptions causing failure for this + * JobExecution. */ public synchronized List getAllFailureExceptions() { @@ -275,8 +269,10 @@ public class JobExecutionEvent extends Entity { */ @Override public String toString() { - return super.toString() - + String.format(", startTime=%s, endTime=%s, lastUpdated=%s, status=%s, exitStatus=%s, job=[%s], jobParameters=[%s]", - startTime, endTime, lastUpdated, status, exitStatus, jobInstance, jobParameters); + 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); } + } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobInstanceEvent.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobInstanceEvent.java index dce1dfe6..bcb24312 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobInstanceEvent.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/batch/listener/support/JobInstanceEvent.java @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener.support; @@ -20,8 +20,9 @@ import org.springframework.batch.core.Entity; import org.springframework.util.Assert; /** - * This is a JobInstance DTO created so that a {@link org.springframework.batch.core.JobInstance} can be serialized into - * Json without having to add mixins to an ObjectMapper. + * This is a JobInstance DTO created so that a + * {@link org.springframework.batch.core.JobInstance} can be serialized into Json without + * having to add mixins to an ObjectMapper. * * @author Glenn Renfro */ @@ -44,11 +45,11 @@ public class JobInstanceEvent extends Entity { * @return the job name. (Equivalent to getJob().getName()) */ public String getJobName() { - return jobName; + return this.jobName; } public String toString() { - return super.toString() + ", Job=[" + jobName + "]"; + return super.toString() + ", Job=[" + this.jobName + "]"; } public long getInstanceId() { 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 e739c1d4..e709c03a 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener.support; @@ -21,11 +21,14 @@ import java.util.Date; import org.springframework.batch.core.JobParameter; /** - * This is a JobParameter DTO created so that a {@link org.springframework.batch.core.JobParameter} can be serialized - * into Json without having to add mixins to an ObjectMapper. + * This is a JobParameter DTO created so that a + * {@link org.springframework.batch.core.JobParameter} can be serialized into Json without + * having to add mixins to an ObjectMapper. + * * @author Glenn Renfro */ public class JobParameterEvent { + private Object parameter; private JobParameterEvent.ParameterType parameterType; @@ -42,7 +45,7 @@ public class JobParameterEvent { } public boolean isIdentifying() { - return identifying; + return this.identifying; } /** @@ -50,11 +53,11 @@ public class JobParameterEvent { */ public Object getValue() { - if (parameter != null && parameter.getClass().isInstance(Date.class)) { - return new Date(((Date) parameter).getTime()); + if (this.parameter != null && this.parameter.getClass().isInstance(Date.class)) { + return new Date(((Date) this.parameter).getTime()); } else { - return parameter; + return this.parameter; } } @@ -62,7 +65,7 @@ public class JobParameterEvent { * @return a ParameterType representing the type of this parameter. */ public JobParameterEvent.ParameterType getType() { - return parameterType; + return this.parameterType; } @Override @@ -76,44 +79,54 @@ public class JobParameterEvent { } JobParameterEvent rhs = (JobParameterEvent) obj; - return parameter==null ? rhs.parameter==null && parameterType==rhs.parameterType: parameter.equals(rhs.parameter); + return this.parameter == null + ? rhs.parameter == null && this.parameterType == rhs.parameterType + : this.parameter.equals(rhs.parameter); } @Override public String toString() { - return parameter == null ? null : (parameterType == JobParameterEvent.ParameterType.DATE ? "" + ((Date) parameter).getTime() - : 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 * (parameter == null ? parameterType.hashCode() : parameter.hashCode()); + return BASE_HASH + MULTIPLIER_HASH * (this.parameter == null + ? this.parameterType.hashCode() : this.parameter.hashCode()); } /** * Enumeration representing the type of a JobParameter. */ public enum ParameterType { + + // @checkstyle:off STRING, DATE, LONG, DOUBLE; + // @checkstyle:on public static ParameterType convert(JobParameter.ParameterType type) { - if(JobParameter.ParameterType.DATE.equals(type)) { + if (JobParameter.ParameterType.DATE.equals(type)) { return DATE; } - else if(JobParameter.ParameterType.DOUBLE.equals(type)) { + else if (JobParameter.ParameterType.DOUBLE.equals(type)) { return DOUBLE; } - else if(JobParameter.ParameterType.LONG.equals(type)) { + else if (JobParameter.ParameterType.LONG.equals(type)) { return LONG; } - else if(JobParameter.ParameterType.STRING.equals(type)) { + else if (JobParameter.ParameterType.STRING.equals(type)) { return STRING; } else { throw new IllegalArgumentException("Unable to convert type"); } } + } + } 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 33c60a5f..4b8f8fa7 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener.support; @@ -24,185 +24,177 @@ import java.util.Properties; import org.springframework.batch.core.JobParameter; /** - * This is a JobParametersEvent DTO created so that a {@link org.springframework.batch.core.JobParameters} can be - * serialized into Json without having to add mixins to an ObjectMapper. + * This is a JobParametersEvent DTO created so that a + * {@link org.springframework.batch.core.JobParameters} can be serialized into Json + * without having to add mixins to an ObjectMapper. * * @author Glenn Renfro */ public class JobParametersEvent { - private final Map parameters; + + private final Map parameters; public JobParametersEvent() { this.parameters = new LinkedHashMap<>(); } - public JobParametersEvent(Map jobParameters) { + public JobParametersEvent(Map jobParameters) { this.parameters = new LinkedHashMap<>(); - for(Map.Entry entry: jobParameters.entrySet()){ - if(entry.getValue().getValue() instanceof String){ - parameters.put(entry.getKey(), new JobParameterEvent(entry.getValue())); + for (Map.Entry entry : jobParameters.entrySet()) { + if (entry.getValue().getValue() instanceof String) { + this.parameters.put(entry.getKey(), + new JobParameterEvent(entry.getValue())); } - else if(entry.getValue().getValue() instanceof Long){ - parameters.put(entry.getKey(), new JobParameterEvent(entry.getValue())); + else if (entry.getValue().getValue() instanceof Long) { + this.parameters.put(entry.getKey(), + new JobParameterEvent(entry.getValue())); } - else if(entry.getValue().getValue() instanceof Date){ - parameters.put(entry.getKey(), new JobParameterEvent(entry.getValue())); + else if (entry.getValue().getValue() instanceof Date) { + this.parameters.put(entry.getKey(), + new JobParameterEvent(entry.getValue())); } - else if(entry.getValue().getValue() instanceof Double){ - parameters.put(entry.getKey(), new JobParameterEvent(entry.getValue())); + else if (entry.getValue().getValue() instanceof Double) { + this.parameters.put(entry.getKey(), + new JobParameterEvent(entry.getValue())); } } } - /** * Typesafe Getter for the Long represented by the provided key. - * * @param key The key to get a value for * @return The Long value */ - public Long getLong(String key){ - if (!parameters.containsKey(key)) { + public Long getLong(String key) { + if (!this.parameters.containsKey(key)) { return 0L; } - Object value = parameters.get(key).getValue(); - return value==null ? 0L : ((Long)value).longValue(); + Object value = this.parameters.get(key).getValue(); + return value == null ? 0L : ((Long) value).longValue(); } /** - * Typesafe Getter for the Long represented by the provided key. If the - * key does not exist, the default value will be returned. - * + * Typesafe Getter for the Long represented by the provided key. If the key does not + * exist, the default value will be returned. * @param key to return the value for * @param defaultValue to return if the value doesn't exist - * @return the parameter represented by the provided key, defaultValue - * otherwise. + * @return the parameter represented by the provided key, defaultValue otherwise. */ - public Long getLong(String key, long defaultValue){ - if(parameters.containsKey(key)){ + public Long getLong(String key, long defaultValue) { + if (this.parameters.containsKey(key)) { return getLong(key); } - else{ + else { return defaultValue; } } /** * Typesafe Getter for the String represented by the provided key. - * * @param key The key to get a value for * @return The String value */ - public String getString(String key){ - JobParameterEvent value = parameters.get(key); - return value==null ? null : value.toString(); + public String getString(String key) { + JobParameterEvent value = this.parameters.get(key); + return value == null ? null : value.toString(); } /** - * Typesafe Getter for the String represented by the provided key. If the - * key does not exist, the default value will be returned. - * + * Typesafe Getter for the String represented by the provided key. If the key does not + * exist, the default value will be returned. * @param key to return the value for * @param defaultValue to return if the value doesn't exist - * @return the parameter represented by the provided key, defaultValue - * otherwise. + * @return the parameter represented by the provided key, defaultValue otherwise. */ - public String getString(String key, String defaultValue){ - if(parameters.containsKey(key)){ + public String getString(String key, String defaultValue) { + if (this.parameters.containsKey(key)) { return getString(key); } - else{ + else { return defaultValue; } } /** * Typesafe Getter for the Long represented by the provided key. - * * @param key The key to get a value for * @return The Double value */ - public Double getDouble(String key){ - if (!parameters.containsKey(key)) { + public Double getDouble(String key) { + if (!this.parameters.containsKey(key)) { return 0.0; } - Double value = (Double)parameters.get(key).getValue(); - return value==null ? 0.0 : value.doubleValue(); + Double value = (Double) this.parameters.get(key).getValue(); + return value == null ? 0.0 : value.doubleValue(); } /** - * Typesafe Getter for the Double represented by the provided key. If the - * key does not exist, the default value will be returned. - * + * Typesafe Getter for the Double represented by the provided key. If the key does not + * exist, the default value will be returned. * @param key to return the value for * @param defaultValue to return if the value doesn't exist - * @return the parameter represented by the provided key, defaultValue - * otherwise. + * @return the parameter represented by the provided key, defaultValue otherwise. */ - public Double getDouble(String key, double defaultValue){ - if(parameters.containsKey(key)){ + public Double getDouble(String key, double defaultValue) { + if (this.parameters.containsKey(key)) { return getDouble(key); } - else{ + else { return defaultValue; } } /** * Typesafe Getter for the Date represented by the provided key. - * * @param key The key to get a value for * @return The java.util.Date value */ - public Date getDate(String key){ - return this.getDate(key,null); + public Date getDate(String key) { + return this.getDate(key, null); } /** - * Typesafe Getter for the Date represented by the provided key. If the - * key does not exist, the default value will be returned. - * + * Typesafe Getter for the Date represented by the provided key. If the key does not + * exist, the default value will be returned. * @param key to return the value for * @param defaultValue to return if the value doesn't exist - * @return the parameter represented by the provided key, defaultValue - * otherwise. + * @return the parameter represented by the provided key, defaultValue otherwise. */ - public Date getDate(String key, Date defaultValue){ - if(parameters.containsKey(key)){ - return (Date)parameters.get(key).getValue(); + public Date getDate(String key, Date defaultValue) { + if (this.parameters.containsKey(key)) { + return (Date) this.parameters.get(key).getValue(); } - else{ + else { return defaultValue; } } /** * Get a map of all parameters, including string, long, and date. - * * @return an unmodifiable map containing all parameters. */ - public Map getParameters(){ - return new LinkedHashMap(parameters); + public Map getParameters() { + return new LinkedHashMap<>(this.parameters); } /** * @return true if the parameters is empty, false otherwise. */ - public boolean isEmpty(){ - return parameters.isEmpty(); + public boolean isEmpty() { + return this.parameters.isEmpty(); } @Override public boolean equals(Object obj) { - if(obj instanceof JobParametersEvent == false){ + if (!(obj instanceof JobParametersEvent)) { return false; } - if(obj == this){ + if (obj == this) { return true; } - JobParametersEvent rhs = (JobParametersEvent)obj; + JobParametersEvent rhs = (JobParametersEvent) obj; return this.parameters.equals(rhs.parameters); } @@ -210,23 +202,24 @@ public class JobParametersEvent { public int hashCode() { final int BASE_HASH = 17; final int MULTIPLIER_HASH = 23; - return BASE_HASH + MULTIPLIER_HASH * parameters.hashCode(); + return BASE_HASH + MULTIPLIER_HASH * this.parameters.hashCode(); } @Override public String toString() { - return parameters.toString(); + return this.parameters.toString(); } public Properties toProperties() { Properties props = new Properties(); - for (Map.Entry param : parameters.entrySet()) { - if(param.getValue() != null) { + for (Map.Entry param : this.parameters.entrySet()) { + if (param.getValue() != null) { props.put(param.getKey(), param.getValue().toString()); } } return props; } + } 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 b0dd68d8..644a6ac8 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener.support; @@ -22,10 +22,13 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.Assert; /** - * Utility class that sends batch job listener payloads to the notification channel. + * Utility class that sends batch job listener payloads to the notification channel. + * + * @param

    payload type * @author Glenn Renfro */ -public class MessagePublisher

    { +public class MessagePublisher

    { + private final MessageChannel listenerEventsChannel; public MessagePublisher(MessageChannel listenerEventsChannel) { @@ -48,8 +51,9 @@ public class MessagePublisher

    { } public void publishWithThrowableHeader(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(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 e729b7f9..63437a4c 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener.support; @@ -27,8 +27,10 @@ import org.springframework.batch.item.ExecutionContext; import org.springframework.util.Assert; /** - * This is a StepExecution DTO created so that a {@link org.springframework.batch.core.StepExecution} can be serialized - * into Json without having to add mixins to an ObjectMapper. + * This is a StepExecution DTO created so that a + * {@link org.springframework.batch.core.StepExecution} can be serialized into Json + * without having to add mixins to an ObjectMapper. + * * @author Glenn Renfro */ public class StepExecutionEvent extends Entity { @@ -61,14 +63,14 @@ 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; private int filterCount; - private List failureExceptions = new CopyOnWriteArrayList(); - + private List failureExceptions = new CopyOnWriteArrayList<>(); public StepExecutionEvent() { super(); @@ -76,13 +78,14 @@ public class StepExecutionEvent extends Entity { /** * Constructor for the StepExecution to initialize the DTO. - * * @param stepExecution the StepExecution to build this DTO around. */ public StepExecutionEvent(StepExecution stepExecution) { super(); - 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"); + 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()); this.jobExecutionId = stepExecution.getJobExecutionId(); this.stepName = stepExecution.getStepName(); @@ -90,7 +93,7 @@ public class StepExecutionEvent extends Entity { this.status = stepExecution.getStatus(); this.exitStatus = new ExitStatus(stepExecution.getExitStatus()); this.executionContext = stepExecution.getExecutionContext(); - for (Throwable throwable : stepExecution.getFailureExceptions()){ + for (Throwable throwable : stepExecution.getFailureExceptions()) { this.failureExceptions.add(throwable); } this.terminateOnly = stepExecution.isTerminateOnly(); @@ -111,8 +114,7 @@ public class StepExecutionEvent extends Entity { } /** - * Returns the {@link ExecutionContext} for this execution - * + * Returns the {@link ExecutionContext} for this execution. * @return the attributes */ public ExecutionContext getExecutionContext() { @@ -120,8 +122,7 @@ public class StepExecutionEvent extends Entity { } /** - * Sets the {@link ExecutionContext} for this execution - * + * Sets the {@link ExecutionContext} for this execution. * @param executionContext the attributes */ public void setExecutionContext(ExecutionContext executionContext) { @@ -129,8 +130,7 @@ public class StepExecutionEvent extends Entity { } /** - * Returns the current number of commits for this execution - * + * Returns the current number of commits for this execution. * @return the current number of commits */ public int getCommitCount() { @@ -138,8 +138,7 @@ public class StepExecutionEvent extends Entity { } /** - * Sets the current number of commits for this execution - * + * Sets the current number of commits for this execution. * @param commitCount the current number of commits */ public void setCommitCount(int commitCount) { @@ -147,8 +146,7 @@ public class StepExecutionEvent extends Entity { } /** - * Returns the time that this execution ended - * + * Returns the time that this execution ended. * @return the time that this execution ended */ public Date getEndTime() { @@ -156,8 +154,7 @@ public class StepExecutionEvent extends Entity { } /** - * Sets the time that this execution ended - * + * Sets the time that this execution ended. * @param endTime the time that this execution ended */ public void setEndTime(Date endTime) { @@ -165,8 +162,7 @@ public class StepExecutionEvent extends Entity { } /** - * Returns the current number of items read for this execution - * + * Returns the current number of items read for this execution. * @return the current number of items read for this execution */ public int getReadCount() { @@ -174,8 +170,7 @@ public class StepExecutionEvent extends Entity { } /** - * Sets the current number of read items for this execution - * + * Sets the current number of read items for this execution. * @param readCount the current number of read items for this execution */ public void setReadCount(int readCount) { @@ -183,8 +178,7 @@ public class StepExecutionEvent extends Entity { } /** - * Returns the current number of items written for this execution - * + * Returns the current number of items written for this execution. * @return the current number of items written for this execution */ public int getWriteCount() { @@ -192,8 +186,7 @@ public class StepExecutionEvent extends Entity { } /** - * Sets the current number of written items for this execution - * + * Sets the current number of written items for this execution. * @param writeCount the current number of written items for this execution */ public void setWriteCount(int writeCount) { @@ -201,8 +194,7 @@ public class StepExecutionEvent extends Entity { } /** - * Returns the current number of rollbacks for this execution - * + * Returns the current number of rollbacks for this execution. * @return the current number of rollbacks for this execution */ public int getRollbackCount() { @@ -210,8 +202,15 @@ public class StepExecutionEvent extends Entity { } /** - * Returns the current number of items filtered out of this execution - * + * Setter for number of rollbacks for this execution. + * @param rollbackCount the number of rollbacks for this execution + */ + public void setRollbackCount(int rollbackCount) { + this.rollbackCount = rollbackCount; + } + + /** + * Returns the current number of items filtered out of this execution. * @return the current number of items filtered out of this execution */ public int getFilterCount() { @@ -220,24 +219,14 @@ public class StepExecutionEvent extends Entity { /** * Public setter for the number of items filtered out of this execution. - * @param filterCount the number of items filtered out of this execution to - * set + * @param filterCount the number of items filtered out of this execution to set */ public void setFilterCount(int filterCount) { this.filterCount = filterCount; } /** - * Setter for number of rollbacks for this execution - * @param rollbackCount the number of rollbacks for this execution - */ - public void setRollbackCount(int rollbackCount) { - this.rollbackCount = rollbackCount; - } - - /** - * Gets the time this execution started - * + * Gets the time this execution started. * @return the time this execution started */ public Date getStartTime() { @@ -245,8 +234,7 @@ public class StepExecutionEvent extends Entity { } /** - * Sets the time this execution started - * + * Sets the time this execution started. * @param startTime the time this execution started */ public void setStartTime(Date startTime) { @@ -254,8 +242,7 @@ public class StepExecutionEvent extends Entity { } /** - * Returns the current status of this step - * + * Returns the current status of this step. * @return the current status of this step */ public BatchStatus getStatus() { @@ -263,29 +250,22 @@ public class StepExecutionEvent extends Entity { } /** - * Sets the current status of this step - * + * Sets the current status of this step. * @param status the current status of this step */ public void setStatus(BatchStatus status) { this.status = status; } - public void setStepName(String stepName) { - this.stepName = stepName; - } /** - * @return the name of the step + * @return the name of the step. */ public String getStepName() { return this.stepName; } - /** - * @param exitStatus the {@link ExitStatus} for the step. - */ - public void setExitStatus(ExitStatus exitStatus) { - this.exitStatus = exitStatus; + public void setStepName(String stepName) { + this.stepName = stepName; } /** @@ -295,6 +275,13 @@ public class StepExecutionEvent extends Entity { return this.exitStatus; } + /** + * @param exitStatus the {@link ExitStatus} for the step. + */ + public void setExitStatus(ExitStatus exitStatus) { + this.exitStatus = exitStatus; + } + /** * @return flag to indicate that an execution should halt */ @@ -303,8 +290,8 @@ public class StepExecutionEvent extends Entity { } /** - * Set a flag that will signal to an execution environment that this - * execution (and its surrounding job) wishes to exit. + * Set a flag that will signal to an execution environment that this execution (and + * its surrounding job) wishes to exit. */ public void setTerminateOnly() { this.terminateOnly = true; @@ -318,19 +305,27 @@ public class StepExecutionEvent extends Entity { } /** - * Increment the number of commits + * Increment the number of commits. */ public void incrementCommitCount() { this.commitCount++; } /** - * @return the number of records skipped on read + * @return the number of records skipped on read. */ public int getReadSkipCount() { return this.readSkipCount; } + /** + * Set the number of records skipped on read. + * @param readSkipCount the number of records to be skipped on read. + */ + public void setReadSkipCount(int readSkipCount) { + this.readSkipCount = readSkipCount; + } + /** * @return the number of records skipped on write */ @@ -339,17 +334,7 @@ public class StepExecutionEvent extends Entity { } /** - * Set the number of records skipped on read - * - * @param readSkipCount the number of records to be skipped on read. - */ - public void setReadSkipCount(int readSkipCount) { - this.readSkipCount = readSkipCount; - } - - /** - * Set the number of records skipped on write - * + * Set the number of records skipped on write. * @param writeSkipCount the number of records to be skipped on write. */ public void setWriteSkipCount(int writeSkipCount) { @@ -365,7 +350,6 @@ public class StepExecutionEvent extends Entity { /** * Set the number of records skipped during processing. - * * @param processSkipCount the number of records skip during processing. */ public void setProcessSkipCount(int processSkipCount) { @@ -380,8 +364,7 @@ public class StepExecutionEvent extends Entity { } /** - * Set the time when the StepExecution was last updated before persisting - * + * Set the time when the StepExecution was last updated before persisting. * @param lastUpdated the {@link Date} the StepExecution was last updated. */ public void setLastUpdated(Date lastUpdated) { @@ -399,19 +382,19 @@ public class StepExecutionEvent extends Entity { /* * (non-Javadoc) * - * @see - * org.springframework.batch.container.common.domain.Entity#equals(java. + * @see org.springframework.batch.container.common.domain.Entity#equals(java. * lang.Object) */ @Override public boolean equals(Object obj) { - if ( !(obj instanceof StepExecution) || getId() == null) { + if (!(obj instanceof StepExecution) || getId() == null) { return super.equals(obj); } 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()); } @@ -424,21 +407,27 @@ 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() { - return super.toString() - + String.format( - ", 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.rollbackCount); + return super.toString() + String.format( + ", 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.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 1e96d22b..7c936ae5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.batch.listener.support; import java.lang.reflect.Field; @@ -39,22 +40,27 @@ import org.springframework.context.ApplicationContext; import org.springframework.util.ReflectionUtils; /** - * Attaches the listeners to the job and its steps. - * Based on the type of bean that is being processed will determine what listener is attached. - *

      - *
    • If the bean is of type AbstactJob then the JobExecutionListener is registered with this bean.
    • - *
    • If the bean is of type AbstactStep then the StepExecutionListener is registered with this bean.
    • - *
    • If the bean is of type TaskletStep then the ChunkEventListener is registered with this bean.
    • - *
    • If the tasklet for the TaskletStep is of type ChunkOrientedTasklet the following listeners will be registered.
    • - *
    • - *
        - *
      • ItemReadListener with the ChunkProvider.
      • - *
      • ItemProcessListener with the ChunkProcessor.
      • - *
      • ItemWriteEventsListener with the ChunkProcessor.
      • - *
      • SkipEventsListener with the ChunkProcessor.
      • - *
      - *
    • - *
    + * Attaches the listeners to the job and its steps. Based on the type of bean that is + * being processed will determine what listener is attached. + *
      + *
    • If the bean is of type AbstactJob then the JobExecutionListener is registered with + * this bean.
    • + *
    • If the bean is of type AbstactStep then the StepExecutionListener is registered + * with this bean.
    • + *
    • If the bean is of type TaskletStep then the ChunkEventListener is registered with + * this bean.
    • + *
    • If the tasklet for the TaskletStep is of type ChunkOrientedTasklet the following + * listeners will be registered.
    • + *
    • + *
        + *
      • ItemReadListener with the ChunkProvider.
      • + *
      • ItemProcessListener with the ChunkProcessor.
      • + *
      • ItemWriteEventsListener with the ChunkProcessor.
      • + *
      • SkipEventsListener with the ChunkProcessor.
      • + *
      + *
    • + *
    + * * @author Michael Minella * @author Glenn Renfro */ @@ -64,7 +70,8 @@ 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); @@ -76,12 +83,16 @@ 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"); + SimpleChunkProvider chunkProvider = (SimpleChunkProvider) ReflectionUtils + .getField(chunkProviderField, tasklet); + Field chunkProcessorField = ReflectionUtils + .findField(ChunkOrientedTasklet.class, "chunkProcessor"); ReflectionUtils.makeAccessible(chunkProcessorField); - SimpleChunkProcessor chunkProcessor = (SimpleChunkProcessor) ReflectionUtils.getField(chunkProcessorField, tasklet); + SimpleChunkProcessor chunkProcessor = (SimpleChunkProcessor) ReflectionUtils + .getField(chunkProcessorField, tasklet); registerItemReadEvents(chunkProvider); registerSkipEvents(chunkProvider); registerItemProcessEvents(chunkProcessor); @@ -95,67 +106,79 @@ 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)) { - chunkProcessor.registerListener((ItemProcessListener) this.applicationContext.getBean(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)) { - chunkProvider.registerListener((ItemReadListener) this.applicationContext.getBean(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)) { - chunkProcessor.registerListener((ItemWriteListener) this.applicationContext.getBean(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)) { - JobExecutionListener jobExecutionEventsListener = - (JobExecutionListener) this.applicationContext.getBean( - 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); AbstractJob job = (AbstractJob) bean; - job.registerJobExecutionListener( - jobExecutionEventsListener); + job.registerJobExecutionListener(jobExecutionEventsListener); } } private void registerStepExecutionEventListener(Object bean) { - if (this.applicationContext.containsBean(BatchEventAutoConfiguration.STEP_EXECUTION_EVENTS_LISTENER)) { - StepExecutionListener stepExecutionListener = - (StepExecutionListener) this.applicationContext.getBean(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; step.registerStepExecutionListener(stepExecutionListener); } } + } 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 7a96fe3e..8d8b539c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,48 +20,48 @@ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.core.Ordered; /** - * @author Ali Shahbour + * @author Ali Shahbour */ @ConfigurationProperties(prefix = "spring.cloud.task.batch.events") public class TaskEventProperties { - /** - * Properties for jobExecution listener order - */ + /** + * Properties for jobExecution listener order. + */ private int jobExecutionOrder = Ordered.LOWEST_PRECEDENCE; - /** - * Properties for stepExecution listener order - */ + /** + * Properties for stepExecution listener order. + */ private int stepExecutionOrder = Ordered.LOWEST_PRECEDENCE; - /** - * Properties for itemRead listener order - */ + /** + * Properties for itemRead listener order. + */ private int itemReadOrder = Ordered.LOWEST_PRECEDENCE; - /** - * Properties for itemProcess listener order - */ + /** + * Properties for itemProcess listener order. + */ private int itemProcessOrder = Ordered.LOWEST_PRECEDENCE; - /** - * Properties for itemWrite listener order - */ + /** + * Properties for itemWrite listener order. + */ private int itemWriteOrder = Ordered.LOWEST_PRECEDENCE; - /** - * Properties for chunk listener order - */ + /** + * Properties for chunk listener order. + */ private int chunkOrder = Ordered.LOWEST_PRECEDENCE; - /** - * Properties for skip listener order - */ + /** + * Properties for skip listener order. + */ private int skipOrder = Ordered.LOWEST_PRECEDENCE; public int getJobExecutionOrder() { - return jobExecutionOrder; + return this.jobExecutionOrder; } public void setJobExecutionOrder(int jobExecutionOrder) { @@ -69,7 +69,7 @@ public class TaskEventProperties { } public int getStepExecutionOrder() { - return stepExecutionOrder; + return this.stepExecutionOrder; } public void setStepExecutionOrder(int stepExecutionOrder) { @@ -77,7 +77,7 @@ public class TaskEventProperties { } public int getItemReadOrder() { - return itemReadOrder; + return this.itemReadOrder; } public void setItemReadOrder(int itemReadOrder) { @@ -85,7 +85,7 @@ public class TaskEventProperties { } public int getItemProcessOrder() { - return itemProcessOrder; + return this.itemProcessOrder; } public void setItemProcessOrder(int itemProcessOrder) { @@ -93,7 +93,7 @@ public class TaskEventProperties { } public int getItemWriteOrder() { - return itemWriteOrder; + return this.itemWriteOrder; } public void setItemWriteOrder(int itemWriteOrder) { @@ -101,7 +101,7 @@ public class TaskEventProperties { } public int getChunkOrder() { - return chunkOrder; + return this.chunkOrder; } public void setChunkOrder(int chunkOrder) { @@ -109,10 +109,11 @@ public class TaskEventProperties { } public int getSkipOrder() { - return skipOrder; + return this.skipOrder; } public void setSkipOrder(int skipOrder) { this.skipOrder = skipOrder; } + } 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 00d31fc7..c20708ad 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,6 @@ package org.springframework.cloud.task.launcher; - import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; @@ -34,13 +33,18 @@ import org.springframework.util.StringUtils; * * @author Glenn Renfro */ -public class TaskLaunchRequest implements Serializable{ +public class TaskLaunchRequest implements Serializable { private static final long serialVersionUID = 1L; + private String uri; + private List commandlineArguments; + private Map environmentProperties; + private Map deploymentProperties; + private String applicationName; /** @@ -49,20 +53,21 @@ public class TaskLaunchRequest implements Serializable{ * @param commandlineArguments list of commandlineArguments to be used by the task * @param environmentProperties are the environment variables for this task. * @param deploymentProperties are the variables used to setup task on the platform. - * @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`. + * @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, - Map deploymentProperties, - String applicationName) { + 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); } @@ -75,17 +80,17 @@ public class TaskLaunchRequest implements Serializable{ } /** - * @return the current uri to the artifact for this launch request. + * @return the current uri to the artifact for this launch request. */ public String getUri() { - return uri; + return this.uri; } /** - * @return an unmodifiable list of arguments that will be used for the task execution + * @return an unmodifiable list of arguments that will be used for the task execution */ public List getCommandlineArguments() { - return Collections.unmodifiableList(commandlineArguments); + return Collections.unmodifiableList(this.commandlineArguments); } /** @@ -94,80 +99,76 @@ public class TaskLaunchRequest implements Serializable{ */ public Map getEnvironmentProperties() { - return environmentProperties; + return this.environmentProperties; } /** - * Returns the properties used by a {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} - * + * Returns the properties used by a + * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher}. * @return deployment properties */ public Map getDeploymentProperties() { - return deploymentProperties; + return this.deploymentProperties; } /** * Returns the name that will be associated with the launched task. - * * @return string containing the application name. */ public String getApplicationName() { - return applicationName; + return this.applicationName; } /** - * Sets the name to be applied to the launched task. If set - * to null then the launched task name will be "Task-`unique id`". - * + * Sets the name to be applied to the launched task. If set to null then the launched + * task name will be "Task-`unique id`". * @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='" + uri + '\'' + - ", commandlineArguments=" + commandlineArguments + - ", environmentProperties=" + environmentProperties + - ", deploymentProperties=" + deploymentProperties + - '}'; + return "TaskLaunchRequest{" + "uri='" + this.uri + '\'' + + ", commandlineArguments=" + this.commandlineArguments + + ", environmentProperties=" + this.environmentProperties + + ", deploymentProperties=" + this.deploymentProperties + '}'; } @Override public boolean equals(Object o) { - if (this == o){ + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()){ + if (o == null || getClass() != o.getClass()) { return false; } TaskLaunchRequest that = (TaskLaunchRequest) o; - if (!uri.equals(that.uri)){ + if (!this.uri.equals(that.uri)) { return false; } - if (!commandlineArguments.equals(that.commandlineArguments)){ + if (!this.commandlineArguments.equals(that.commandlineArguments)) { return false; } - if(!deploymentProperties.equals(that.deploymentProperties)) - { + if (!this.deploymentProperties.equals(that.deploymentProperties)) { return false; } - return environmentProperties.equals(that.environmentProperties); + return this.environmentProperties.equals(that.environmentProperties); } @Override public int hashCode() { final int HASH_DEFAULT = 31; - int result = uri.hashCode(); - result = HASH_DEFAULT * result + commandlineArguments.hashCode(); - result = HASH_DEFAULT * result + environmentProperties.hashCode(); - result = HASH_DEFAULT * result + deploymentProperties.hashCode(); + int result = this.uri.hashCode(); + result = HASH_DEFAULT * result + this.commandlineArguments.hashCode(); + result = HASH_DEFAULT * result + this.environmentProperties.hashCode(); + result = HASH_DEFAULT * result + this.deploymentProperties.hashCode(); return result; } + } 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 1f23cc3c..7841b4a0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,6 @@ import org.springframework.core.io.Resource; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.util.Assert; - /** * A sink stream application that launches a tasks. * @@ -42,20 +41,23 @@ public class TaskLauncherSink { private final static Logger logger = LoggerFactory.getLogger(TaskLauncherSink.class); + // @checkstyle:off @Autowired public TaskLauncher taskLauncher; + // @checkstyle:on + @Autowired private DelegatingResourceLoader resourceLoader; /** * Launches a task upon the receipt of a valid TaskLaunchRequest. - * @param taskLaunchRequest is a TaskLaunchRequest containing the information required to launch - * a task. + * @param taskLaunchRequest is a TaskLaunchRequest containing the information required + * to launch a task. * @throws Exception if error occurs during task launch. */ @ServiceActivator(inputChannel = Sink.INPUT) - public void taskLauncherSink(TaskLaunchRequest taskLaunchRequest) throws Exception{ + public void taskLauncherSink(TaskLaunchRequest taskLaunchRequest) throws Exception { launchTask(taskLaunchRequest); } @@ -63,8 +65,12 @@ 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(), taskLaunchRequest.getEnvironmentProperties()); - AppDeploymentRequest request = new AppDeploymentRequest(definition, resource, taskLaunchRequest.getDeploymentProperties(), taskLaunchRequest.getCommandlineArguments()); + AppDefinition definition = new AppDefinition( + taskLaunchRequest.getApplicationName(), + taskLaunchRequest.getEnvironmentProperties()); + AppDeploymentRequest request = new AppDeploymentRequest(definition, resource, + taskLaunchRequest.getDeploymentProperties(), + taskLaunchRequest.getCommandlineArguments()); this.taskLauncher.launch(request); } diff --git a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/annotation/EnableTaskLauncher.java b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/annotation/EnableTaskLauncher.java index edb044d0..939c58b7 100644 --- a/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/annotation/EnableTaskLauncher.java +++ b/spring-cloud-task-stream/src/main/java/org/springframework/cloud/task/launcher/annotation/EnableTaskLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,12 +42,12 @@ import org.springframework.context.annotation.Import; * @Bean * public MyCommandLineRunner myCommandLineRunner() { * return new MyCommandLineRunner() - * } + * } * } * * - * Note that only one of your configuration classes needs to have the @EnableTaskLauncher - * annotation. + * Note that only one of your configuration classes needs to have the + * @EnableTaskLauncher annotation. * * @author Glenn Renfro */ @@ -55,6 +55,7 @@ import org.springframework.context.annotation.Import; @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited -@Import({TaskLauncherSink.class}) +@Import({ TaskLauncherSink.class }) public @interface EnableTaskLauncher { + } 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 a5de53e8..b84ca790 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.listener; import org.springframework.boot.autoconfigure.AutoConfigureAfter; @@ -31,38 +32,51 @@ import org.springframework.integration.gateway.GatewayProxyFactoryBean; import org.springframework.messaging.MessageChannel; /** - * * @author Michael Minella */ @Configuration @ConditionalOnClass(EnableBinding.class) @ConditionalOnBean(TaskLifecycleListener.class) +// @checkstyle:off @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) @AutoConfigureAfter(SimpleTaskAutoConfiguration.class) public class TaskEventAutoConfiguration { + /** + * Task Event channels definition. + */ + public interface TaskEventChannels { + + /** + * Name of the task events channel. + */ + String TASK_EVENTS = "task-events"; + + @Output(TASK_EVENTS) + MessageChannel taskEvents(); + + } + + /** + * Configuration for a {@link TaskExecutionListener}. + */ @Configuration @EnableBinding(TaskEventChannels.class) public static class ListenerConfiguration { @Bean public GatewayProxyFactoryBean taskEventListener() { - GatewayProxyFactoryBean factoryBean = - new GatewayProxyFactoryBean(TaskExecutionListener.class); + GatewayProxyFactoryBean factoryBean = new GatewayProxyFactoryBean( + TaskExecutionListener.class); factoryBean.setDefaultRequestChannelName(TaskEventChannels.TASK_EVENTS); return factoryBean; } + } - public interface TaskEventChannels { - - String TASK_EVENTS = "task-events"; - - @Output(TASK_EVENTS) - MessageChannel taskEvents(); - } } diff --git a/spring-cloud-task-stream/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-task-stream/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 312e0e7a..f0853ef3 100644 --- a/spring-cloud-task-stream/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/spring-cloud-task-stream/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -1,10 +1,10 @@ { - "properties": [ - { - "defaultValue": true, - "name": "spring.cloud.task.events.enabled", - "description": "This property is used to determine if a task app should emit task events.", - "type": "java.lang.Boolean" - } - ] + "properties": [ + { + "defaultValue": true, + "name": "spring.cloud.task.events.enabled", + "description": "This property is used to determine if a task app should emit task events.", + "type": "java.lang.Boolean" + } + ] } 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 7bd4581f..6e35ada3 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener; @@ -35,7 +35,7 @@ import org.springframework.core.Ordered; import org.springframework.integration.channel.QueueChannel; import org.springframework.messaging.Message; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro @@ -46,229 +46,247 @@ public class EventListenerTests { private QueueChannel queueChannel; private EventEmittingSkipListener eventEmittingSkipListener; + private EventEmittingItemProcessListener eventEmittingItemProcessListener; + private EventEmittingItemReadListener eventEmittingItemReadListener; + private EventEmittingItemWriteListener eventEmittingItemWriteListener; + private EventEmittingJobExecutionListener eventEmittingJobExecutionListener; + private EventEmittingStepExecutionListener eventEmittingStepExecutionListener; + private EventEmittingChunkListener eventEmittingChunkListener; @Before public void beforeTests() { - queueChannel = new QueueChannel(1); - eventEmittingSkipListener = new EventEmittingSkipListener(queueChannel); - eventEmittingItemProcessListener = new EventEmittingItemProcessListener(queueChannel); - eventEmittingItemReadListener = new EventEmittingItemReadListener(queueChannel); - eventEmittingItemWriteListener = new EventEmittingItemWriteListener(queueChannel); - eventEmittingJobExecutionListener = new EventEmittingJobExecutionListener(queueChannel); - eventEmittingStepExecutionListener = new EventEmittingStepExecutionListener(queueChannel); - eventEmittingChunkListener = new EventEmittingChunkListener(queueChannel,0); + this.queueChannel = new QueueChannel(1); + this.eventEmittingSkipListener = new EventEmittingSkipListener(this.queueChannel); + this.eventEmittingItemProcessListener = new EventEmittingItemProcessListener( + this.queueChannel); + this.eventEmittingItemReadListener = new EventEmittingItemReadListener( + this.queueChannel); + this.eventEmittingItemWriteListener = new EventEmittingItemWriteListener( + this.queueChannel); + this.eventEmittingJobExecutionListener = new EventEmittingJobExecutionListener( + this.queueChannel); + this.eventEmittingStepExecutionListener = new EventEmittingStepExecutionListener( + this.queueChannel); + this.eventEmittingChunkListener = new EventEmittingChunkListener( + this.queueChannel, 0); } @Test public void testEventListenerOrderProperty() { - assertEquals(eventEmittingSkipListener.getOrder(),Ordered.LOWEST_PRECEDENCE); - assertEquals(eventEmittingItemProcessListener.getOrder(), Ordered.LOWEST_PRECEDENCE); - assertEquals(eventEmittingItemReadListener.getOrder(), Ordered.LOWEST_PRECEDENCE); - assertEquals(eventEmittingItemWriteListener.getOrder(), Ordered.LOWEST_PRECEDENCE); - assertEquals(eventEmittingJobExecutionListener.getOrder(), Ordered.LOWEST_PRECEDENCE); - assertEquals(eventEmittingStepExecutionListener.getOrder(), Ordered.LOWEST_PRECEDENCE); - assertEquals(eventEmittingChunkListener.getOrder(),0); + 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() { RuntimeException exeption = new RuntimeException("Test Exception"); - eventEmittingItemProcessListener.onProcessError("HELLO", exeption); - assertEquals(1, queueChannel.getQueueSize()); + this.eventEmittingItemProcessListener.onProcessError("HELLO", exeption); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); - Message msg = queueChannel.receive(); - assertEquals("Exception while item was being processed", msg.getPayload()); + Message msg = this.queueChannel.receive(); + assertThat(msg.getPayload()) + .isEqualTo("Exception while item was being processed"); } @Test public void testItemProcessListenerAfterProcess() { - eventEmittingItemProcessListener.afterProcess("HELLO_AFTER_PROCESS_EQUAL", + this.eventEmittingItemProcessListener.afterProcess("HELLO_AFTER_PROCESS_EQUAL", "HELLO_AFTER_PROCESS_EQUAL"); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); - assertEquals("item equaled result after processing", msg.getPayload()); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); + assertThat(msg.getPayload()).isEqualTo("item equaled result after processing"); - eventEmittingItemProcessListener.afterProcess("HELLO_NOT_EQUAL", "WORLD"); - assertEquals(1, queueChannel.getQueueSize()); - msg = queueChannel.receive(); - assertEquals("item did not equal result after processing", msg.getPayload()); + this.eventEmittingItemProcessListener.afterProcess("HELLO_NOT_EQUAL", "WORLD"); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + msg = this.queueChannel.receive(); + assertThat(msg.getPayload()) + .isEqualTo("item did not equal result after processing"); - eventEmittingItemProcessListener.afterProcess("HELLO_AFTER_PROCESS", null); - assertEquals(1, queueChannel.getQueueSize()); - msg = queueChannel.receive(); - assertEquals("1 item was filtered", msg.getPayload()); + this.eventEmittingItemProcessListener.afterProcess("HELLO_AFTER_PROCESS", null); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + msg = this.queueChannel.receive(); + assertThat(msg.getPayload()).isEqualTo("1 item was filtered"); } @Test public void testItemProcessBeforeProcessor() { - eventEmittingItemProcessListener.beforeProcess("HELLO_BEFORE_PROCESS"); - assertEquals(0, queueChannel.getQueueSize()); + this.eventEmittingItemProcessListener.beforeProcess("HELLO_BEFORE_PROCESS"); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(0); } @Test public void EventEmittingSkipListenerSkipRead() { RuntimeException exeption = new RuntimeException("Text Exception"); - eventEmittingSkipListener.onSkipInRead(exeption); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); - assertEquals("Skipped when reading.", msg.getPayload()); + this.eventEmittingSkipListener.onSkipInRead(exeption); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); + assertThat(msg.getPayload()).isEqualTo("Skipped when reading."); } @Test public void EventEmittingSkipListenerSkipWrite() { final String MESSAGE = "HELLO_SKIP_WRITE"; RuntimeException exeption = new RuntimeException("Text Exception"); - eventEmittingSkipListener.onSkipInWrite(MESSAGE, exeption); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); - assertEquals(MESSAGE, msg.getPayload()); + this.eventEmittingSkipListener.onSkipInWrite(MESSAGE, exeption); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); + assertThat(msg.getPayload()).isEqualTo(MESSAGE); } @Test public void EventEmittingSkipListenerSkipProcess() { final String MESSAGE = "HELLO_SKIP_PROCESS"; RuntimeException exeption = new RuntimeException("Text Exception"); - eventEmittingSkipListener.onSkipInProcess(MESSAGE, exeption); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); - assertEquals(MESSAGE, msg.getPayload()); + this.eventEmittingSkipListener.onSkipInProcess(MESSAGE, exeption); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); + assertThat(msg.getPayload()).isEqualTo(MESSAGE); } @Test public void EventEmittingItemReadListener() { RuntimeException exeption = new RuntimeException("Text Exception"); - eventEmittingItemReadListener.onReadError(exeption); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); - assertEquals("Exception while item was being read", msg.getPayload()); + this.eventEmittingItemReadListener.onReadError(exeption); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); + assertThat(msg.getPayload()).isEqualTo("Exception while item was being read"); } @Test public void EventEmittingItemReadListenerBeforeRead() { - eventEmittingItemReadListener.beforeRead(); - assertEquals(0, queueChannel.getQueueSize()); + this.eventEmittingItemReadListener.beforeRead(); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(0); } @Test public void EventEmittingItemReadListenerAfterRead() { - eventEmittingItemReadListener.afterRead("HELLO_AFTER_READ"); - assertEquals(0, queueChannel.getQueueSize()); + this.eventEmittingItemReadListener.afterRead("HELLO_AFTER_READ"); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(0); } @Test public void EventEmittingItemWriteListenerBeforeWrite() { - eventEmittingItemWriteListener.beforeWrite(getSampleList()); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); - assertEquals("3 items to be written.", msg.getPayload()); + this.eventEmittingItemWriteListener.beforeWrite(getSampleList()); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); + assertThat(msg.getPayload()).isEqualTo("3 items to be written."); } @Test public void EventEmittingItemWriteListenerAfterWrite() { - eventEmittingItemWriteListener.afterWrite(getSampleList()); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); - assertEquals("3 items have been written.", msg.getPayload()); + this.eventEmittingItemWriteListener.afterWrite(getSampleList()); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); + assertThat(msg.getPayload()).isEqualTo("3 items have been written."); } @Test public void EventEmittingItemWriteListenerWriteError() { RuntimeException exeption = new RuntimeException("Text Exception"); - eventEmittingItemWriteListener.onWriteError(exeption, getSampleList()); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); - assertEquals("Exception while 3 items are attempted to be written.", msg.getPayload()); + this.eventEmittingItemWriteListener.onWriteError(exeption, getSampleList()); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); + assertThat(msg.getPayload()) + .isEqualTo("Exception while 3 items are attempted to be written."); } - @Test public void EventEmittingJobExecutionListenerBeforeJob() { JobExecution jobExecution = getJobExecution(); - eventEmittingJobExecutionListener.beforeJob(jobExecution); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); + this.eventEmittingJobExecutionListener.beforeJob(jobExecution); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); JobExecutionEvent jobEvent = (JobExecutionEvent) msg.getPayload(); - assertEquals(jobExecution.getJobInstance().getJobName(), - jobEvent.getJobInstance().getJobName()); + assertThat(jobEvent.getJobInstance().getJobName()) + .isEqualTo(jobExecution.getJobInstance().getJobName()); } @Test public void EventEmittingJobExecutionListenerAfterJob() { JobExecution jobExecution = getJobExecution(); - eventEmittingJobExecutionListener.afterJob(jobExecution); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); + this.eventEmittingJobExecutionListener.afterJob(jobExecution); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); JobExecutionEvent jobEvent = (JobExecutionEvent) msg.getPayload(); - assertEquals(jobExecution.getJobInstance().getJobName(), - jobEvent.getJobInstance().getJobName()); + assertThat(jobEvent.getJobInstance().getJobName()) + .isEqualTo(jobExecution.getJobInstance().getJobName()); } @Test public void EventEmittingStepExecutionListenerBeforeStep() { final String STEP_MESSAGE = "BEFORE_STEP_MESSAGE"; JobExecution jobExecution = getJobExecution(); - StepExecution stepExecution = new StepExecution(STEP_MESSAGE,jobExecution); - eventEmittingStepExecutionListener.beforeStep(stepExecution); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); + StepExecution stepExecution = new StepExecution(STEP_MESSAGE, jobExecution); + this.eventEmittingStepExecutionListener.beforeStep(stepExecution); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); StepExecutionEvent stepExecutionEvent = (StepExecutionEvent) msg.getPayload(); - assertEquals(STEP_MESSAGE, - stepExecutionEvent.getStepName()); + assertThat(stepExecutionEvent.getStepName()).isEqualTo(STEP_MESSAGE); } @Test public void EventEmittingStepExecutionListenerAfterStep() { final String STEP_MESSAGE = "AFTER_STEP_MESSAGE"; JobExecution jobExecution = getJobExecution(); - StepExecution stepExecution = new StepExecution(STEP_MESSAGE,jobExecution); - eventEmittingStepExecutionListener.afterStep(stepExecution); - assertEquals(1, queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); + StepExecution stepExecution = new StepExecution(STEP_MESSAGE, jobExecution); + this.eventEmittingStepExecutionListener.afterStep(stepExecution); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); StepExecutionEvent stepExecutionEvent = (StepExecutionEvent) msg.getPayload(); - assertEquals(STEP_MESSAGE, - stepExecutionEvent.getStepName()); + assertThat(stepExecutionEvent.getStepName()).isEqualTo(STEP_MESSAGE); } @Test public void EventEmittingChunkExecutionListenerBeforeChunk() { final String CHUNK_MESSAGE = "Before Chunk Processing"; ChunkContext chunkContext = getChunkContext(); - eventEmittingChunkListener.beforeChunk(chunkContext); - assertEquals(1,queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); - assertEquals(CHUNK_MESSAGE,msg.getPayload()); + this.eventEmittingChunkListener.beforeChunk(chunkContext); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); + assertThat(msg.getPayload()).isEqualTo(CHUNK_MESSAGE); } @Test public void EventEmittingChunkExecutionListenerAfterChunk() { final String CHUNK_MESSAGE = "After Chunk Processing"; ChunkContext chunkContext = getChunkContext(); - eventEmittingChunkListener.afterChunk(chunkContext); - assertEquals(1,queueChannel.getQueueSize()); - Message msg = queueChannel.receive(); - assertEquals(CHUNK_MESSAGE,msg.getPayload()); + this.eventEmittingChunkListener.afterChunk(chunkContext); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(1); + Message msg = this.queueChannel.receive(); + assertThat(msg.getPayload()).isEqualTo(CHUNK_MESSAGE); } @Test public void EventEmittingChunkExecutionListenerAfterChunkError() { ChunkContext chunkContext = getChunkContext(); - eventEmittingChunkListener.afterChunkError(chunkContext); - assertEquals(0,queueChannel.getQueueSize()); + this.eventEmittingChunkListener.afterChunkError(chunkContext); + assertThat(this.queueChannel.getQueueSize()).isEqualTo(0); } private JobExecution getJobExecution() { final String JOB_NAME = UUID.randomUUID().toString(); JobInstance jobInstance = new JobInstance(1L, JOB_NAME); - return new JobExecution(jobInstance, 1L, - new JobParameters(), UUID.randomUUID().toString()); + return new JobExecution(jobInstance, 1L, new JobParameters(), + UUID.randomUUID().toString()); } + private List getSampleList() { List testList = new ArrayList<>(3); testList.add("Hello"); @@ -276,9 +294,10 @@ public class EventListenerTests { testList.add("foo"); return testList; } + private ChunkContext getChunkContext() { JobExecution jobExecution = getJobExecution(); - StepExecution stepExecution = new StepExecution("STEP1",jobExecution); + StepExecution stepExecution = new StepExecution("STEP1", jobExecution); StepContext stepContext = new StepContext(stepExecution); ChunkContext chunkContext = new ChunkContext(stepContext); return chunkContext; 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 1e8088f9..a05105e6 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener; @@ -34,7 +34,6 @@ import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; import org.springframework.batch.item.ExecutionContext; import org.springframework.beans.factory.NoSuchBeanDefinitionException; - import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -47,10 +46,7 @@ import org.springframework.cloud.task.configuration.SingleTaskConfiguration; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro. @@ -59,67 +55,98 @@ import static org.junit.Assert.assertTrue; public class JobExecutionEventTests { private static final String JOB_NAME = "FOODJOB"; + private static final Long JOB_INSTANCE_ID = 1L; + private static final Long JOB_EXECUTION_ID = 2L; + private static final String JOB_CONFIGURATION_NAME = "FOO_JOB_CONFIG"; - 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; + private JobInstance jobInstance; @Before public void setup() { - jobInstance = new JobInstance(JOB_INSTANCE_ID, JOB_NAME); - jobParameters = new JobParameters(); + this.jobInstance = new JobInstance(JOB_INSTANCE_ID, JOB_NAME); + this.jobParameters = new JobParameters(); } @Test public void testBasic() { - JobExecution jobExecution = new JobExecution(jobInstance, JOB_EXECUTION_ID, jobParameters, JOB_CONFIGURATION_NAME); + JobExecution jobExecution; + jobExecution = new JobExecution(this.jobInstance, JOB_EXECUTION_ID, + this.jobParameters, JOB_CONFIGURATION_NAME); JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(jobExecution); - assertNotNull("jobInstance should not be null", jobExecutionEvent.getJobInstance()); - assertNotNull("jobParameters should not be null", jobExecutionEvent.getJobParameters()); - assertEquals("jobConfigurationName did not match expected", JOB_CONFIGURATION_NAME, - jobExecutionEvent.getJobConfigurationName()); + assertThat(jobExecutionEvent.getJobInstance()) + .as("jobInstance should not be null").isNotNull(); + assertThat(jobExecutionEvent.getJobParameters()) + .as("jobParameters should not be null").isNotNull(); + assertThat(jobExecutionEvent.getJobConfigurationName()) + .as("jobConfigurationName did not match expected") + .isEqualTo(JOB_CONFIGURATION_NAME); - assertEquals("jobParameters size did not match", 0, jobExecutionEvent.getJobParameters().getParameters().size()); - assertEquals("jobInstance name did not match", JOB_NAME, jobExecutionEvent.getJobInstance().getJobName()); - assertEquals("no step executions were expected", 0, jobExecutionEvent.getStepExecutions().size()); - assertEquals("exitStatus did not match expected", "UNKNOWN", jobExecutionEvent.getExitStatus().getExitCode()); + 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++) { jobParamMap.put(JOB_PARAM_KEYS[paramCount], PARAMETERS[paramCount]); } - jobParameters = new JobParameters(jobParamMap); - JobExecution jobExecution = new JobExecution(jobInstance, JOB_EXECUTION_ID, jobParameters, JOB_CONFIGURATION_NAME); + this.jobParameters = new JobParameters(jobParamMap); + JobExecution jobExecution; + jobExecution = new JobExecution(this.jobInstance, JOB_EXECUTION_ID, + this.jobParameters, JOB_CONFIGURATION_NAME); JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(jobExecution); - assertNotNull("Job Parameter A was expected", jobExecutionEvent.getJobParameters().getString("A")); - assertNotNull("Job Parameter B was expected", jobExecutionEvent.getJobParameters().getLong("B")); - assertNotNull("Job Parameter C was expected", jobExecutionEvent.getJobParameters().getDouble("C")); - assertNotNull("Job Parameter D was expected", jobExecutionEvent.getJobParameters().getDate("D")); + 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(); - assertEquals("Job Parameter A value was not correct", "FOO", jobExecutionEvent.getJobParameters().getString("A")); - assertEquals("Job Parameter B value was not correct", new Long(1), jobExecutionEvent.getJobParameters().getLong("B")); - assertEquals("Job Parameter C value was not correct", new Double(1), jobExecutionEvent.getJobParameters().getDouble("C")); - assertEquals("Job Parameter D value was not correct", testDate, jobExecutionEvent.getJobParameters().getDate("D")); + 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(new Long(1)); + assertThat(jobExecutionEvent.getJobParameters().getDouble("C")) + .as("Job Parameter C value was not correct").isEqualTo(new Double(1)); + assertThat(jobExecutionEvent.getJobParameters().getDate("D")) + .as("Job Parameter D value was not correct").isEqualTo(testDate); } @Test public void testStepExecutions() { - JobExecution jobExecution = new JobExecution(jobInstance, JOB_EXECUTION_ID, jobParameters, JOB_CONFIGURATION_NAME); + JobExecution jobExecution; + jobExecution = new JobExecution(this.jobInstance, JOB_EXECUTION_ID, + this.jobParameters, JOB_CONFIGURATION_NAME); List stepsExecutions = new ArrayList<>(); stepsExecutions.add(new StepExecution("foo", jobExecution)); stepsExecutions.add(new StepExecution("bar", jobExecution)); @@ -127,11 +154,16 @@ public class JobExecutionEventTests { jobExecution.addStepExecutions(stepsExecutions); JobExecutionEvent jobExecutionsEvent = new JobExecutionEvent(jobExecution); - assertEquals("stepExecutions count is incorrect", 3, jobExecutionsEvent.getStepExecutions().size()); - Iterator iter = jobExecutionsEvent.getStepExecutions().iterator(); - assertEquals("foo stepExecution is not present", "foo", iter.next().getStepName()); - assertEquals("bar stepExecution is not present", "bar", iter.next().getStepName()); - assertEquals("baz stepExecution is not present", "baz", iter.next().getStepName()); + 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 @@ -184,25 +216,29 @@ public class JobExecutionEventTests { @Test public void testDefaultConstructor() { JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); - assertEquals("UNKNOWN", jobExecutionEvent.getExitStatus().getExitCode()); + assertThat(jobExecutionEvent.getExitStatus().getExitCode()).isEqualTo("UNKNOWN"); } @Test public void testFailureExceptions() { final String EXCEPTION_MESSAGE = "TEST EXCEPTION"; JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); - assertEquals(0, jobExecutionEvent.getFailureExceptions().size()); - jobExecutionEvent.addFailureException(new IllegalStateException(EXCEPTION_MESSAGE)); - assertEquals(1, jobExecutionEvent.getFailureExceptions().size()); - assertEquals(1, jobExecutionEvent.getAllFailureExceptions().size()); - assertEquals(jobExecutionEvent.getFailureExceptions().get(0).getMessage(), EXCEPTION_MESSAGE); - assertEquals(jobExecutionEvent.getAllFailureExceptions().get(0).getMessage(), EXCEPTION_MESSAGE); + assertThat(jobExecutionEvent.getFailureExceptions().size()).isEqualTo(0); + 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()); } @Test public void testToString() { JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); - assertTrue(jobExecutionEvent.toString().startsWith("JobExecutionEvent:")); + assertThat(jobExecutionEvent.toString().startsWith("JobExecutionEvent:")) + .isTrue(); } @Test @@ -210,40 +246,39 @@ public class JobExecutionEventTests { Date date = new Date(); JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); jobExecutionEvent.setLastUpdated(date); - assertEquals(date, jobExecutionEvent.getLastUpdated()); + assertThat(jobExecutionEvent.getLastUpdated()).isEqualTo(date); jobExecutionEvent.setCreateTime(date); - assertEquals(date, jobExecutionEvent.getCreateTime()); + assertThat(jobExecutionEvent.getCreateTime()).isEqualTo(date); jobExecutionEvent.setEndTime(date); - assertEquals(date, jobExecutionEvent.getEndTime()); + assertThat(jobExecutionEvent.getEndTime()).isEqualTo(date); jobExecutionEvent.setStartTime(date); - assertEquals(date, jobExecutionEvent.getStartTime()); + assertThat(jobExecutionEvent.getStartTime()).isEqualTo(date); } @Test public void testExitStatus() { final String EXIT_CODE = "KNOWN"; JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); - assertEquals("UNKNOWN", jobExecutionEvent.getExitStatus().getExitCode()); - org.springframework.cloud.task.batch.listener.support.ExitStatus expectedExitStatus = - new org.springframework.cloud.task.batch.listener.support.ExitStatus(); + assertThat(jobExecutionEvent.getExitStatus().getExitCode()).isEqualTo("UNKNOWN"); + org.springframework.cloud.task.batch.listener.support.ExitStatus expectedExitStatus; + expectedExitStatus = new org.springframework.cloud.task.batch.listener.support.ExitStatus(); expectedExitStatus.setExitCode(EXIT_CODE); jobExecutionEvent.setExitStatus(expectedExitStatus); - assertEquals(EXIT_CODE, jobExecutionEvent.getExitStatus().getExitCode()); + assertThat(jobExecutionEvent.getExitStatus().getExitCode()).isEqualTo(EXIT_CODE); } @Test public void testJobInstance() { final String JOB_NAME = "KNOWN"; JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); - assertNull(jobExecutionEvent.getJobInstance()); - assertNull(jobExecutionEvent.getJobId()); - JobInstanceEvent expectedJobInstanceEvent = new JobInstanceEvent(1L, - JOB_NAME); + assertThat(jobExecutionEvent.getJobInstance()).isNull(); + assertThat(jobExecutionEvent.getJobId()).isNull(); + JobInstanceEvent expectedJobInstanceEvent = new JobInstanceEvent(1L, JOB_NAME); jobExecutionEvent.setJobInstance(expectedJobInstanceEvent); - assertEquals(expectedJobInstanceEvent.getJobName(), - jobExecutionEvent.getJobInstance().getJobName()); - assertEquals(expectedJobInstanceEvent.getId(), - jobExecutionEvent.getJobId()); + assertThat(jobExecutionEvent.getJobInstance().getJobName()) + .isEqualTo(expectedJobInstanceEvent.getJobName()); + assertThat(jobExecutionEvent.getJobId()) + .isEqualTo(expectedJobInstanceEvent.getId()); } @Test @@ -251,27 +286,28 @@ public class JobExecutionEventTests { ExecutionContext executionContext = new ExecutionContext(); executionContext.put("hello", "world"); JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); - assertNotNull(jobExecutionEvent.getExecutionContext()); + assertThat(jobExecutionEvent.getExecutionContext()).isNotNull(); jobExecutionEvent.setExecutionContext(executionContext); - assertEquals("world", jobExecutionEvent.getExecutionContext().getString("hello")); + assertThat(jobExecutionEvent.getExecutionContext().getString("hello")) + .isEqualTo("world"); } @Test - public void testBatchStatus() { + public void testBatchStatus() { JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); - assertEquals(BatchStatus.STARTING, jobExecutionEvent.getStatus()); + assertThat(jobExecutionEvent.getStatus()).isEqualTo(BatchStatus.STARTING); jobExecutionEvent.setStatus(BatchStatus.ABANDONED); - assertEquals(BatchStatus.ABANDONED, jobExecutionEvent.getStatus()); + assertThat(jobExecutionEvent.getStatus()).isEqualTo(BatchStatus.ABANDONED); } @Test - public void testUpgradeBatchStatus() { + public void testUpgradeBatchStatus() { JobExecutionEvent jobExecutionEvent = new JobExecutionEvent(); - assertEquals(BatchStatus.STARTING, jobExecutionEvent.getStatus()); + assertThat(jobExecutionEvent.getStatus()).isEqualTo(BatchStatus.STARTING); jobExecutionEvent.upgradeStatus(BatchStatus.FAILED); - assertEquals(BatchStatus.FAILED, jobExecutionEvent.getStatus()); + assertThat(jobExecutionEvent.getStatus()).isEqualTo(BatchStatus.FAILED); jobExecutionEvent.upgradeStatus(BatchStatus.COMPLETED); - assertEquals(BatchStatus.FAILED, jobExecutionEvent.getStatus()); + assertThat(jobExecutionEvent.getStatus()).isEqualTo(BatchStatus.FAILED); } @Test @@ -281,23 +317,24 @@ public class JobExecutionEventTests { EventJobExecutionConfiguration.class, PropertyPlaceholderAutoConfiguration.class, TestSupportBinderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.class)) - .withUserConfiguration(BatchEventAutoConfiguration.JobExecutionListenerConfiguration.class) + SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) + .withUserConfiguration( + BatchEventAutoConfiguration.JobExecutionListenerConfiguration.class) .withPropertyValues("--spring.cloud.task.closecontext_enabled=false", - "--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", - "--spring.cloud.task.batch.events.job-execution-order=5", - "--spring.cloud.task.batch.events.skip-order=5", - "--spring.cloud.task.batch.events.step-execution-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", + "--spring.cloud.task.batch.events.job-execution-order=5", + "--spring.cloud.task.batch.events.skip-order=5", + "--spring.cloud.task.batch.events.step-execution-order=5"); applicationContextRunner.run((context) -> { - for (String beanName : LISTENER_BEAN_NAMES) { - Ordered ordered = (Ordered)context.getBean(beanName); - assertEquals("Expected order value of 5 for " + beanName,ordered.getOrder(),5); - } + 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()); + } }); } @@ -306,37 +343,39 @@ public class JobExecutionEventTests { String disabledPropertyArg = (property != null) ? "--" + property + "=false" : ""; ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of( - EventJobExecutionConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - TestSupportBinderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.class)) - .withUserConfiguration(BatchEventAutoConfiguration.JobExecutionListenerConfiguration.class) + EventJobExecutionConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, + TestSupportBinderAutoConfiguration.class, + SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class)) + .withUserConfiguration( + BatchEventAutoConfiguration.JobExecutionListenerConfiguration.class) .withPropertyValues("--spring.cloud.task.closecontext_enabled=false", - "--spring.main.web-environment=false", - disabledPropertyArg); + "--spring.main.web-environment=false", disabledPropertyArg); applicationContextRunner.run((context) -> { boolean exceptionThrown = false; - for (String beanName : LISTENER_BEAN_NAMES) { - if (disabledListener != null && disabledListener.equals(beanName)) { - try { - context.getBean(disabledListener); + for (String beanName : LISTENER_BEAN_NAMES) { + if (disabledListener != null && disabledListener.equals(beanName)) { + try { + context.getBean(disabledListener); + } + catch (NoSuchBeanDefinitionException nsbde) { + exceptionThrown = true; + } + assertThat(exceptionThrown).as( + String.format("Did not expect %s bean in context", beanName)) + .isTrue(); } - catch (NoSuchBeanDefinitionException nsbde) { - exceptionThrown = true; + else { + context.getBean(beanName); } - assertTrue(String.format("Did not expect %s bean in context", beanName), exceptionThrown); } - else { - context.getBean(beanName); - } - } }); } - @Configuration public static class EventJobExecutionConfiguration { + } + } 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 d371f176..d190379a 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener; @@ -20,8 +20,7 @@ import org.junit.Test; import org.springframework.cloud.task.batch.listener.support.JobInstanceEvent; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro @@ -29,19 +28,20 @@ import static org.junit.Assert.assertNull; public class JobInstanceEventTests { public static final long INSTANCE_ID = 1; + public static final String JOB_NAME = "FOOBAR"; @Test public void testConstructor() { JobInstanceEvent jobInstanceEvent = new JobInstanceEvent(INSTANCE_ID, JOB_NAME); - assertEquals(INSTANCE_ID, jobInstanceEvent.getInstanceId()); - assertEquals(JOB_NAME, jobInstanceEvent.getJobName()); + assertThat(jobInstanceEvent.getInstanceId()).isEqualTo(INSTANCE_ID); + assertThat(jobInstanceEvent.getJobName()).isEqualTo(JOB_NAME); } @Test public void testEmptyConstructor() { JobInstanceEvent jobInstanceEvent = new JobInstanceEvent(); - assertNull(jobInstanceEvent.getJobName()); + assertThat(jobInstanceEvent.getJobName()).isNull(); } @Test @@ -53,7 +53,8 @@ public class JobInstanceEventTests { @Test public void testToString() { JobInstanceEvent jobInstanceEvent = new JobInstanceEvent(INSTANCE_ID, JOB_NAME); - assertEquals("JobInstanceEvent: id=1, version=null, Job=[FOOBAR]", - jobInstanceEvent.toString()); + 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 b94d2c61..19bcda83 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener; @@ -25,9 +25,7 @@ import org.springframework.cloud.task.batch.listener.support.JobParameterEvent; import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro @@ -37,10 +35,10 @@ public class JobParameterEventTests { @Test public void testDefaultConstructor() { JobParameterEvent jobParameterEvent = new JobParameterEvent(); - assertNull(jobParameterEvent.getValue()); - assertNull(jobParameterEvent.getType()); + assertThat(jobParameterEvent.getValue()).isNull(); + assertThat(jobParameterEvent.getType()).isNull(); assertFalse(jobParameterEvent.isIdentifying()); - assertEquals(new JobParameterEvent(), jobParameterEvent); + assertThat(jobParameterEvent).isEqualTo(new JobParameterEvent()); } @Test @@ -49,14 +47,16 @@ public class JobParameterEventTests { final Date EXPECTED_DATE_VALUE = new Date(); JobParameter jobParameter = new JobParameter(EXPECTED_VALUE, true); JobParameterEvent jobParameterEvent = new JobParameterEvent(jobParameter); - assertEquals(EXPECTED_VALUE, jobParameterEvent.getValue()); - assertEquals(JobParameterEvent.ParameterType.STRING, jobParameterEvent.getType()); + assertThat(jobParameterEvent.getValue()).isEqualTo(EXPECTED_VALUE); + assertThat(jobParameterEvent.getType()) + .isEqualTo(JobParameterEvent.ParameterType.STRING); assertTrue(jobParameterEvent.isIdentifying()); jobParameter = new JobParameter(EXPECTED_DATE_VALUE, true); jobParameterEvent = new JobParameterEvent(jobParameter); - assertEquals(EXPECTED_DATE_VALUE, jobParameterEvent.getValue()); - assertEquals(JobParameterEvent.ParameterType.DATE, jobParameterEvent.getType()); + assertThat(jobParameterEvent.getValue()).isEqualTo(EXPECTED_DATE_VALUE); + assertThat(jobParameterEvent.getType()) + .isEqualTo(JobParameterEvent.ParameterType.DATE); assertTrue(jobParameterEvent.isIdentifying()); assertTrue(new JobParameterEvent(jobParameter).equals(jobParameterEvent)); } @@ -76,11 +76,11 @@ public class JobParameterEventTests { @Test(expected = NullPointerException.class) public void testInvalidHashCode() { JobParameterEvent jobParameterEvent = new JobParameterEvent(); - assertNull(jobParameterEvent.hashCode()); + assertThat(jobParameterEvent.hashCode()).isNull(); final String EXPECTED_VALUE = "FOO"; JobParameter jobParameter = new JobParameter(EXPECTED_VALUE, true); jobParameterEvent = new JobParameterEvent(jobParameter); - assertNotNull(jobParameterEvent.hashCode()); + assertThat(jobParameterEvent.hashCode()).isNotNull(); } @Test @@ -88,7 +88,7 @@ public class JobParameterEventTests { final String EXPECTED_VALUE = "FOO"; JobParameter jobParameter = new JobParameter(EXPECTED_VALUE, true); JobParameterEvent jobParameterEvent = new JobParameterEvent(jobParameter); - assertNotNull(jobParameterEvent.hashCode()); + assertThat(jobParameterEvent.hashCode()).isNotNull(); } } 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 1793850b..1b6a36b2 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener; @@ -28,9 +28,7 @@ import org.springframework.cloud.task.batch.listener.support.JobParametersEvent; import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro @@ -38,31 +36,40 @@ import static org.junit.Assert.assertNotNull; public class JobParametersEventTests { private final static JobParameter STRING_PARAM = new JobParameter("FOO", true); + private final static JobParameter DATE_PARAM = new JobParameter(new Date(), true); + private final static JobParameter LONG_PARAM = new JobParameter(1L, true); + private final static JobParameter DOUBLE_PARAM = new JobParameter(2D, true); + private final static String DATE_KEY = "DATE_KEY"; + private final static String STRING_KEY = "STRING_KEY"; + private final static String LONG_KEY = "LONG_KEY"; + private final static String DOUBLE_KEY = "DOUBLE_KEY"; @Test public void testDefaultConstructor() { JobParametersEvent jobParametersEvent = new JobParametersEvent(); - assertEquals(0, jobParametersEvent.getParameters().size()); + assertThat(jobParametersEvent.getParameters().size()).isEqualTo(0); assertTrue(jobParametersEvent.isEmpty()); } @Test public void testConstructor() { JobParametersEvent jobParametersEvent = getPopulatedParametersEvent(); - assertEquals(STRING_PARAM.getValue(), jobParametersEvent.getString(STRING_KEY)); - assertEquals(LONG_PARAM.getValue(), jobParametersEvent.getLong(LONG_KEY)); - assertEquals(DATE_PARAM.getValue(), jobParametersEvent.getDate(DATE_KEY)); - assertEquals(DOUBLE_PARAM.getValue(), jobParametersEvent.getDouble(DOUBLE_KEY)); + 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()); JobParametersEvent jobParametersEventNew = getPopulatedParametersEvent(); - assertEquals(jobParametersEventNew, jobParametersEvent); + assertThat(jobParametersEvent).isEqualTo(jobParametersEventNew); } @Test @@ -76,54 +83,62 @@ public class JobParametersEventTests { @Test public void testHashCode() { JobParametersEvent jobParametersEvent = new JobParametersEvent(); - assertNotNull(jobParametersEvent.hashCode()); + assertThat(jobParametersEvent.hashCode()).isNotNull(); JobParametersEvent jobParametersEventPopulated = getPopulatedParametersEvent(); - assertNotNull(jobParametersEvent); - assertNotEquals(jobParametersEvent.hashCode(), jobParametersEventPopulated.hashCode()); + assertThat(jobParametersEvent).isNotNull(); + assertThat(jobParametersEventPopulated.hashCode()) + .isNotEqualTo(jobParametersEvent.hashCode()); } @Test public void testToProperties() { JobParametersEvent jobParametersEvent = getPopulatedParametersEvent(); Properties properties = jobParametersEvent.toProperties(); - assertEquals(properties.getProperty(DATE_KEY), jobParametersEvent.getString(DATE_KEY)); - assertEquals(properties.getProperty(STRING_KEY), jobParametersEvent.getString(STRING_KEY)); - assertEquals(properties.getProperty(LONG_KEY), jobParametersEvent.getString(LONG_KEY)); - assertEquals(properties.getProperty(DOUBLE_KEY), jobParametersEvent.getString(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 public void testToString() { JobParametersEvent jobParametersEvent = getPopulatedParametersEvent(); - assertNotNull(toString()); + assertThat(toString()).isNotNull(); } @Test public void testGetterSetterDefaults() { JobParametersEvent jobParametersEvent = getPopulatedParametersEvent(); - assertEquals(new Double(0), jobParametersEvent.getDouble("FOOBAR")); - assertEquals(new Long(0), jobParametersEvent.getLong("FOOBAR")); - assertEquals(new Double(5), jobParametersEvent.getDouble("FOOBAR", 5)); - assertEquals(DOUBLE_PARAM.getValue(), jobParametersEvent.getDouble(DOUBLE_KEY, 0)); - assertEquals(new Long(5), jobParametersEvent.getLong("FOOBAR", 5)); - assertEquals(LONG_PARAM.getValue(), jobParametersEvent.getLong(LONG_KEY, 5)); - assertEquals("TESTVAL", jobParametersEvent.getString("FOOBAR","TESTVAL")); - assertEquals(STRING_PARAM.getValue(), - jobParametersEvent.getString(STRING_KEY,"TESTVAL")); + assertThat(jobParametersEvent.getDouble("FOOBAR")).isEqualTo(new Double(0)); + assertThat(jobParametersEvent.getLong("FOOBAR")).isEqualTo(new Long(0)); + assertThat(jobParametersEvent.getDouble("FOOBAR", 5)).isEqualTo(new Double(5)); + assertThat(jobParametersEvent.getDouble(DOUBLE_KEY, 0)) + .isEqualTo(DOUBLE_PARAM.getValue()); + assertThat(jobParametersEvent.getLong("FOOBAR", 5)).isEqualTo(new Long(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()); Date date = new Date(); - assertEquals(date, jobParametersEvent.getDate("FOOBAR", date)); - assertEquals(DATE_PARAM.getValue(), - jobParametersEvent.getDate(DATE_KEY, date)); + assertThat(jobParametersEvent.getDate("FOOBAR", date)).isEqualTo(date); + assertThat(jobParametersEvent.getDate(DATE_KEY, date)) + .isEqualTo(DATE_PARAM.getValue()); } public JobParametersEvent getPopulatedParametersEvent() { Map jobParameters = new HashMap<>(); jobParameters.put(DATE_KEY, DATE_PARAM); - jobParameters.put(STRING_KEY,STRING_PARAM); - jobParameters.put(LONG_KEY,LONG_PARAM); - jobParameters.put(DOUBLE_KEY,DOUBLE_PARAM); + jobParameters.put(STRING_KEY, STRING_PARAM); + jobParameters.put(LONG_KEY, LONG_PARAM); + jobParameters.put(DOUBLE_KEY, DOUBLE_PARAM); return new JobParametersEvent(jobParameters); } 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 6a9da17d..39355942 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener; @@ -29,23 +29,25 @@ import org.springframework.batch.item.ExecutionContext; import org.springframework.cloud.task.batch.listener.support.ExitStatus; import org.springframework.cloud.task.batch.listener.support.StepExecutionEvent; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro */ public class StepExecutionEventTests { + private static final String JOB_NAME = "FOO_JOB"; + private static final String STEP_NAME = "STEP_NAME"; - private static final Long JOB_INSTANCE_ID = 1l; - private static final Long JOB_EXECUTION_ID = 2l; + + private static final Long JOB_INSTANCE_ID = 1L; + + private static final Long JOB_EXECUTION_ID = 2L; + private static final String JOB_CONFIGURATION_NAME = "FOO_JOB_CONFIG"; @Test - public void testBasic(){ + public void testBasic() { StepExecution stepExecution = getBasicStepExecution(); stepExecution.setCommitCount(1); stepExecution.setReadCount(2); @@ -54,16 +56,35 @@ public class StepExecutionEventTests { stepExecution.setWriteSkipCount(5); StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(stepExecution); - assertEquals("stepName result was not as expected", STEP_NAME, stepExecutionEvent.getStepName()); - assertEquals("startTime result was not as expected", stepExecution.getStartTime(), stepExecutionEvent.getStartTime()); - assertEquals("endTime result was not as expected", stepExecution.getEndTime(), stepExecutionEvent.getEndTime()); - assertEquals("lastUpdated result was not as expected", stepExecution.getLastUpdated(), stepExecutionEvent.getLastUpdated()); - assertEquals("commitCount result was not as expected", stepExecution.getCommitCount(), stepExecutionEvent.getCommitCount()); - assertEquals("readCount result was not as expected", stepExecution.getReadCount(), stepExecutionEvent.getReadCount()); - assertEquals("readSkipCount result was not as expected", stepExecution.getReadSkipCount(), stepExecutionEvent.getReadSkipCount()); - assertEquals("writeCount result was not as expected", stepExecution.getWriteCount(), stepExecutionEvent.getWriteCount()); - assertEquals("writeSkipCount result was not as expected", stepExecution.getWriteSkipCount(), stepExecutionEvent.getWriteSkipCount()); - assertEquals("skipCount result was not as expected", stepExecution.getSkipCount(), stepExecutionEvent.getSkipCount()); + 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") + .isEqualTo(stepExecution.getEndTime()); + assertThat(stepExecutionEvent.getLastUpdated()) + .as("lastUpdated result was not as expected") + .isEqualTo(stepExecution.getLastUpdated()); + assertThat(stepExecutionEvent.getCommitCount()) + .as("commitCount result was not as expected") + .isEqualTo(stepExecution.getCommitCount()); + assertThat(stepExecutionEvent.getReadCount()) + .as("readCount result was not as expected") + .isEqualTo(stepExecution.getReadCount()); + assertThat(stepExecutionEvent.getReadSkipCount()) + .as("readSkipCount result was not as expected") + .isEqualTo(stepExecution.getReadSkipCount()); + assertThat(stepExecutionEvent.getWriteCount()) + .as("writeCount result was not as expected") + .isEqualTo(stepExecution.getWriteCount()); + assertThat(stepExecutionEvent.getWriteSkipCount()) + .as("writeSkipCount result was not as expected") + .isEqualTo(stepExecution.getWriteSkipCount()); + assertThat(stepExecutionEvent.getSkipCount()) + .as("skipCount result was not as expected") + .isEqualTo(stepExecution.getSkipCount()); } @Test @@ -72,37 +93,37 @@ public class StepExecutionEventTests { StepExecution stepExecution = getBasicStepExecution(); stepExecution.addFailureException(exception); StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(stepExecution); - assertEquals(1, stepExecutionEvent.getFailureExceptions().size()); - assertEquals(exception, stepExecution.getFailureExceptions().get(0)); + assertThat(stepExecutionEvent.getFailureExceptions().size()).isEqualTo(1); + assertThat(stepExecution.getFailureExceptions().get(0)).isEqualTo(exception); } @Test public void testGetSummary() { StepExecution stepExecution = getBasicStepExecution(); StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(stepExecution); - assertEquals("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", - stepExecutionEvent.getSummary()); + 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"); } @Test public void testHashCode() { StepExecution stepExecution = getBasicStepExecution(); - StepExecutionEvent stepExecutionEvent = - new StepExecutionEvent(stepExecution); - assertEquals("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=", stepExecutionEvent.toString()); + 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="); } @Test public void testToString() { StepExecution stepExecution = getBasicStepExecution(); StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(stepExecution); - assertNotNull(stepExecutionEvent.hashCode()); + assertThat(stepExecutionEvent.hashCode()).isNotNull(); } @Test @@ -110,63 +131,65 @@ public class StepExecutionEventTests { StepExecution stepExecution = getBasicStepExecution(); stepExecution.setId(1L); StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(stepExecution); - assertFalse(stepExecutionEvent.equals(getBasicStepExecution())); - assertTrue(stepExecutionEvent.equals(stepExecution)); + assertThat(stepExecutionEvent.equals(getBasicStepExecution())).isFalse(); + assertThat(stepExecutionEvent.equals(stepExecution)).isTrue(); } @Test public void testSettersGetters() { - StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(getBasicStepExecution()); + StepExecutionEvent stepExecutionEvent = new StepExecutionEvent( + getBasicStepExecution()); Date date = new Date(); stepExecutionEvent.setLastUpdated(date); - assertEquals(date, stepExecutionEvent.getLastUpdated()); + assertThat(stepExecutionEvent.getLastUpdated()).isEqualTo(date); stepExecutionEvent.setProcessSkipCount(55); - assertEquals(55, stepExecutionEvent.getProcessSkipCount()); + assertThat(stepExecutionEvent.getProcessSkipCount()).isEqualTo(55); stepExecutionEvent.setWriteSkipCount(47); - assertEquals(47, stepExecutionEvent.getWriteSkipCount()); + assertThat(stepExecutionEvent.getWriteSkipCount()).isEqualTo(47); stepExecutionEvent.setReadSkipCount(49); - assertEquals(49, stepExecutionEvent.getReadSkipCount()); + assertThat(stepExecutionEvent.getReadSkipCount()).isEqualTo(49); - assertEquals(0, stepExecutionEvent.getCommitCount()); + assertThat(stepExecutionEvent.getCommitCount()).isEqualTo(0); stepExecutionEvent.incrementCommitCount(); - assertEquals(1, stepExecutionEvent.getCommitCount()); + assertThat(stepExecutionEvent.getCommitCount()).isEqualTo(1); - assertFalse(stepExecutionEvent.isTerminateOnly()); + assertThat(stepExecutionEvent.isTerminateOnly()).isFalse(); stepExecutionEvent.setTerminateOnly(); - assertTrue(stepExecutionEvent.isTerminateOnly()); + assertThat(stepExecutionEvent.isTerminateOnly()).isTrue(); stepExecutionEvent.setStepName("FOOBAR"); - assertEquals("FOOBAR", stepExecutionEvent.getStepName()); + assertThat(stepExecutionEvent.getStepName()).isEqualTo("FOOBAR"); stepExecutionEvent.setStartTime(date); - assertEquals(date, stepExecutionEvent.getStartTime()); + assertThat(stepExecutionEvent.getStartTime()).isEqualTo(date); - assertEquals(0, stepExecutionEvent.getRollbackCount()); + assertThat(stepExecutionEvent.getRollbackCount()).isEqualTo(0); stepExecutionEvent.setRollbackCount(33); - assertEquals(33, stepExecutionEvent.getRollbackCount()); + assertThat(stepExecutionEvent.getRollbackCount()).isEqualTo(33); stepExecutionEvent.setFilterCount(23); - assertEquals(23, stepExecutionEvent.getFilterCount()); + assertThat(stepExecutionEvent.getFilterCount()).isEqualTo(23); stepExecutionEvent.setWriteCount(11); - assertEquals(11,stepExecutionEvent.getWriteCount()); + assertThat(stepExecutionEvent.getWriteCount()).isEqualTo(11); stepExecutionEvent.setReadCount(12); - assertEquals(12, stepExecutionEvent.getReadCount()); + assertThat(stepExecutionEvent.getReadCount()).isEqualTo(12); stepExecutionEvent.setEndTime(date); - assertEquals(date, stepExecutionEvent.getEndTime()); + assertThat(stepExecutionEvent.getEndTime()).isEqualTo(date); stepExecutionEvent.setCommitCount(29); - assertEquals(29, stepExecutionEvent.getCommitCount()); + assertThat(stepExecutionEvent.getCommitCount()).isEqualTo(29); } @Test - public void testExitStatus() { - StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(getBasicStepExecution()); + public void testExitStatus() { + StepExecutionEvent stepExecutionEvent = new StepExecutionEvent( + getBasicStepExecution()); final String EXIT_CODE = "1"; final String EXIT_DESCRIPTION = "EXPECTED FAILURE"; ExitStatus exitStatus = new ExitStatus(); @@ -175,41 +198,48 @@ public class StepExecutionEventTests { stepExecutionEvent.setExitStatus(exitStatus); ExitStatus actualExitStatus = stepExecutionEvent.getExitStatus(); - assertNotNull(actualExitStatus); - assertEquals(exitStatus.getExitCode(), actualExitStatus.getExitCode()); - assertEquals(exitStatus.getExitDescription(), actualExitStatus.getExitDescription()); + assertThat(actualExitStatus).isNotNull(); + assertThat(actualExitStatus.getExitCode()).isEqualTo(exitStatus.getExitCode()); + assertThat(actualExitStatus.getExitDescription()) + .isEqualTo(exitStatus.getExitDescription()); } @Test - public void testBatchStatus() { - StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(getBasicStepExecution()); - assertEquals(BatchStatus.STARTING, stepExecutionEvent.getStatus()); + public void testBatchStatus() { + StepExecutionEvent stepExecutionEvent = new StepExecutionEvent( + getBasicStepExecution()); + assertThat(stepExecutionEvent.getStatus()).isEqualTo(BatchStatus.STARTING); stepExecutionEvent.setStatus(BatchStatus.ABANDONED); - assertEquals(BatchStatus.ABANDONED, stepExecutionEvent.getStatus()); + assertThat(stepExecutionEvent.getStatus()).isEqualTo(BatchStatus.ABANDONED); } @Test public void testDefaultConstructor() { StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(); - assertEquals(BatchStatus.STARTING, stepExecutionEvent.getStatus()); - assertNotNull(stepExecutionEvent.getExitStatus()); - assertEquals("EXECUTING", stepExecutionEvent.getExitStatus().getExitCode()); + assertThat(stepExecutionEvent.getStatus()).isEqualTo(BatchStatus.STARTING); + assertThat(stepExecutionEvent.getExitStatus()).isNotNull(); + assertThat(stepExecutionEvent.getExitStatus().getExitCode()) + .isEqualTo("EXECUTING"); } @Test public void testExecutionContext() { ExecutionContext executionContext = new ExecutionContext(); executionContext.put("hello", "world"); - StepExecutionEvent stepExecutionEvent = new StepExecutionEvent(getBasicStepExecution()); - assertNotNull(stepExecutionEvent.getExecutionContext()); + StepExecutionEvent stepExecutionEvent = new StepExecutionEvent( + getBasicStepExecution()); + assertThat(stepExecutionEvent.getExecutionContext()).isNotNull(); stepExecutionEvent.setExecutionContext(executionContext); - assertEquals("world", stepExecutionEvent.getExecutionContext().getString("hello")); + 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, JOB_CONFIGURATION_NAME); + JobExecution jobExecution = new JobExecution(jobInstance, JOB_EXECUTION_ID, + jobParameters, JOB_CONFIGURATION_NAME); 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 6633a8de..df2c1796 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.batch.listener; @@ -40,8 +40,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.support.GenericApplicationContext; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; /** @@ -51,15 +50,6 @@ import static org.mockito.Mockito.when; @SpringBootTest public class TaskBatchEventListenerBeanPostProcessorTests { - @MockBean - private TaskletStep taskletStep; - - @MockBean - private SimpleChunkProvider chunkProvider; - - @MockBean - private SimpleChunkProcessor chunkProcessor; - @MockBean ItemProcessListener itemProcessListener; @@ -78,46 +68,63 @@ public class TaskBatchEventListenerBeanPostProcessorTests { @MockBean SkipListener skipListener; + @MockBean + private TaskletStep taskletStep; + + @MockBean + private SimpleChunkProvider chunkProvider; + + @MockBean + private SimpleChunkProcessor chunkProcessor; + @Autowired private GenericApplicationContext context; - @Before public void setupMock() { - when(taskletStep.getTasklet()).thenReturn( - new ChunkOrientedTasklet(chunkProvider, chunkProcessor)); - when(taskletStep.getName()).thenReturn("FOOOBAR"); + 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 public void testPostProcessor() { - TaskBatchEventListenerBeanPostProcessor postProcessor = - context.getBean(TaskBatchEventListenerBeanPostProcessor.class); - assertNotNull(postProcessor); - TaskletStep updatedTaskletStep = (TaskletStep) - postProcessor.postProcessBeforeInitialization(taskletStep, "FOO"); - assertEquals(taskletStep, updatedTaskletStep); + TaskBatchEventListenerBeanPostProcessor postProcessor = this.context + .getBean(TaskBatchEventListenerBeanPostProcessor.class); + assertThat(postProcessor).isNotNull(); + TaskletStep updatedTaskletStep = (TaskletStep) postProcessor + .postProcessBeforeInitialization(this.taskletStep, "FOO"); + assertThat(updatedTaskletStep).isEqualTo(this.taskletStep); + } + + private void registerAlias(Class clazz, String name) { + assertThat(this.context.getBeanNamesForType(clazz).length).isEqualTo(1); + this.context.registerAlias(this.context.getBeanNamesForType(clazz)[0], name); + } @Configuration @EnableAutoConfiguration public static class TestConfiguration { + @Bean public TaskBatchEventListenerBeanPostProcessor taskBatchEventListenerBeanPostProcessor() { return new TaskBatchEventListenerBeanPostProcessor(); } - } - - private void registerAlias(Class clazz, String name) { - assertEquals(1, context.getBeanNamesForType(clazz).length); - context.registerAlias(context.getBeanNamesForType(clazz)[0],name); } + } 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 d801b56b..e576b162 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.launcher; @@ -29,42 +29,40 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - +import static org.assertj.core.api.Assertions.assertThat; /** - * Tests the TaskLauncherConfiguration in a case where a TaskLauncher is already - * present. + * Tests the TaskLauncherConfiguration in a case where a TaskLauncher is already present. * - * @author Glenn Renfro + * @author Glenn Renfro */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = - {TaskLaunchConfigurationExistingTests.TestTaskDeployerConfiguration.class}) +@SpringBootTest(classes = { + TaskLaunchConfigurationExistingTests.TestTaskDeployerConfiguration.class }) public class TaskLaunchConfigurationExistingTests { + private static TaskLauncher testTaskLauncher; + @Autowired private ApplicationContext context; - private static TaskLauncher testTaskLauncher; - @Test public void testTaskLauncher() { - LocalTaskLauncher taskLauncher = - context.getBean(LocalTaskLauncher.class); - assertNotNull(testTaskLauncher); - assertNotNull(taskLauncher); - assertEquals(testTaskLauncher, taskLauncher); + LocalTaskLauncher taskLauncher = this.context.getBean(LocalTaskLauncher.class); + assertThat(testTaskLauncher).isNotNull(); + assertThat(taskLauncher).isNotNull(); + assertThat(taskLauncher).isEqualTo(testTaskLauncher); } @Configuration protected static class TestTaskDeployerConfiguration { + @Bean public TaskLauncher taskLauncher() { - testTaskLauncher = - new LocalTaskLauncher(new LocalDeployerProperties()); + testTaskLauncher = new LocalTaskLauncher(new LocalDeployerProperties()); return testTaskLauncher; } + } + } 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 463ece05..291ca1ef 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 @@ -1,17 +1,17 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.task.launcher; @@ -24,14 +24,13 @@ import java.util.Map; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Glenn Renfro */ public class TaskLaunchRequestTests { + public static final String URI = "http://myURI"; public static final String APP_NAME = "MY_APP_NAME"; @@ -43,51 +42,47 @@ 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); - assertFalse(request.equals(null)); - assertFalse(request.equals("nope")); - assertTrue(request.equals(request)); - assertTrue(request.equals(request2)); + 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("http://oops", - Collections.EMPTY_LIST, Collections.EMPTY_MAP, - Collections.EMPTY_MAP, null); - assertFalse(request.equals(requestDiff)); + 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); - assertFalse(request.equals(requestDiff)); + assertThat(request.equals(requestDiff)).isFalse(); - requestDiff = new TaskLaunchRequest(URI, - null, null, null, null); - assertTrue(request.equals(requestDiff)); + 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); - assertFalse(request.equals(requestDiff)); + assertThat(request.equals(requestDiff)).isFalse(); requestDiff = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, map, null); - assertFalse(request.equals(requestDiff)); + assertThat(request.equals(requestDiff)).isFalse(); - assertEquals(request.hashCode(), request.hashCode()); + assertThat(request.hashCode()).isEqualTo(request.hashCode()); } @Test public void testApplicationName() { - TaskLaunchRequest request = new TaskLaunchRequest(URI, - Collections.EMPTY_LIST, Collections.EMPTY_MAP, - Collections.EMPTY_MAP, null); - assertTrue(request.getApplicationName().startsWith("Task-")); + 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); - assertEquals(APP_NAME, request.getApplicationName()); + 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/TaskLauncherSinkTests.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLauncherSinkTests.java index 4c558b5f..c523f2ac 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLauncherSinkTests.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/TaskLauncherSinkTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,11 +36,10 @@ import org.springframework.context.ApplicationContext; import org.springframework.messaging.support.GenericMessage; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = {TaskLauncherSinkApplication.class, TaskConfiguration.class} ) +@SpringBootTest(classes = { TaskLauncherSinkApplication.class, TaskConfiguration.class }) public class TaskLauncherSinkTests { private final static String TASK_NAME_PREFIX = "Task-"; @@ -57,10 +56,10 @@ public class TaskLauncherSinkTests { private final static String INVALID_URL = "maven://not.real.group:" + "invalid:jar:1.0.0.BUILD-SNAPSHOT"; - private Map properties; - private final static String DEFAULT_STATUS = "test_status"; + private Map properties; + @Autowired private ApplicationContext context; @@ -69,8 +68,8 @@ public class TaskLauncherSinkTests { @Before public void setup() { - properties = new HashMap<>(); - properties.put("server.port", "0"); + this.properties = new HashMap<>(); + this.properties.put("server.port", "0"); } @Test @@ -79,7 +78,8 @@ public class TaskLauncherSinkTests { commandLineArgs.add(PARAM1); commandLineArgs.add(PARAM2); - TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskString(VALID_URL, commandLineArgs, null); + TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskString(VALID_URL, + commandLineArgs, null); verifySuccessWithParams(testTaskLauncher); testTaskLauncher = launchTaskByteArray(VALID_URL, commandLineArgs, null); @@ -89,17 +89,21 @@ public class TaskLauncherSinkTests { verifySuccessWithParams(testTaskLauncher); } - private void verifySuccessWithParams(TaskConfiguration.TestTaskLauncher testTaskLauncher) { - assertEquals(LaunchState.complete, testTaskLauncher.status(DEFAULT_STATUS).getState()); - assertEquals(2, testTaskLauncher.getCommandlineArguments().size()); - assertEquals(PARAM1, testTaskLauncher.getCommandlineArguments().get(0)); - assertEquals(PARAM2, testTaskLauncher.getCommandlineArguments().get(1)); - assertTrue(testTaskLauncher.getApplicationName().startsWith(TASK_NAME_PREFIX)); + 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(); } @Test public void testSuccessWithAppName() throws Exception { - TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskString(VALID_URL, null, APP_NAME); + TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskString(VALID_URL, + null, APP_NAME); verifySuccessWithAppName(testTaskLauncher); testTaskLauncher = launchTaskByteArray(VALID_URL, null, APP_NAME); @@ -110,21 +114,24 @@ public class TaskLauncherSinkTests { } @Test - public void testInvalidJar() throws Exception{ + public void testInvalidJar() throws Exception { TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskTaskLaunchRequest( INVALID_URL, null, APP_NAME); verifySuccessWithAppName(testTaskLauncher); } - private void verifySuccessWithAppName(TaskConfiguration.TestTaskLauncher testTaskLauncher) { - assertEquals(LaunchState.complete, testTaskLauncher.status(DEFAULT_STATUS).getState()); - assertEquals(0, testTaskLauncher.getCommandlineArguments().size()); - assertEquals(APP_NAME, testTaskLauncher.getApplicationName()); + 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); } @Test public void testSuccessNoParams() throws Exception { - TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskString(VALID_URL, null, null); + TaskConfiguration.TestTaskLauncher testTaskLauncher = launchTaskString(VALID_URL, + null, null); verifySuccessWithNoParams(testTaskLauncher); testTaskLauncher = launchTaskByteArray(VALID_URL, null, null); @@ -134,23 +141,29 @@ public class TaskLauncherSinkTests { verifySuccessWithNoParams(testTaskLauncher); } - private void verifySuccessWithNoParams(TaskConfiguration.TestTaskLauncher testTaskLauncher) { - assertEquals(LaunchState.complete, testTaskLauncher.status(DEFAULT_STATUS).getState()); - assertEquals(0, testTaskLauncher.getCommandlineArguments().size()); - assertTrue(testTaskLauncher.getApplicationName().startsWith(TASK_NAME_PREFIX)); + private void verifySuccessWithNoParams( + TaskConfiguration.TestTaskLauncher testTaskLauncher) { + assertThat(testTaskLauncher.status(DEFAULT_STATUS).getState()) + .isEqualTo(LaunchState.complete); + assertThat(testTaskLauncher.getCommandlineArguments().size()).isEqualTo(0); + assertThat(testTaskLauncher.getApplicationName().startsWith(TASK_NAME_PREFIX)) + .isTrue(); } @Test public void testNoRun() { - TaskConfiguration.TestTaskLauncher testTaskLauncher = - context.getBean(TaskConfiguration.TestTaskLauncher.class); - assertEquals(LaunchState.unknown, testTaskLauncher.status(DEFAULT_STATUS).getState()); + TaskConfiguration.TestTaskLauncher testTaskLauncher = this.context + .getBean(TaskConfiguration.TestTaskLauncher.class); + assertThat(testTaskLauncher.status(DEFAULT_STATUS).getState()) + .isEqualTo(LaunchState.unknown); } private TaskConfiguration.TestTaskLauncher launchTaskString(String artifactURL, List commandLineArgs, String applicationName) throws Exception { - TaskConfiguration.TestTaskLauncher testTaskLauncher = context.getBean(TaskConfiguration.TestTaskLauncher.class); - String stringRequest = getStringTaskLaunchRequest(artifactURL, commandLineArgs, applicationName); + TaskConfiguration.TestTaskLauncher testTaskLauncher = this.context + .getBean(TaskConfiguration.TestTaskLauncher.class); + String stringRequest = getStringTaskLaunchRequest(artifactURL, commandLineArgs, + applicationName); GenericMessage message = new GenericMessage<>(stringRequest); this.sink.input().send(message); @@ -159,9 +172,10 @@ public class TaskLauncherSinkTests { private TaskConfiguration.TestTaskLauncher launchTaskByteArray(String artifactURL, List commandLineArgs, String applicationName) throws Exception { - TaskConfiguration.TestTaskLauncher testTaskLauncher = - context.getBean(TaskConfiguration.TestTaskLauncher.class); - String stringRequest = getStringTaskLaunchRequest(artifactURL, commandLineArgs, applicationName); + TaskConfiguration.TestTaskLauncher testTaskLauncher = this.context + .getBean(TaskConfiguration.TestTaskLauncher.class); + String stringRequest = getStringTaskLaunchRequest(artifactURL, commandLineArgs, + applicationName); GenericMessage message = new GenericMessage<>(stringRequest.getBytes()); this.sink.input().send(message); @@ -170,21 +184,23 @@ public class TaskLauncherSinkTests { private String getStringTaskLaunchRequest(String artifactURL, List commandLineArgs, String applicationName) throws Exception { - TaskLaunchRequest request = new TaskLaunchRequest(artifactURL, - commandLineArgs, properties, null, applicationName); + TaskLaunchRequest request = new TaskLaunchRequest(artifactURL, commandLineArgs, + this.properties, null, applicationName); ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(request); } - private TaskConfiguration.TestTaskLauncher launchTaskTaskLaunchRequest(String artifactURL, - List commandLineArgs, String applicationName) throws Exception { - TaskConfiguration.TestTaskLauncher testTaskLauncher = - context.getBean(TaskConfiguration.TestTaskLauncher.class); - TaskLaunchRequest request = new TaskLaunchRequest(artifactURL, - commandLineArgs, properties, null, applicationName); + private TaskConfiguration.TestTaskLauncher launchTaskTaskLaunchRequest( + String artifactURL, List commandLineArgs, String applicationName) + throws Exception { + TaskConfiguration.TestTaskLauncher testTaskLauncher = this.context + .getBean(TaskConfiguration.TestTaskLauncher.class); + TaskLaunchRequest request = new TaskLaunchRequest(artifactURL, commandLineArgs, + this.properties, null, applicationName); GenericMessage message = new GenericMessage<>(request); this.sink.input().send(message); return testTaskLauncher; } + } diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/configuration/TaskConfiguration.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/configuration/TaskConfiguration.java index c4a89cec..bd87ae4f 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/configuration/TaskConfiguration.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/configuration/TaskConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,11 +34,11 @@ import org.springframework.context.annotation.Configuration; public class TaskConfiguration { @Bean - public TaskLauncher taskLauncher(){ + public TaskLauncher taskLauncher() { return new TestTaskLauncher(); } - public static class TestTaskLauncher implements TaskLauncher{ + public static class TestTaskLauncher implements TaskLauncher { public static final String LAUNCH_ID = "TEST_LAUNCH_ID"; @@ -50,7 +50,7 @@ public class TaskConfiguration { @Override public String launch(AppDeploymentRequest request) { - state = LaunchState.complete; + this.state = LaunchState.complete; this.commandlineArguments = request.getCommandlineArguments(); this.applicationName = request.getDefinition().getName(); return null; @@ -63,7 +63,7 @@ public class TaskConfiguration { @Override public TaskStatus status(String id) { - return new TaskStatus(LAUNCH_ID, state, null); + return new TaskStatus(LAUNCH_ID, this.state, null); } @Override @@ -82,11 +82,13 @@ public class TaskConfiguration { } public List getCommandlineArguments() { - return commandlineArguments; + return this.commandlineArguments; } public String getApplicationName() { - return applicationName; + return this.applicationName; } + } + } diff --git a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/util/TaskLauncherSinkApplication.java b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/util/TaskLauncherSinkApplication.java index 141d7eb3..7b8aafff 100644 --- a/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/util/TaskLauncherSinkApplication.java +++ b/spring-cloud-task-stream/src/test/java/org/springframework/cloud/task/launcher/util/TaskLauncherSinkApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,4 +30,5 @@ public class TaskLauncherSinkApplication { public static void main(String[] args) { SpringApplication.run(TaskLauncherSinkApplication.class, args); } + } 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 5b515557..5e619c68 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 @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.task.listener; import org.junit.Test; @@ -31,7 +32,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.integration.annotation.BridgeFrom; import org.springframework.integration.channel.NullChannel; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michael Minella @@ -43,19 +44,21 @@ public class TaskEventTests { @Test public void testDefaultConfiguration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EmbeddedDataSourceConfiguration.class, + .withConfiguration(AutoConfigurations.of( + EmbeddedDataSourceConfiguration.class, TaskEventAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, TestSupportBinderAutoConfiguration.class, - SimpleTaskAutoConfiguration.class, - SingleTaskConfiguration.class, + SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class, BindingServiceConfiguration.class)) .withUserConfiguration(TaskEventsConfiguration.class) .withPropertyValues("spring.cloud.task.closecontext_enabled=false", "spring.main.web-environment=false"); applicationContextRunner.run((context) -> { - assertNotNull(context.getBean("taskEventListener")); - assertNotNull(context.getBean(TaskEventAutoConfiguration.TaskEventChannels.class)); + assertThat(context.getBean("taskEventListener")).isNotNull(); + assertThat( + context.getBean(TaskEventAutoConfiguration.TaskEventChannels.class)) + .isNotNull(); }); } @@ -68,6 +71,7 @@ public class TaskEventTests { public NullChannel testEmptyChannel() { return new NullChannel(); } + } }