Updated to files to fit the Standard.

This commit is contained in:
Glenn Renfro
2022-07-25 11:41:43 -04:00
parent 39908bb499
commit 76a5d12136
200 changed files with 2839 additions and 4125 deletions

View File

@@ -96,16 +96,14 @@ public class DefaultTaskConfigurer implements TaskConfigurer {
* infrastructure.
* @param context the context to be used.
*/
public DefaultTaskConfigurer(DataSource dataSource, String tablePrefix,
ApplicationContext context) {
public DefaultTaskConfigurer(DataSource dataSource, String tablePrefix, ApplicationContext context) {
this.dataSource = dataSource;
this.context = context;
TaskExecutionDaoFactoryBean taskExecutionDaoFactoryBean;
if (this.dataSource != null) {
taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(this.dataSource,
tablePrefix);
taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(this.dataSource, tablePrefix);
}
else {
taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean();
@@ -136,27 +134,22 @@ public class DefaultTaskConfigurer implements TaskConfigurer {
if (isDataSourceAvailable()) {
try {
Class.forName("javax.persistence.EntityManager");
if (this.context != null && this.context
.getBeanNamesForType(EntityManager.class).length > 0) {
logger.debug(
"EntityManager was found, using JpaTransactionManager");
if (this.context != null && this.context.getBeanNamesForType(EntityManager.class).length > 0) {
logger.debug("EntityManager was found, using JpaTransactionManager");
this.transactionManager = new JpaTransactionManager();
}
}
catch (ClassNotFoundException ignore) {
logger.debug(
"No EntityManager was found, using DataSourceTransactionManager");
logger.debug("No EntityManager was found, using DataSourceTransactionManager");
}
finally {
if (this.transactionManager == null) {
this.transactionManager = new DataSourceTransactionManager(
this.dataSource);
this.transactionManager = new DataSourceTransactionManager(this.dataSource);
}
}
}
else {
logger.debug(
"No DataSource was found, using ResourcelessTransactionManager");
logger.debug("No DataSource was found, using ResourcelessTransactionManager");
this.transactionManager = new ResourcelessTransactionManager();
}
}

View File

@@ -55,13 +55,12 @@ import org.springframework.util.CollectionUtils;
@EnableTransactionManagement
@EnableConfigurationProperties({ TaskProperties.class })
// @checkstyle:off
@ConditionalOnProperty(prefix = "spring.cloud.task.autoconfiguration", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.cloud.task.autoconfiguration", name = "enabled", havingValue = "true",
matchIfMissing = true)
// @checkstyle:on
public class SimpleTaskAutoConfiguration {
protected static final Log logger = LogFactory
.getLog(SimpleTaskAutoConfiguration.class);
protected static final Log logger = LogFactory.getLog(SimpleTaskAutoConfiguration.class);
@Autowired(required = false)
private Collection<DataSource> dataSources;
@@ -85,7 +84,6 @@ public class SimpleTaskAutoConfiguration {
return this.taskRepository;
}
@Bean
public PlatformTransactionManager springCloudTaskTransactionManager() {
return this.platformTransactionManager;
@@ -104,8 +102,7 @@ public class SimpleTaskAutoConfiguration {
@Bean
@Lazy(false)
public TaskRepositoryInitializer taskRepositoryInitializer() {
TaskRepositoryInitializer taskRepositoryInitializer = new TaskRepositoryInitializer(
this.taskProperties);
TaskRepositoryInitializer taskRepositoryInitializer = new TaskRepositoryInitializer(this.taskProperties);
DataSource initializerDataSource = getDefaultConfigurer().getTaskDataSource();
if (initializerDataSource != null) {
taskRepositoryInitializer.setDataSource(initializerDataSource);
@@ -114,7 +111,6 @@ public class SimpleTaskAutoConfiguration {
return taskRepositoryInitializer;
}
@Bean
@Profile("cloud")
TaskObservationCloudKeyValues taskObservationCloudKeyValues() {
@@ -132,8 +128,7 @@ public class SimpleTaskAutoConfiguration {
TaskConfigurer taskConfigurer = getDefaultConfigurer();
logger.debug(String.format("Using %s TaskConfigurer",
taskConfigurer.getClass().getName()));
logger.debug(String.format("Using %s TaskConfigurer", taskConfigurer.getClass().getName()));
this.taskRepository = taskConfigurer.getTaskRepository();
this.platformTransactionManager = taskConfigurer.getTransactionManager();
@@ -148,18 +143,14 @@ public class SimpleTaskAutoConfiguration {
if (configurers < 1) {
TaskConfigurer taskConfigurer;
if (!CollectionUtils.isEmpty(this.dataSources)
&& this.dataSources.size() == 1) {
taskConfigurer = new DefaultTaskConfigurer(
this.dataSources.iterator().next(),
if (!CollectionUtils.isEmpty(this.dataSources) && this.dataSources.size() == 1) {
taskConfigurer = new DefaultTaskConfigurer(this.dataSources.iterator().next(),
this.taskProperties.getTablePrefix(), this.context);
}
else {
taskConfigurer = new DefaultTaskConfigurer(
this.taskProperties.getTablePrefix());
taskConfigurer = new DefaultTaskConfigurer(this.taskProperties.getTablePrefix());
}
this.context.getBeanFactory().registerSingleton("taskConfigurer",
taskConfigurer);
this.context.getBeanFactory().registerSingleton("taskConfigurer", taskConfigurer);
return taskConfigurer;
}
else {
@@ -167,8 +158,7 @@ public class SimpleTaskAutoConfiguration {
return this.context.getBean(TaskConfigurer.class);
}
else {
throw new IllegalStateException(
"Expected one TaskConfigurer but found " + configurers);
throw new IllegalStateException("Expected one TaskConfigurer but found " + configurers);
}
}
}
@@ -177,14 +167,12 @@ public class SimpleTaskAutoConfiguration {
int configurers = this.context.getBeanNamesForType(TaskConfigurer.class).length;
// retrieve the count of dataSources (without instantiating them) excluding
// DataSource proxy beans
long dataSources = Arrays
.stream(this.context.getBeanNamesForType(DataSource.class))
long dataSources = Arrays.stream(this.context.getBeanNamesForType(DataSource.class))
.filter((name -> !ScopedProxyUtils.isScopedTarget(name))).count();
if (configurers == 0 && dataSources > 1) {
throw new IllegalStateException(
"To use the default TaskConfigurer the context must contain no more than"
+ " one DataSource, found " + dataSources);
throw new IllegalStateException("To use the default TaskConfigurer the context must contain no more than"
+ " one DataSource, found " + dataSources);
}
}

View File

@@ -73,29 +73,27 @@ public class SingleInstanceTaskListener implements ApplicationListener<Applicati
private PlatformTransactionManager platformTransactionManager;
public SingleInstanceTaskListener(LockRegistry lockRegistry,
TaskNameResolver taskNameResolver, TaskProperties taskProperties,
ApplicationEventPublisher applicationEventPublisher,
public SingleInstanceTaskListener(LockRegistry lockRegistry, TaskNameResolver taskNameResolver,
TaskProperties taskProperties, ApplicationEventPublisher applicationEventPublisher,
ApplicationContext applicationContext) {
this.lockRegistry = lockRegistry;
this.taskNameResolver = taskNameResolver;
this.taskProperties = taskProperties;
this.lockRegistryLeaderInitiator = new LockRegistryLeaderInitiator(
this.lockRegistry);
this.lockRegistryLeaderInitiator = new LockRegistryLeaderInitiator(this.lockRegistry);
this.applicationEventPublisher = applicationEventPublisher;
this.applicationContext = applicationContext;
}
public SingleInstanceTaskListener(DataSource dataSource,
TaskNameResolver taskNameResolver, TaskProperties taskProperties,
ApplicationEventPublisher applicationEventPublisher,
public SingleInstanceTaskListener(DataSource dataSource, TaskNameResolver taskNameResolver,
TaskProperties taskProperties, ApplicationEventPublisher applicationEventPublisher,
ApplicationContext applicationContext) {
this.taskNameResolver = taskNameResolver;
this.applicationEventPublisher = applicationEventPublisher;
this.dataSource = dataSource;
this.taskProperties = taskProperties;
this.applicationContext = applicationContext;
this.platformTransactionManager = this.applicationContext.getBean("springCloudTaskTransactionManager", PlatformTransactionManager.class);
this.platformTransactionManager = this.applicationContext.getBean("springCloudTaskTransactionManager",
PlatformTransactionManager.class);
}
@BeforeTask
@@ -103,12 +101,9 @@ public class SingleInstanceTaskListener implements ApplicationListener<Applicati
if (this.lockRegistry == null) {
this.lockRegistry = getDefaultLockRegistry(taskExecution.getExecutionId());
}
this.lockRegistryLeaderInitiator = new LockRegistryLeaderInitiator(
this.lockRegistry,
new DefaultCandidate(String.valueOf(taskExecution.getExecutionId()),
this.taskNameResolver.getTaskName()));
this.lockRegistryLeaderInitiator
.setApplicationEventPublisher(this.applicationEventPublisher);
this.lockRegistryLeaderInitiator = new LockRegistryLeaderInitiator(this.lockRegistry, new DefaultCandidate(
String.valueOf(taskExecution.getExecutionId()), this.taskNameResolver.getTaskName()));
this.lockRegistryLeaderInitiator.setApplicationEventPublisher(this.applicationEventPublisher);
this.lockRegistryLeaderInitiator.setPublishFailedEvents(true);
this.lockRegistryLeaderInitiator.start();
while (!this.lockReady) {
@@ -119,15 +114,13 @@ public class SingleInstanceTaskListener implements ApplicationListener<Applicati
logger.warn("Thread Sleep Failed", ex);
}
if (this.lockFailed) {
String errorMessage = String.format(
"Task with name \"%s\" is already running.",
String errorMessage = String.format("Task with name \"%s\" is already running.",
this.taskNameResolver.getTaskName());
try {
this.lockRegistryLeaderInitiator.destroy();
}
catch (Exception exception) {
throw new TaskExecutionException("Failed to destroy lock.",
exception);
throw new TaskExecutionException("Failed to destroy lock.", exception);
}
throw new TaskExecutionException(errorMessage);
}
@@ -140,8 +133,7 @@ public class SingleInstanceTaskListener implements ApplicationListener<Applicati
}
@FailedTask
public void unlockTaskOnError(TaskExecution taskExecution, Throwable throwable)
throws Exception {
public void unlockTaskOnError(TaskExecution taskExecution, Throwable throwable) throws Exception {
this.lockRegistryLeaderInitiator.destroy();
}
@@ -156,8 +148,7 @@ public class SingleInstanceTaskListener implements ApplicationListener<Applicati
}
private LockRegistry getDefaultLockRegistry(long executionId) {
DefaultLockRepository lockRepository = new DefaultLockRepository(this.dataSource,
String.valueOf(executionId));
DefaultLockRepository lockRepository = new DefaultLockRepository(this.dataSource, String.valueOf(executionId));
lockRepository.setPrefix(this.taskProperties.getTablePrefix());
lockRepository.setTimeToLive(this.taskProperties.getSingleInstanceLockTtl());
lockRepository.setApplicationContext(this.applicationContext);

View File

@@ -36,8 +36,7 @@ import org.springframework.integration.support.locks.PassThruLockRegistry;
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "spring.cloud.task", name = "single-instance-enabled",
havingValue = "true")
@ConditionalOnProperty(prefix = "spring.cloud.task", name = "single-instance-enabled", havingValue = "true")
public class SingleTaskConfiguration {
@Autowired
@@ -52,12 +51,12 @@ public class SingleTaskConfiguration {
@Bean
public SingleInstanceTaskListener taskListener(TaskNameResolver resolver, ApplicationContext applicationContext) {
if (this.taskConfigurer.getTaskDataSource() == null) {
return new SingleInstanceTaskListener(new PassThruLockRegistry(), resolver,
this.taskProperties, this.applicationEventPublisher, applicationContext);
return new SingleInstanceTaskListener(new PassThruLockRegistry(), resolver, this.taskProperties,
this.applicationEventPublisher, applicationContext);
}
return new SingleInstanceTaskListener(this.taskConfigurer.getTaskDataSource(),
resolver, this.taskProperties, this.applicationEventPublisher, applicationContext);
return new SingleInstanceTaskListener(this.taskConfigurer.getTaskDataSource(), resolver, this.taskProperties,
this.applicationEventPublisher, applicationContext);
}
}

View File

@@ -43,8 +43,7 @@ import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class TaskLifecycleConfiguration {
protected static final Log logger = LogFactory
.getLog(TaskLifecycleConfiguration.class);
protected static final Log logger = LogFactory.getLog(TaskLifecycleConfiguration.class);
private TaskProperties taskProperties;
@@ -67,12 +66,11 @@ public class TaskLifecycleConfiguration {
private TaskObservationCloudKeyValues taskObservationCloudKeyValues;
@Autowired
public TaskLifecycleConfiguration(TaskProperties taskProperties,
ConfigurableApplicationContext context, TaskRepository taskRepository,
TaskExplorer taskExplorer, TaskNameResolver taskNameResolver,
ObjectProvider<ApplicationArguments> applicationArguments,
@Autowired(required = false) ObservationRegistry observationRegistry,
@Autowired(required = false) TaskObservationCloudKeyValues taskObservationCloudKeyValues) {
public TaskLifecycleConfiguration(TaskProperties taskProperties, ConfigurableApplicationContext context,
TaskRepository taskRepository, TaskExplorer taskExplorer, TaskNameResolver taskNameResolver,
ObjectProvider<ApplicationArguments> applicationArguments,
@Autowired(required = false) ObservationRegistry observationRegistry,
@Autowired(required = false) TaskObservationCloudKeyValues taskObservationCloudKeyValues) {
this.taskProperties = taskProperties;
this.context = context;
@@ -96,11 +94,10 @@ public class TaskLifecycleConfiguration {
@PostConstruct
protected void initialize() {
if (!this.initialized) {
this.taskLifecycleListener = new TaskLifecycleListener(this.taskRepository,
this.taskNameResolver, this.applicationArguments, this.taskExplorer,
this.taskProperties,
new TaskListenerExecutorObjectFactory(this.context),
this.observationRegistry, taskObservationCloudKeyValues);
this.taskLifecycleListener = new TaskLifecycleListener(this.taskRepository, this.taskNameResolver,
this.applicationArguments, this.taskExplorer, this.taskProperties,
new TaskListenerExecutorObjectFactory(this.context), this.observationRegistry,
taskObservationCloudKeyValues);
this.initialized = true;
}

View File

@@ -103,4 +103,5 @@ public class TaskObservationCloudKeyValues {
public void setInstanceIndex(String instanceIndex) {
this.instanceIndex = instanceIndex;
}
}

View File

@@ -36,4 +36,5 @@ public class DefaultTaskObservationConvention implements TaskObservationConventi
public String getName() {
return "spring.cloud.task.runner";
}
}

View File

@@ -51,8 +51,9 @@ class ObservationApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
TaskObservationContext context = new TaskObservationContext(this.beanName);
Observation observation = TaskDocumentedObservation.TASK_RUNNER_OBSERVATION.observation(this.taskObservationConvention, INSTANCE, context, registry())
.contextualName(this.beanName);
Observation observation = TaskDocumentedObservation.TASK_RUNNER_OBSERVATION
.observation(this.taskObservationConvention, INSTANCE, context, registry())
.contextualName(this.beanName);
try (Observation.Scope scope = observation.start().openScope()) {
this.delegate.run(args);

View File

@@ -50,8 +50,9 @@ class ObservationCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
TaskObservationContext context = new TaskObservationContext(this.beanName);
Observation observation = TaskDocumentedObservation.TASK_RUNNER_OBSERVATION.observation(this.taskObservationConvention, INSTANCE, context, registry())
.contextualName(this.beanName);
Observation observation = TaskDocumentedObservation.TASK_RUNNER_OBSERVATION
.observation(this.taskObservationConvention, INSTANCE, context, registry())
.contextualName(this.beanName);
try (Observation.Scope scope = observation.start().openScope()) {
this.delegate.run(args);
}
@@ -70,4 +71,5 @@ class ObservationCommandLineRunner implements CommandLineRunner {
}
return this.registry;
}
}

View File

@@ -39,12 +39,14 @@ import org.springframework.context.annotation.Configuration;
public class ObservationTaskAutoConfiguration {
@Bean
static ObservationCommandLineRunnerBeanPostProcessor observedCommandLineRunnerBeanPostProcessor(BeanFactory beanFactory) {
static ObservationCommandLineRunnerBeanPostProcessor observedCommandLineRunnerBeanPostProcessor(
BeanFactory beanFactory) {
return new ObservationCommandLineRunnerBeanPostProcessor(beanFactory);
}
@Bean
static ObservationApplicationRunnerBeanPostProcessor observedApplicationRunnerBeanPostProcessor(BeanFactory beanFactory) {
static ObservationApplicationRunnerBeanPostProcessor observedApplicationRunnerBeanPostProcessor(
BeanFactory beanFactory) {
return new ObservationApplicationRunnerBeanPostProcessor(beanFactory);
}

View File

@@ -57,5 +57,7 @@ enum TaskDocumentedObservation implements DocumentedObservation {
return "spring.cloud.task.runner.bean-name";
}
}
}
}

View File

@@ -35,4 +35,5 @@ public class TaskObservationContext extends Observation.Context {
public String getBeanName() {
return beanName;
}
}

View File

@@ -30,4 +30,5 @@ public interface TaskObservationConvention extends Observation.ObservationConven
default boolean supportsContext(Observation.Context context) {
return context instanceof TaskObservationContext;
}
}

View File

@@ -21,8 +21,7 @@ import io.micrometer.common.KeyValues;
import org.springframework.cloud.task.repository.TaskExecution;
/**
* /**
* Default {@link TaskExecutionObservationConvention} implementation.
* /** Default {@link TaskExecutionObservationConvention} implementation.
*
* @author Glenn Renfro
* @since 3.0.0
@@ -41,15 +40,16 @@ public class DefaultTaskExecutionObservationConvention implements TaskExecutionO
private KeyValues getKeyValuesForTaskExecution(TaskExecutionObservationContext context) {
TaskExecution execution = context.getTaskExecution();
return KeyValues.of(
TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), context.getStatus(),
TaskExecutionObservation.TaskKeyValues.TASK_EXIT_CODE.getKeyName(), String.valueOf(execution.getExitCode()),
TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(),
String.valueOf(execution.getExecutionId()));
return KeyValues.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), context.getStatus(),
TaskExecutionObservation.TaskKeyValues.TASK_EXIT_CODE.getKeyName(),
String.valueOf(execution.getExitCode()),
TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(),
String.valueOf(execution.getExecutionId()));
}
@Override
public String getName() {
return "spring.cloud.task";
}
}

View File

@@ -22,7 +22,8 @@ package org.springframework.cloud.task.listener;
*
* @author Michael Minella
* @since 1.2
* @deprecated since 3.0 in favor of the default implementations of {@link TaskExecutionListener}
* @deprecated since 3.0 in favor of the default implementations of
* {@link TaskExecutionListener}
*/
@Deprecated
public class TaskExecutionListenerSupport implements TaskExecutionListener {

View File

@@ -27,6 +27,7 @@ import io.micrometer.observation.docs.DocumentedObservation;
* @since 3.0.0
*/
public enum TaskExecutionObservation implements DocumentedObservation {
/**
* Metrics created around a task execution.
*/
@@ -41,6 +42,7 @@ public enum TaskExecutionObservation implements DocumentedObservation {
return "spring.cloud.task";
}
};
@Override
public KeyName[] getLowCardinalityKeyNames() {
return TaskKeyValues.values();

View File

@@ -28,6 +28,7 @@ import org.springframework.cloud.task.repository.TaskExecution;
* @since 3.0.0
*/
public class TaskExecutionObservationContext extends Observation.Context {
private final TaskExecution taskExecution;
private String exceptionMessage = "none";
@@ -57,4 +58,5 @@ public class TaskExecutionObservationContext extends Observation.Context {
public void setStatus(String status) {
this.status = status;
}
}

View File

@@ -24,10 +24,12 @@ import io.micrometer.observation.Observation;
* @author Glenn Renfro
* @since 3.0.0
*/
public interface TaskExecutionObservationConvention extends Observation.ObservationConvention<TaskExecutionObservationContext> {
public interface TaskExecutionObservationConvention
extends Observation.ObservationConvention<TaskExecutionObservationContext> {
@Override
default boolean supportsContext(Observation.Context context) {
return context instanceof TaskExecutionObservationContext;
}
}

View File

@@ -80,8 +80,8 @@ import org.springframework.util.StringUtils;
* @author Michael Minella
* @author Glenn Renfro
*/
public class TaskLifecycleListener implements ApplicationListener<ApplicationEvent>,
SmartLifecycle, DisposableBean, Ordered {
public class TaskLifecycleListener
implements ApplicationListener<ApplicationEvent>, SmartLifecycle, DisposableBean, Ordered {
private static final Log logger = LogFactory.getLog(TaskLifecycleListener.class);
@@ -135,18 +135,16 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
* @param taskListenerExecutorObjectFactory {@link TaskListenerExecutorObjectFactory}
* to initialize TaskListenerExecutor for a task
*/
public TaskLifecycleListener(TaskRepository taskRepository,
TaskNameResolver taskNameResolver, ApplicationArguments applicationArguments,
TaskExplorer taskExplorer, TaskProperties taskProperties,
public TaskLifecycleListener(TaskRepository taskRepository, TaskNameResolver taskNameResolver,
ApplicationArguments applicationArguments, TaskExplorer taskExplorer, TaskProperties taskProperties,
TaskListenerExecutorObjectFactory taskListenerExecutorObjectFactory,
@Autowired(required = false) ObservationRegistry observationRegistry,
TaskObservationCloudKeyValues taskObservationCloudKeyValues) {
@Autowired(required = false) ObservationRegistry observationRegistry,
TaskObservationCloudKeyValues taskObservationCloudKeyValues) {
Assert.notNull(taskRepository, "A taskRepository is required");
Assert.notNull(taskNameResolver, "A taskNameResolver is required");
Assert.notNull(taskExplorer, "A taskExplorer is required");
Assert.notNull(taskProperties, "TaskProperties is required");
Assert.notNull(taskListenerExecutorObjectFactory,
"A TaskListenerExecutorObjectFactory is required");
Assert.notNull(taskListenerExecutorObjectFactory, "A TaskListenerExecutorObjectFactory is required");
this.taskRepository = taskRepository;
this.taskNameResolver = taskNameResolver;
@@ -155,7 +153,8 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
this.taskProperties = taskProperties;
this.taskListenerExecutorObjectFactory = taskListenerExecutorObjectFactory;
observationRegistry = observationRegistry == null ? ObservationRegistry.NOOP : observationRegistry;
this.taskObservations = new TaskObservations(observationRegistry, taskObservationCloudKeyValues, observationConvention);
this.taskObservations = new TaskObservations(observationRegistry, taskObservationCloudKeyValues,
observationConvention);
}
/**
@@ -170,8 +169,7 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
if (applicationEvent instanceof ApplicationFailedEvent) {
this.applicationFailedException = ((ApplicationFailedEvent) applicationEvent)
.getException();
this.applicationFailedException = ((ApplicationFailedEvent) applicationEvent).getException();
doTaskEnd();
}
else if (applicationEvent instanceof ExitCodeEvent) {
@@ -196,21 +194,18 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
this.taskExecution.setEndTime(new Date());
if (this.applicationFailedException != null) {
this.taskExecution.setErrorMessage(
stackTraceToString(this.applicationFailedException));
this.taskExecution.setErrorMessage(stackTraceToString(this.applicationFailedException));
}
this.taskExecution.setExitCode(calcExitStatus());
if (this.applicationFailedException != null) {
setExitMessage(invokeOnTaskError(this.taskExecution,
this.applicationFailedException));
setExitMessage(invokeOnTaskError(this.taskExecution, this.applicationFailedException));
}
setExitMessage(invokeOnTaskEnd(this.taskExecution));
this.taskRepository.completeTaskExecution(this.taskExecution.getExecutionId(),
this.taskExecution.getExitCode(), this.taskExecution.getEndTime(),
this.taskExecution.getExitMessage(),
this.taskExecution.getErrorMessage());
this.taskExecution.getExitMessage(), this.taskExecution.getErrorMessage());
this.finished = true;
@@ -220,8 +215,7 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
}
else if (!this.started) {
logger.error("An event to end a task has been received for a task that has "
+ "not yet started.");
logger.error("An event to end a task has been received for a task that has " + "not yet started.");
}
}
@@ -240,12 +234,10 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
Throwable exception = this.listenerException;
if (exception instanceof TaskExecutionException) {
TaskExecutionException taskExecutionException = (TaskExecutionException) exception;
if (taskExecutionException
.getCause() instanceof InvocationTargetException) {
if (taskExecutionException.getCause() instanceof InvocationTargetException) {
InvocationTargetException invocationTargetException = (InvocationTargetException) taskExecutionException
.getCause();
if (invocationTargetException != null
&& invocationTargetException.getTargetException() != null) {
if (invocationTargetException != null && invocationTargetException.getTargetException() != null) {
exception = invocationTargetException.getTargetException();
}
}
@@ -268,11 +260,9 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
this.taskExecutionListeners = new ArrayList<>();
this.taskListenerExecutorObjectFactory.getObject();
if (!CollectionUtils.isEmpty(this.taskExecutionListenersFromContext)) {
this.taskExecutionListeners
.addAll(this.taskExecutionListenersFromContext);
this.taskExecutionListeners.addAll(this.taskExecutionListenersFromContext);
}
this.taskExecutionListeners
.add(this.taskListenerExecutorObjectFactory.getObject());
this.taskExecutionListeners.add(this.taskListenerExecutorObjectFactory.getObject());
List<String> args = new ArrayList<>(0);
@@ -282,35 +272,27 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
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",
Assert.notNull(taskExecution, String.format("Invalid TaskExecution, ID %s not found",
this.taskProperties.getExecutionid()));
this.taskExecution = this.taskRepository.startTaskExecution(
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(),
this.taskNameResolver.getTaskName(), new Date(), args,
this.taskProperties.getExternalExecutionId(),
this.taskProperties.getParentExecutionId());
this.taskProperties.getExternalExecutionId(), this.taskProperties.getParentExecutionId());
}
else {
TaskExecution taskExecution = new TaskExecution();
taskExecution.setTaskName(this.taskNameResolver.getTaskName());
taskExecution.setStartTime(new Date());
taskExecution.setArguments(args);
taskExecution.setExternalExecutionId(
this.taskProperties.getExternalExecutionId());
taskExecution.setParentExecutionId(
this.taskProperties.getParentExecutionId());
this.taskExecution = this.taskRepository
.createTaskExecution(taskExecution);
taskExecution.setExternalExecutionId(this.taskProperties.getExternalExecutionId());
taskExecution.setParentExecutionId(this.taskProperties.getParentExecutionId());
this.taskExecution = this.taskRepository.createTaskExecution(taskExecution);
}
}
else {
logger.error(
"Multiple start events have been received. The first one was "
+ "recorded.");
logger.error("Multiple start events have been received. The first one was " + "recorded.");
}
setExitMessage(invokeOnTaskStartup(this.taskExecution));
@@ -326,8 +308,7 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
private TaskExecution invokeOnTaskStartup(TaskExecution taskExecution) {
this.taskObservations.onTaskStartup(taskExecution);
TaskExecution listenerTaskExecution = getTaskExecutionCopy(taskExecution);
List<TaskExecutionListener> startupListenerList = new ArrayList<>(
this.taskExecutionListeners);
List<TaskExecutionListener> startupListenerList = new ArrayList<>(this.taskExecutionListeners);
if (!CollectionUtils.isEmpty(startupListenerList)) {
try {
Collections.reverse(startupListenerList);
@@ -360,8 +341,8 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
catch (Throwable listenerException) {
String errorMessage = stackTraceToString(listenerException);
if (StringUtils.hasText(listenerTaskExecution.getErrorMessage())) {
errorMessage = String.format("%s :Task also threw this Exception: %s",
errorMessage, listenerTaskExecution.getErrorMessage());
errorMessage = String.format("%s :Task also threw this Exception: %s", errorMessage,
listenerTaskExecution.getErrorMessage());
}
logger.error(errorMessage);
listenerTaskExecution.setErrorMessage(errorMessage);
@@ -371,8 +352,7 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
return listenerTaskExecution;
}
private TaskExecution invokeOnTaskError(TaskExecution taskExecution,
Throwable throwable) {
private TaskExecution invokeOnTaskError(TaskExecution taskExecution, Throwable throwable) {
if (this.taskObservations != null) {
this.taskObservations.onTaskFailed(throwable);
}
@@ -388,8 +368,7 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
String errorMessage;
if (StringUtils.hasText(listenerTaskExecution.getErrorMessage())) {
errorMessage = String.format("%s :While handling " + "this error: %s",
listenerException.getMessage(),
listenerTaskExecution.getErrorMessage());
listenerException.getMessage(), listenerTaskExecution.getErrorMessage());
}
else {
errorMessage = listenerTaskExecution.getErrorMessage();
@@ -405,14 +384,12 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
private TaskExecution getTaskExecutionCopy(TaskExecution taskExecution) {
Date startTime = new Date(taskExecution.getStartTime().getTime());
Date endTime = (taskExecution.getEndTime() == null) ? null
: new Date(taskExecution.getEndTime().getTime());
Date endTime = (taskExecution.getEndTime() == null) ? null : new Date(taskExecution.getEndTime().getTime());
return new TaskExecution(taskExecution.getExecutionId(),
taskExecution.getExitCode(), taskExecution.getTaskName(), startTime,
endTime, taskExecution.getExitMessage(),
Collections.unmodifiableList(taskExecution.getArguments()),
taskExecution.getErrorMessage(), taskExecution.getExternalExecutionId());
return new TaskExecution(taskExecution.getExecutionId(), taskExecution.getExitCode(),
taskExecution.getTaskName(), startTime, endTime, taskExecution.getExitMessage(),
Collections.unmodifiableList(taskExecution.getArguments()), taskExecution.getErrorMessage(),
taskExecution.getExternalExecutionId());
}
@Override

View File

@@ -49,13 +49,11 @@ import org.springframework.core.annotation.AnnotationUtils;
* @author Isik Erhan
* @since 2.1.0
*/
public class TaskListenerExecutorObjectFactory
implements ObjectFactory<TaskExecutionListener> {
public class TaskListenerExecutorObjectFactory implements ObjectFactory<TaskExecutionListener> {
private static final Log logger = LogFactory.getLog(TaskListenerExecutor.class);
private final Set<Class<?>> nonAnnotatedClasses = Collections
.newSetFromMap(new ConcurrentHashMap<>());
private final Set<Class<?>> nonAnnotatedClasses = Collections.newSetFromMap(new ConcurrentHashMap<>());
private ConfigurableApplicationContext context;
@@ -75,8 +73,7 @@ public class TaskListenerExecutorObjectFactory
this.afterTaskInstances = new HashMap<>();
this.failedTaskInstances = new HashMap<>();
initializeExecutor();
return new TaskListenerExecutor(this.beforeTaskInstances, this.afterTaskInstances,
this.failedTaskInstances);
return new TaskListenerExecutor(this.beforeTaskInstances, this.afterTaskInstances, this.failedTaskInstances);
}
private void initializeExecutor() {
@@ -92,8 +89,7 @@ public class TaskListenerExecutorObjectFactory
// An unresolvable bean type, probably from a lazy bean - let's ignore
// it.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve target class for bean with name '"
+ beanName + "'", ex);
logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
}
}
if (type != null) {
@@ -105,10 +101,7 @@ public class TaskListenerExecutorObjectFactory
catch (RuntimeException ex) {
// An invalid scoped proxy arrangement - let's ignore it.
if (logger.isDebugEnabled()) {
logger.debug(
"Could not resolve target bean for scoped proxy '"
+ beanName + "'",
ex);
logger.debug("Could not resolve target bean for scoped proxy '" + beanName + "'", ex);
}
}
}
@@ -117,9 +110,7 @@ public class TaskListenerExecutorObjectFactory
}
catch (RuntimeException ex) {
throw new BeanInitializationException(
"Failed to process @BeforeTask "
+ "annotation on bean with name '" + beanName
+ "'",
"Failed to process @BeforeTask " + "annotation on bean with name '" + beanName + "'",
ex);
}
}
@@ -130,12 +121,11 @@ public class TaskListenerExecutorObjectFactory
private void processBean(String beanName, final Class<?> type) {
if (!this.nonAnnotatedClasses.contains(type)) {
Map<Method, BeforeTask> beforeTaskMethods = (new MethodGetter<BeforeTask>())
.getMethods(type, BeforeTask.class);
Map<Method, AfterTask> afterTaskMethods = (new MethodGetter<AfterTask>())
.getMethods(type, AfterTask.class);
Map<Method, FailedTask> failedTaskMethods = (new MethodGetter<FailedTask>())
.getMethods(type, FailedTask.class);
Map<Method, BeforeTask> beforeTaskMethods = (new MethodGetter<BeforeTask>()).getMethods(type,
BeforeTask.class);
Map<Method, AfterTask> afterTaskMethods = (new MethodGetter<AfterTask>()).getMethods(type, AfterTask.class);
Map<Method, FailedTask> failedTaskMethods = (new MethodGetter<FailedTask>()).getMethods(type,
FailedTask.class);
if (beforeTaskMethods.isEmpty() && afterTaskMethods.isEmpty()) {
this.nonAnnotatedClasses.add(type);
@@ -143,22 +133,19 @@ public class TaskListenerExecutorObjectFactory
}
if (!beforeTaskMethods.isEmpty()) {
for (Method beforeTaskMethod : beforeTaskMethods.keySet()) {
this.beforeTaskInstances
.computeIfAbsent(beforeTaskMethod, k -> new LinkedHashSet<>())
this.beforeTaskInstances.computeIfAbsent(beforeTaskMethod, k -> new LinkedHashSet<>())
.add(this.context.getBean(beanName));
}
}
if (!afterTaskMethods.isEmpty()) {
for (Method afterTaskMethod : afterTaskMethods.keySet()) {
this.afterTaskInstances
.computeIfAbsent(afterTaskMethod, k -> new LinkedHashSet<>())
this.afterTaskInstances.computeIfAbsent(afterTaskMethod, k -> new LinkedHashSet<>())
.add(this.context.getBean(beanName));
}
}
if (!failedTaskMethods.isEmpty()) {
for (Method failedTaskMethod : failedTaskMethods.keySet()) {
this.failedTaskInstances
.computeIfAbsent(failedTaskMethod, k -> new LinkedHashSet<>())
this.failedTaskInstances.computeIfAbsent(failedTaskMethod, k -> new LinkedHashSet<>())
.add(this.context.getBean(beanName));
}
}
@@ -167,11 +154,10 @@ public class TaskListenerExecutorObjectFactory
private static class MethodGetter<T extends Annotation> {
public Map<Method, T> getMethods(final Class<?> type,
final Class<T> annotationClass) {
public Map<Method, T> getMethods(final Class<?> type, final Class<T> annotationClass) {
return MethodIntrospector.selectMethods(type,
(MethodIntrospector.MetadataLookup<T>) method -> AnnotationUtils
.findAnnotation(method, annotationClass));
(MethodIntrospector.MetadataLookup<T>) method -> AnnotationUtils.findAnnotation(method,
annotationClass));
}
}

View File

@@ -51,8 +51,9 @@ public class TaskObservations {
private Observation.ObservationConvention customObservationConvention;
public TaskObservations(ObservationRegistry observationRegistry, TaskObservationCloudKeyValues taskObservationCloudKeyValues,
Observation.ObservationConvention customObservationConvention) {
public TaskObservations(ObservationRegistry observationRegistry,
TaskObservationCloudKeyValues taskObservationCloudKeyValues,
Observation.ObservationConvention customObservationConvention) {
this.observationRegistry = observationRegistry;
this.taskObservationCloudKeyValues = taskObservationCloudKeyValues;
this.customObservationConvention = customObservationConvention;
@@ -68,34 +69,38 @@ public class TaskObservations {
public void onTaskStartup(TaskExecution taskExecution) {
this.taskObservationContext = new TaskExecutionObservationContext(taskExecution);
Observation observation = TaskExecutionObservation.TASK_ACTIVE.observation(this.customObservationConvention, new DefaultTaskExecutionObservationConvention(), this.taskObservationContext, this.observationRegistry)
.contextualName(String.valueOf(taskExecution.getExecutionId()))
.keyValuesProvider(this.observationsProvider)
.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), getValueOrDefault(taskExecution.getTaskName()))
.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(), "" + taskExecution.getExecutionId())
.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_PARENT_EXECUTION_ID.getKeyName(),
(getValueOrDefault(taskExecution.getParentExecutionId())))
.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_EXTERNAL_EXECUTION_ID.getKeyName(),
(getValueOrDefault(taskExecution.getExternalExecutionId())));
Observation observation = TaskExecutionObservation.TASK_ACTIVE
.observation(this.customObservationConvention, new DefaultTaskExecutionObservationConvention(),
this.taskObservationContext, this.observationRegistry)
.contextualName(String.valueOf(taskExecution.getExecutionId()))
.keyValuesProvider(this.observationsProvider)
.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(),
getValueOrDefault(taskExecution.getTaskName()))
.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(),
"" + taskExecution.getExecutionId())
.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_PARENT_EXECUTION_ID.getKeyName(),
(getValueOrDefault(taskExecution.getParentExecutionId())))
.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_EXTERNAL_EXECUTION_ID.getKeyName(),
(getValueOrDefault(taskExecution.getExternalExecutionId())));
if (taskObservationCloudKeyValues != null) {
observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_ORG_NAME.getKeyName(),
this.taskObservationCloudKeyValues.getOrganizationName());
this.taskObservationCloudKeyValues.getOrganizationName());
observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_ID.getKeyName(),
this.taskObservationCloudKeyValues.getSpaceId());
this.taskObservationCloudKeyValues.getSpaceId());
observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_NAME.getKeyName(),
this.taskObservationCloudKeyValues.getSpaceName());
this.taskObservationCloudKeyValues.getSpaceName());
observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_ID.getKeyName(),
this.taskObservationCloudKeyValues.getApplicationId());
this.taskObservationCloudKeyValues.getApplicationId());
observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_NAME.getKeyName(),
this.taskObservationCloudKeyValues.getApplicationName());
this.taskObservationCloudKeyValues.getApplicationName());
observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_VERSION.getKeyName(),
this.taskObservationCloudKeyValues.getApplicationVersion());
observation.lowCardinalityKeyValue(TaskExecutionObservation.TaskKeyValues.TASK_CF_INSTANCE_INDEX.getKeyName(),
this.taskObservationCloudKeyValues.getInstanceIndex());
this.taskObservationCloudKeyValues.getApplicationVersion());
observation.lowCardinalityKeyValue(
TaskExecutionObservation.TaskKeyValues.TASK_CF_INSTANCE_INDEX.getKeyName(),
this.taskObservationCloudKeyValues.getInstanceIndex());
}
observation.start();
@@ -107,8 +112,8 @@ public class TaskObservations {
}
public void onTaskFailed(Throwable throwable) {
this.taskObservationContext.setStatus(STATUS_FAILURE);
this.scope.getCurrentObservation().error(throwable);
this.taskObservationContext.setStatus(STATUS_FAILURE);
this.scope.getCurrentObservation().error(throwable);
}
public void onTaskEnd(TaskExecution taskExecution) {
@@ -118,4 +123,5 @@ public class TaskObservations {
this.scope.getCurrentObservation().stop();
}
}
}

View File

@@ -42,8 +42,7 @@ public class TaskListenerExecutor implements TaskExecutionListener {
private Map<Method, Set<Object>> failedTaskInstances;
public TaskListenerExecutor(Map<Method, Set<Object>> beforeTaskInstances,
Map<Method, Set<Object>> afterTaskInstances,
Map<Method, Set<Object>> failedTaskInstances) {
Map<Method, Set<Object>> afterTaskInstances, Map<Method, Set<Object>> failedTaskInstances) {
this.beforeTaskInstances = beforeTaskInstances;
this.afterTaskInstances = afterTaskInstances;
@@ -56,8 +55,7 @@ public class TaskListenerExecutor implements TaskExecutionListener {
*/
@Override
public void onTaskStartup(TaskExecution taskExecution) {
executeTaskListener(taskExecution, this.beforeTaskInstances.keySet(),
this.beforeTaskInstances);
executeTaskListener(taskExecution, this.beforeTaskInstances.keySet(), this.beforeTaskInstances);
}
/**
@@ -66,8 +64,7 @@ public class TaskListenerExecutor implements TaskExecutionListener {
*/
@Override
public void onTaskEnd(TaskExecution taskExecution) {
executeTaskListener(taskExecution, this.afterTaskInstances.keySet(),
this.afterTaskInstances);
executeTaskListener(taskExecution, this.afterTaskInstances.keySet(), this.afterTaskInstances);
}
/**
@@ -77,8 +74,8 @@ public class TaskListenerExecutor implements TaskExecutionListener {
*/
@Override
public void onTaskFailed(TaskExecution taskExecution, Throwable throwable) {
executeTaskListenerWithThrowable(taskExecution, throwable,
this.failedTaskInstances.keySet(), this.failedTaskInstances);
executeTaskListenerWithThrowable(taskExecution, throwable, this.failedTaskInstances.keySet(),
this.failedTaskInstances);
}
private void executeTaskListener(TaskExecution taskExecution, Set<Method> methods,
@@ -89,27 +86,24 @@ public class TaskListenerExecutor implements TaskExecutionListener {
method.invoke(instance, taskExecution);
}
catch (IllegalAccessException e) {
throw new TaskExecutionException(
"@BeforeTask and @AfterTask annotated methods must be public.",
e);
throw new TaskExecutionException("@BeforeTask and @AfterTask annotated methods must be public.", e);
}
catch (InvocationTargetException e) {
throw new TaskExecutionException(String.format(
"Failed to process @BeforeTask or @AfterTask"
+ " annotation because: %s",
e.getTargetException().getMessage()), e);
throw new TaskExecutionException(
String.format("Failed to process @BeforeTask or @AfterTask" + " annotation because: %s",
e.getTargetException().getMessage()),
e);
}
catch (IllegalArgumentException e) {
throw new TaskExecutionException("taskExecution parameter "
+ "is required for @BeforeTask and @AfterTask annotated methods",
throw new TaskExecutionException(
"taskExecution parameter " + "is required for @BeforeTask and @AfterTask annotated methods",
e);
}
}
}
}
private void executeTaskListenerWithThrowable(TaskExecution taskExecution,
Throwable throwable, Set<Method> methods,
private void executeTaskListenerWithThrowable(TaskExecution taskExecution, Throwable throwable, Set<Method> methods,
Map<Method, Set<Object>> instances) {
for (Method method : methods) {
for (Object instance : instances.get(method)) {
@@ -117,19 +111,17 @@ public class TaskListenerExecutor implements TaskExecutionListener {
method.invoke(instance, taskExecution, throwable);
}
catch (IllegalAccessException e) {
throw new TaskExecutionException(
"@FailedTask annotated methods must be public.", e);
throw new TaskExecutionException("@FailedTask annotated methods must be public.", e);
}
catch (InvocationTargetException e) {
throw new TaskExecutionException(String.format(
"Failed to process @FailedTask " + "annotation because: %s",
e.getTargetException().getMessage()), e);
throw new TaskExecutionException(
String.format("Failed to process @FailedTask " + "annotation because: %s",
e.getTargetException().getMessage()),
e);
}
catch (IllegalArgumentException e) {
throw new TaskExecutionException(
"taskExecution and throwable parameters "
+ "are required for @FailedTask annotated methods",
e);
throw new TaskExecutionException("taskExecution and throwable parameters "
+ "are required for @FailedTask annotated methods", e);
}
}
}

View File

@@ -90,9 +90,9 @@ public class TaskExecution {
this.arguments = new ArrayList<>();
}
public TaskExecution(long executionId, Integer exitCode, String taskName,
Date startTime, Date endTime, String exitMessage, List<String> arguments,
String errorMessage, String externalExecutionId, Long parentExecutionId) {
public TaskExecution(long executionId, Integer exitCode, String taskName, Date startTime, Date endTime,
String exitMessage, List<String> arguments, String errorMessage, String externalExecutionId,
Long parentExecutionId) {
Assert.notNull(arguments, "arguments must not be null");
this.executionId = executionId;
@@ -107,12 +107,11 @@ public class TaskExecution {
this.parentExecutionId = parentExecutionId;
}
public TaskExecution(long executionId, Integer exitCode, String taskName,
Date startTime, Date endTime, String exitMessage, List<String> arguments,
String errorMessage, String externalExecutionId) {
public TaskExecution(long executionId, Integer exitCode, String taskName, Date startTime, Date endTime,
String exitMessage, List<String> arguments, String errorMessage, String externalExecutionId) {
this(executionId, exitCode, taskName, startTime, endTime, exitMessage, arguments,
errorMessage, externalExecutionId, null);
this(executionId, exitCode, taskName, startTime, endTime, exitMessage, arguments, errorMessage,
externalExecutionId, null);
}
public long getExecutionId() {
@@ -193,12 +192,10 @@ public class TaskExecution {
@Override
public String toString() {
return "TaskExecution{" + "executionId=" + this.executionId
+ ", parentExecutionId=" + this.parentExecutionId + ", exitCode="
+ this.exitCode + ", taskName='" + this.taskName + '\'' + ", startTime="
+ this.startTime + ", endTime=" + this.endTime + ", exitMessage='"
+ this.exitMessage + '\'' + ", externalExecutionId='"
+ this.externalExecutionId + '\'' + ", errorMessage='" + this.errorMessage
return "TaskExecution{" + "executionId=" + this.executionId + ", parentExecutionId=" + this.parentExecutionId
+ ", exitCode=" + this.exitCode + ", taskName='" + this.taskName + '\'' + ", startTime="
+ this.startTime + ", endTime=" + this.endTime + ", exitMessage='" + this.exitMessage + '\''
+ ", externalExecutionId='" + this.externalExecutionId + '\'' + ", errorMessage='" + this.errorMessage
+ '\'' + ", arguments=" + this.arguments + '}';
}

View File

@@ -39,8 +39,7 @@ public interface TaskRepository {
* @return the updated {@link TaskExecution}
*/
@Transactional("springCloudTaskTransactionManager")
TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime,
String exitMessage);
TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage);
/**
* Notifies the repository that a taskExecution has completed.
@@ -53,8 +52,8 @@ public interface TaskRepository {
* @since 1.1.0
*/
@Transactional("springCloudTaskTransactionManager")
TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime,
String exitMessage, String errorMessage);
TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage,
String errorMessage);
/**
* Notifies the repository that a taskExecution needs to be created.
@@ -99,8 +98,8 @@ public interface TaskRepository {
* @return TaskExecution created based on the parameters.
*/
@Transactional("springCloudTaskTransactionManager")
TaskExecution startTaskExecution(long executionid, String taskName, Date startTime,
List<String> arguments, String externalExecutionId);
TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, List<String> arguments,
String externalExecutionId);
/**
* Notifies the repository to update the taskExecution's externalExecutionId.
@@ -122,7 +121,7 @@ public interface TaskRepository {
* a TaskExecution.
*/
@Transactional("springCloudTaskTransactionManager")
TaskExecution startTaskExecution(long executionid, String taskName, Date startTime,
List<String> arguments, String externalExecutionId, Long parentExecutionId);
TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, List<String> arguments,
String externalExecutionId, Long parentExecutionId);
}

View File

@@ -66,10 +66,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
/**
* SELECT clause for task execution.
*/
public static final String SELECT_CLAUSE = "TASK_EXECUTION_ID, "
+ "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, "
+ "EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, "
+ "EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID ";
public static final String SELECT_CLAUSE = "TASK_EXECUTION_ID, " + "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, "
+ "EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, " + "EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID ";
/**
* FROM clause for task execution.
@@ -116,15 +114,13 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
private static final String GET_EXECUTION_BY_ID = "SELECT TASK_EXECUTION_ID, "
+ "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, "
+ "EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, "
+ "PARENT_EXECUTION_ID "
+ "EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, " + "PARENT_EXECUTION_ID "
+ "from %PREFIX%EXECUTION where TASK_EXECUTION_ID = :taskExecutionId";
private static final String FIND_ARGUMENT_FROM_ID = "SELECT TASK_EXECUTION_ID, "
+ "TASK_PARAM from %PREFIX%EXECUTION_PARAMS where TASK_EXECUTION_ID = :taskExecutionId";
private static final String TASK_EXECUTION_COUNT = "SELECT COUNT(*) FROM "
+ "%PREFIX%EXECUTION ";
private static final String TASK_EXECUTION_COUNT = "SELECT COUNT(*) FROM " + "%PREFIX%EXECUTION ";
private static final String TASK_EXECUTION_COUNT_BY_NAME = "SELECT COUNT(*) FROM "
+ "%PREFIX%EXECUTION where TASK_NAME = :taskName";
@@ -138,8 +134,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
private static final String LAST_TASK_EXECUTIONS_BY_TASK_NAMES = "select TE2.* from ("
+ "select MAX(TE.TASK_EXECUTION_ID) as TASK_EXECUTION_ID, TE.TASK_NAME, TE.START_TIME from ("
+ "select TASK_NAME, MAX(START_TIME) as START_TIME"
+ " FROM %PREFIX%EXECUTION where TASK_NAME in (:taskNames)"
+ " GROUP BY TASK_NAME" + ") TE_MAX "
+ " FROM %PREFIX%EXECUTION where TASK_NAME in (:taskNames)" + " GROUP BY TASK_NAME" + ") TE_MAX "
+ "inner join %PREFIX%EXECUTION TE ON TE.TASK_NAME = TE_MAX.TASK_NAME AND TE.START_TIME = TE_MAX.START_TIME "
+ "group by TE.TASK_NAME, TE.START_TIME" + ") TE1 "
+ "inner join %PREFIX%EXECUTION TE2 ON TE1.TASK_EXECUTION_ID = TE2.TASK_EXECUTION_ID "
@@ -152,6 +147,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
private static final String FIND_JOB_EXECUTION_BY_TASK_EXECUTION_ID = "SELECT JOB_EXECUTION_ID "
+ "FROM %PREFIX%TASK_BATCH WHERE TASK_EXECUTION_ID = :taskExecutionId";
private static final Set<String> validSortColumns = new HashSet<>(10);
static {
@@ -168,9 +164,13 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
private final NamedParameterJdbcTemplate jdbcTemplate;
private String tablePrefix = TaskProperties.DEFAULT_TABLE_PREFIX;
private DataSource dataSource;
private LinkedHashMap<String, Order> orderMap;
private DataFieldMaxValueIncrementer taskIncrementer;
/**
@@ -199,25 +199,22 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
@Override
public TaskExecution createTaskExecution(String taskName, Date startTime,
List<String> arguments, String externalExecutionId) {
return createTaskExecution(taskName, startTime, arguments, externalExecutionId,
null);
public TaskExecution createTaskExecution(String taskName, Date startTime, List<String> arguments,
String externalExecutionId) {
return createTaskExecution(taskName, startTime, arguments, externalExecutionId, null);
}
@Override
public TaskExecution createTaskExecution(String taskName, Date startTime,
List<String> arguments, String externalExecutionId, Long parentExecutionId) {
public TaskExecution createTaskExecution(String taskName, Date startTime, List<String> arguments,
String externalExecutionId, Long parentExecutionId) {
long nextExecutionId = getNextExecutionId();
TaskExecution taskExecution = new TaskExecution(nextExecutionId, null, taskName,
startTime, null, null, arguments, null, externalExecutionId);
TaskExecution taskExecution = new TaskExecution(nextExecutionId, null, taskName, startTime, null, null,
arguments, null, externalExecutionId);
final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
.addValue("taskExecutionId", nextExecutionId, Types.BIGINT)
.addValue("exitCode", null, Types.INTEGER)
.addValue("startTime", startTime, Types.TIMESTAMP)
.addValue("taskName", taskName, Types.VARCHAR)
.addValue("taskExecutionId", nextExecutionId, Types.BIGINT).addValue("exitCode", null, Types.INTEGER)
.addValue("startTime", startTime, Types.TIMESTAMP).addValue("taskName", taskName, Types.VARCHAR)
.addValue("lastUpdated", new Date(), Types.TIMESTAMP)
.addValue("externalExecutionId", externalExecutionId, Types.VARCHAR)
.addValue("parentExecutionId", parentExecutionId, Types.BIGINT);
@@ -228,25 +225,20 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
@Override
public TaskExecution startTaskExecution(long executionId, String taskName,
Date startTime, List<String> arguments, String externalExecutionId) {
return startTaskExecution(executionId, taskName, startTime, arguments,
externalExecutionId, null);
public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments,
String externalExecutionId) {
return startTaskExecution(executionId, taskName, startTime, arguments, externalExecutionId, null);
}
@Override
public TaskExecution startTaskExecution(long executionId, String taskName,
Date startTime, List<String> arguments, String externalExecutionId,
Long parentExecutionId) {
TaskExecution taskExecution = new TaskExecution(executionId, null, taskName,
startTime, null, null, arguments, null, externalExecutionId,
parentExecutionId);
public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments,
String externalExecutionId, Long parentExecutionId) {
TaskExecution taskExecution = new TaskExecution(executionId, null, taskName, startTime, null, null, arguments,
null, externalExecutionId, parentExecutionId);
final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
.addValue("startTime", startTime, Types.TIMESTAMP)
.addValue("exitCode", null, Types.INTEGER)
.addValue("taskName", taskName, Types.VARCHAR)
.addValue("lastUpdated", new Date(), Types.TIMESTAMP)
.addValue("startTime", startTime, Types.TIMESTAMP).addValue("exitCode", null, Types.INTEGER)
.addValue("taskName", taskName, Types.VARCHAR).addValue("lastUpdated", new Date(), Types.TIMESTAMP)
.addValue("parentExecutionId", parentExecutionId, Types.BIGINT)
.addValue("taskExecutionId", executionId, Types.BIGINT);
@@ -257,8 +249,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
else {
updateString += START_TASK_EXECUTION_EXTERNAL_ID_SUFFIX;
queryParameters.addValue("externalExecutionId", externalExecutionId,
Types.VARCHAR);
queryParameters.addValue("externalExecutionId", externalExecutionId, Types.VARCHAR);
}
this.jdbcTemplate.update(getQuery(updateString), queryParameters);
@@ -267,22 +258,20 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
@Override
public void completeTaskExecution(long taskExecutionId, Integer exitCode,
Date endTime, String exitMessage, String errorMessage) {
final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
.addValue("taskExecutionId", taskExecutionId, Types.BIGINT);
public void completeTaskExecution(long taskExecutionId, Integer exitCode, Date endTime, String exitMessage,
String errorMessage) {
final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("taskExecutionId",
taskExecutionId, Types.BIGINT);
// Check if given TaskExecution's Id already exists, if none is found
// it is invalid and an exception should be thrown.
if (this.jdbcTemplate.queryForObject(getQuery(CHECK_TASK_EXECUTION_EXISTS),
queryParameters, Integer.class) != 1) {
throw new IllegalStateException(
"Invalid TaskExecution, ID " + taskExecutionId + " not found.");
if (this.jdbcTemplate.queryForObject(getQuery(CHECK_TASK_EXECUTION_EXISTS), queryParameters,
Integer.class) != 1) {
throw new IllegalStateException("Invalid TaskExecution, ID " + taskExecutionId + " not found.");
}
final MapSqlParameterSource parameters = new MapSqlParameterSource()
.addValue("endTime", endTime, Types.TIMESTAMP)
.addValue("exitCode", exitCode, Types.INTEGER)
.addValue("endTime", endTime, Types.TIMESTAMP).addValue("exitCode", exitCode, Types.INTEGER)
.addValue("exitMessage", exitMessage, Types.VARCHAR)
.addValue("errorMessage", errorMessage, Types.VARCHAR)
.addValue("lastUpdated", new Date(), Types.TIMESTAMP)
@@ -292,20 +281,18 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
@Override
public void completeTaskExecution(long taskExecutionId, Integer exitCode,
Date endTime, String exitMessage) {
public void completeTaskExecution(long taskExecutionId, Integer exitCode, Date endTime, String exitMessage) {
completeTaskExecution(taskExecutionId, exitCode, endTime, exitMessage, null);
}
@Override
public TaskExecution getTaskExecution(long executionId) {
final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
.addValue("taskExecutionId", executionId, Types.BIGINT);
final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("taskExecutionId",
executionId, Types.BIGINT);
try {
TaskExecution taskExecution = this.jdbcTemplate.queryForObject(
getQuery(GET_EXECUTION_BY_ID), queryParameters,
new TaskExecutionRowMapper());
TaskExecution taskExecution = this.jdbcTemplate.queryForObject(getQuery(GET_EXECUTION_BY_ID),
queryParameters, new TaskExecutionRowMapper());
taskExecution.setArguments(getTaskArguments(executionId));
return taskExecution;
}
@@ -317,12 +304,12 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
@Override
public long getTaskExecutionCountByTaskName(String taskName) {
final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
.addValue("taskName", taskName, Types.VARCHAR);
final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("taskName", taskName,
Types.VARCHAR);
try {
return this.jdbcTemplate.queryForObject(
getQuery(TASK_EXECUTION_COUNT_BY_NAME), queryParameters, Long.class);
return this.jdbcTemplate.queryForObject(getQuery(TASK_EXECUTION_COUNT_BY_NAME), queryParameters,
Long.class);
}
catch (EmptyResultDataAccessException e) {
return 0;
@@ -331,12 +318,11 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
@Override
public long getRunningTaskExecutionCountByTaskName(String taskName) {
final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
.addValue("taskName", taskName, Types.VARCHAR);
final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("taskName", taskName,
Types.VARCHAR);
try {
return this.jdbcTemplate.queryForObject(
getQuery(RUNNING_TASK_EXECUTION_COUNT_BY_NAME), queryParameters,
return this.jdbcTemplate.queryForObject(getQuery(RUNNING_TASK_EXECUTION_COUNT_BY_NAME), queryParameters,
Long.class);
}
catch (EmptyResultDataAccessException e) {
@@ -349,8 +335,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
try {
final MapSqlParameterSource queryParameters = new MapSqlParameterSource();
return this.jdbcTemplate.queryForObject(
getQuery(RUNNING_TASK_EXECUTION_COUNT), queryParameters, Long.class);
return this.jdbcTemplate.queryForObject(getQuery(RUNNING_TASK_EXECUTION_COUNT), queryParameters,
Long.class);
}
catch (EmptyResultDataAccessException e) {
return 0;
@@ -369,15 +355,14 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
}
Assert.isTrue(taskNamesAsList.size() == taskNames.length, String.format(
"Task names must not contain any empty elements but %s of %s were empty or null.",
taskNames.length - taskNamesAsList.size(), taskNames.length));
Assert.isTrue(taskNamesAsList.size() == taskNames.length,
String.format("Task names must not contain any empty elements but %s of %s were empty or null.",
taskNames.length - taskNamesAsList.size(), taskNames.length));
try {
final Map<String, List<String>> paramMap = Collections
.singletonMap("taskNames", taskNamesAsList);
return this.jdbcTemplate.query(getQuery(LAST_TASK_EXECUTIONS_BY_TASK_NAMES),
paramMap, new TaskExecutionRowMapper());
final Map<String, List<String>> paramMap = Collections.singletonMap("taskNames", taskNamesAsList);
return this.jdbcTemplate.query(getQuery(LAST_TASK_EXECUTIONS_BY_TASK_NAMES), paramMap,
new TaskExecutionRowMapper());
}
catch (EmptyResultDataAccessException e) {
return Collections.emptyList();
@@ -387,8 +372,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
@Override
public TaskExecution getLatestTaskExecutionForTaskName(String taskName) {
Assert.hasText(taskName, "The task name must not be empty.");
final List<TaskExecution> taskExecutions = this
.getLatestTaskExecutionsByTaskNames(taskName);
final List<TaskExecution> taskExecutions = this.getLatestTaskExecutionsByTaskNames(taskName);
if (taskExecutions.isEmpty()) {
return null;
}
@@ -397,8 +381,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
else {
throw new IllegalStateException(
"Only expected a single TaskExecution but received "
+ taskExecutions.size());
"Only expected a single TaskExecution but received " + taskExecutions.size());
}
}
@@ -406,8 +389,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
public long getTaskExecutionCount() {
try {
return this.jdbcTemplate.queryForObject(getQuery(TASK_EXECUTION_COUNT),
new MapSqlParameterSource(), Long.class);
return this.jdbcTemplate.queryForObject(getQuery(TASK_EXECUTION_COUNT), new MapSqlParameterSource(),
Long.class);
}
catch (EmptyResultDataAccessException e) {
return 0;
@@ -415,32 +398,26 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
@Override
public Page<TaskExecution> findRunningTaskExecutions(String taskName,
Pageable pageable) {
return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE,
RUNNING_TASK_WHERE_CLAUSE,
new MapSqlParameterSource("taskName", taskName),
getRunningTaskExecutionCountByTaskName(taskName));
public Page<TaskExecution> findRunningTaskExecutions(String taskName, Pageable pageable) {
return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, RUNNING_TASK_WHERE_CLAUSE,
new MapSqlParameterSource("taskName", taskName), getRunningTaskExecutionCountByTaskName(taskName));
}
@Override
public Page<TaskExecution> findTaskExecutionsByName(String taskName,
Pageable pageable) {
return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE,
TASK_NAME_WHERE_CLAUSE, new MapSqlParameterSource("taskName", taskName),
getTaskExecutionCountByTaskName(taskName));
public Page<TaskExecution> findTaskExecutionsByName(String taskName, Pageable pageable) {
return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, TASK_NAME_WHERE_CLAUSE,
new MapSqlParameterSource("taskName", taskName), getTaskExecutionCountByTaskName(taskName));
}
@Override
public List<String> getTaskNames() {
return this.jdbcTemplate.queryForList(getQuery(FIND_TASK_NAMES),
new MapSqlParameterSource(), String.class);
return this.jdbcTemplate.queryForList(getQuery(FIND_TASK_NAMES), new MapSqlParameterSource(), String.class);
}
@Override
public Page<TaskExecution> findAll(Pageable pageable) {
return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, null,
new MapSqlParameterSource(), getTaskExecutionCount());
return queryForPageableResults(pageable, SELECT_CLAUSE, FROM_CLAUSE, null, new MapSqlParameterSource(),
getTaskExecutionCount());
}
public void setTaskIncrementer(DataFieldMaxValueIncrementer taskIncrementer) {
@@ -453,12 +430,11 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
@Override
public Long getTaskExecutionIdByJobExecutionId(long jobExecutionId) {
final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
.addValue("jobExecutionId", jobExecutionId, Types.BIGINT);
final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("jobExecutionId",
jobExecutionId, Types.BIGINT);
try {
return this.jdbcTemplate.queryForObject(
getQuery(FIND_TASK_EXECUTION_BY_JOB_EXECUTION_ID), queryParameters,
return this.jdbcTemplate.queryForObject(getQuery(FIND_TASK_EXECUTION_BY_JOB_EXECUTION_ID), queryParameters,
Long.class);
}
catch (EmptyResultDataAccessException e) {
@@ -468,21 +444,18 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
@Override
public Set<Long> getJobExecutionIdsByTaskExecutionId(long taskExecutionId) {
final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
.addValue("taskExecutionId", taskExecutionId, Types.BIGINT);
final MapSqlParameterSource queryParameters = new MapSqlParameterSource().addValue("taskExecutionId",
taskExecutionId, Types.BIGINT);
try {
return this.jdbcTemplate.query(
getQuery(FIND_JOB_EXECUTION_BY_TASK_EXECUTION_ID), queryParameters,
return this.jdbcTemplate.query(getQuery(FIND_JOB_EXECUTION_BY_TASK_EXECUTION_ID), queryParameters,
new ResultSetExtractor<Set<Long>>() {
@Override
public Set<Long> extractData(ResultSet resultSet)
throws SQLException, DataAccessException {
public Set<Long> extractData(ResultSet resultSet) throws SQLException, DataAccessException {
Set<Long> jobExecutionIds = new TreeSet<>();
while (resultSet.next()) {
jobExecutionIds
.add(resultSet.getLong("JOB_EXECUTION_ID"));
jobExecutionIds.add(resultSet.getLong("JOB_EXECUTION_ID"));
}
return jobExecutionIds;
@@ -495,23 +468,18 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
@Override
public void updateExternalExecutionId(long taskExecutionId,
String externalExecutionId) {
public void updateExternalExecutionId(long taskExecutionId, String externalExecutionId) {
final MapSqlParameterSource queryParameters = new MapSqlParameterSource()
.addValue("externalExecutionId", externalExecutionId, Types.VARCHAR)
.addValue("taskExecutionId", taskExecutionId, Types.BIGINT);
if (this.jdbcTemplate.update(
getQuery(UPDATE_TASK_EXECUTION_EXTERNAL_EXECUTION_ID),
queryParameters) != 1) {
throw new IllegalStateException(
"Invalid TaskExecution, ID " + taskExecutionId + " not found.");
if (this.jdbcTemplate.update(getQuery(UPDATE_TASK_EXECUTION_EXTERNAL_EXECUTION_ID), queryParameters) != 1) {
throw new IllegalStateException("Invalid TaskExecution, ID " + taskExecutionId + " not found.");
}
}
private Page<TaskExecution> queryForPageableResults(Pageable pageable,
String selectClause, String fromClause, String whereClause,
MapSqlParameterSource queryParameters, long totalCount) {
private Page<TaskExecution> queryForPageableResults(Pageable pageable, String selectClause, String fromClause,
String whereClause, MapSqlParameterSource queryParameters, long totalCount) {
SqlPagingQueryProviderFactoryBean factoryBean = new SqlPagingQueryProviderFactoryBean();
factoryBean.setSelectClause(selectClause);
factoryBean.setFromClause(fromClause);
@@ -551,8 +519,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
throw new IllegalStateException(e);
}
String query = pagingQueryProvider.getPageQuery(pageable);
List<TaskExecution> resultList = this.jdbcTemplate.query(getQuery(query),
queryParameters, new TaskExecutionRowMapper());
List<TaskExecution> resultList = this.jdbcTemplate.query(getQuery(query), queryParameters,
new TaskExecutionRowMapper());
return new PageImpl<>(resultList, pageable, totalCount);
}
@@ -572,8 +540,8 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
/**
* Convenience method that inserts an individual records into the TASK_EXECUTION_PARAMS
* table.
* Convenience method that inserts an individual records into the
* TASK_EXECUTION_PARAMS table.
* @param taskExecutionId id of a task execution
* @param taskParam task parameters
*/
@@ -613,11 +581,10 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
if (rs.wasNull()) {
parentExecutionId = null;
}
return new TaskExecution(id, getNullableExitCode(rs),
rs.getString("TASK_NAME"), rs.getTimestamp("START_TIME"),
rs.getTimestamp("END_TIME"), rs.getString("EXIT_MESSAGE"),
getTaskArguments(id), rs.getString("ERROR_MESSAGE"),
rs.getString("EXTERNAL_EXECUTION_ID"), parentExecutionId);
return new TaskExecution(id, getNullableExitCode(rs), rs.getString("TASK_NAME"),
rs.getTimestamp("START_TIME"), rs.getTimestamp("END_TIME"), rs.getString("EXIT_MESSAGE"),
getTaskArguments(id), rs.getString("ERROR_MESSAGE"), rs.getString("EXTERNAL_EXECUTION_ID"),
parentExecutionId);
}
private Integer getNullableExitCode(ResultSet rs) throws SQLException {

View File

@@ -58,34 +58,30 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
}
@Override
public TaskExecution createTaskExecution(String taskName, Date startTime,
List<String> arguments, String externalExecutionId) {
return createTaskExecution(taskName, startTime, arguments, externalExecutionId,
null);
public TaskExecution createTaskExecution(String taskName, Date startTime, List<String> arguments,
String externalExecutionId) {
return createTaskExecution(taskName, startTime, arguments, externalExecutionId, null);
}
@Override
public TaskExecution createTaskExecution(String taskName, Date startTime,
List<String> arguments, String externalExecutionId, Long parentExecutionId) {
public TaskExecution createTaskExecution(String taskName, Date startTime, List<String> arguments,
String externalExecutionId, Long parentExecutionId) {
long taskExecutionId = getNextExecutionId();
TaskExecution taskExecution = new TaskExecution(taskExecutionId, null, taskName,
startTime, null, null, arguments, null, externalExecutionId,
parentExecutionId);
TaskExecution taskExecution = new TaskExecution(taskExecutionId, null, taskName, startTime, null, null,
arguments, null, externalExecutionId, parentExecutionId);
this.taskExecutions.put(taskExecutionId, taskExecution);
return taskExecution;
}
@Override
public TaskExecution startTaskExecution(long executionId, String taskName,
Date startTime, List<String> arguments, String externalExecutionid) {
return startTaskExecution(executionId, taskName, startTime, arguments,
externalExecutionid, null);
public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments,
String externalExecutionid) {
return startTaskExecution(executionId, taskName, startTime, arguments, externalExecutionid, null);
}
@Override
public TaskExecution startTaskExecution(long executionId, String taskName,
Date startTime, List<String> arguments, String externalExecutionid,
Long parentExecutionId) {
public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments,
String externalExecutionid, Long parentExecutionId) {
TaskExecution taskExecution = this.taskExecutions.get(executionId);
taskExecution.setTaskName(taskName);
taskExecution.setStartTime(startTime);
@@ -98,11 +94,10 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
}
@Override
public void completeTaskExecution(long executionId, Integer exitCode, Date endTime,
String exitMessage, String errorMessage) {
public void completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage,
String errorMessage) {
if (!this.taskExecutions.containsKey(executionId)) {
throw new IllegalStateException(
"Invalid TaskExecution, ID " + executionId + " not found.");
throw new IllegalStateException("Invalid TaskExecution, ID " + executionId + " not found.");
}
TaskExecution taskExecution = this.taskExecutions.get(executionId);
@@ -113,8 +108,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
}
@Override
public void completeTaskExecution(long executionId, Integer exitCode, Date endTime,
String exitMessage) {
public void completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage) {
completeTaskExecution(executionId, exitCode, endTime, exitMessage, null);
}
@@ -138,8 +132,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
public long getRunningTaskExecutionCountByTaskName(String taskName) {
int count = 0;
for (Map.Entry<Long, TaskExecution> entry : this.taskExecutions.entrySet()) {
if (entry.getValue().getTaskName().equals(taskName)
&& entry.getValue().getEndTime() == null) {
if (entry.getValue().getTaskName().equals(taskName) && entry.getValue().getEndTime() == null) {
count++;
}
}
@@ -163,30 +156,25 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
}
@Override
public Page<TaskExecution> findRunningTaskExecutions(String taskName,
Pageable pageable) {
public Page<TaskExecution> findRunningTaskExecutions(String taskName, Pageable pageable) {
Set<TaskExecution> result = getTaskExecutionTreeSet();
for (Map.Entry<Long, TaskExecution> entry : this.taskExecutions.entrySet()) {
if (entry.getValue().getTaskName().equals(taskName)
&& entry.getValue().getEndTime() == null) {
if (entry.getValue().getTaskName().equals(taskName) && entry.getValue().getEndTime() == null) {
result.add(entry.getValue());
}
}
return getPageFromList(new ArrayList<>(result), pageable,
getRunningTaskExecutionCountByTaskName(taskName));
return getPageFromList(new ArrayList<>(result), pageable, getRunningTaskExecutionCountByTaskName(taskName));
}
@Override
public Page<TaskExecution> findTaskExecutionsByName(String taskName,
Pageable pageable) {
public Page<TaskExecution> findTaskExecutionsByName(String taskName, Pageable pageable) {
Set<TaskExecution> filteredSet = getTaskExecutionTreeSet();
for (Map.Entry<Long, TaskExecution> entry : this.taskExecutions.entrySet()) {
if (entry.getValue().getTaskName().equals(taskName)) {
filteredSet.add(entry.getValue());
}
}
return getPageFromList(new ArrayList<>(filteredSet), pageable,
getTaskExecutionCountByTaskName(taskName));
return getPageFromList(new ArrayList<>(filteredSet), pageable, getTaskExecutionCountByTaskName(taskName));
}
@Override
@@ -220,8 +208,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
found:
for (Map.Entry<Long, Set<Long>> association : this.batchJobAssociations
.entrySet()) {
for (Map.Entry<Long, Set<Long>> association : this.batchJobAssociations.entrySet()) {
for (Long curJobExecutionId : association.getValue()) {
if (curJobExecutionId.equals(jobExecutionId)) {
taskId = association.getKey();
@@ -236,8 +223,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
@Override
public Set<Long> getJobExecutionIdsByTaskExecutionId(long taskExecutionId) {
if (this.batchJobAssociations.containsKey(taskExecutionId)) {
return Collections
.unmodifiableSet(this.batchJobAssociations.get(taskExecutionId));
return Collections.unmodifiableSet(this.batchJobAssociations.get(taskExecutionId));
}
else {
return new TreeSet<>();
@@ -245,11 +231,9 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
}
@Override
public void updateExternalExecutionId(long taskExecutionId,
String externalExecutionId) {
public void updateExternalExecutionId(long taskExecutionId, String externalExecutionId) {
TaskExecution taskExecution = this.taskExecutions.get(taskExecutionId);
Assert.notNull(taskExecution,
"Invalid TaskExecution, ID " + taskExecutionId + " not found.");
Assert.notNull(taskExecution, "Invalid TaskExecution, ID " + taskExecutionId + " not found.");
taskExecution.setExternalExecutionId(externalExecutionId);
}
@@ -263,22 +247,17 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
public int compare(TaskExecution e1, TaskExecution e2) {
int result = e1.getStartTime().compareTo(e2.getStartTime());
if (result == 0) {
result = Long.valueOf(e1.getExecutionId())
.compareTo(e2.getExecutionId());
result = Long.valueOf(e1.getExecutionId()).compareTo(e2.getExecutionId());
}
return result;
}
});
}
private Page getPageFromList(List<TaskExecution> executionList, Pageable pageable,
long maxSize) {
long toIndex = (pageable.getOffset() + pageable.getPageSize() > executionList
.size()) ? executionList.size()
: pageable.getOffset() + pageable.getPageSize();
return new PageImpl<>(
executionList.subList((int) pageable.getOffset(), (int) toIndex),
pageable, maxSize);
private Page getPageFromList(List<TaskExecution> executionList, Pageable pageable, long maxSize) {
long toIndex = (pageable.getOffset() + pageable.getPageSize() > executionList.size()) ? executionList.size()
: pageable.getOffset() + pageable.getPageSize();
return new PageImpl<>(executionList.subList((int) pageable.getOffset(), (int) toIndex), pageable, maxSize);
}
@Override
@@ -294,34 +273,29 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
}
}
Assert.isTrue(taskNamesAsList.size() == taskNames.length, String.format(
"Task names must not contain any empty elements but %s of %s were empty or null.",
taskNames.length - taskNamesAsList.size(), taskNames.length));
Assert.isTrue(taskNamesAsList.size() == taskNames.length,
String.format("Task names must not contain any empty elements but %s of %s were empty or null.",
taskNames.length - taskNamesAsList.size(), taskNames.length));
final Map<String, TaskExecution> tempTaskExecutions = new HashMap<>();
for (Map.Entry<Long, TaskExecution> taskExecutionMapEntry : this.taskExecutions
.entrySet()) {
if (!taskNamesAsList
.contains(taskExecutionMapEntry.getValue().getTaskName())) {
for (Map.Entry<Long, TaskExecution> taskExecutionMapEntry : this.taskExecutions.entrySet()) {
if (!taskNamesAsList.contains(taskExecutionMapEntry.getValue().getTaskName())) {
continue;
}
final TaskExecution tempTaskExecution = tempTaskExecutions
.get(taskExecutionMapEntry.getValue().getTaskName());
if (tempTaskExecution == null
|| tempTaskExecution.getStartTime()
.before(taskExecutionMapEntry.getValue().getStartTime())
|| (tempTaskExecution.getStartTime()
.equals(taskExecutionMapEntry.getValue().getStartTime())
&& tempTaskExecution.getExecutionId() < taskExecutionMapEntry
.getValue().getExecutionId())) {
|| tempTaskExecution.getStartTime().before(taskExecutionMapEntry.getValue().getStartTime())
|| (tempTaskExecution.getStartTime().equals(taskExecutionMapEntry.getValue().getStartTime())
&& tempTaskExecution.getExecutionId() < taskExecutionMapEntry.getValue()
.getExecutionId())) {
tempTaskExecutions.put(taskExecutionMapEntry.getValue().getTaskName(),
taskExecutionMapEntry.getValue());
}
}
final List<TaskExecution> latestTaskExecutions = new ArrayList<>(
tempTaskExecutions.values());
final List<TaskExecution> latestTaskExecutions = new ArrayList<>(tempTaskExecutions.values());
Collections.sort(latestTaskExecutions, new TaskExecutionComparator());
return latestTaskExecutions;
}
@@ -329,8 +303,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
@Override
public TaskExecution getLatestTaskExecutionForTaskName(String taskName) {
Assert.hasText(taskName, "The task name must not be empty.");
final List<TaskExecution> taskExecutions = this
.getLatestTaskExecutionsByTaskNames(taskName);
final List<TaskExecution> taskExecutions = this.getLatestTaskExecutionsByTaskNames(taskName);
if (taskExecutions.isEmpty()) {
return null;
}
@@ -339,25 +312,19 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
}
else {
throw new IllegalStateException(
"Only expected a single TaskExecution but received "
+ taskExecutions.size());
"Only expected a single TaskExecution but received " + taskExecutions.size());
}
}
private static class TaskExecutionComparator
implements Comparator<TaskExecution>, Serializable {
private static class TaskExecutionComparator implements Comparator<TaskExecution>, 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());
}
}

View File

@@ -42,8 +42,8 @@ public interface TaskExecutionDao {
* @param externalExecutionId id assigned to the task by the platform
* @return A fully qualified {@link TaskExecution} instance.
*/
TaskExecution createTaskExecution(String taskName, Date startTime,
List<String> arguments, String externalExecutionId);
TaskExecution createTaskExecution(String taskName, Date startTime, List<String> arguments,
String externalExecutionId);
/**
* Save a new {@link TaskExecution}.
@@ -55,8 +55,8 @@ public interface TaskExecutionDao {
* @return A fully qualified {@link TaskExecution} instance.
* @since 1.2.0
*/
TaskExecution createTaskExecution(String taskName, Date startTime,
List<String> arguments, String externalExecutionId, Long parentExecutionId);
TaskExecution createTaskExecution(String taskName, Date startTime, List<String> arguments,
String externalExecutionId, Long parentExecutionId);
/**
* Update and existing {@link TaskExecution} to mark it as started.
@@ -69,8 +69,8 @@ public interface TaskExecutionDao {
* start.
* @since 1.1.0
*/
TaskExecution startTaskExecution(long executionId, String taskName, Date startTime,
List<String> arguments, String externalExecutionId);
TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments,
String externalExecutionId);
/**
* Update and existing {@link TaskExecution} to mark it as started.
@@ -84,8 +84,8 @@ public interface TaskExecutionDao {
* start.
* @since 1.2.0
*/
TaskExecution startTaskExecution(long executionId, String taskName, Date startTime,
List<String> arguments, String externalExecutionId, Long parentExecutionId);
TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments,
String externalExecutionId, Long parentExecutionId);
/**
* Update and existing {@link TaskExecution} to mark it as completed.
@@ -96,8 +96,8 @@ public interface TaskExecutionDao {
* @param errorMessage error information available upon failure of a task.
* @since 1.1.0
*/
void completeTaskExecution(long executionId, Integer exitCode, Date endTime,
String exitMessage, String errorMessage);
void completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage,
String errorMessage);
/**
* Update and existing {@link TaskExecution}.
@@ -106,8 +106,7 @@ public interface TaskExecutionDao {
* @param endTime the time the task completed.
* @param exitMessage the message assigned to the task upon completion.
*/
void completeTaskExecution(long executionId, Integer exitCode, Date endTime,
String exitMessage);
void completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage);
/**
* Retrieves a task execution from the task repository.

View File

@@ -144,13 +144,11 @@ public abstract class AbstractSqlPagingQueryProvider implements PagingQueryProvi
sql.append(" WHERE ").append(this.whereClause);
}
List<String> namedParameters = new ArrayList<>();
this.parameterCount = JdbcParameterUtils
.countParameterPlaceholders(sql.toString(), namedParameters);
this.parameterCount = JdbcParameterUtils.countParameterPlaceholders(sql.toString(), namedParameters);
if (namedParameters.size() > 0) {
if (this.parameterCount != namedParameters.size()) {
throw new InvalidDataAccessApiUsageException(
"You can't use both named parameters and classic \"?\" placeholders: "
+ sql);
"You can't use both named parameters and classic \"?\" placeholders: " + sql);
}
this.usingNamedParameters = true;
}
@@ -159,8 +157,7 @@ public abstract class AbstractSqlPagingQueryProvider implements PagingQueryProvi
private String removeKeyWord(String keyWord, String clause) {
String temp = clause.trim();
String keyWordString = keyWord + " ";
if (temp.toLowerCase().startsWith(keyWordString)
&& temp.length() > keyWordString.length()) {
if (temp.toLowerCase().startsWith(keyWordString) && temp.length() > keyWordString.length()) {
return temp.substring(keyWordString.length());
}
else {

View File

@@ -32,17 +32,15 @@ public class Db2PagingQueryProvider extends AbstractSqlPagingQueryProvider {
public String getPageQuery(Pageable pageable) {
long offset = pageable.getOffset() + 1;
return generateRowNumSqlQueryWithNesting(getSelectClause(), false,
"TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " + (offset + pageable.getPageSize()));
"TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " + (offset + pageable.getPageSize()));
}
private String generateRowNumSqlQueryWithNesting(String selectClause,
boolean remainingPageQuery, String rowNumClause) {
private String generateRowNumSqlQueryWithNesting(String selectClause, boolean remainingPageQuery,
String rowNumClause) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ")
.append(selectClause).append(", ")
sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ").append(selectClause).append(", ")
.append("ROW_NUMBER() OVER() as TMP_ROW_NUM");
sql.append(" FROM (SELECT ").append(selectClause).append(" FROM ")
.append(this.getFromClause());
sql.append(" FROM (SELECT ").append(selectClause).append(" FROM ").append(this.getFromClause());
SqlPagingQueryUtils.buildWhereClause(this, remainingPageQuery, sql);
sql.append(" ORDER BY ").append(SqlPagingQueryUtils.buildSortClause(this));
sql.append(")) WHERE ").append(rowNumClause);

View File

@@ -29,10 +29,8 @@ public class H2PagingQueryProvider extends AbstractSqlPagingQueryProvider {
@Override
public String getPageQuery(Pageable pageable) {
String limitClause = new StringBuilder().append("OFFSET ")
.append(pageable.getOffset()).append(" ROWS FETCH NEXT ")
.append(pageable.getPageSize()).append(" ROWS ONLY")
.toString();
String limitClause = new StringBuilder().append("OFFSET ").append(pageable.getOffset())
.append(" ROWS FETCH NEXT ").append(pageable.getPageSize()).append(" ROWS ONLY").toString();
return SqlPagingQueryUtils.generateLimitJumpToQuery(this, limitClause);
}

View File

@@ -29,9 +29,8 @@ public class HsqlPagingQueryProvider extends AbstractSqlPagingQueryProvider {
@Override
public String getPageQuery(Pageable pageable) {
String topClause = new StringBuilder().append("LIMIT ")
.append(pageable.getOffset()).append(" ").append(pageable.getPageSize())
.toString();
String topClause = new StringBuilder().append("LIMIT ").append(pageable.getOffset()).append(" ")
.append(pageable.getPageSize()).toString();
return SqlPagingQueryUtils.generateTopJumpToQuery(this, topClause);
}

View File

@@ -28,9 +28,8 @@ public class MySqlPagingQueryProvider extends AbstractSqlPagingQueryProvider {
@Override
public String getPageQuery(Pageable pageable) {
String topClause = new StringBuilder().append("LIMIT ")
.append(pageable.getOffset()).append(", ").append(pageable.getPageSize())
.toString();
String topClause = new StringBuilder().append("LIMIT ").append(pageable.getOffset()).append(", ")
.append(pageable.getPageSize()).toString();
return SqlPagingQueryUtils.generateLimitJumpToQuery(this, topClause);
}

View File

@@ -31,17 +31,15 @@ public class OraclePagingQueryProvider extends AbstractSqlPagingQueryProvider {
public String getPageQuery(Pageable pageable) {
long offset = pageable.getOffset() + 1;
return generateRowNumSqlQueryWithNesting(getSelectClause(), false,
"TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < "
+ (offset + pageable.getPageSize()));
"TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " + (offset + pageable.getPageSize()));
}
private String generateRowNumSqlQueryWithNesting(String selectClause,
boolean remainingPageQuery, String rowNumClause) {
private String generateRowNumSqlQueryWithNesting(String selectClause, boolean remainingPageQuery,
String rowNumClause) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ")
.append(selectClause).append(", ").append("ROWNUM as TMP_ROW_NUM");
sql.append(" FROM (SELECT ").append(selectClause).append(" FROM ")
.append(this.getFromClause());
sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ").append(selectClause).append(", ")
.append("ROWNUM as TMP_ROW_NUM");
sql.append(" FROM (SELECT ").append(selectClause).append(" FROM ").append(this.getFromClause());
SqlPagingQueryUtils.buildWhereClause(this, remainingPageQuery, sql);
sql.append(" ORDER BY ").append(SqlPagingQueryUtils.buildSortClause(this));
sql.append(")) WHERE ").append(rowNumClause);

View File

@@ -29,8 +29,7 @@ public class PostgresPagingQueryProvider extends AbstractSqlPagingQueryProvider
@Override
public String getPageQuery(Pageable pageable) {
String limitClause = new StringBuilder().append("LIMIT ")
.append(pageable.getPageSize()).append(" OFFSET ")
String limitClause = new StringBuilder().append("LIMIT ").append(pageable.getPageSize()).append(" OFFSET ")
.append(pageable.getOffset()).toString();
return SqlPagingQueryUtils.generateLimitJumpToQuery(this, limitClause);
}

View File

@@ -47,8 +47,7 @@ import static org.springframework.cloud.task.repository.support.DatabaseType.SQL
*
* @author Glenn Renfro
*/
public class SqlPagingQueryProviderFactoryBean
implements FactoryBean<PagingQueryProvider> {
public class SqlPagingQueryProviderFactoryBean implements FactoryBean<PagingQueryProvider> {
private DataSource dataSource;
@@ -134,20 +133,16 @@ public class SqlPagingQueryProviderFactoryBean
DatabaseType type;
try {
type = this.databaseType != null
? DatabaseType.valueOf(this.databaseType.toUpperCase())
type = this.databaseType != null ? DatabaseType.valueOf(this.databaseType.toUpperCase())
: DatabaseType.fromMetaData(this.dataSource);
}
catch (MetaDataAccessException e) {
throw new IllegalArgumentException(
"Could not inspect meta data for database type. You have to supply it explicitly.",
e);
"Could not inspect meta data for database type. You have to supply it explicitly.", e);
}
AbstractSqlPagingQueryProvider provider = this.providers.get(type);
Assert.state(provider != null,
"Should not happen: missing PagingQueryProvider for DatabaseType="
+ type);
Assert.state(provider != null, "Should not happen: missing PagingQueryProvider for DatabaseType=" + type);
provider.setFromClause(this.fromClause);
provider.setWhereClause(this.whereClause);

View File

@@ -37,13 +37,11 @@ public final class SqlPagingQueryUtils {
* @param limitClause the implementation specific top clause to be used
* @return the generated query
*/
public static String generateLimitJumpToQuery(AbstractSqlPagingQueryProvider provider,
String limitClause) {
public static String generateLimitJumpToQuery(AbstractSqlPagingQueryProvider provider, String limitClause) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT ").append(provider.getSelectClause());
sql.append(" FROM ").append(provider.getFromClause());
sql.append(provider.getWhereClause() == null ? ""
: " WHERE " + provider.getWhereClause());
sql.append(provider.getWhereClause() == null ? "" : " WHERE " + provider.getWhereClause());
sql.append(" ORDER BY ").append(buildSortClause(provider));
sql.append(" ").append(limitClause);
@@ -57,14 +55,11 @@ public final class SqlPagingQueryUtils {
* @param topClause the implementation specific top clause to be used
* @return the generated query
*/
public static String generateTopJumpToQuery(AbstractSqlPagingQueryProvider provider,
String topClause) {
public static String generateTopJumpToQuery(AbstractSqlPagingQueryProvider provider, String topClause) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT ").append(topClause).append(" ")
.append(provider.getSelectClause());
sql.append("SELECT ").append(topClause).append(" ").append(provider.getSelectClause());
sql.append(" FROM ").append(provider.getFromClause());
sql.append(provider.getWhereClause() == null ? ""
: " WHERE " + provider.getWhereClause());
sql.append(provider.getWhereClause() == null ? "" : " WHERE " + provider.getWhereClause());
sql.append(" ORDER BY ").append(buildSortClause(provider));
return sql.toString();
@@ -76,8 +71,8 @@ public final class SqlPagingQueryUtils {
* @param remainingPageQuery if true assumes more will be appended to where clause
* @param sql the sql statement to be appended.
*/
public static void buildWhereClause(AbstractSqlPagingQueryProvider provider,
boolean remainingPageQuery, StringBuilder sql) {
public static void buildWhereClause(AbstractSqlPagingQueryProvider provider, boolean remainingPageQuery,
StringBuilder sql) {
if (remainingPageQuery) {
sql.append(" WHERE ");
if (provider.getWhereClause() != null) {
@@ -87,8 +82,7 @@ public final class SqlPagingQueryUtils {
}
}
else {
sql.append(provider.getWhereClause() == null ? ""
: " WHERE " + provider.getWhereClause());
sql.append(provider.getWhereClause() == null ? "" : " WHERE " + provider.getWhereClause());
}
}

View File

@@ -31,16 +31,14 @@ public class SqlServerPagingQueryProvider extends AbstractSqlPagingQueryProvider
public String getPageQuery(Pageable pageable) {
long offset = pageable.getOffset() + 1;
return generateRowNumSqlQueryWithNesting(getSelectClause(), false,
"TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < "
+ (offset + pageable.getPageSize()));
"TMP_ROW_NUM >= " + offset + " AND TMP_ROW_NUM < " + (offset + pageable.getPageSize()));
}
private String generateRowNumSqlQueryWithNesting(String selectClause,
boolean remainingPageQuery, String rowNumClause) {
private String generateRowNumSqlQueryWithNesting(String selectClause, boolean remainingPageQuery,
String rowNumClause) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ")
.append(selectClause).append(", ").append("ROW_NUMBER() OVER (ORDER BY ")
.append(SqlPagingQueryUtils.buildSortClause(this))
sql.append("SELECT ").append(selectClause).append(" FROM (SELECT ").append(selectClause).append(", ")
.append("ROW_NUMBER() OVER (ORDER BY ").append(SqlPagingQueryUtils.buildSortClause(this))
.append(") AS TMP_ROW_NUM ").append(" FROM ").append(getFromClause());
SqlPagingQueryUtils.buildWhereClause(this, remainingPageQuery, sql);
sql.append(") TASK_EXECUTION_PAGE ");

View File

@@ -109,24 +109,22 @@ public enum DatabaseType {
* @return DatabaseType The database type associated with the datasource.
* @throws MetaDataAccessException thrown if failure occurs on metadata lookup.
*/
public static DatabaseType fromMetaData(DataSource dataSource)
throws SQLException, MetaDataAccessException {
String databaseProductName = JdbcUtils
.extractDatabaseMetaData(dataSource, new DatabaseMetaDataCallback() {
public static DatabaseType fromMetaData(DataSource dataSource) throws SQLException, MetaDataAccessException {
String databaseProductName = JdbcUtils.extractDatabaseMetaData(dataSource, new DatabaseMetaDataCallback() {
@Override
public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
return dbmd.getDatabaseProductName();
}
}).toString();
if (StringUtils.hasText(databaseProductName)
&& !databaseProductName.equals("DB2/Linux")
@Override
public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
return dbmd.getDatabaseProductName();
}
}).toString();
if (StringUtils.hasText(databaseProductName) && !databaseProductName.equals("DB2/Linux")
&& databaseProductName.startsWith("DB2")) {
String databaseProductVersion = JdbcUtils
.extractDatabaseMetaData(dataSource, new DatabaseMetaDataCallback() {
@Override
public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
public Object processMetaData(DatabaseMetaData dbmd)
throws SQLException, MetaDataAccessException {
return dbmd.getDatabaseProductVersion();
}
}).toString();
@@ -139,8 +137,7 @@ public enum DatabaseType {
}
else if (databaseProductName.indexOf("AS") != -1
&& (databaseProductVersion.startsWith("QSQ") || databaseProductVersion
.substring(databaseProductVersion.indexOf('V'))
.matches("V\\dR\\d[mM]\\d"))) {
.substring(databaseProductVersion.indexOf('V')).matches("V\\dR\\d[mM]\\d"))) {
databaseProductName = "DB2AS400";
}
else {
@@ -164,8 +161,7 @@ public enum DatabaseType {
productName = "MySQL";
}
if (!dbNameMap.containsKey(productName)) {
throw new IllegalArgumentException(
"DatabaseType not found for product name: [" + productName + "]");
throw new IllegalArgumentException("DatabaseType not found for product name: [" + productName + "]");
}
else {
return dbNameMap.get(productName);

View File

@@ -39,8 +39,7 @@ public class SimpleTaskExplorer implements TaskExplorer {
private TaskExecutionDao taskExecutionDao;
public SimpleTaskExplorer(TaskExecutionDaoFactoryBean taskExecutionDaoFactoryBean) {
Assert.notNull(taskExecutionDaoFactoryBean,
"taskExecutionDaoFactoryBean must not be null");
Assert.notNull(taskExecutionDaoFactoryBean, "taskExecutionDaoFactoryBean must not be null");
try {
this.taskExecutionDao = taskExecutionDaoFactoryBean.getObject();
@@ -56,8 +55,7 @@ public class SimpleTaskExplorer implements TaskExplorer {
}
@Override
public Page<TaskExecution> findRunningTaskExecutions(String taskName,
Pageable pageable) {
public Page<TaskExecution> findRunningTaskExecutions(String taskName, Pageable pageable) {
return this.taskExecutionDao.findRunningTaskExecutions(taskName, pageable);
}
@@ -82,8 +80,7 @@ public class SimpleTaskExplorer implements TaskExplorer {
}
@Override
public Page<TaskExecution> findTaskExecutionsByName(String taskName,
Pageable pageable) {
public Page<TaskExecution> findTaskExecutionsByName(String taskName, Pageable pageable) {
return this.taskExecutionDao.findTaskExecutionsByName(taskName, pageable);
}

View File

@@ -46,8 +46,7 @@ public class SimpleTaskNameResolver implements TaskNameResolver, ApplicationCont
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}

View File

@@ -65,19 +65,15 @@ public class SimpleTaskRepository implements TaskRepository {
private int maxErrorMessageSize = MAX_ERROR_MESSAGE_SIZE;
public SimpleTaskRepository(
FactoryBean<TaskExecutionDao> taskExecutionDaoFactoryBean) {
Assert.notNull(taskExecutionDaoFactoryBean,
"A FactoryBean that provides a TaskExecutionDao is required");
public SimpleTaskRepository(FactoryBean<TaskExecutionDao> taskExecutionDaoFactoryBean) {
Assert.notNull(taskExecutionDaoFactoryBean, "A FactoryBean that provides a TaskExecutionDao is required");
this.taskExecutionDaoFactoryBean = taskExecutionDaoFactoryBean;
}
public SimpleTaskRepository(FactoryBean<TaskExecutionDao> taskExecutionDaoFactoryBean,
Integer maxExitMessageSize, Integer maxTaskNameSize,
Integer maxErrorMessageSize) {
Assert.notNull(taskExecutionDaoFactoryBean,
"A FactoryBean that provides a TaskExecutionDao is required");
public SimpleTaskRepository(FactoryBean<TaskExecutionDao> taskExecutionDaoFactoryBean, Integer maxExitMessageSize,
Integer maxTaskNameSize, Integer maxErrorMessageSize) {
Assert.notNull(taskExecutionDaoFactoryBean, "A FactoryBean that provides a TaskExecutionDao is required");
if (maxTaskNameSize != null) {
this.maxTaskNameSize = maxTaskNameSize;
}
@@ -91,24 +87,21 @@ public class SimpleTaskRepository implements TaskRepository {
}
@Override
public TaskExecution completeTaskExecution(long executionId, Integer exitCode,
Date endTime, String exitMessage) {
public TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage) {
return completeTaskExecution(executionId, exitCode, endTime, exitMessage, null);
}
@Override
public TaskExecution completeTaskExecution(long executionId, Integer exitCode,
Date endTime, String exitMessage, String errorMessage) {
public TaskExecution completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage,
String errorMessage) {
initialize();
validateCompletedTaskExitInformation(executionId, exitCode, endTime);
exitMessage = trimMessage(exitMessage, this.maxExitMessageSize);
errorMessage = trimMessage(errorMessage, this.maxErrorMessageSize);
this.taskExecutionDao.completeTaskExecution(executionId, exitCode, endTime,
exitMessage, errorMessage);
logger.debug("Updating: TaskExecution with executionId=" + executionId
+ " with the following {" + "exitCode=" + exitCode + ", endTime="
+ endTime + ", exitMessage='" + exitMessage + '\'' + ", errorMessage='"
this.taskExecutionDao.completeTaskExecution(executionId, exitCode, endTime, exitMessage, errorMessage);
logger.debug("Updating: TaskExecution with executionId=" + executionId + " with the following {" + "exitCode="
+ exitCode + ", endTime=" + endTime + ", exitMessage='" + exitMessage + '\'' + ", errorMessage='"
+ errorMessage + '\'' + '}');
return this.taskExecutionDao.getTaskExecution(executionId);
@@ -118,9 +111,8 @@ public class SimpleTaskRepository implements TaskRepository {
public TaskExecution createTaskExecution(TaskExecution taskExecution) {
initialize();
validateCreateInformation(taskExecution);
TaskExecution daoTaskExecution = this.taskExecutionDao.createTaskExecution(
taskExecution.getTaskName(), taskExecution.getStartTime(),
taskExecution.getArguments(), taskExecution.getExternalExecutionId(),
TaskExecution daoTaskExecution = this.taskExecutionDao.createTaskExecution(taskExecution.getTaskName(),
taskExecution.getStartTime(), taskExecution.getArguments(), taskExecution.getExternalExecutionId(),
taskExecution.getParentExecutionId());
logger.debug("Creating: " + taskExecution.toString());
return daoTaskExecution;
@@ -129,8 +121,8 @@ public class SimpleTaskRepository implements TaskRepository {
@Override
public TaskExecution createTaskExecution(String name) {
initialize();
TaskExecution taskExecution = this.taskExecutionDao.createTaskExecution(name,
null, Collections.<String>emptyList(), null);
TaskExecution taskExecution = this.taskExecutionDao.createTaskExecution(name, null,
Collections.<String>emptyList(), null);
logger.debug("Creating: " + taskExecution.toString());
return taskExecution;
}
@@ -141,10 +133,9 @@ public class SimpleTaskRepository implements TaskRepository {
}
@Override
public TaskExecution startTaskExecution(long executionid, String taskName,
Date startTime, List<String> arguments, String externalExecutionId) {
return startTaskExecution(executionid, taskName, startTime, arguments,
externalExecutionId, null);
public TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, List<String> arguments,
String externalExecutionId) {
return startTaskExecution(executionid, taskName, startTime, arguments, externalExecutionId, null);
}
@Override
@@ -154,13 +145,11 @@ public class SimpleTaskRepository implements TaskRepository {
}
@Override
public TaskExecution startTaskExecution(long executionid, String taskName,
Date startTime, List<String> arguments, String externalExecutionId,
Long parentExecutionId) {
public TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, List<String> arguments,
String externalExecutionId, Long parentExecutionId) {
initialize();
TaskExecution taskExecution = this.taskExecutionDao.startTaskExecution(
executionid, taskName, startTime, arguments, externalExecutionId,
parentExecutionId);
TaskExecution taskExecution = this.taskExecutionDao.startTaskExecution(executionid, taskName, startTime,
arguments, externalExecutionId, parentExecutionId);
logger.debug("Starting: " + taskExecution.toString());
return taskExecution;
}
@@ -181,8 +170,7 @@ public class SimpleTaskRepository implements TaskRepository {
this.initialized = true;
}
catch (Exception e) {
throw new IllegalStateException("Unable to create the TaskExecutionDao",
e);
throw new IllegalStateException("Unable to create the TaskExecutionDao", e);
}
}
}
@@ -192,18 +180,14 @@ public class SimpleTaskRepository implements TaskRepository {
* @param taskExecution task execution to validate
*/
private void validateCreateInformation(TaskExecution taskExecution) {
Assert.notNull(taskExecution.getStartTime(),
"TaskExecution start time cannot be null.");
Assert.notNull(taskExecution.getStartTime(), "TaskExecution start time cannot be null.");
if (taskExecution.getTaskName() != null
&& taskExecution.getTaskName().length() > this.maxTaskNameSize) {
throw new IllegalArgumentException(
"TaskName length exceeds " + this.maxTaskNameSize + " characters");
if (taskExecution.getTaskName() != null && taskExecution.getTaskName().length() > this.maxTaskNameSize) {
throw new IllegalArgumentException("TaskName length exceeds " + this.maxTaskNameSize + " characters");
}
}
private void validateCompletedTaskExitInformation(long executionId, Integer exitCode,
Date endTime) {
private void validateCompletedTaskExitInformation(long executionId, Integer exitCode, Date endTime) {
Assert.notNull(exitCode, "exitCode should not be null");
Assert.isTrue(exitCode >= 0, "exit code must be greater than or equal to zero");
Assert.notNull(endTime, "TaskExecution endTime cannot be null.");

View File

@@ -22,6 +22,7 @@ import org.springframework.jdbc.support.incrementer.AbstractSequenceMaxValueIncr
/**
* Incrementer using SQL Server's sequence.
*
* @author Glenn Renfro
* @since 2.3.2
*/
@@ -30,8 +31,10 @@ public class SqlServerSequenceMaxValueIncrementer extends AbstractSequenceMaxVal
SqlServerSequenceMaxValueIncrementer(DataSource dataSource, String incrementerName) {
super(dataSource, incrementerName);
}
@Override
protected String getSequenceQuery() {
return "select next value for " + getIncrementerName();
}
}

View File

@@ -100,8 +100,8 @@ public class TaskExecutionDaoFactoryBean implements FactoryBean<TaskExecutionDao
String incrementerName = this.tablePrefix + "SEQ";
DataFieldMaxValueIncrementerFactory incrementerFactory = new DefaultDataFieldMaxValueIncrementerFactory(
dataSource);
DataFieldMaxValueIncrementer incrementer = incrementerFactory
.getIncrementer(databaseType, incrementerName);
DataFieldMaxValueIncrementer incrementer = incrementerFactory.getIncrementer(databaseType,
incrementerName);
if (!isSqlServerTableSequenceAvailable(incrementerName)) {
incrementer = new SqlServerSequenceMaxValueIncrementer(dataSource, this.tablePrefix + "SEQ");
}
@@ -135,8 +135,8 @@ public class TaskExecutionDaoFactoryBean implements FactoryBean<TaskExecutionDao
catch (SQLException e) {
throw new IllegalStateException(e);
}
((JdbcTaskExecutionDao) this.dao).setTaskIncrementer(incrementerFactory
.getIncrementer(databaseType, this.tablePrefix + "SEQ"));
((JdbcTaskExecutionDao) this.dao)
.setTaskIncrementer(incrementerFactory.getIncrementer(databaseType, this.tablePrefix + "SEQ"));
}
private boolean isSqlServerTableSequenceAvailable(String incrementerName) {

View File

@@ -84,9 +84,7 @@ 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);
@@ -99,10 +97,9 @@ public final class TaskRepositoryInitializer implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
boolean isInitializeEnabled = (this.taskProperties.isInitializeEnabled() != null)
? this.taskProperties.isInitializeEnabled()
: this.taskInitializationEnabled;
if (this.dataSource != null && isInitializeEnabled && this.taskProperties
.getTablePrefix().equals(TaskProperties.DEFAULT_TABLE_PREFIX)) {
? this.taskProperties.isInitializeEnabled() : this.taskInitializationEnabled;
if (this.dataSource != null && isInitializeEnabled
&& this.taskProperties.getTablePrefix().equals(TaskProperties.DEFAULT_TABLE_PREFIX)) {
String platform = getDatabaseType(this.dataSource);
if ("hsql".equals(platform)) {
platform = "hsqldb";
@@ -124,8 +121,7 @@ public final class TaskRepositoryInitializer implements InitializingBean {
schemaLocation = schemaLocation.replace("@@platform@@", platform);
populator.addScript(this.resourceLoader.getResource(schemaLocation));
populator.setContinueOnError(true);
logger.debug(
String.format("Initializing task schema for %s database", platform));
logger.debug(String.format("Initializing task schema for %s database", platform));
DatabasePopulatorUtils.execute(populator, this.dataSource);
}
}

View File

@@ -40,19 +40,15 @@ public class SimpleSingleTaskAutoConfigurationTests {
public void testConfiguration() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PropertyPlaceholderAutoConfiguration.class,
.withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.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);
assertThat(singleInstanceTaskListener)
.as("singleInstanceTaskListener should not be null").isNotNull();
assertThat(singleInstanceTaskListener).as("singleInstanceTaskListener should not be null").isNotNull();
assertThat(SingleInstanceTaskListener.class)
.isEqualTo(singleInstanceTaskListener.getClass());
assertThat(SingleInstanceTaskListener.class).isEqualTo(singleInstanceTaskListener.getClass());
});
}

View File

@@ -41,20 +41,16 @@ public class SimpleSingleTaskAutoConfigurationWithDataSourceTests {
public void testConfiguration() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PropertyPlaceholderAutoConfiguration.class,
.withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class,
EmbeddedDataSourceConfiguration.class))
.withPropertyValues("spring.cloud.task.singleInstanceEnabled=true");
applicationContextRunner.run((context) -> {
SingleInstanceTaskListener singleInstanceTaskListener = context
.getBean(SingleInstanceTaskListener.class);
SingleInstanceTaskListener singleInstanceTaskListener = context.getBean(SingleInstanceTaskListener.class);
assertThat(singleInstanceTaskListener)
.as("singleInstanceTaskListener should not be null").isNotNull();
assertThat(singleInstanceTaskListener).as("singleInstanceTaskListener should not be null").isNotNull();
assertThat(SingleInstanceTaskListener.class)
.isEqualTo(singleInstanceTaskListener.getClass());
assertThat(SingleInstanceTaskListener.class).isEqualTo(singleInstanceTaskListener.getClass());
});
}

View File

@@ -62,10 +62,8 @@ public class SimpleTaskAutoConfigurationTests {
@Test
public void testRepository() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class,
SingleTaskConfiguration.class));
.withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class));
applicationContextRunner.run((context) -> {
TaskRepository taskRepository = context.getBean(TaskRepository.class);
@@ -78,8 +76,7 @@ public class SimpleTaskAutoConfigurationTests {
@Test
public void testAutoConfigurationDisabled() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PropertyPlaceholderAutoConfiguration.class,
.withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class))
.withPropertyValues("spring.cloud.task.autoconfiguration.enabled=false");
Executable executable = () -> {
@@ -87,17 +84,16 @@ public class SimpleTaskAutoConfigurationTests {
context.getBean(TaskRepository.class);
});
};
verifyExceptionThrown(NoSuchBeanDefinitionException.class, "No qualifying "
+ "bean of type 'org.springframework.cloud.task.repository.TaskRepository' "
+ "available", executable);
verifyExceptionThrown(
NoSuchBeanDefinitionException.class, "No qualifying "
+ "bean of type 'org.springframework.cloud.task.repository.TaskRepository' " + "available",
executable);
}
@Test
public void testRepositoryInitialized() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class,
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class))
.withUserConfiguration(TaskLifecycleListenerConfiguration.class);
applicationContextRunner.run((context) -> {
@@ -108,14 +104,12 @@ public class SimpleTaskAutoConfigurationTests {
@Test
public void testRepositoryInitializedWithLazyInitialization() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withInitializer((context) -> context
.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor()))
.withConfiguration(AutoConfigurations.of(
EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class))
.withUserConfiguration(TaskLifecycleListenerConfiguration.class);
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withInitializer(
(context) -> context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor()))
.withConfiguration(AutoConfigurations.of(EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class, SimpleTaskAutoConfiguration.class,
SingleTaskConfiguration.class))
.withUserConfiguration(TaskLifecycleListenerConfiguration.class);
applicationContextRunner.run((context) -> {
TaskExplorer taskExplorer = context.getBean(TaskExplorer.class);
assertThat(taskExplorer.getTaskExecutionCount()).isEqualTo(1L);
@@ -125,47 +119,42 @@ public class SimpleTaskAutoConfigurationTests {
@Test
public void testRepositoryNotInitialized() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class))
.withConfiguration(AutoConfigurations.of(EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class, SimpleTaskAutoConfiguration.class,
SingleTaskConfiguration.class))
.withUserConfiguration(TaskLifecycleListenerConfiguration.class)
.withPropertyValues("spring.cloud.task.tablePrefix=foobarless");
verifyExceptionThrownDefaultExecutable(ApplicationContextException.class,
applicationContextRunner);
verifyExceptionThrownDefaultExecutable(ApplicationContextException.class, applicationContextRunner);
}
@Test
public void testMultipleConfigurers() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PropertyPlaceholderAutoConfiguration.class,
.withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class))
.withUserConfiguration(MultipleConfigurers.class);
verifyExceptionThrownDefaultExecutable(BeanCreationException.class,
"Error creating bean "
+ "with name 'simpleTaskAutoConfiguration': Invocation of init method failed",
"Error creating bean " + "with name 'simpleTaskAutoConfiguration': Invocation of init method failed",
applicationContextRunner);
}
@Test
public void testMultipleDataSources() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PropertyPlaceholderAutoConfiguration.class,
.withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class))
.withUserConfiguration(MultipleDataSources.class);
verifyExceptionThrownDefaultExecutable(BeanCreationException.class,
"Error creating bean "
+ "with name 'simpleTaskAutoConfiguration': Invocation of init method failed",
"Error creating bean " + "with name 'simpleTaskAutoConfiguration': Invocation of init method failed",
applicationContextRunner);
}
public void verifyExceptionThrownDefaultExecutable(Class classToCheck, ApplicationContextRunner applicationContextRunner) {
public void verifyExceptionThrownDefaultExecutable(Class classToCheck,
ApplicationContextRunner applicationContextRunner) {
Executable executable = () -> {
applicationContextRunner.run((context) -> {
Throwable expectedException = context.getStartupFailure();
@@ -188,10 +177,8 @@ public class SimpleTaskAutoConfigurationTests {
verifyExceptionThrown(classToCheck, message, executable);
}
public void verifyExceptionThrown(Class classToCheck, String message,
Executable executable) {
assertThatExceptionOfType(classToCheck).isThrownBy(executable::execute)
.withMessage(message);
public void verifyExceptionThrown(Class classToCheck, String message, Executable executable) {
assertThatExceptionOfType(classToCheck).isThrownBy(executable::execute).withMessage(message);
}
/**
@@ -200,16 +187,13 @@ public class SimpleTaskAutoConfigurationTests {
*/
@Test
public void testWithDataSourceProxy() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class,
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class))
.withUserConfiguration(DataSourceProxyConfiguration.class);
applicationContextRunner.run((context) -> {
assertThat(context.getBeanNamesForType(DataSource.class).length).isEqualTo(2);
SimpleTaskAutoConfiguration taskConfiguration = context
.getBean(SimpleTaskAutoConfiguration.class);
SimpleTaskAutoConfiguration taskConfiguration = context.getBean(SimpleTaskAutoConfiguration.class);
assertThat(taskConfiguration).isNotNull();
assertThat(taskConfiguration.taskExplorer()).isNotNull();
});
@@ -255,10 +239,9 @@ public class SimpleTaskAutoConfigurationTests {
public BeanDefinitionHolder proxyDataSource() {
GenericBeanDefinition proxyBeanDefinition = new GenericBeanDefinition();
proxyBeanDefinition.setBeanClassName("javax.sql.DataSource");
BeanDefinitionHolder myDataSource = new BeanDefinitionHolder(
proxyBeanDefinition, "dataSource2");
ScopedProxyUtils.createScopedProxy(myDataSource,
(BeanDefinitionRegistry) this.context.getBeanFactory(), true);
BeanDefinitionHolder myDataSource = new BeanDefinitionHolder(proxyBeanDefinition, "dataSource2");
ScopedProxyUtils.createScopedProxy(myDataSource, (BeanDefinitionRegistry) this.context.getBeanFactory(),
true);
return myDataSource;
}

View File

@@ -72,17 +72,16 @@ public class TaskCoreTests {
@Test
public void successfulTaskTest(CapturedOutput capturedOutput) {
this.applicationContext = SpringApplication.run(TaskConfiguration.class,
"--spring.cloud.task.closecontext.enable=false",
"--spring.cloud.task.name=" + TASK_NAME,
"--spring.cloud.task.closecontext.enable=false", "--spring.cloud.task.name=" + TASK_NAME,
"--spring.main.web-environment=false");
String output = capturedOutput.toString();
assertThat(output.contains(CREATE_TASK_MESSAGE))
.as("Test results do not show create task message: " + output).isTrue();
assertThat(output.contains(UPDATE_TASK_MESSAGE))
.as("Test results do not show success message: " + output).isTrue();
assertThat(output.contains(SUCCESS_EXIT_CODE_MESSAGE))
.as("Test results have incorrect exit code: " + output).isTrue();
assertThat(output.contains(CREATE_TASK_MESSAGE)).as("Test results do not show create task message: " + output)
.isTrue();
assertThat(output.contains(UPDATE_TASK_MESSAGE)).as("Test results do not show success message: " + output)
.isTrue();
assertThat(output.contains(SUCCESS_EXIT_CODE_MESSAGE)).as("Test results have incorrect exit code: " + output)
.isTrue();
}
/**
@@ -90,76 +89,63 @@ public class TaskCoreTests {
*/
@Test
public void successfulTaskTestWithAnnotation(CapturedOutput capturedOutput) {
this.applicationContext = SpringApplication.run(
TaskConfigurationWithAnotation.class,
"--spring.cloud.task.closecontext.enable=false",
"--spring.cloud.task.name=" + TASK_NAME,
this.applicationContext = SpringApplication.run(TaskConfigurationWithAnotation.class,
"--spring.cloud.task.closecontext.enable=false", "--spring.cloud.task.name=" + TASK_NAME,
"--spring.main.web-environment=false");
String output = capturedOutput.toString();
assertThat(output.contains(CREATE_TASK_MESSAGE))
.as("Test results do not show create task message: " + output).isTrue();
assertThat(output.contains(UPDATE_TASK_MESSAGE))
.as("Test results do not show success message: " + output).isTrue();
assertThat(output.contains(SUCCESS_EXIT_CODE_MESSAGE))
.as("Test results have incorrect exit code: " + output).isTrue();
assertThat(output.contains(CREATE_TASK_MESSAGE)).as("Test results do not show create task message: " + output)
.isTrue();
assertThat(output.contains(UPDATE_TASK_MESSAGE)).as("Test results do not show success message: " + output)
.isTrue();
assertThat(output.contains(SUCCESS_EXIT_CODE_MESSAGE)).as("Test results have incorrect exit code: " + output)
.isTrue();
}
@Test
public void exceptionTaskTest(CapturedOutput capturedOutput) {
boolean exceptionFired = false;
try {
this.applicationContext = SpringApplication.run(
TaskExceptionConfiguration.class,
"--spring.cloud.task.closecontext.enable=false",
"--spring.cloud.task.name=" + TASK_NAME,
this.applicationContext = SpringApplication.run(TaskExceptionConfiguration.class,
"--spring.cloud.task.closecontext.enable=false", "--spring.cloud.task.name=" + TASK_NAME,
"--spring.main.web-environment=false");
}
catch (IllegalStateException exception) {
exceptionFired = true;
}
assertThat(exceptionFired).as("An IllegalStateException should have been thrown")
.isTrue();
assertThat(exceptionFired).as("An IllegalStateException should have been thrown").isTrue();
String output = capturedOutput.toString();
assertThat(output.contains(CREATE_TASK_MESSAGE))
.as("Test results do not show create task message: " + output).isTrue();
assertThat(output.contains(UPDATE_TASK_MESSAGE))
.as("Test results do not show success message: " + output).isTrue();
assertThat(output.contains(EXCEPTION_EXIT_CODE_MESSAGE))
.as("Test results have incorrect exit code: " + output).isTrue();
assertThat(output.contains(ERROR_MESSAGE))
.as("Test results have incorrect exit message: " + output).isTrue();
assertThat(output.contains(EXCEPTION_MESSAGE))
.as("Test results have exception message: " + output).isTrue();
assertThat(output.contains(CREATE_TASK_MESSAGE)).as("Test results do not show create task message: " + output)
.isTrue();
assertThat(output.contains(UPDATE_TASK_MESSAGE)).as("Test results do not show success message: " + output)
.isTrue();
assertThat(output.contains(EXCEPTION_EXIT_CODE_MESSAGE)).as("Test results have incorrect exit code: " + output)
.isTrue();
assertThat(output.contains(ERROR_MESSAGE)).as("Test results have incorrect exit message: " + output).isTrue();
assertThat(output.contains(EXCEPTION_MESSAGE)).as("Test results have exception message: " + output).isTrue();
}
@Test
public void invalidExecutionId(CapturedOutput capturedOutput) {
boolean exceptionFired = false;
try {
this.applicationContext = SpringApplication.run(
TaskExceptionConfiguration.class,
"--spring.cloud.task.closecontext.enable=false",
"--spring.cloud.task.name=" + TASK_NAME,
"--spring.main.web-environment=false",
"--spring.cloud.task.executionid=55");
this.applicationContext = SpringApplication.run(TaskExceptionConfiguration.class,
"--spring.cloud.task.closecontext.enable=false", "--spring.cloud.task.name=" + TASK_NAME,
"--spring.main.web-environment=false", "--spring.cloud.task.executionid=55");
}
catch (ApplicationContextException exception) {
exceptionFired = true;
}
assertThat(exceptionFired)
.as("An ApplicationContextException should have been thrown").isTrue();
assertThat(exceptionFired).as("An ApplicationContextException should have been thrown").isTrue();
String output = capturedOutput.toString();
assertThat(output.contains(EXCEPTION_INVALID_TASK_EXECUTION_ID))
.as("Test results do not show the correct exception message: " + output)
.isTrue();
.as("Test results do not show the correct exception message: " + output).isTrue();
}
@EnableTask
@ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
public static class TaskConfiguration {
@Bean
@@ -174,8 +160,7 @@ public class TaskCoreTests {
}
@EnableTask
@ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
public static class TaskConfigurationWithAnotation {
@Bean
@@ -190,8 +175,7 @@ public class TaskCoreTests {
}
@EnableTask
@ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
public static class TaskExceptionConfiguration {
@Bean

View File

@@ -43,8 +43,7 @@ import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
* @since 2.0.0
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { SimpleTaskAutoConfiguration.class,
EmbeddedDataSourceConfiguration.class })
@ContextConfiguration(classes = { SimpleTaskAutoConfiguration.class, EmbeddedDataSourceConfiguration.class })
@DirtiesContext
public class TaskRepositoryInitializerDefaultTaskConfigurerTests {

View File

@@ -44,9 +44,8 @@ import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
* @since 2.0.0
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
classes = { SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class,
EmbeddedDataSourceConfiguration.class, DefaultTaskConfigurer.class })
@ContextConfiguration(classes = { SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class,
EmbeddedDataSourceConfiguration.class, DefaultTaskConfigurer.class })
public class TaskRepositoryInitializerNoDataSourceTaskConfigurerTests {
@Autowired

View File

@@ -51,48 +51,39 @@ public class DefaultTaskConfigurerTests {
public void resourcelessTransactionManagerTest() {
DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer();
assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName())
.isEqualTo(
"org.springframework.batch.support.transaction.ResourcelessTransactionManager");
.isEqualTo("org.springframework.batch.support.transaction.ResourcelessTransactionManager");
defaultTaskConfigurer = new DefaultTaskConfigurer("foo");
assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName())
.isEqualTo(
"org.springframework.batch.support.transaction.ResourcelessTransactionManager");
.isEqualTo("org.springframework.batch.support.transaction.ResourcelessTransactionManager");
}
@Test
public void testDefaultContext() throws Exception {
AnnotationConfigApplicationContext localContext = new AnnotationConfigApplicationContext();
localContext.register(EmbeddedDataSourceConfiguration.class,
EntityManagerConfiguration.class);
localContext.register(EmbeddedDataSourceConfiguration.class, EntityManagerConfiguration.class);
localContext.refresh();
DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(
this.dataSource, TaskProperties.DEFAULT_TABLE_PREFIX, localContext);
DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource,
TaskProperties.DEFAULT_TABLE_PREFIX, localContext);
assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName())
.isEqualTo("org.springframework.jdbc.datasource.DataSourceTransactionManager");
}
@Test
public void dataSourceTransactionManagerTest() {
DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(
this.dataSource);
DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource);
assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName())
.isEqualTo(
"org.springframework.jdbc.datasource.DataSourceTransactionManager");
.isEqualTo("org.springframework.jdbc.datasource.DataSourceTransactionManager");
defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource, "FOO", null);
assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName())
.isEqualTo(
"org.springframework.jdbc.datasource.DataSourceTransactionManager");
defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource, "FOO",
this.context);
.isEqualTo("org.springframework.jdbc.datasource.DataSourceTransactionManager");
defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource, "FOO", this.context);
assertThat(defaultTaskConfigurer.getTransactionManager().getClass().getName())
.isEqualTo(
"org.springframework.jdbc.datasource.DataSourceTransactionManager");
.isEqualTo("org.springframework.jdbc.datasource.DataSourceTransactionManager");
}
@Test
public void taskExplorerTest() {
DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(
this.dataSource);
DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource);
assertThat(defaultTaskConfigurer.getTaskExplorer()).isNotNull();
defaultTaskConfigurer = new DefaultTaskConfigurer();
assertThat(defaultTaskConfigurer.getTaskExplorer()).isNotNull();
@@ -100,8 +91,7 @@ public class DefaultTaskConfigurerTests {
@Test
public void taskRepositoryTest() {
DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(
this.dataSource);
DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource);
assertThat(defaultTaskConfigurer.getTaskRepository()).isNotNull();
defaultTaskConfigurer = new DefaultTaskConfigurer();
assertThat(defaultTaskConfigurer.getTaskRepository()).isNotNull();
@@ -109,8 +99,7 @@ public class DefaultTaskConfigurerTests {
@Test
public void taskDataSource() {
DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(
this.dataSource);
DefaultTaskConfigurer defaultTaskConfigurer = new DefaultTaskConfigurer(this.dataSource);
assertThat(defaultTaskConfigurer.getTaskDataSource()).isNotNull();
defaultTaskConfigurer = new DefaultTaskConfigurer();
assertThat(defaultTaskConfigurer.getTaskDataSource()).isNull();

View File

@@ -50,17 +50,14 @@ public class RepositoryTransactionManagerConfigurationTests {
@Test
public void testZeroCustomTransactionManagerConfiguration() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class,
ZeroTransactionManagerConfiguration.class))
.withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, ZeroTransactionManagerConfiguration.class))
.withPropertyValues("application.name=transactionManagerTask");
applicationContextRunner.run((context) -> {
DataSource dataSource = context.getBean("dataSource", DataSource.class);
int taskExecutionCount = JdbcTestUtils
.countRowsInTable(new JdbcTemplate(dataSource), "TASK_EXECUTION");
int taskExecutionCount = JdbcTestUtils.countRowsInTable(new JdbcTemplate(dataSource), "TASK_EXECUTION");
assertThat(taskExecutionCount).isEqualTo(1);
});
@@ -78,29 +75,24 @@ public class RepositoryTransactionManagerConfigurationTests {
private void testConfiguration(Class configurationClass) {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, configurationClass))
.withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
SimpleTaskAutoConfiguration.class, configurationClass))
.withPropertyValues("application.name=transactionManagerTask");
applicationContextRunner.run((context) -> {
DataSource dataSource = context.getBean("dataSource", DataSource.class);
int taskExecutionCount = JdbcTestUtils
.countRowsInTable(new JdbcTemplate(dataSource), "TASK_EXECUTION");
int taskExecutionCount = JdbcTestUtils.countRowsInTable(new JdbcTemplate(dataSource), "TASK_EXECUTION");
// Verify that the create call was rolled back
assertThat(taskExecutionCount).isEqualTo(0);
// Execute a new create call so that things close cleanly
TaskRepository taskRepository = context.getBean("taskRepository",
TaskRepository.class);
TaskRepository taskRepository = context.getBean("taskRepository", TaskRepository.class);
TaskExecution taskExecution = taskRepository
.createTaskExecution("transactionManagerTask");
taskExecution = taskRepository.startTaskExecution(
taskExecution.getExecutionId(), taskExecution.getTaskName(),
new Date(), new ArrayList<>(0), null);
TaskExecution taskExecution = taskRepository.createTaskExecution("transactionManagerTask");
taskExecution = taskRepository.startTaskExecution(taskExecution.getExecutionId(),
taskExecution.getTaskName(), new Date(), new ArrayList<>(0), null);
TaskLifecycleListener listener = context.getBean(TaskLifecycleListener.class);
@@ -129,8 +121,7 @@ public class RepositoryTransactionManagerConfigurationTests {
public static class SingleTransactionManagerConfiguration {
@Bean
public TaskConfigurer taskConfigurer(DataSource dataSource,
PlatformTransactionManager transactionManager) {
public TaskConfigurer taskConfigurer(DataSource dataSource, PlatformTransactionManager transactionManager) {
return new DefaultTaskConfigurer(dataSource) {
@Override
public PlatformTransactionManager getTransactionManager() {
@@ -156,8 +147,7 @@ public class RepositoryTransactionManagerConfigurationTests {
public static class MultipleTransactionManagerConfiguration {
@Bean
public TaskConfigurer taskConfigurer(DataSource dataSource,
PlatformTransactionManager transactionManager) {
public TaskConfigurer taskConfigurer(DataSource dataSource, PlatformTransactionManager transactionManager) {
return new DefaultTaskConfigurer(dataSource) {
@Override
public PlatformTransactionManager getTransactionManager() {
@@ -188,8 +178,7 @@ public class RepositoryTransactionManagerConfigurationTests {
}
private static class TestDataSourceTransactionManager
extends DataSourceTransactionManager {
private static class TestDataSourceTransactionManager extends DataSourceTransactionManager {
protected TestDataSourceTransactionManager(DataSource dataSource) {
super(dataSource);

View File

@@ -28,10 +28,8 @@ import static org.assertj.core.api.Assertions.assertThat;
@DirtiesContext
@ExtendWith(SpringExtension.class)
@SpringBootTest(
classes = { SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class },
properties = { "spring.cloud.task.closecontextEnabled=false",
"spring.cloud.task.initialize-enabled=false" })
@SpringBootTest(classes = { SimpleTaskAutoConfiguration.class, SingleTaskConfiguration.class },
properties = { "spring.cloud.task.closecontextEnabled=false", "spring.cloud.task.initialize-enabled=false" })
public class TaskPropertiesTests {
@Autowired

View File

@@ -50,8 +50,7 @@ public class TestConfiguration implements InitializingBean {
@Bean
public TaskRepositoryInitializer taskRepositoryInitializer() throws Exception {
TaskRepositoryInitializer taskRepositoryInitializer = new TaskRepositoryInitializer(
new TaskProperties());
TaskRepositoryInitializer taskRepositoryInitializer = new TaskRepositoryInitializer(new TaskProperties());
taskRepositoryInitializer.setDataSource(this.dataSource);
taskRepositoryInitializer.setResourceLoader(this.resourceLoader);
taskRepositoryInitializer.afterPropertiesSet();
@@ -82,8 +81,7 @@ public class TestConfiguration implements InitializingBean {
@Override
public void afterPropertiesSet() {
if (this.dataSource != null) {
this.taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(
this.dataSource);
this.taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean(this.dataSource);
}
else {
this.taskExecutionDaoFactoryBean = new TaskExecutionDaoFactoryBean();

View File

@@ -63,15 +63,15 @@ class ObservationIntegrationTests {
void testSuccessfulObservation() {
List<FinishedSpan> finishedSpans = finishedSpans();
SpansAssert.then(finishedSpans)
.thenASpanWithNameEqualTo("my-command-line-runner")
.hasTag("spring.cloud.task.runner.bean-name", "myCommandLineRunner")
.backToSpans()
.thenASpanWithNameEqualTo("my-application-runner")
.hasTag("spring.cloud.task.runner.bean-name", "myApplicationRunner");
SpansAssert.then(finishedSpans).thenASpanWithNameEqualTo("my-command-line-runner")
.hasTag("spring.cloud.task.runner.bean-name", "myCommandLineRunner").backToSpans()
.thenASpanWithNameEqualTo("my-application-runner")
.hasTag("spring.cloud.task.runner.bean-name", "myApplicationRunner");
MeterRegistryAssert.then(this.meterRegistry)
.hasTimerWithNameAndTags("spring.cloud.task.runner", KeyValues.of("spring.cloud.task.runner.bean-name", "myCommandLineRunner"))
.hasTimerWithNameAndTags("spring.cloud.task.runner", KeyValues.of("spring.cloud.task.runner.bean-name", "myApplicationRunner"));
.hasTimerWithNameAndTags("spring.cloud.task.runner",
KeyValues.of("spring.cloud.task.runner.bean-name", "myCommandLineRunner"))
.hasTimerWithNameAndTags("spring.cloud.task.runner",
KeyValues.of("spring.cloud.task.runner.bean-name", "myApplicationRunner"));
}
private List<FinishedSpan> finishedSpans() {
@@ -80,8 +80,12 @@ class ObservationIntegrationTests {
@Configuration
@EnableTask
@ImportAutoConfiguration({SimpleTaskAutoConfiguration.class, ObservationAutoConfiguration.class, ObservationTaskAutoConfiguration.class, BraveAutoConfiguration.class, MicrometerTracingAutoConfiguration.class, MetricsAutoConfiguration.class, CompositeMeterRegistryAutoConfiguration.class, ZipkinAutoConfiguration.class})
@ImportAutoConfiguration({ SimpleTaskAutoConfiguration.class, ObservationAutoConfiguration.class,
ObservationTaskAutoConfiguration.class, BraveAutoConfiguration.class,
MicrometerTracingAutoConfiguration.class, MetricsAutoConfiguration.class,
CompositeMeterRegistryAutoConfiguration.class, ZipkinAutoConfiguration.class })
static class Config {
private static final Logger log = LoggerFactory.getLogger(Config.class);
@Bean
@@ -96,12 +100,16 @@ class ObservationIntegrationTests {
@Bean
CommandLineRunner myCommandLineRunner(Tracer tracer) {
return args -> log.info("<TRACE:{}> Hello from command line runner", tracer.currentSpan().context().traceId());
return args -> log.info("<TRACE:{}> Hello from command line runner",
tracer.currentSpan().context().traceId());
}
@Bean
ApplicationRunner myApplicationRunner(Tracer tracer) {
return args -> log.info("<TRACE:{}> Hello from application runner", tracer.currentSpan().context().traceId());
return args -> log.info("<TRACE:{}> Hello from application runner",
tracer.currentSpan().context().traceId());
}
}
}

View File

@@ -32,8 +32,7 @@ public class TaskExceptionTests {
TaskException taskException = new TaskException(ERROR_MESSAGE);
assertThat(taskException.getMessage()).isEqualTo(ERROR_MESSAGE);
taskException = new TaskException(ERROR_MESSAGE,
new IllegalStateException(ERROR_MESSAGE));
taskException = new TaskException(ERROR_MESSAGE, new IllegalStateException(ERROR_MESSAGE));
assertThat(taskException.getMessage()).isEqualTo(ERROR_MESSAGE);
assertThat(taskException.getCause()).isNotNull();
assertThat(taskException.getCause().getMessage()).isEqualTo(ERROR_MESSAGE);
@@ -44,8 +43,7 @@ public class TaskExceptionTests {
TaskExecutionException taskException = new TaskExecutionException(ERROR_MESSAGE);
assertThat(taskException.getMessage()).isEqualTo(ERROR_MESSAGE);
taskException = new TaskExecutionException(ERROR_MESSAGE,
new IllegalStateException(ERROR_MESSAGE));
taskException = new TaskExecutionException(ERROR_MESSAGE, new IllegalStateException(ERROR_MESSAGE));
assertThat(taskException.getMessage()).isEqualTo(ERROR_MESSAGE);
assertThat(taskException.getCause()).isNotNull();
assertThat(taskException.getCause().getMessage()).isEqualTo(ERROR_MESSAGE);

View File

@@ -80,10 +80,9 @@ public class TaskExecutionListenerTests {
public void testTaskCreate() {
setupContextForTaskExecutionListener();
DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context
.getBean(
DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat", new Date(),
new Date(), null, new ArrayList<>(), null, null);
.getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat", new Date(), new Date(), null,
new ArrayList<>(), null, null);
verifyListenerResults(false, false, taskExecution, taskExecutionListener);
}
@@ -101,12 +100,9 @@ public class TaskExecutionListenerTests {
exceptionFired = true;
}
assertThat(exceptionFired).as("Exception should have fired").isTrue();
assertThat(beforeTaskDidFireOnError)
.as("BeforeTask Listener should have executed").isTrue();
assertThat(endTaskDidFireOnError).as("EndTask Listener should have executed")
.isTrue();
assertThat(failedTaskDidFireOnError)
.as("FailedTask Listener should have executed").isTrue();
assertThat(beforeTaskDidFireOnError).as("BeforeTask Listener should have executed").isTrue();
assertThat(endTaskDidFireOnError).as("EndTask Listener should have executed").isTrue();
assertThat(failedTaskDidFireOnError).as("FailedTask Listener should have executed").isTrue();
}
/**
@@ -123,10 +119,8 @@ public class TaskExecutionListenerTests {
exceptionFired = true;
}
assertThat(exceptionFired).as("Exception should have fired").isTrue();
assertThat(endTaskDidFireOnError).as("EndTask Listener should have executed")
.isTrue();
assertThat(failedTaskDidFireOnError)
.as("FailedTask Listener should not have executed").isTrue();
assertThat(endTaskDidFireOnError).as("EndTask Listener should have executed").isTrue();
assertThat(failedTaskDidFireOnError).as("FailedTask Listener should not have executed").isTrue();
}
/**
@@ -137,18 +131,15 @@ public class TaskExecutionListenerTests {
public void testAfterTaskErrorCreate() {
setupContextForAfterTaskErrorAnnotatedListener();
AfterTaskErrorAnnotationConfiguration.AnnotatedTaskListener taskExecutionListener = this.context
.getBean(
AfterTaskErrorAnnotationConfiguration.AnnotatedTaskListener.class);
this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(),
new String[0], this.context, Duration.ofSeconds(50)));
.getBean(AfterTaskErrorAnnotationConfiguration.AnnotatedTaskListener.class);
this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], this.context,
Duration.ofSeconds(50)));
assertThat(taskExecutionListener.isTaskStartup()).isTrue();
assertThat(taskExecutionListener.isTaskEnd()).isTrue();
assertThat(taskExecutionListener.getTaskExecution().getExitMessage())
.isEqualTo(TestListener.END_MESSAGE);
assertThat(taskExecutionListener.getTaskExecution().getErrorMessage().contains(
"Failed to process @BeforeTask or @AfterTask annotation because: AfterTaskFailure"))
.isTrue();
assertThat(taskExecutionListener.getTaskExecution().getExitMessage()).isEqualTo(TestListener.END_MESSAGE);
assertThat(taskExecutionListener.getTaskExecution().getErrorMessage()
.contains("Failed to process @BeforeTask or @AfterTask annotation because: AfterTaskFailure")).isTrue();
assertThat(taskExecutionListener.getThrowable()).isNull();
}
@@ -160,13 +151,12 @@ public class TaskExecutionListenerTests {
public void testTaskUpdate() {
setupContextForTaskExecutionListener();
DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context
.getBean(
DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(),
new String[0], this.context, Duration.ofSeconds(50)));
.getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], this.context,
Duration.ofSeconds(50)));
TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(),
new Date(), null, new ArrayList<>(), null, null);
TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(), new Date(), null, new ArrayList<>(),
null, null);
verifyListenerResults(true, false, taskExecution, taskExecutionListener);
}
@@ -180,15 +170,13 @@ public class TaskExecutionListenerTests {
setupContextForTaskExecutionListener();
SpringApplication application = new SpringApplication();
DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context
.getBean(
DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
this.context.publishEvent(new ApplicationFailedEvent(application, new String[0],
this.context, exception));
.getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], this.context, exception));
this.context.publishEvent(
new ApplicationReadyEvent(application, new String[0], this.context, Duration.ofSeconds(50)));
TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(),
new Date(), null, new ArrayList<>(), null, null);
TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(), new Date(), null, new ArrayList<>(),
null, null);
verifyListenerResults(true, true, taskExecution, taskExecutionListener);
}
@@ -201,8 +189,8 @@ public class TaskExecutionListenerTests {
setupContextForAnnotatedListener();
DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener = this.context
.getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat", new Date(),
new Date(), null, new ArrayList<>(), null, null);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat", new Date(), new Date(), null,
new ArrayList<>(), null, null);
verifyListenerResults(false, false, taskExecution, annotatedListener);
}
@@ -215,11 +203,11 @@ public class TaskExecutionListenerTests {
setupContextForAnnotatedListener();
DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener = this.context
.getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class);
this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(),
new String[0], this.context, Duration.ofSeconds(50)));
this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], this.context,
Duration.ofSeconds(50)));
TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(),
new Date(), null, new ArrayList<>(), null, null);
TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(), new Date(), null, new ArrayList<>(),
null, null);
verifyListenerResults(true, false, taskExecution, annotatedListener);
}
@@ -234,88 +222,71 @@ public class TaskExecutionListenerTests {
SpringApplication application = new SpringApplication();
DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener = this.context
.getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class);
this.context.publishEvent(new ApplicationFailedEvent(application, new String[0],
this.context, exception));
this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], this.context, exception));
this.context.publishEvent(
new ApplicationReadyEvent(application, new String[0], this.context, Duration.ofSeconds(50)));
TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(),
new Date(), null, new ArrayList<>(), null, null);
TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(), new Date(), null, new ArrayList<>(),
null, null);
verifyListenerResults(true, true, taskExecution, annotatedListener);
}
private void verifyListenerResults(boolean isTaskEnd, boolean isTaskFailed,
TaskExecution taskExecution, TestListener actualListener) {
private void verifyListenerResults(boolean isTaskEnd, boolean isTaskFailed, TaskExecution taskExecution,
TestListener actualListener) {
assertThat(actualListener.isTaskStartup()).isTrue();
assertThat(actualListener.isTaskEnd()).isEqualTo(isTaskEnd);
assertThat(actualListener.isTaskFailed()).isEqualTo(isTaskFailed);
if (isTaskFailed) {
assertThat(actualListener.getTaskExecution().getExitMessage())
.isEqualTo(TestListener.END_MESSAGE);
assertThat(actualListener.getTaskExecution().getExitMessage()).isEqualTo(TestListener.END_MESSAGE);
assertThat(actualListener.getThrowable()).isNotNull();
assertThat(actualListener.getThrowable() instanceof RuntimeException)
.isTrue();
assertThat(actualListener.getThrowable() instanceof RuntimeException).isTrue();
assertThat(actualListener.getTaskExecution().getErrorMessage()
.startsWith("java.lang.RuntimeException: This was expected"))
.isTrue();
.startsWith("java.lang.RuntimeException: This was expected")).isTrue();
}
else if (isTaskEnd) {
assertThat(actualListener.getTaskExecution().getExitMessage())
.isEqualTo(TestListener.END_MESSAGE);
assertThat(actualListener.getTaskExecution().getErrorMessage())
.isEqualTo(taskExecution.getErrorMessage());
assertThat(actualListener.getTaskExecution().getExitMessage()).isEqualTo(TestListener.END_MESSAGE);
assertThat(actualListener.getTaskExecution().getErrorMessage()).isEqualTo(taskExecution.getErrorMessage());
assertThat(actualListener.getThrowable()).isNull();
}
else {
assertThat(actualListener.getTaskExecution().getExitMessage())
.isEqualTo(TestListener.START_MESSAGE);
assertThat(actualListener.getTaskExecution().getExitMessage()).isEqualTo(TestListener.START_MESSAGE);
assertThat(actualListener.getTaskExecution().getErrorMessage()).isNull();
assertThat(actualListener.getThrowable()).isNull();
}
assertThat(actualListener.getTaskExecution().getExecutionId())
.isEqualTo(taskExecution.getExecutionId());
assertThat(actualListener.getTaskExecution().getExitCode())
.isEqualTo(taskExecution.getExitCode());
assertThat(actualListener.getTaskExecution().getExecutionId()).isEqualTo(taskExecution.getExecutionId());
assertThat(actualListener.getTaskExecution().getExitCode()).isEqualTo(taskExecution.getExitCode());
assertThat(actualListener.getTaskExecution().getExternalExecutionId())
.isEqualTo(taskExecution.getExternalExecutionId());
}
private void setupContextForTaskExecutionListener() {
this.context = new AnnotationConfigApplicationContext(
DefaultTaskListenerConfiguration.class, TestDefaultConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context = new AnnotationConfigApplicationContext(DefaultTaskListenerConfiguration.class,
TestDefaultConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
this.context.setId("testTask");
}
private void setupContextForAnnotatedListener() {
this.context = new AnnotationConfigApplicationContext(
TestDefaultConfiguration.class, DefaultAnnotationConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class,
DefaultAnnotationConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
this.context.setId("annotatedTask");
}
private void setupContextForBeforeTaskErrorAnnotatedListener() {
this.context = new AnnotationConfigApplicationContext(
TestDefaultConfiguration.class,
BeforeTaskErrorAnnotationConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class,
BeforeTaskErrorAnnotationConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
this.context.setId("beforeTaskAnnotatedTask");
}
private void setupContextForFailedTaskErrorAnnotatedListener() {
this.context = new AnnotationConfigApplicationContext(
TestDefaultConfiguration.class,
FailedTaskErrorAnnotationConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class,
FailedTaskErrorAnnotationConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
this.context.setId("failedTaskAnnotatedTask");
}
private void setupContextForAfterTaskErrorAnnotatedListener() {
this.context = new AnnotationConfigApplicationContext(
TestDefaultConfiguration.class,
AfterTaskErrorAnnotationConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context = new AnnotationConfigApplicationContext(TestDefaultConfiguration.class,
AfterTaskErrorAnnotationConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
this.context.setId("afterTaskAnnotatedTask");
}
@@ -457,8 +428,7 @@ public class TaskExecutionListenerTests {
return new TestTaskExecutionListener();
}
public static class TestTaskExecutionListener extends TestListener
implements TaskExecutionListener {
public static class TestTaskExecutionListener extends TestListener implements TaskExecutionListener {
@Override
public void onTaskStartup(TaskExecution taskExecution) {

View File

@@ -74,8 +74,7 @@ public class TaskLifecycleListenerTests {
public void setUp() {
this.context = new AnnotationConfigApplicationContext();
this.context.setId("testTask");
this.context.register(TestDefaultConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.register(TestDefaultConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
TestListener.getStartupOrderList().clear();
TestListener.getFailOrderList().clear();
TestListener.getEndOrderList().clear();
@@ -109,8 +108,8 @@ public class TaskLifecycleListenerTests {
this.context.refresh();
this.taskExplorer = this.context.getBean(TaskExplorer.class);
this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(),
new String[0], this.context, Duration.ofSeconds(50)));
this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], this.context,
Duration.ofSeconds(50)));
verifyTaskExecution(0, true, 0);
}
@@ -121,8 +120,7 @@ public class TaskLifecycleListenerTests {
RuntimeException exception = new RuntimeException("This was expected");
SpringApplication application = new SpringApplication();
this.taskExplorer = this.context.getBean(TaskExplorer.class);
this.context.publishEvent(new ApplicationFailedEvent(application, new String[0],
this.context, exception));
this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], this.context, exception));
this.context.publishEvent(
new ApplicationReadyEvent(application, new String[0], this.context, Duration.ofSeconds(50)));
@@ -140,17 +138,14 @@ public class TaskLifecycleListenerTests {
SpringApplication application = new SpringApplication();
this.taskExplorer = this.context.getBean(TaskExplorer.class);
this.context.publishEvent(new ExitCodeEvent(this.context, exitCode));
this.context.publishEvent(new ApplicationFailedEvent(application, new String[0],
this.context, exception));
this.context.publishEvent(new ApplicationFailedEvent(application, new String[0], this.context, exception));
this.context.publishEvent(
new ApplicationReadyEvent(application, new String[0], this.context, Duration.ofSeconds(50)));
verifyTaskExecution(0, true, exitCode, exception, null);
assertThat(TestListener.getStartupOrderList().size()).isEqualTo(2);
assertThat(TestListener.getStartupOrderList().get(0))
.isEqualTo(Integer.valueOf(2));
assertThat(TestListener.getStartupOrderList().get(1))
.isEqualTo(Integer.valueOf(1));
assertThat(TestListener.getStartupOrderList().get(0)).isEqualTo(Integer.valueOf(2));
assertThat(TestListener.getStartupOrderList().get(1)).isEqualTo(Integer.valueOf(1));
assertThat(TestListener.getEndOrderList().size()).isEqualTo(2);
assertThat(TestListener.getEndOrderList().get(0)).isEqualTo(Integer.valueOf(1));
@@ -166,8 +161,7 @@ public class TaskLifecycleListenerTests {
public void testNoClosingOfContext() {
try (ConfigurableApplicationContext applicationContext = SpringApplication.run(
new Class[] { TestDefaultConfiguration.class,
PropertyPlaceholderAutoConfiguration.class },
new Class[] { TestDefaultConfiguration.class, PropertyPlaceholderAutoConfiguration.class },
new String[] { "--spring.cloud.task.closecontext_enabled=false" })) {
assertThat(applicationContext.isActive()).isTrue();
}
@@ -180,8 +174,7 @@ public class TaskLifecycleListenerTests {
MutablePropertySources propertySources = environment.getPropertySources();
Map<String, Object> myMap = new HashMap<>();
myMap.put("spring.cloud.task.executionid", "55");
propertySources
.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
propertySources.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
this.context.setEnvironment(environment);
this.context.refresh();
});
@@ -190,8 +183,7 @@ public class TaskLifecycleListenerTests {
@Test
public void testRestartExistingTask(CapturedOutput capturedOutput) {
this.context.refresh();
TaskLifecycleListener taskLifecycleListener = this.context
.getBean(TaskLifecycleListener.class);
TaskLifecycleListener taskLifecycleListener = this.context.getBean(TaskLifecycleListener.class);
taskLifecycleListener.start();
String output = capturedOutput.toString();
assertThat(output.contains("Multiple start events have been received"))
@@ -204,8 +196,7 @@ public class TaskLifecycleListenerTests {
MutablePropertySources propertySources = environment.getPropertySources();
Map<String, Object> myMap = new HashMap<>();
myMap.put("spring.cloud.task.external-execution-id", "myid");
propertySources
.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
propertySources.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
this.context.setEnvironment(environment);
this.context.refresh();
this.taskExplorer = this.context.getBean(TaskExplorer.class);
@@ -219,8 +210,7 @@ public class TaskLifecycleListenerTests {
MutablePropertySources propertySources = environment.getPropertySources();
Map<String, Object> myMap = new HashMap<>();
myMap.put("spring.cloud.task.parentExecutionId", 789);
propertySources
.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
propertySources.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
this.context.setEnvironment(environment);
this.context.refresh();
this.taskExplorer = this.context.getBean(TaskExplorer.class);
@@ -228,8 +218,7 @@ public class TaskLifecycleListenerTests {
verifyTaskExecution(0, false, null, null, null, 789L);
}
private void verifyTaskExecution(int numberOfParams, boolean update,
Integer exitCode) {
private void verifyTaskExecution(int numberOfParams, boolean update, Integer exitCode) {
verifyTaskExecution(numberOfParams, update, exitCode, null, null);
}
@@ -237,21 +226,19 @@ public class TaskLifecycleListenerTests {
verifyTaskExecution(numberOfParams, update, null, null, null);
}
private void verifyTaskExecution(int numberOfParams, boolean update, Integer exitCode,
Throwable exception, String externalExecutionId) {
verifyTaskExecution(numberOfParams, update, exitCode, exception,
externalExecutionId, null);
private void verifyTaskExecution(int numberOfParams, boolean update, Integer exitCode, Throwable exception,
String externalExecutionId) {
verifyTaskExecution(numberOfParams, update, exitCode, exception, externalExecutionId, null);
}
private void verifyTaskExecution(int numberOfParams, boolean update, Integer exitCode,
Throwable exception, String externalExecutionId, Long parentExecutionId) {
private void verifyTaskExecution(int numberOfParams, boolean update, Integer exitCode, Throwable exception,
String externalExecutionId, Long parentExecutionId) {
Sort sort = Sort.by("id");
PageRequest request = PageRequest.of(0, Integer.MAX_VALUE, sort);
Page<TaskExecution> taskExecutionsByName = this.taskExplorer
.findTaskExecutionsByName("testTask", request);
Page<TaskExecution> taskExecutionsByName = this.taskExplorer.findTaskExecutionsByName("testTask", request);
assertThat(taskExecutionsByName.iterator().hasNext()).isTrue();
TaskExecution taskExecution = taskExecutionsByName.iterator().next();
@@ -261,16 +248,14 @@ public class TaskLifecycleListenerTests {
assertThat(taskExecution.getParentExecutionId()).isEqualTo(parentExecutionId);
if (exception != null) {
assertThat(taskExecution.getErrorMessage()
.length() > exception.getStackTrace().length).isTrue();
assertThat(taskExecution.getErrorMessage().length() > exception.getStackTrace().length).isTrue();
}
else {
assertThat(taskExecution.getExitMessage()).isNull();
}
if (update) {
assertThat(taskExecution.getEndTime().getTime() >= taskExecution
.getStartTime().getTime()).isTrue();
assertThat(taskExecution.getEndTime().getTime() >= taskExecution.getStartTime().getTime()).isTrue();
assertThat(taskExecution.getExitCode()).isNotNull();
}
else {
@@ -310,8 +295,7 @@ public class TaskLifecycleListenerTests {
int i = 0;
for (Map.Entry<String, String> stringStringEntry : this.args.entrySet()) {
sourceArgs[i] = "--" + stringStringEntry.getKey() + "="
+ stringStringEntry.getValue();
sourceArgs[i] = "--" + stringStringEntry.getKey() + "=" + stringStringEntry.getValue();
i++;
}

View File

@@ -46,8 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @since 2.1.0
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
TaskListenerExecutorObjectFactoryTests.TaskExecutionListenerConfiguration.class })
@ContextConfiguration(classes = { TaskListenerExecutorObjectFactoryTests.TaskExecutionListenerConfiguration.class })
@DirtiesContext
public class TaskListenerExecutorObjectFactoryTests {
@@ -77,8 +76,7 @@ public class TaskListenerExecutorObjectFactoryTests {
public void setup(ConfigurableApplicationContext context) {
taskExecutionListenerResults.clear();
this.taskListenerExecutorObjectFactory = new TaskListenerExecutorObjectFactory(
context);
this.taskListenerExecutorObjectFactory = new TaskListenerExecutorObjectFactory(context);
this.taskListenerExecutor = this.taskListenerExecutorObjectFactory.getObject();
}
@@ -90,8 +88,7 @@ public class TaskListenerExecutorObjectFactoryTests {
applicationContextRunner.run((context) -> {
setup(context);
this.taskListenerExecutor
.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER));
this.taskListenerExecutor.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER));
validateSingleEntry(BEFORE_LISTENER);
});
}
@@ -104,8 +101,7 @@ public class TaskListenerExecutorObjectFactoryTests {
applicationContextRunner.run((context) -> {
setup(context);
this.taskListenerExecutor.onTaskFailed(
createSampleTaskExecution(FAIL_LISTENER),
this.taskListenerExecutor.onTaskFailed(createSampleTaskExecution(FAIL_LISTENER),
new IllegalStateException("oops"));
validateSingleEntry(FAIL_LISTENER);
});
@@ -119,8 +115,7 @@ public class TaskListenerExecutorObjectFactoryTests {
applicationContextRunner.run((context) -> {
setup(context);
this.taskListenerExecutor
.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER));
this.taskListenerExecutor.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER));
validateSingleEntry(AFTER_LISTENER);
});
}
@@ -133,34 +128,26 @@ public class TaskListenerExecutorObjectFactoryTests {
applicationContextRunner.run((context) -> {
setup(context);
this.taskListenerExecutor
.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER));
this.taskListenerExecutor.onTaskFailed(
createSampleTaskExecution(FAIL_LISTENER),
this.taskListenerExecutor.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER));
this.taskListenerExecutor.onTaskFailed(createSampleTaskExecution(FAIL_LISTENER),
new IllegalStateException("oops"));
this.taskListenerExecutor
.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER));
this.taskListenerExecutor.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER));
assertThat(taskExecutionListenerResults.size()).isEqualTo(3);
assertThat(taskExecutionListenerResults.get(0).getTaskName())
.isEqualTo(BEFORE_LISTENER);
assertThat(taskExecutionListenerResults.get(1).getTaskName())
.isEqualTo(FAIL_LISTENER);
assertThat(taskExecutionListenerResults.get(2).getTaskName())
.isEqualTo(AFTER_LISTENER);
assertThat(taskExecutionListenerResults.get(0).getTaskName()).isEqualTo(BEFORE_LISTENER);
assertThat(taskExecutionListenerResults.get(1).getTaskName()).isEqualTo(FAIL_LISTENER);
assertThat(taskExecutionListenerResults.get(2).getTaskName()).isEqualTo(AFTER_LISTENER);
});
}
@Test
public void verifyTaskStartupListenerWithMultipleInstances() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withUserConfiguration(
TaskExecutionListenerMultipleInstanceConfiguration.class);
.withUserConfiguration(TaskExecutionListenerMultipleInstanceConfiguration.class);
applicationContextRunner.run((context) -> {
setup(context);
this.taskListenerExecutor
.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER));
this.taskListenerExecutor.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER));
validateSingleEventWithMultipleInstances(BEFORE_LISTENER);
});
}
@@ -168,14 +155,12 @@ public class TaskListenerExecutorObjectFactoryTests {
@Test
public void verifyTaskFailedListenerWithMultipleInstances() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withUserConfiguration(
TaskExecutionListenerMultipleInstanceConfiguration.class);
.withUserConfiguration(TaskExecutionListenerMultipleInstanceConfiguration.class);
applicationContextRunner.run((context) -> {
setup(context);
this.taskListenerExecutor.onTaskFailed(
createSampleTaskExecution(FAIL_LISTENER),
this.taskListenerExecutor.onTaskFailed(createSampleTaskExecution(FAIL_LISTENER),
new IllegalStateException("oops"));
validateSingleEventWithMultipleInstances(FAIL_LISTENER);
});
@@ -184,14 +169,12 @@ public class TaskListenerExecutorObjectFactoryTests {
@Test
public void verifyTaskEndListenerWithMultipleInstances() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withUserConfiguration(
TaskExecutionListenerMultipleInstanceConfiguration.class);
.withUserConfiguration(TaskExecutionListenerMultipleInstanceConfiguration.class);
applicationContextRunner.run((context) -> {
setup(context);
this.taskListenerExecutor
.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER));
this.taskListenerExecutor.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER));
validateSingleEventWithMultipleInstances(AFTER_LISTENER);
});
}
@@ -199,32 +182,22 @@ public class TaskListenerExecutorObjectFactoryTests {
@Test
public void verifyAllListenerWithMultipleInstances() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withUserConfiguration(
TaskExecutionListenerMultipleInstanceConfiguration.class);
.withUserConfiguration(TaskExecutionListenerMultipleInstanceConfiguration.class);
applicationContextRunner.run((context) -> {
setup(context);
this.taskListenerExecutor
.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER));
this.taskListenerExecutor.onTaskFailed(
createSampleTaskExecution(FAIL_LISTENER),
this.taskListenerExecutor.onTaskStartup(createSampleTaskExecution(BEFORE_LISTENER));
this.taskListenerExecutor.onTaskFailed(createSampleTaskExecution(FAIL_LISTENER),
new IllegalStateException("oops"));
this.taskListenerExecutor
.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER));
this.taskListenerExecutor.onTaskEnd(createSampleTaskExecution(AFTER_LISTENER));
assertThat(taskExecutionListenerResults.size()).isEqualTo(6);
assertThat(taskExecutionListenerResults.get(0).getTaskName())
.isEqualTo(BEFORE_LISTENER);
assertThat(taskExecutionListenerResults.get(1).getTaskName())
.isEqualTo(BEFORE_LISTENER);
assertThat(taskExecutionListenerResults.get(2).getTaskName())
.isEqualTo(FAIL_LISTENER);
assertThat(taskExecutionListenerResults.get(3).getTaskName())
.isEqualTo(FAIL_LISTENER);
assertThat(taskExecutionListenerResults.get(4).getTaskName())
.isEqualTo(AFTER_LISTENER);
assertThat(taskExecutionListenerResults.get(5).getTaskName())
.isEqualTo(AFTER_LISTENER);
assertThat(taskExecutionListenerResults.get(0).getTaskName()).isEqualTo(BEFORE_LISTENER);
assertThat(taskExecutionListenerResults.get(1).getTaskName()).isEqualTo(BEFORE_LISTENER);
assertThat(taskExecutionListenerResults.get(2).getTaskName()).isEqualTo(FAIL_LISTENER);
assertThat(taskExecutionListenerResults.get(3).getTaskName()).isEqualTo(FAIL_LISTENER);
assertThat(taskExecutionListenerResults.get(4).getTaskName()).isEqualTo(AFTER_LISTENER);
assertThat(taskExecutionListenerResults.get(5).getTaskName()).isEqualTo(AFTER_LISTENER);
});
}
@@ -241,8 +214,7 @@ public class TaskListenerExecutorObjectFactoryTests {
private void validateSingleEventWithMultipleInstances(String event) {
assertThat(taskExecutionListenerResults.size()).isEqualTo(2);
assertThat(taskExecutionListenerResults)
.allSatisfy(task -> assertThat(task.getTaskName()).isEqualTo(event));
assertThat(taskExecutionListenerResults).allSatisfy(task -> assertThat(task.getTaskName()).isEqualTo(event));
}
@Configuration
@@ -267,26 +239,24 @@ public class TaskListenerExecutorObjectFactoryTests {
public TaskRunComponent otherTaskRunComponent() {
return new TaskRunComponent();
}
}
public static class TaskRunComponent {
@BeforeTask
public void initBeforeListener(TaskExecution taskExecution) {
TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults
.add(taskExecution);
TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults.add(taskExecution);
}
@AfterTask
public void initAfterListener(TaskExecution taskExecution) {
TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults
.add(taskExecution);
TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults.add(taskExecution);
}
@FailedTask
public void initFailedListener(TaskExecution taskExecution, Throwable exception) {
TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults
.add(taskExecution);
TaskListenerExecutorObjectFactoryTests.taskExecutionListenerResults.add(taskExecution);
}
}

View File

@@ -63,7 +63,8 @@ public class TaskObservationsTests {
public void before() {
this.simpleMeterRegistry = new SimpleMeterRegistry();
this.observationRegistry = TestObservationRegistry.create();
ObservationHandler<Observation.Context> timerObservationHandler = new TimerObservationHandler(this.simpleMeterRegistry);
ObservationHandler<Observation.Context> timerObservationHandler = new TimerObservationHandler(
this.simpleMeterRegistry);
this.observationRegistry.observationConfig().observationHandler(timerObservationHandler);
this.taskObservations = new TaskObservations(this.observationRegistry, null, null);
}
@@ -86,9 +87,8 @@ public class TaskObservationsTests {
verifyDefaultKeyValues();
TaskExecutionObservation.TASK_ACTIVE.getDefaultConvention();
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags("spring.cloud.task",
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags("spring.cloud.task", Tags
.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS));
verifyLongTaskTimerAfterStop(longTaskTimer, "myTask72", "123");
}
@@ -96,43 +96,35 @@ public class TaskObservationsTests {
@Test
public void defaultTaskTest() {
TaskExecution taskExecution = new TaskExecution(123L, 0, null, new Date(),
new Date(), null, new ArrayList<>(), null, null, null);
TaskExecution taskExecution = new TaskExecution(123L, 0, null, new Date(), new Date(), null, new ArrayList<>(),
null, null, null);
// Start Task
taskObservations.onTaskStartup(taskExecution);
LongTaskTimer longTaskTimer = initializeBasicTest(UNKNOWN, "123");
// Finish Task
taskObservations.onTaskEnd(taskExecution);
// Test Timer
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), UNKNOWN));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(), "123"));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_PARENT_EXECUTION_ID.getKeyName(), UNKNOWN));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXTERNAL_EXECUTION_ID.getKeyName(), UNKNOWN));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXIT_CODE.getKeyName(), "0"));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags
.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS));
verifyLongTaskTimerAfterStop(longTaskTimer, "unknown", "123");
@@ -153,25 +145,20 @@ public class TaskObservationsTests {
taskExecution.setExitCode(1);
taskObservations.onTaskEnd(taskExecution);
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), "myTask72"));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(), "123"));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_PARENT_EXECUTION_ID.getKeyName(), "-1"));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXIT_CODE.getKeyName(), "1"));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_FAILURE));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags
.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_FAILURE));
verifyLongTaskTimerAfterStop(longTaskTimer, "myTask72", "123");
}
@@ -204,37 +191,29 @@ public class TaskObservationsTests {
verifyDefaultKeyValues();
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_ORG_NAME.getKeyName(), ORGANIZATION_NAME));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_ID.getKeyName(), SPACE_ID));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_NAME.getKeyName(), SPACE_NAME));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_NAME.getKeyName(), APPLICATION_NAME));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_ID.getKeyName(), APPLICATION_ID));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_VERSION.getKeyName(), APPLICATION_VERSION));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_INSTANCE_INDEX.getKeyName(), INSTANCE_INDEX));
// Test Timer
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), "myTask72"));
verifyLongTaskTimerAfterStop(longTaskTimer, "myTask72", "123");
@@ -243,14 +222,13 @@ public class TaskObservationsTests {
@Test
public void testCloudVariablesUninitialized() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
CloudConfigurationForDefaultValues.class));
.withConfiguration(AutoConfigurations.of(CloudConfigurationForDefaultValues.class));
applicationContextRunner.run((context) -> {
TaskObservationCloudKeyValues taskObservationCloudKeyValues = context
.getBean(TaskObservationCloudKeyValues.class);
.getBean(TaskObservationCloudKeyValues.class);
assertThat(taskObservationCloudKeyValues)
.as("taskObservationCloudKeyValues should not be null").isNotNull();
assertThat(taskObservationCloudKeyValues).as("taskObservationCloudKeyValues should not be null")
.isNotNull();
this.taskObservations = new TaskObservations(this.observationRegistry, taskObservationCloudKeyValues, null);
@@ -263,37 +241,29 @@ public class TaskObservationsTests {
verifyDefaultKeyValues();
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_ORG_NAME.getKeyName(), "default"));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_ID.getKeyName(), UNKNOWN));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_SPACE_NAME.getKeyName(), UNKNOWN));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_NAME.getKeyName(), UNKNOWN));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_ID.getKeyName(), UNKNOWN));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_APP_VERSION.getKeyName(), UNKNOWN));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_CF_INSTANCE_INDEX.getKeyName(), "0"));
// Test Timer
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), "myTask72"));
verifyLongTaskTimerAfterStop(longTaskTimer, "myTask72", "123");
@@ -301,8 +271,8 @@ public class TaskObservationsTests {
}
private TaskExecution startupObservationForBasicTests(String taskName, long taskExecutionId) {
TaskExecution taskExecution = new TaskExecution(taskExecutionId, 0, taskName, new Date(),
new Date(), null, new ArrayList<>(), null, "-1", -1L);
TaskExecution taskExecution = new TaskExecution(taskExecutionId, 0, taskName, new Date(), new Date(), null,
new ArrayList<>(), null, "-1", -1L);
// Start Task
taskObservations.onTaskStartup(taskExecution);
@@ -312,56 +282,52 @@ public class TaskObservationsTests {
private LongTaskTimer initializeBasicTest(String taskName, String executionId) {
// Test Long Task Timer while the task is running.
LongTaskTimer longTaskTimer = simpleMeterRegistry
.find(TaskExecutionObservation.TASK_ACTIVE.getPrefix() + ".active").longTaskTimer();
.find(TaskExecutionObservation.TASK_ACTIVE.getPrefix() + ".active").longTaskTimer();
System.out.println(simpleMeterRegistry.getMetersAsString());
assertThat(longTaskTimer)
.withFailMessage("LongTask timer should be created on Task start")
.isNotNull();
assertThat(longTaskTimer).withFailMessage("LongTask timer should be created on Task start").isNotNull();
assertThat(longTaskTimer.activeTasks()).isEqualTo(1);
assertThat(longTaskTimer.getId().getTag(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName()))
.isEqualTo(taskName);
.isEqualTo(taskName);
assertThat(longTaskTimer.getId().getTag(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName()))
.isEqualTo(executionId);
.isEqualTo(executionId);
return longTaskTimer;
}
private void verifyDefaultKeyValues() {
// Test Timer
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName(), "myTask72"));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName(), "123"));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_PARENT_EXECUTION_ID.getKeyName(), "-1"));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_EXIT_CODE.getKeyName(), "0"));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry)
.hasTimerWithNameAndTags(PREFIX,
Tags.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS));
MeterRegistryAssert.assertThat(this.simpleMeterRegistry).hasTimerWithNameAndTags(PREFIX, Tags
.of(TaskExecutionObservation.TaskKeyValues.TASK_STATUS.getKeyName(), TaskObservations.STATUS_SUCCESS));
}
private void verifyLongTaskTimerAfterStop(LongTaskTimer longTaskTimer, String taskName, String executionId) {
// Test Long Task Timer after the task has completed.
assertThat(longTaskTimer.activeTasks()).isEqualTo(0);
assertThat(longTaskTimer.getId().getTag(TaskExecutionObservation.TaskKeyValues.TASK_NAME.getKeyName()))
.isEqualTo(taskName);
.isEqualTo(taskName);
assertThat(longTaskTimer.getId().getTag(TaskExecutionObservation.TaskKeyValues.TASK_EXECUTION_ID.getKeyName()))
.isEqualTo(executionId);
.isEqualTo(executionId);
}
@Configuration
static class CloudConfigurationForDefaultValues {
@Bean
public TaskObservationCloudKeyValues taskObservationCloudKeyValues() {
return new TaskObservationCloudKeyValues();
}
}
}

View File

@@ -42,9 +42,8 @@ class H2TaskRepositoryIntegrationTests {
void testTaskRepository(ModeEnum mode) {
String connectionUrl = String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;MODE=%s", UUID.randomUUID(), mode);
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
.withUserConfiguration(TestConfiguration.class)
.withBean(DataSource.class,
() -> new SimpleDriverDataSource(new org.h2.Driver(), connectionUrl, "sa", ""));
.withUserConfiguration(TestConfiguration.class).withBean(DataSource.class,
() -> new SimpleDriverDataSource(new org.h2.Driver(), connectionUrl, "sa", ""));
applicationContextRunner.run((context -> {
TaskExplorer taskExplorer = context.getBean(TaskExplorer.class);
@@ -55,6 +54,7 @@ class H2TaskRepositoryIntegrationTests {
@EnableTask
@ImportAutoConfiguration(SimpleTaskAutoConfiguration.class)
static class TestConfiguration {
}
}

View File

@@ -46,8 +46,7 @@ public abstract class BaseTaskExecutionDaoTestCases {
this.dao.getLatestTaskExecutionsByTaskNames(null);
}
catch (IllegalArgumentException e) {
assertThat(e.getMessage())
.isEqualTo("At least 1 task name must be provided.");
assertThat(e.getMessage()).isEqualTo("At least 1 task name must be provided.");
return;
}
fail("Expected an IllegalArgumentException to be thrown.");
@@ -60,8 +59,7 @@ public abstract class BaseTaskExecutionDaoTestCases {
this.dao.getLatestTaskExecutionsByTaskNames(new String[0]);
}
catch (IllegalArgumentException e) {
assertThat(e.getMessage())
.isEqualTo("At least 1 task name must be provided.");
assertThat(e.getMessage()).isEqualTo("At least 1 task name must be provided.");
return;
}
fail("Expected an IllegalArgumentException to be thrown.");
@@ -74,8 +72,8 @@ public abstract class BaseTaskExecutionDaoTestCases {
this.dao.getLatestTaskExecutionsByTaskNames("foo", null, "bar", " ");
}
catch (IllegalArgumentException e) {
assertThat(e.getMessage()).isEqualTo(
"Task names must not contain any empty elements but 2 of 4 were empty or null.");
assertThat(e.getMessage())
.isEqualTo("Task names must not contain any empty elements but 2 of 4 were empty or null.");
return;
}
fail("Expected an IllegalArgumentException to be thrown.");
@@ -85,11 +83,9 @@ public abstract class BaseTaskExecutionDaoTestCases {
@DirtiesContext
public void getLatestTaskExecutionsByTaskNamesWithSingleTaskName() {
initializeRepositoryNotInOrderWithMultipleTaskExecutions();
final List<TaskExecution> latestTaskExecutions = this.dao
.getLatestTaskExecutionsByTaskNames("FOO1");
assertThat(latestTaskExecutions.size() == 1).as(
"Expected only 1 taskExecution but got " + latestTaskExecutions.size())
.isTrue();
final List<TaskExecution> latestTaskExecutions = this.dao.getLatestTaskExecutionsByTaskNames("FOO1");
assertThat(latestTaskExecutions.size() == 1)
.as("Expected only 1 taskExecution but got " + latestTaskExecutions.size()).isTrue();
final TaskExecution lastTaskExecution = latestTaskExecutions.get(0);
assertThat(lastTaskExecution.getTaskName()).isEqualTo("FOO1");
@@ -109,11 +105,10 @@ public abstract class BaseTaskExecutionDaoTestCases {
@DirtiesContext
public void getLatestTaskExecutionsByTaskNamesWithMultipleTaskNames() {
initializeRepositoryNotInOrderWithMultipleTaskExecutions();
final List<TaskExecution> latestTaskExecutions = this.dao
.getLatestTaskExecutionsByTaskNames("FOO1", "FOO3", "FOO4");
final List<TaskExecution> latestTaskExecutions = this.dao.getLatestTaskExecutionsByTaskNames("FOO1", "FOO3",
"FOO4");
assertThat(latestTaskExecutions.size() == 3)
.as("Expected 3 taskExecutions but got " + latestTaskExecutions.size())
.isTrue();
.as("Expected 3 taskExecutions but got " + latestTaskExecutions.size()).isTrue();
final Calendar dateTimeFoo3 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
dateTimeFoo3.setTime(latestTaskExecutions.get(0).getStartTime());
@@ -155,11 +150,9 @@ public abstract class BaseTaskExecutionDaoTestCases {
@DirtiesContext
public void getLatestTaskExecutionsByTaskNamesWithIdenticalTaskExecutions() {
long executionIdOffset = initializeRepositoryNotInOrderWithMultipleTaskExecutions();
final List<TaskExecution> latestTaskExecutions = this.dao
.getLatestTaskExecutionsByTaskNames("FOO5");
assertThat(latestTaskExecutions.size() == 1).as(
"Expected only 1 taskExecution but got " + latestTaskExecutions.size())
.isTrue();
final List<TaskExecution> latestTaskExecutions = this.dao.getLatestTaskExecutionsByTaskNames("FOO5");
assertThat(latestTaskExecutions.size() == 1)
.as("Expected only 1 taskExecution but got " + latestTaskExecutions.size()).isTrue();
final Calendar dateTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
dateTime.setTime(latestTaskExecutions.get(0).getStartTime());
@@ -170,8 +163,7 @@ public abstract class BaseTaskExecutionDaoTestCases {
assertThat(dateTime.get(Calendar.HOUR_OF_DAY)).isEqualTo(23);
assertThat(dateTime.get(Calendar.MINUTE)).isEqualTo(59);
assertThat(dateTime.get(Calendar.SECOND)).isEqualTo(0);
assertThat(latestTaskExecutions.get(0).getExecutionId())
.isEqualTo(9 + executionIdOffset);
assertThat(latestTaskExecutions.get(0).getExecutionId()).isEqualTo(9 + executionIdOffset);
}
@Test
@@ -204,11 +196,8 @@ public abstract class BaseTaskExecutionDaoTestCases {
@DirtiesContext
public void getLatestTaskExecutionForNonExistingTaskName() {
initializeRepositoryNotInOrderWithMultipleTaskExecutions();
final TaskExecution latestTaskExecution = this.dao
.getLatestTaskExecutionForTaskName("Bar5");
assertThat(latestTaskExecution)
.as("Expected the latestTaskExecution to be null but got"
+ latestTaskExecution)
final TaskExecution latestTaskExecution = this.dao.getLatestTaskExecutionForTaskName("Bar5");
assertThat(latestTaskExecution).as("Expected the latestTaskExecution to be null but got" + latestTaskExecution)
.isNull();
}
@@ -216,10 +205,8 @@ public abstract class BaseTaskExecutionDaoTestCases {
@DirtiesContext
public void getLatestTaskExecutionForExistingTaskName() {
initializeRepositoryNotInOrderWithMultipleTaskExecutions();
final TaskExecution latestTaskExecution = this.dao
.getLatestTaskExecutionForTaskName("FOO1");
assertThat(latestTaskExecution)
.as("Expected the latestTaskExecution not to be null").isNotNull();
final TaskExecution latestTaskExecution = this.dao.getLatestTaskExecutionForTaskName("FOO1");
assertThat(latestTaskExecution).as("Expected the latestTaskExecution not to be null").isNotNull();
final Calendar dateTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
dateTime.setTime(latestTaskExecution.getStartTime());
@@ -241,10 +228,8 @@ public abstract class BaseTaskExecutionDaoTestCases {
@DirtiesContext
public void getLatestTaskExecutionForTaskNameWithIdenticalTaskExecutions() {
long executionIdOffset = initializeRepositoryNotInOrderWithMultipleTaskExecutions();
final TaskExecution latestTaskExecution = this.dao
.getLatestTaskExecutionForTaskName("FOO5");
assertThat(latestTaskExecution)
.as("Expected the latestTaskExecution not to be null").isNotNull();
final TaskExecution latestTaskExecution = this.dao.getLatestTaskExecutionForTaskName("FOO5");
assertThat(latestTaskExecution).as("Expected the latestTaskExecution not to be null").isNotNull();
final Calendar dateTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
dateTime.setTime(latestTaskExecution.getStartTime());
@@ -262,11 +247,9 @@ public abstract class BaseTaskExecutionDaoTestCases {
@DirtiesContext
public void getRunningTaskExecutions() {
initializeRepositoryNotInOrderWithMultipleTaskExecutions();
assertThat(this.dao.getRunningTaskExecutionCount())
.isEqualTo(this.dao.getTaskExecutionCount());
assertThat(this.dao.getRunningTaskExecutionCount()).isEqualTo(this.dao.getTaskExecutionCount());
this.dao.completeTaskExecution(1, 0, new Date(), "c'est fini!");
assertThat(this.dao.getRunningTaskExecutionCount())
.isEqualTo(this.dao.getTaskExecutionCount() - 1);
assertThat(this.dao.getRunningTaskExecutionCount()).isEqualTo(this.dao.getTaskExecutionCount() - 1);
}
protected long initializeRepositoryNotInOrderWithMultipleTaskExecutions() {
@@ -325,12 +308,11 @@ public abstract class BaseTaskExecutionDaoTestCases {
}
private long createTaskExecution(TaskExecution te) {
return this.dao.createTaskExecution(te.getTaskName(), te.getStartTime(),
te.getArguments(), te.getExternalExecutionId()).getExecutionId();
return this.dao.createTaskExecution(te.getTaskName(), te.getStartTime(), te.getArguments(),
te.getExternalExecutionId()).getExecutionId();
}
protected TaskExecution getTaskExecution(String taskName,
String externalExecutionId) {
protected TaskExecution getTaskExecution(String taskName, String externalExecutionId) {
TaskExecution taskExecution = new TaskExecution();
taskExecution.setTaskName(taskName);
taskExecution.setExternalExecutionId(externalExecutionId);

View File

@@ -56,9 +56,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
* @author Michael Minella
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
classes = { TestConfiguration.class, EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@ContextConfiguration(classes = { TestConfiguration.class, EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases {
@Autowired
@@ -77,65 +76,52 @@ public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases {
@Test
@DirtiesContext
public void testStartTaskExecution() {
TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null,
new ArrayList<>(0), null);
TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, new ArrayList<>(0), null);
expectedTaskExecution.setArguments(
Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setStartTime(new Date());
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
TestDBUtils.getTaskExecutionFromDB(this.dataSource,
expectedTaskExecution.getExecutionId()));
TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId()));
}
@Test
@DirtiesContext
public void createTaskExecution() {
TaskExecution expectedTaskExecution = TestVerifierUtils
.createSampleTaskExecutionNoArg();
expectedTaskExecution = this.dao.createTaskExecution(
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
TestDBUtils.getTaskExecutionFromDB(this.dataSource,
expectedTaskExecution.getExecutionId()));
TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId()));
}
@Test
@DirtiesContext
public void createEmptyTaskExecution() {
TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null,
new ArrayList<>(0), null);
TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, new ArrayList<>(0), null);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
TestDBUtils.getTaskExecutionFromDB(this.dataSource,
expectedTaskExecution.getExecutionId()));
TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId()));
}
@Test
@DirtiesContext
public void completeTaskExecution() {
TaskExecution expectedTaskExecution = TestVerifierUtils
.endSampleTaskExecutionNoArg();
expectedTaskExecution = this.dao.createTaskExecution(
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
TaskExecution expectedTaskExecution = TestVerifierUtils.endSampleTaskExecutionNoArg();
expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId());
this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(),
expectedTaskExecution.getExitMessage());
this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(),
expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
TestDBUtils.getTaskExecutionFromDB(this.dataSource,
expectedTaskExecution.getExecutionId()));
TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId()));
}
@Test
@@ -143,13 +129,10 @@ public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases {
public void completeTaskExecutionWithNoCreate() {
JdbcTaskExecutionDao dao = new JdbcTaskExecutionDao(this.dataSource);
TaskExecution expectedTaskExecution = TestVerifierUtils
.endSampleTaskExecutionNoArg();
TaskExecution expectedTaskExecution = TestVerifierUtils.endSampleTaskExecutionNoArg();
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> {
dao.completeTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExitCode(),
expectedTaskExecution.getEndTime(),
expectedTaskExecution.getExitMessage());
dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(),
expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage());
});
}
@@ -189,12 +172,10 @@ public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases {
public void testStartExecutionWithNullExternalExecutionIdExisting() {
TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId();
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(), null);
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), null);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
TestDBUtils.getTaskExecutionFromDB(this.dataSource,
expectedTaskExecution.getExecutionId()));
TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId()));
}
@Test
@@ -202,50 +183,48 @@ public class JdbcTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases {
public void testStartExecutionWithNullExternalExecutionIdNonExisting() {
TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId();
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(), "BAR");
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), "BAR");
expectedTaskExecution.setExternalExecutionId("BAR");
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
TestDBUtils.getTaskExecutionFromDB(this.dataSource,
expectedTaskExecution.getExecutionId()));
TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId()));
}
@Test
@DirtiesContext
public void testFindRunningTaskExecutions() {
initializeRepositoryNotInOrderWithMultipleTaskExecutions();
assertThat(this.dao.findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("START_TIME"))).getTotalElements())
.isEqualTo(4);
assertThat(
this.dao.findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("START_TIME")))
.getTotalElements()).isEqualTo(4);
}
@Test
@DirtiesContext
public void testFindRunningTaskExecutionsIllegalSort() {
initializeRepositoryNotInOrderWithMultipleTaskExecutions();
assertThatThrownBy(() -> this.dao.findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("ILLEGAL_SORT"))).getTotalElements())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid sort option selected: ILLEGAL_SORT");
assertThatThrownBy(() -> this.dao
.findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("ILLEGAL_SORT")))
.getTotalElements()).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid sort option selected: ILLEGAL_SORT");
}
@Test
@DirtiesContext
public void testFindRunningTaskExecutionsSortWithDifferentCase() {
initializeRepositoryNotInOrderWithMultipleTaskExecutions();
assertThat(this.dao.findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("StArT_TiMe"))).getTotalElements())
.isEqualTo(4);
assertThat(
this.dao.findRunningTaskExecutions("FOO1", PageRequest.of(1, Integer.MAX_VALUE, Sort.by("StArT_TiMe")))
.getTotalElements()).isEqualTo(4);
}
private TaskExecution initializeTaskExecutionWithExternalExecutionId() {
TaskExecution expectedTaskExecution = TestVerifierUtils
.createSampleTaskExecutionNoArg();
return this.dao.createTaskExecution(expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(),
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
return this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(), "FOO1");
}
private Iterator<TaskExecution> getPageIterator(int pageNum, int pageSize,
Sort sort) {
private Iterator<TaskExecution> getPageIterator(int pageNum, int pageSize, Sort sort) {
Pageable pageable = (sort == null) ? PageRequest.of(pageNum, pageSize)
: PageRequest.of(pageNum, pageSize, sort);
Page<TaskExecution> page = this.dao.findAll(pageable);

View File

@@ -52,20 +52,16 @@ public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases {
@Test
public void testStartTaskExecution() {
TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null,
new ArrayList<>(0), null);
TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, new ArrayList<>(0), null);
expectedTaskExecution.setArguments(
Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setStartTime(new Date());
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId());
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao
.getTaskExecutions();
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions();
assertThat(taskExecutionMap).as("taskExecutionMap must not be null").isNotNull();
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));
@@ -73,37 +69,29 @@ public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases {
@Test
public void createEmptyTaskExecution() {
TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null,
new ArrayList<>(0), null);
TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, new ArrayList<>(0), null);
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao
.getTaskExecutions();
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions();
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));
}
@Test
public void completeTaskExecutionWithNoCreate() {
TaskExecution expectedTaskExecution = TestVerifierUtils
.createSampleTaskExecutionNoArg();
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> {
this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExitCode(),
expectedTaskExecution.getEndTime(),
expectedTaskExecution.getExitMessage());
this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(),
expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage());
});
}
@Test
public void saveTaskExecution() {
TaskExecution expectedTaskExecution = TestVerifierUtils
.createSampleTaskExecutionNoArg();
expectedTaskExecution = this.dao.createTaskExecution(
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId());
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao
.getTaskExecutions();
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions();
assertThat(taskExecutionMap).as("taskExecutionMap must not be null").isNotNull();
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));
@@ -111,17 +99,13 @@ public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases {
@Test
public void completeTaskExecution() {
TaskExecution expectedTaskExecution = TestVerifierUtils
.createSampleTaskExecutionNoArg();
expectedTaskExecution = this.dao.createTaskExecution(
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId());
this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(),
expectedTaskExecution.getExitMessage());
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao
.getTaskExecutions();
this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(),
expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage());
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions();
assertThat(taskExecutionMap).as("taskExecutionMap must not be null").isNotNull();
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));
@@ -134,37 +118,31 @@ public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases {
expectedTaskExecutionList.add(TestVerifierUtils.createSampleTaskExecutionNoArg());
for (TaskExecution expectedTaskExecution : expectedTaskExecutionList) {
expectedTaskExecution = this.dao.createTaskExecution(
expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId());
this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExitCode(),
expectedTaskExecution.getEndTime(),
expectedTaskExecution.getExitMessage());
this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getExitCode(),
expectedTaskExecution.getEndTime(), expectedTaskExecution.getExitMessage());
}
Set<Long> jobIds = new HashSet<>(2);
jobIds.add(123L);
jobIds.add(456L);
this.mapTaskExecutionDao.getBatchJobAssociations()
.put(expectedTaskExecutionList.get(0).getExecutionId(), jobIds);
this.mapTaskExecutionDao.getBatchJobAssociations().put(expectedTaskExecutionList.get(0).getExecutionId(),
jobIds);
assertThat(this.dao.getTaskExecutionIdByJobExecutionId(123L)).isEqualTo(
Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId()));
assertThat(this.dao.getTaskExecutionIdByJobExecutionId(456L)).isEqualTo(
Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId()));
assertThat(this.dao.getTaskExecutionIdByJobExecutionId(123L))
.isEqualTo(Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId()));
assertThat(this.dao.getTaskExecutionIdByJobExecutionId(456L))
.isEqualTo(Long.valueOf(expectedTaskExecutionList.get(0).getExecutionId()));
assertThat(this.dao.getTaskExecutionIdByJobExecutionId(789L)).isNull();
}
@Test
public void testStartExecutionWithNullExternalExecutionIdExisting() {
TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId();
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao
.getTaskExecutions();
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(), null);
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions();
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), null);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));
}
@@ -172,20 +150,16 @@ public class MapTaskExecutionDaoTests extends BaseTaskExecutionDaoTestCases {
@Test
public void testStartExecutionWithNullExternalExecutionIdNonExisting() {
TaskExecution expectedTaskExecution = initializeTaskExecutionWithExternalExecutionId();
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao
.getTaskExecutions();
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(), "BAR");
Map<Long, TaskExecution> taskExecutionMap = this.mapTaskExecutionDao.getTaskExecutions();
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(), "BAR");
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));
}
private TaskExecution initializeTaskExecutionWithExternalExecutionId() {
TaskExecution expectedTaskExecution = TestVerifierUtils
.createSampleTaskExecutionNoArg();
return this.dao.createTaskExecution(expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(),
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
return this.dao.createTaskExecution(expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(), "FOO1");
}

View File

@@ -37,16 +37,14 @@ public class FindAllPagingQueryProviderTests {
private Pageable pageable = PageRequest.of(0, 10);
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROWNUM as "
+ "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, START_TIME, "
+ "END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID "
+ "FROM %PREFIX%EXECUTION ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC)) WHERE TMP_ROW_NUM >= 1 AND "
+ "TMP_ROW_NUM < 11" },
return Arrays.asList(new Object[][] { { "Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROWNUM as "
+ "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, START_TIME, "
+ "END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID "
+ "FROM %PREFIX%EXECUTION ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC)) WHERE TMP_ROW_NUM >= 1 AND " + "TMP_ROW_NUM < 11" },
{ "HSQL Database Engine", "SELECT LIMIT 0 10 TASK_EXECUTION_ID, "
+ "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, "
+ "ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION ORDER BY "
@@ -57,37 +55,31 @@ public class FindAllPagingQueryProviderTests {
+ "TASK_EXECUTION_ID DESC LIMIT 10 OFFSET 0" },
{ "MySQL", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "%PREFIX%EXECUTION ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC LIMIT 0, 10" },
{ "Microsoft SQL Server",
"SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, "
+ "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() "
+ "OVER (ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC) AS "
+ "TMP_ROW_NUM FROM %PREFIX%EXECUTION) TASK_EXECUTION_PAGE "
+ "WHERE TMP_ROW_NUM >= 1 AND TMP_ROW_NUM < 11 ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC" },
{ "DB2/Linux",
"SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, "
+ "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() "
+ "OVER() as TMP_ROW_NUM FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, "
+ "EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC)) "
+ "WHERE TMP_ROW_NUM >= 1 AND TMP_ROW_NUM < 11"}});
+ "%PREFIX%EXECUTION ORDER BY START_TIME DESC, " + "TASK_EXECUTION_ID DESC LIMIT 0, 10" },
{ "Microsoft SQL Server", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, "
+ "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() "
+ "OVER (ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC) AS "
+ "TMP_ROW_NUM FROM %PREFIX%EXECUTION) TASK_EXECUTION_PAGE "
+ "WHERE TMP_ROW_NUM >= 1 AND TMP_ROW_NUM < 11 ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC" },
{ "DB2/Linux", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, "
+ "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() "
+ "OVER() as TMP_ROW_NUM FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, "
+ "EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC)) "
+ "WHERE TMP_ROW_NUM >= 1 AND TMP_ROW_NUM < 11" } });
}
@ParameterizedTest
@MethodSource("data")
public void testGeneratedQuery(String databaseProductName, String expectedQuery)
throws Exception {
String actualQuery = TestDBUtils.getPagingQueryProvider(databaseProductName)
.getPageQuery(this.pageable);
assertThat(actualQuery).as(
String.format("the generated query for %s, was not the expected query",
databaseProductName))
public void testGeneratedQuery(String databaseProductName, String expectedQuery) throws Exception {
String actualQuery = TestDBUtils.getPagingQueryProvider(databaseProductName).getPageQuery(this.pageable);
assertThat(actualQuery)
.as(String.format("the generated query for %s, was not the expected query", databaseProductName))
.isEqualTo(expectedQuery);
}

View File

@@ -64,16 +64,12 @@ class H2PagingQueryProviderTests {
sortKeys.put("ID", Order.ASCENDING);
queryProvider.setSortKeys(sortKeys);
List<String> firstPage = jdbcTemplate.queryForList(
queryProvider.getPageQuery(PageRequest.of(0, 2)),
String.class
);
List<String> firstPage = jdbcTemplate.queryForList(queryProvider.getPageQuery(PageRequest.of(0, 2)),
String.class);
assertThat(firstPage).containsExactly("Spring", "Cloud");
List<String> secondPage = jdbcTemplate.queryForList(
queryProvider.getPageQuery(PageRequest.of(1, 2)),
String.class
);
List<String> secondPage = jdbcTemplate.queryForList(queryProvider.getPageQuery(PageRequest.of(1, 2)),
String.class);
assertThat(secondPage).containsExactly("Task");
});
}

View File

@@ -37,53 +37,45 @@ public class WhereClausePagingQueryProviderTests {
private Pageable pageable = PageRequest.of(0, 10);
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROWNUM as "
+ "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, START_TIME, "
+ "END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, "
+ "LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION "
+ "WHERE TASK_EXECUTION_ID = '0000' ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC)) WHERE TMP_ROW_NUM >= 1 AND "
+ "TMP_ROW_NUM < 11" },
return Arrays.asList(new Object[][] { { "Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROWNUM as "
+ "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, START_TIME, "
+ "END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, "
+ "LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION "
+ "WHERE TASK_EXECUTION_ID = '0000' ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC)) WHERE TMP_ROW_NUM >= 1 AND " + "TMP_ROW_NUM < 11" },
{ "HSQL Database Engine", "SELECT LIMIT 0 10 TASK_EXECUTION_ID, "
+ "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, "
+ "ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM %PREFIX%EXECUTION "
+ "WHERE TASK_EXECUTION_ID = '0000' ORDER BY "
+ "START_TIME DESC, TASK_EXECUTION_ID DESC" },
+ "WHERE TASK_EXECUTION_ID = '0000' ORDER BY " + "START_TIME DESC, TASK_EXECUTION_ID DESC" },
{ "PostgreSQL", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, "
+ "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID "
+ "FROM %PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = '0000' "
+ "ORDER BY START_TIME DESC, "
+ "FROM %PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = '0000' " + "ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC LIMIT 10 OFFSET 0" },
{ "MySQL", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "%PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = '0000' "
+ "ORDER BY START_TIME DESC, "
+ "%PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = '0000' " + "ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC LIMIT 0, 10" },
{ "Microsoft SQL Server",
"SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, "
+ "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() "
+ "OVER (ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC) AS "
+ "TMP_ROW_NUM FROM %PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = "
+ "'0000') TASK_EXECUTION_PAGE WHERE TMP_ROW_NUM >= 1 "
+ "AND TMP_ROW_NUM < 11 ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC" } });
{ "Microsoft SQL Server", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, "
+ "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, ERROR_MESSAGE, LAST_UPDATED, EXTERNAL_EXECUTION_ID, PARENT_EXECUTION_ID, ROW_NUMBER() "
+ "OVER (ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC) AS "
+ "TMP_ROW_NUM FROM %PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = "
+ "'0000') TASK_EXECUTION_PAGE WHERE TMP_ROW_NUM >= 1 "
+ "AND TMP_ROW_NUM < 11 ORDER BY START_TIME DESC, TASK_EXECUTION_ID DESC" } });
}
@ParameterizedTest
@MethodSource("data")
public void testGeneratedQuery(String databaseProductName, String expectedQuery)
throws Exception {
PagingQueryProvider pagingQueryProvider = TestDBUtils.getPagingQueryProvider(
databaseProductName, "TASK_EXECUTION_ID = '0000'");
public void testGeneratedQuery(String databaseProductName, String expectedQuery) throws Exception {
PagingQueryProvider pagingQueryProvider = TestDBUtils.getPagingQueryProvider(databaseProductName,
"TASK_EXECUTION_ID = '0000'");
String actualQuery = pagingQueryProvider.getPageQuery(this.pageable);
assertThat(actualQuery).as(
String.format("the generated query for %s, was not the expected query",
databaseProductName))
assertThat(actualQuery)
.as(String.format("the generated query for %s, was not the expected query", databaseProductName))
.isEqualTo(expectedQuery);
}

View File

@@ -51,8 +51,7 @@ public class DatabaseTypeTests {
@Test
public void testInvalidProductName() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> fromProductName("bad product name"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> fromProductName("bad product name"));
}
@Test

View File

@@ -94,13 +94,10 @@ public class SimpleTaskExplorerTests {
testDefaultContext(testType);
Map<Long, TaskExecution> expectedResults = createSampleDataSet(5);
for (Long taskExecutionId : expectedResults.keySet()) {
TaskExecution actualTaskExecution = this.taskExplorer
.getTaskExecution(taskExecutionId);
assertThat(actualTaskExecution).as(String.format(
"expected a taskExecution but got null for test type %s", testType))
.isNotNull();
TestVerifierUtils.verifyTaskExecution(expectedResults.get(taskExecutionId),
actualTaskExecution);
TaskExecution actualTaskExecution = this.taskExplorer.getTaskExecution(taskExecutionId);
assertThat(actualTaskExecution)
.as(String.format("expected a taskExecution but got null for test type %s", testType)).isNotNull();
TestVerifierUtils.verifyTaskExecution(expectedResults.get(taskExecutionId), actualTaskExecution);
}
}
@@ -111,8 +108,7 @@ public class SimpleTaskExplorerTests {
createSampleDataSet(5);
TaskExecution actualTaskExecution = this.taskExplorer.getTaskExecution(-5);
assertThat(actualTaskExecution)
.as(String.format("expected null for actualTaskExecution %s", testType))
assertThat(actualTaskExecution).as(String.format("expected null for actualTaskExecution %s", testType))
.isNull();
}
@@ -123,10 +119,8 @@ public class SimpleTaskExplorerTests {
Map<Long, TaskExecution> expectedResults = createSampleDataSet(5);
for (Map.Entry<Long, TaskExecution> entry : expectedResults.entrySet()) {
String taskName = entry.getValue().getTaskName();
assertThat(this.taskExplorer.getTaskExecutionCountByTaskName(taskName))
.as(String.format(
"task count for task name did not match expected result for testType %s",
testType))
assertThat(this.taskExplorer.getTaskExecutionCountByTaskName(taskName)).as(
String.format("task count for task name did not match expected result for testType %s", testType))
.isEqualTo(1);
}
}
@@ -136,9 +130,8 @@ public class SimpleTaskExplorerTests {
public void getTaskCount(DaoType testType) {
testDefaultContext(testType);
createSampleDataSet(33);
assertThat(this.taskExplorer.getTaskExecutionCount()).as(String.format(
"task count did not match expected result for test Type %s", testType))
.isEqualTo(33);
assertThat(this.taskExplorer.getTaskExecutionCount())
.as(String.format("task count did not match expected result for test Type %s", testType)).isEqualTo(33);
}
@ParameterizedTest
@@ -146,9 +139,8 @@ public class SimpleTaskExplorerTests {
public void getRunningTaskCount(DaoType testType) {
testDefaultContext(testType);
createSampleDataSet(33);
assertThat(this.taskExplorer.getRunningTaskExecutionCount()).as(String.format(
"task count did not match expected result for test Type %s", testType))
.isEqualTo(33);
assertThat(this.taskExplorer.getRunningTaskExecutionCount())
.as(String.format("task count did not match expected result for test Type %s", testType)).isEqualTo(33);
}
@ParameterizedTest
@@ -166,27 +158,23 @@ public class SimpleTaskExplorerTests {
}
for (; i < (COMPLETE_COUNT + TEST_COUNT); i++) {
TaskExecution expectedTaskExecution = this.taskRepository
.createTaskExecution(getSimpleTaskExecution());
expectedResults.put(expectedTaskExecution.getExecutionId(),
expectedTaskExecution);
TaskExecution expectedTaskExecution = this.taskRepository.createTaskExecution(getSimpleTaskExecution());
expectedResults.put(expectedTaskExecution.getExecutionId(), expectedTaskExecution);
}
Pageable pageable = PageRequest.of(0, 10);
Page<TaskExecution> actualResults = this.taskExplorer
.findRunningTaskExecutions(TASK_NAME, pageable);
assertThat(actualResults.getNumberOfElements()).as(String.format(
"Running task count for task name did not match expected result for testType %s",
testType)).isEqualTo(TEST_COUNT);
Page<TaskExecution> actualResults = this.taskExplorer.findRunningTaskExecutions(TASK_NAME, pageable);
assertThat(actualResults.getNumberOfElements()).as(String
.format("Running task count for task name did not match expected result for testType %s", testType))
.isEqualTo(TEST_COUNT);
for (TaskExecution result : actualResults) {
assertThat(expectedResults.containsKey(result.getExecutionId())).as(String
.format("result returned from repo %s not expected for testType %s",
assertThat(expectedResults.containsKey(result.getExecutionId()))
.as(String.format("result returned from repo %s not expected for testType %s",
result.getExecutionId(), testType))
.isTrue();
assertThat(result.getEndTime()).as(String.format(
"result had non null for endTime for the testType %s", testType))
.isNull();
assertThat(result.getEndTime())
.as(String.format("result had non null for endTime for the testType %s", testType)).isNull();
}
}
@@ -204,26 +192,22 @@ public class SimpleTaskExplorerTests {
}
for (int i = 0; i < TEST_COUNT; i++) {
TaskExecution expectedTaskExecution = this.taskRepository
.createTaskExecution(getSimpleTaskExecution());
expectedResults.put(expectedTaskExecution.getExecutionId(),
expectedTaskExecution);
TaskExecution expectedTaskExecution = this.taskRepository.createTaskExecution(getSimpleTaskExecution());
expectedResults.put(expectedTaskExecution.getExecutionId(), expectedTaskExecution);
}
Pageable pageable = PageRequest.of(0, 10);
Page<TaskExecution> resultSet = this.taskExplorer
.findTaskExecutionsByName(TASK_NAME, pageable);
assertThat(resultSet.getNumberOfElements()).as(String.format(
"Running task count for task name did not match expected result for testType %s",
testType)).isEqualTo(TEST_COUNT);
Page<TaskExecution> resultSet = this.taskExplorer.findTaskExecutionsByName(TASK_NAME, pageable);
assertThat(resultSet.getNumberOfElements()).as(String
.format("Running task count for task name did not match expected result for testType %s", testType))
.isEqualTo(TEST_COUNT);
for (TaskExecution result : resultSet) {
assertThat(expectedResults.containsKey(result.getExecutionId()))
.as(String.format("result returned from %s repo %s not expected",
testType, result.getExecutionId()))
assertThat(expectedResults.containsKey(result.getExecutionId())).as(
String.format("result returned from %s repo %s not expected", testType, result.getExecutionId()))
.isTrue();
assertThat(result.getTaskName()).as(String.format(
"taskName for taskExecution is incorrect for testType %s", testType))
assertThat(result.getTaskName())
.as(String.format("taskName for taskExecution is incorrect for testType %s", testType))
.isEqualTo(TASK_NAME);
}
}
@@ -240,9 +224,8 @@ public class SimpleTaskExplorerTests {
}
List<String> actualTaskNames = this.taskExplorer.getTaskNames();
for (String taskName : actualTaskNames) {
assertThat(expectedResults.contains(taskName)).as(String.format(
"taskName was not in expected results for testType %s", testType))
.isTrue();
assertThat(expectedResults.contains(taskName))
.as(String.format("taskName was not in expected results for testType %s", testType)).isTrue();
}
}
@@ -289,8 +272,7 @@ public class SimpleTaskExplorerTests {
@MethodSource("data")
public void findJobsExecutionIdsForInvalidTask(DaoType testType) {
testDefaultContext(testType);
assertThat(this.taskExplorer.getJobExecutionIdsByTaskExecutionId(555555L).size())
.isEqualTo(0);
assertThat(this.taskExplorer.getJobExecutionIdsByTaskExecutionId(555555L).size()).isEqualTo(0);
}
@ParameterizedTest
@@ -298,16 +280,12 @@ public class SimpleTaskExplorerTests {
public void getLatestTaskExecutionForTaskName(DaoType testType) {
testDefaultContext(testType);
Map<Long, TaskExecution> expectedResults = createSampleDataSet(5);
for (Map.Entry<Long, TaskExecution> taskExecutionMapEntry : expectedResults
.entrySet()) {
for (Map.Entry<Long, TaskExecution> taskExecutionMapEntry : expectedResults.entrySet()) {
TaskExecution latestTaskExecution = this.taskExplorer
.getLatestTaskExecutionForTaskName(
taskExecutionMapEntry.getValue().getTaskName());
assertThat(latestTaskExecution).as(String.format(
"expected a taskExecution but got null for test type %s", testType))
.isNotNull();
TestVerifierUtils.verifyTaskExecution(
expectedResults.get(latestTaskExecution.getExecutionId()),
.getLatestTaskExecutionForTaskName(taskExecutionMapEntry.getValue().getTaskName());
assertThat(latestTaskExecution)
.as(String.format("expected a taskExecution but got null for test type %s", testType)).isNotNull();
TestVerifierUtils.verifyTaskExecution(expectedResults.get(latestTaskExecution.getExecutionId()),
latestTaskExecution);
}
}
@@ -325,33 +303,26 @@ public class SimpleTaskExplorerTests {
}
final List<TaskExecution> latestTaskExecutions = this.taskExplorer
.getLatestTaskExecutionsByTaskNames(
taskNamesAsList.toArray(new String[taskNamesAsList.size()]));
.getLatestTaskExecutionsByTaskNames(taskNamesAsList.toArray(new String[taskNamesAsList.size()]));
for (TaskExecution latestTaskExecution : latestTaskExecutions) {
assertThat(latestTaskExecution).as(String.format(
"expected a taskExecution but got null for test type %s", testType))
.isNotNull();
TestVerifierUtils.verifyTaskExecution(
expectedResults.get(latestTaskExecution.getExecutionId()),
assertThat(latestTaskExecution)
.as(String.format("expected a taskExecution but got null for test type %s", testType)).isNotNull();
TestVerifierUtils.verifyTaskExecution(expectedResults.get(latestTaskExecution.getExecutionId()),
latestTaskExecution);
}
}
private void verifyPageResults(Pageable pageable, int totalNumberOfExecs) {
Map<Long, TaskExecution> expectedResults = createSampleDataSet(
totalNumberOfExecs);
Map<Long, TaskExecution> expectedResults = createSampleDataSet(totalNumberOfExecs);
List<Long> sortedExecIds = getSortedOfTaskExecIds(expectedResults);
Iterator<Long> expectedTaskExecutionIter = sortedExecIds.iterator();
// Verify pageable totals
Page<TaskExecution> taskPage = this.taskExplorer.findAll(pageable);
int pagesExpected = (int) Math
.ceil(totalNumberOfExecs / ((double) pageable.getPageSize()));
assertThat(taskPage.getTotalPages())
.as("actual page count return was not the expected total")
int pagesExpected = (int) Math.ceil(totalNumberOfExecs / ((double) pageable.getPageSize()));
assertThat(taskPage.getTotalPages()).as("actual page count return was not the expected total")
.isEqualTo(pagesExpected);
assertThat(taskPage.getTotalElements())
.as("actual element count was not the expected count")
assertThat(taskPage.getTotalElements()).as("actual element count was not the expected count")
.isEqualTo(totalNumberOfExecs);
// Verify pagination
@@ -367,16 +338,14 @@ public class SimpleTaskExplorerTests {
if (!hasMorePages && pageable.getPageSize() != actualTaskExecutions.size()) {
expectedPageSize = totalNumberOfExecs % pageable.getPageSize();
}
assertThat(actualTaskExecutions.size()).as(String.format(
"Element count on page did not match on the %n page", pageNumber))
assertThat(actualTaskExecutions.size())
.as(String.format("Element count on page did not match on the %n page", pageNumber))
.isEqualTo(expectedPageSize);
for (TaskExecution actualExecution : actualTaskExecutions) {
assertThat(actualExecution.getExecutionId())
.as(String.format("Element on page %n did not match expected",
pageNumber))
.as(String.format("Element on page %n did not match expected", pageNumber))
.isEqualTo((long) expectedTaskExecutionIter.next());
TestVerifierUtils.verifyTaskExecution(
expectedResults.get(actualExecution.getExecutionId()),
TestVerifierUtils.verifyTaskExecution(expectedResults.get(actualExecution.getExecutionId()),
actualExecution);
elementCount++;
}
@@ -384,10 +353,8 @@ public class SimpleTaskExplorerTests {
pageNumber++;
}
// Verify actual totals
assertThat(pageNumber).as("Pages processed did not equal expected")
.isEqualTo(pagesExpected);
assertThat(elementCount).as("Elements processed did not equal expected,")
.isEqualTo(totalNumberOfExecs);
assertThat(pageNumber).as("Pages processed did not equal expected").isEqualTo(pagesExpected);
assertThat(elementCount).as("Elements processed did not equal expected,").isEqualTo(totalNumberOfExecs);
}
private TaskExecution createAndSaveTaskExecution(int i) {
@@ -398,8 +365,7 @@ public class SimpleTaskExplorerTests {
private void initializeJdbcExplorerTest() {
this.context = new AnnotationConfigApplicationContext();
this.context.register(TestConfiguration.class,
EmbeddedDataSourceConfiguration.class,
this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
@@ -409,8 +375,7 @@ public class SimpleTaskExplorerTests {
private void initializeMapExplorerTest() {
this.context = new AnnotationConfigApplicationContext();
this.context.register(TestConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.register(TestConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
@@ -421,8 +386,7 @@ public class SimpleTaskExplorerTests {
Map<Long, TaskExecution> expectedResults = new HashMap<>();
for (int i = 0; i < count; i++) {
TaskExecution expectedTaskExecution = createAndSaveTaskExecution(i);
expectedResults.put(expectedTaskExecution.getExecutionId(),
expectedTaskExecution);
expectedResults.put(expectedTaskExecution.getExecutionId(), expectedTaskExecution);
}
return expectedResults;
}
@@ -444,8 +408,7 @@ public class SimpleTaskExplorerTests {
public int compare(TaskExecution e1, TaskExecution e2) {
int result = e1.getStartTime().compareTo(e2.getStartTime());
if (result == 0) {
result = Long.valueOf(e1.getExecutionId())
.compareTo(e2.getExecutionId());
result = Long.valueOf(e1.getExecutionId()).compareTo(e2.getExecutionId());
}
return result;
}

View File

@@ -34,9 +34,8 @@ public class SimpleTaskNameResolverTests {
SimpleTaskNameResolver taskNameResolver = new SimpleTaskNameResolver();
taskNameResolver.setApplicationContext(context);
assertThat(taskNameResolver.getTaskName().startsWith(
"org.springframework.context.support.GenericApplicationContext"))
.isTrue();
assertThat(taskNameResolver.getTaskName()
.startsWith("org.springframework.context.support.GenericApplicationContext")).isTrue();
}
@Test

View File

@@ -49,8 +49,8 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
* @author Ilayaperumal Gopinathan
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { EmbeddedDataSourceConfiguration.class,
SimpleTaskAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
@ContextConfiguration(classes = { EmbeddedDataSourceConfiguration.class, SimpleTaskAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@DirtiesContext
public class SimpleTaskRepositoryJdbcTests {
@@ -65,8 +65,8 @@ public class SimpleTaskRepositoryJdbcTests {
public void testCreateEmptyExecution() {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreEmptyTaskExecution(this.taskRepository);
TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(
this.dataSource, expectedTaskExecution.getExecutionId());
TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(this.dataSource,
expectedTaskExecution.getExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@@ -75,8 +75,8 @@ public class SimpleTaskRepositoryJdbcTests {
public void testCreateTaskExecutionNoParam() {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionNoParams(this.taskRepository);
TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(
this.dataSource, expectedTaskExecution.getExecutionId());
TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(this.dataSource,
expectedTaskExecution.getExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@@ -85,8 +85,8 @@ public class SimpleTaskRepositoryJdbcTests {
public void testCreateTaskExecutionWithParam() {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionWithParams(this.taskRepository);
TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(
this.dataSource, expectedTaskExecution.getExecutionId());
TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(this.dataSource,
expectedTaskExecution.getExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@@ -96,15 +96,13 @@ public class SimpleTaskRepositoryJdbcTests {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreEmptyTaskExecution(this.taskRepository);
expectedTaskExecution.setArguments(
Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setStartTime(new Date());
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(
expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
@@ -120,9 +118,8 @@ public class SimpleTaskRepositoryJdbcTests {
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(
expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
@@ -133,12 +130,10 @@ public class SimpleTaskRepositoryJdbcTests {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionNoParams(this.taskRepository);
expectedTaskExecution.setExternalExecutionId(UUID.randomUUID().toString());
this.taskRepository.updateExternalExecutionId(
expectedTaskExecution.getExecutionId(),
this.taskRepository.updateExternalExecutionId(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExternalExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
TestDBUtils.getTaskExecutionFromDB(this.dataSource,
expectedTaskExecution.getExecutionId()));
TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId()));
}
@Test
@@ -146,12 +141,10 @@ public class SimpleTaskRepositoryJdbcTests {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionNoParams(this.taskRepository);
expectedTaskExecution.setExternalExecutionId(null);
this.taskRepository.updateExternalExecutionId(
expectedTaskExecution.getExecutionId(),
this.taskRepository.updateExternalExecutionId(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExternalExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
TestDBUtils.getTaskExecutionFromDB(this.dataSource,
expectedTaskExecution.getExecutionId()));
TestDBUtils.getTaskExecutionFromDB(this.dataSource, expectedTaskExecution.getExecutionId()));
}
@Test
@@ -160,8 +153,7 @@ public class SimpleTaskRepositoryJdbcTests {
.createAndStoreTaskExecutionNoParams(this.taskRepository);
expectedTaskExecution.setExternalExecutionId(null);
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> {
this.taskRepository.updateExternalExecutionId(-1,
expectedTaskExecution.getExternalExecutionId());
this.taskRepository.updateExternalExecutionId(-1, expectedTaskExecution.getExternalExecutionId());
});
}
@@ -176,11 +168,9 @@ public class SimpleTaskRepositoryJdbcTests {
expectedTaskExecution.setParentExecutionId(12345L);
TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(
expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId(),
expectedTaskExecution.getParentExecutionId());
expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId(), expectedTaskExecution.getParentExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@@ -194,8 +184,8 @@ public class SimpleTaskRepositoryJdbcTests {
expectedTaskExecution.setExitCode(77);
expectedTaskExecution.setExitMessage(UUID.randomUUID().toString());
TaskExecution actualTaskExecution = TaskExecutionCreator
.completeExecution(this.taskRepository, expectedTaskExecution);
TaskExecution actualTaskExecution = TaskExecutionCreator.completeExecution(this.taskRepository,
expectedTaskExecution);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@@ -204,14 +194,11 @@ public class SimpleTaskRepositoryJdbcTests {
public void testCreateTaskExecutionNoParamMaxExitDefaultMessageSize() {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionNoParams(this.taskRepository);
expectedTaskExecution.setExitMessage(
new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE + 1]));
expectedTaskExecution.setExitMessage(new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE + 1]));
expectedTaskExecution.setEndTime(new Date());
expectedTaskExecution.setExitCode(0);
TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution,
this.taskRepository);
assertThat(actualTaskExecution.getExitMessage().length())
.isEqualTo(SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE);
TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, this.taskRepository);
assertThat(actualTaskExecution.getExitMessage().length()).isEqualTo(SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE);
}
@Test
@@ -222,12 +209,10 @@ public class SimpleTaskRepositoryJdbcTests {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionNoParams(simpleTaskRepository);
expectedTaskExecution.setExitMessage(
new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE + 1]));
expectedTaskExecution.setExitMessage(new String(new char[SimpleTaskRepository.MAX_EXIT_MESSAGE_SIZE + 1]));
expectedTaskExecution.setEndTime(new Date());
expectedTaskExecution.setExitCode(0);
TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution,
simpleTaskRepository);
TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, simpleTaskRepository);
assertThat(actualTaskExecution.getExitMessage().length()).isEqualTo(5);
}
@@ -236,12 +221,10 @@ public class SimpleTaskRepositoryJdbcTests {
public void testCreateTaskExecutionNoParamMaxErrorDefaultMessageSize() {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionNoParams(this.taskRepository);
expectedTaskExecution.setErrorMessage(
new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE + 1]));
expectedTaskExecution.setErrorMessage(new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE + 1]));
expectedTaskExecution.setEndTime(new Date());
expectedTaskExecution.setExitCode(0);
TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution,
this.taskRepository);
TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, this.taskRepository);
assertThat(actualTaskExecution.getErrorMessage().length())
.isEqualTo(SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE);
}
@@ -254,12 +237,10 @@ public class SimpleTaskRepositoryJdbcTests {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionNoParams(simpleTaskRepository);
expectedTaskExecution.setErrorMessage(
new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE + 1]));
expectedTaskExecution.setErrorMessage(new String(new char[SimpleTaskRepository.MAX_ERROR_MESSAGE_SIZE + 1]));
expectedTaskExecution.setEndTime(new Date());
expectedTaskExecution.setExitCode(0);
TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution,
simpleTaskRepository);
TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, simpleTaskRepository);
assertThat(actualTaskExecution.getErrorMessage().length()).isEqualTo(5);
}
@@ -269,10 +250,9 @@ public class SimpleTaskRepositoryJdbcTests {
final int MAX_ERROR_MESSAGE_SIZE = 20;
final int MAX_TASK_NAME_SIZE = 30;
SimpleTaskRepository simpleTaskRepository = new SimpleTaskRepository(
new TaskExecutionDaoFactoryBean(this.dataSource), MAX_EXIT_MESSAGE_SIZE,
MAX_TASK_NAME_SIZE, MAX_ERROR_MESSAGE_SIZE);
TaskExecution expectedTaskExecution = TestVerifierUtils
.createSampleTaskExecutionNoArg();
new TaskExecutionDaoFactoryBean(this.dataSource), MAX_EXIT_MESSAGE_SIZE, MAX_TASK_NAME_SIZE,
MAX_ERROR_MESSAGE_SIZE);
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
expectedTaskExecution.setTaskName(new String(new char[MAX_TASK_NAME_SIZE + 1]));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
simpleTaskRepository.createTaskExecution(expectedTaskExecution);
@@ -283,10 +263,8 @@ public class SimpleTaskRepositoryJdbcTests {
public void testDefaultMaxTaskNameSizeForConstructor() {
SimpleTaskRepository simpleTaskRepository = new SimpleTaskRepository(
new TaskExecutionDaoFactoryBean(this.dataSource), null, null, null);
TaskExecution expectedTaskExecution = TestVerifierUtils
.createSampleTaskExecutionNoArg();
expectedTaskExecution.setTaskName(
new String(new char[SimpleTaskRepository.MAX_TASK_NAME_SIZE + 1]));
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
expectedTaskExecution.setTaskName(new String(new char[SimpleTaskRepository.MAX_TASK_NAME_SIZE + 1]));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
simpleTaskRepository.createTaskExecution(expectedTaskExecution);
});
@@ -297,10 +275,8 @@ public class SimpleTaskRepositoryJdbcTests {
final int MAX_EXIT_MESSAGE_SIZE = 10;
final int MAX_ERROR_MESSAGE_SIZE = 20;
SimpleTaskRepository simpleTaskRepository = new SimpleTaskRepository(
new TaskExecutionDaoFactoryBean(this.dataSource), MAX_EXIT_MESSAGE_SIZE,
null, MAX_ERROR_MESSAGE_SIZE);
verifyTaskRepositoryConstructor(MAX_EXIT_MESSAGE_SIZE, MAX_ERROR_MESSAGE_SIZE,
simpleTaskRepository);
new TaskExecutionDaoFactoryBean(this.dataSource), MAX_EXIT_MESSAGE_SIZE, null, MAX_ERROR_MESSAGE_SIZE);
verifyTaskRepositoryConstructor(MAX_EXIT_MESSAGE_SIZE, MAX_ERROR_MESSAGE_SIZE, simpleTaskRepository);
}
@Test
@@ -315,8 +291,7 @@ public class SimpleTaskRepositoryJdbcTests {
@DirtiesContext
public void testCreateTaskExecutionNoParamMaxTaskName() {
TaskExecution taskExecution = new TaskExecution();
taskExecution.setTaskName(
new String(new char[SimpleTaskRepository.MAX_TASK_NAME_SIZE + 1]));
taskExecution.setTaskName(new String(new char[SimpleTaskRepository.MAX_TASK_NAME_SIZE + 1]));
taskExecution.setStartTime(new Date());
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
this.taskRepository.createTaskExecution(taskExecution);
@@ -332,10 +307,9 @@ public class SimpleTaskRepositoryJdbcTests {
expectedTaskExecution.setExitCode(-1);
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
TaskExecution actualTaskExecution = TaskExecutionCreator
.completeExecution(this.taskRepository, expectedTaskExecution);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
actualTaskExecution);
TaskExecution actualTaskExecution = TaskExecutionCreator.completeExecution(this.taskRepository,
expectedTaskExecution);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
});
}
@@ -346,35 +320,27 @@ public class SimpleTaskRepositoryJdbcTests {
.createAndStoreTaskExecutionNoParams(this.taskRepository);
expectedTaskExecution.setExitCode(-1);
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
TaskExecutionCreator.completeExecution(this.taskRepository,
expectedTaskExecution);
TaskExecutionCreator.completeExecution(this.taskRepository, expectedTaskExecution);
});
}
private TaskExecution completeTaskExecution(TaskExecution expectedTaskExecution,
TaskRepository taskRepository) {
return taskRepository.completeTaskExecution(
expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExitCode(), new Date(),
expectedTaskExecution.getExitMessage(),
private TaskExecution completeTaskExecution(TaskExecution expectedTaskExecution, TaskRepository taskRepository) {
return taskRepository.completeTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExitCode(), new Date(), expectedTaskExecution.getExitMessage(),
expectedTaskExecution.getErrorMessage());
}
private void verifyTaskRepositoryConstructor(Integer maxExitMessage,
Integer maxErrorMessage, TaskRepository taskRepository) {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionNoParams(taskRepository);
private void verifyTaskRepositoryConstructor(Integer maxExitMessage, Integer maxErrorMessage,
TaskRepository taskRepository) {
TaskExecution expectedTaskExecution = TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository);
expectedTaskExecution.setErrorMessage(new String(new char[maxErrorMessage + 1]));
expectedTaskExecution.setExitMessage(new String(new char[maxExitMessage + 1]));
expectedTaskExecution.setEndTime(new Date());
expectedTaskExecution.setExitCode(0);
TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution,
taskRepository);
assertThat(actualTaskExecution.getErrorMessage().length())
.isEqualTo(maxErrorMessage.intValue());
assertThat(actualTaskExecution.getExitMessage().length())
.isEqualTo(maxExitMessage.intValue());
TaskExecution actualTaskExecution = completeTaskExecution(expectedTaskExecution, taskRepository);
assertThat(actualTaskExecution.getErrorMessage().length()).isEqualTo(maxErrorMessage.intValue());
assertThat(actualTaskExecution.getExitMessage().length()).isEqualTo(maxExitMessage.intValue());
}
}

View File

@@ -53,8 +53,7 @@ public class SimpleTaskRepositoryMapTests {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreEmptyTaskExecution(this.taskRepository);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
getSingleTaskExecutionFromMapRepository(
expectedTaskExecution.getExecutionId()));
getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId()));
}
@Test
@@ -62,8 +61,7 @@ public class SimpleTaskRepositoryMapTests {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionNoParams(this.taskRepository);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
getSingleTaskExecutionFromMapRepository(
expectedTaskExecution.getExecutionId()));
getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId()));
}
@Test
@@ -71,12 +69,10 @@ public class SimpleTaskRepositoryMapTests {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionNoParams(this.taskRepository);
expectedTaskExecution.setExternalExecutionId(UUID.randomUUID().toString());
this.taskRepository.updateExternalExecutionId(
expectedTaskExecution.getExecutionId(),
this.taskRepository.updateExternalExecutionId(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExternalExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
getSingleTaskExecutionFromMapRepository(
expectedTaskExecution.getExecutionId()));
getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId()));
}
@Test
@@ -84,12 +80,10 @@ public class SimpleTaskRepositoryMapTests {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionNoParams(this.taskRepository);
expectedTaskExecution.setExternalExecutionId(null);
this.taskRepository.updateExternalExecutionId(
expectedTaskExecution.getExecutionId(),
this.taskRepository.updateExternalExecutionId(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExternalExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
getSingleTaskExecutionFromMapRepository(
expectedTaskExecution.getExecutionId()));
getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId()));
}
@Test
@@ -98,8 +92,7 @@ public class SimpleTaskRepositoryMapTests {
.createAndStoreTaskExecutionNoParams(this.taskRepository);
expectedTaskExecution.setExternalExecutionId(null);
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
this.taskRepository.updateExternalExecutionId(-1,
expectedTaskExecution.getExternalExecutionId());
this.taskRepository.updateExternalExecutionId(-1, expectedTaskExecution.getExternalExecutionId());
});
}
@@ -108,8 +101,7 @@ public class SimpleTaskRepositoryMapTests {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreTaskExecutionWithParams(this.taskRepository);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
getSingleTaskExecutionFromMapRepository(
expectedTaskExecution.getExecutionId()));
getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId()));
}
@Test
@@ -117,17 +109,14 @@ public class SimpleTaskRepositoryMapTests {
TaskExecution expectedTaskExecution = TaskExecutionCreator
.createAndStoreEmptyTaskExecution(this.taskRepository);
expectedTaskExecution.setArguments(
Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setStartTime(new Date());
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(
expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId(),
expectedTaskExecution.getParentExecutionId());
expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId(), expectedTaskExecution.getParentExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@@ -141,9 +130,8 @@ public class SimpleTaskRepositoryMapTests {
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(
expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
@@ -159,9 +147,8 @@ public class SimpleTaskRepositoryMapTests {
expectedTaskExecution.setParentExecutionId(12345L);
TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(
expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments(),
expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments(),
expectedTaskExecution.getExternalExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
@@ -173,16 +160,15 @@ public class SimpleTaskRepositoryMapTests {
.createAndStoreTaskExecutionNoParams(this.taskRepository);
expectedTaskExecution.setEndTime(new Date());
expectedTaskExecution.setExitCode(0);
TaskExecution actualTaskExecution = TaskExecutionCreator
.completeExecution(this.taskRepository, expectedTaskExecution);
TaskExecution actualTaskExecution = TaskExecutionCreator.completeExecution(this.taskRepository,
expectedTaskExecution);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
private TaskExecution getSingleTaskExecutionFromMapRepository(long taskExecutionId) {
Map<Long, TaskExecution> taskMap = ((MapTaskExecutionDao) ((SimpleTaskRepository) this.taskRepository)
.getTaskExecutionDao()).getTaskExecutions();
assertTrue("taskExecutionId must be in MapTaskExecutionRepository",
taskMap.containsKey(taskExecutionId));
assertTrue("taskExecutionId must be in MapTaskExecutionRepository", taskMap.containsKey(taskExecutionId));
return taskMap.get(taskExecutionId);
}
@@ -192,8 +178,7 @@ public class SimpleTaskRepositoryMapTests {
.createAndStoreTaskExecutionNoParams(this.taskRepository);
expectedTaskExecution.setExitCode(-1);
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
TaskExecutionCreator.completeExecution(this.taskRepository,
expectedTaskExecution);
TaskExecutionCreator.completeExecution(this.taskRepository, expectedTaskExecution);
});
}

View File

@@ -40,7 +40,7 @@ public class SqlServerSequenceMaxValueIncrementerTests {
@Test
public void testDefaultDataSourceConfiguration() throws Exception {
this.context = new AnnotationConfigApplicationContext(
TaskExecutionDaoFactoryBeanTests.DefaultDataSourceConfiguration.class);
TaskExecutionDaoFactoryBeanTests.DefaultDataSourceConfiguration.class);
DataSource dataSource = this.context.getBean(DataSource.class);
@@ -48,4 +48,5 @@ public class SqlServerSequenceMaxValueIncrementerTests {
assertThat(incrementer.getSequenceQuery()).isEqualTo("select next value for foo");
assertThat(incrementer.getIncrementerName()).isEqualTo("foo");
}
}

View File

@@ -54,21 +54,18 @@ public class TaskDatabaseInitializerTests {
@Test
public void testDefaultContext() {
this.context = new AnnotationConfigApplicationContext();
this.context.register(TestConfiguration.class,
EmbeddedDataSourceConfiguration.class,
this.context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
assertThat(new JdbcTemplate(this.context.getBean(DataSource.class))
.queryForList("select * from TASK_EXECUTION").size()).isEqualTo(0);
assertThat(new JdbcTemplate(this.context.getBean(DataSource.class)).queryForList("select * from TASK_EXECUTION")
.size()).isEqualTo(0);
}
@Test
public void testNoDatabase() {
this.context = new AnnotationConfigApplicationContext(EmptyConfiguration.class);
SimpleTaskRepository repository = new SimpleTaskRepository(
new TaskExecutionDaoFactoryBean());
assertThat(repository.getTaskExecutionDao())
.isInstanceOf(MapTaskExecutionDao.class);
SimpleTaskRepository repository = new SimpleTaskRepository(new TaskExecutionDaoFactoryBean());
assertThat(repository.getTaskExecutionDao()).isInstanceOf(MapTaskExecutionDao.class);
MapTaskExecutionDao dao = (MapTaskExecutionDao) repository.getTaskExecutionDao();
assertThat(dao.getTaskExecutions().size()).isEqualTo(0);
}
@@ -76,19 +73,16 @@ public class TaskDatabaseInitializerTests {
@Test
public void testNoTaskConfiguration() {
this.context = new AnnotationConfigApplicationContext();
this.context.register(EmptyConfiguration.class,
EmbeddedDataSourceConfiguration.class,
this.context.register(EmptyConfiguration.class, EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
this.context.refresh();
assertThat(this.context.getBeanNamesForType(SimpleTaskRepository.class).length)
.isEqualTo(0);
assertThat(this.context.getBeanNamesForType(SimpleTaskRepository.class).length).isEqualTo(0);
}
@Test
public void testMultipleDataSourcesContext() {
this.context = new AnnotationConfigApplicationContext();
this.context.register(SimpleTaskAutoConfiguration.class,
EmbeddedDataSourceConfiguration.class,
this.context.register(SimpleTaskAutoConfiguration.class, EmbeddedDataSourceConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
DataSource dataSource = mock(DataSource.class);
this.context.getBeanFactory().registerSingleton("mockDataSource", dataSource);

View File

@@ -51,8 +51,7 @@ public class TaskExecutionDaoFactoryBeanTests {
@Test
public void testGetObjectType() {
assertThat(TaskExecutionDao.class)
.isEqualTo(new TaskExecutionDaoFactoryBean().getObjectType());
assertThat(TaskExecutionDao.class).isEqualTo(new TaskExecutionDaoFactoryBean().getObjectType());
}
@Test
@@ -81,13 +80,11 @@ public class TaskExecutionDaoFactoryBeanTests {
@Test
public void testDefaultDataSourceConfiguration() throws Exception {
this.context = new AnnotationConfigApplicationContext(
DefaultDataSourceConfiguration.class);
this.context = new AnnotationConfigApplicationContext(DefaultDataSourceConfiguration.class);
DataSource dataSource = this.context.getBean(DataSource.class);
TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean(
dataSource);
TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean(dataSource);
TaskExecutionDao taskExecutionDao = factoryBean.getObject();
assertThat(taskExecutionDao instanceof JdbcTaskExecutionDao).isTrue();
@@ -99,17 +96,14 @@ public class TaskExecutionDaoFactoryBeanTests {
@Test
public void testSettingTablePrefix() throws Exception {
this.context = new AnnotationConfigApplicationContext(
DefaultDataSourceConfiguration.class);
this.context = new AnnotationConfigApplicationContext(DefaultDataSourceConfiguration.class);
DataSource dataSource = this.context.getBean(DataSource.class);
TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean(
dataSource, "foo_");
TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean(dataSource, "foo_");
TaskExecutionDao taskExecutionDao = factoryBean.getObject();
assertThat(ReflectionTestUtils.getField(taskExecutionDao, "tablePrefix"))
.isEqualTo("foo_");
assertThat(ReflectionTestUtils.getField(taskExecutionDao, "tablePrefix")).isEqualTo("foo_");
}
@Configuration
@@ -117,8 +111,7 @@ public class TaskExecutionDaoFactoryBeanTests {
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2);
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2);
return builder.build();
}

View File

@@ -38,8 +38,7 @@ public final class TaskExecutionCreator {
* @param taskRepository the taskRepository where the taskExecution should be stored.
* @return the taskExecution created.
*/
public static TaskExecution createAndStoreEmptyTaskExecution(
TaskRepository taskRepository) {
public static TaskExecution createAndStoreEmptyTaskExecution(TaskRepository taskRepository) {
return taskRepository.createTaskExecution();
}
@@ -48,8 +47,7 @@ public final class TaskExecutionCreator {
* @param taskRepository the taskRepository where the taskExecution should be stored.
* @return the taskExecution created.
*/
public static TaskExecution createAndStoreTaskExecutionNoParams(
TaskRepository taskRepository) {
public static TaskExecution createAndStoreTaskExecutionNoParams(TaskRepository taskRepository) {
TaskExecution expectedTaskExecution = taskRepository.createTaskExecution();
return expectedTaskExecution;
}
@@ -59,10 +57,8 @@ public final class TaskExecutionCreator {
* @param taskRepository the taskRepository where the taskExecution should be stored.
* @return the taskExecution created.
*/
public static TaskExecution createAndStoreTaskExecutionWithParams(
TaskRepository taskRepository) {
TaskExecution expectedTaskExecution = TestVerifierUtils
.createSampleTaskExecutionNoArg();
public static TaskExecution createAndStoreTaskExecutionWithParams(TaskRepository taskRepository) {
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
List<String> params = new ArrayList<>();
params.add(UUID.randomUUID().toString());
params.add(UUID.randomUUID().toString());
@@ -77,13 +73,10 @@ public final class TaskExecutionCreator {
* @param expectedTaskExecution the expected task execution.
* @return the taskExecution created.
*/
public static TaskExecution completeExecution(TaskRepository taskRepository,
TaskExecution expectedTaskExecution) {
return taskRepository.completeTaskExecution(
expectedTaskExecution.getExecutionId(),
public static TaskExecution completeExecution(TaskRepository taskRepository, TaskExecution expectedTaskExecution) {
return taskRepository.completeTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(),
expectedTaskExecution.getExitMessage(),
expectedTaskExecution.getErrorMessage());
expectedTaskExecution.getExitMessage(), expectedTaskExecution.getErrorMessage());
}
}

View File

@@ -63,29 +63,22 @@ public final class TestDBUtils {
* @param taskExecutionId The id of the task to search.
* @return taskExecution retrieved from the database.
*/
public static TaskExecution getTaskExecutionFromDB(DataSource dataSource,
long taskExecutionId) {
String sql = "SELECT * FROM TASK_EXECUTION WHERE " + "TASK_EXECUTION_ID = '"
+ taskExecutionId + "'";
public static TaskExecution getTaskExecutionFromDB(DataSource dataSource, long taskExecutionId) {
String sql = "SELECT * FROM TASK_EXECUTION WHERE " + "TASK_EXECUTION_ID = '" + taskExecutionId + "'";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<TaskExecution> rows = jdbcTemplate.query(sql,
new RowMapper<TaskExecution>() {
@Override
public TaskExecution mapRow(ResultSet rs, int rownumber)
throws SQLException {
TaskExecution taskExecution = new TaskExecution(
rs.getLong("TASK_EXECUTION_ID"),
StringUtils.hasText(rs.getString("EXIT_CODE"))
? Integer.valueOf(rs.getString("EXIT_CODE"))
: null,
rs.getString("TASK_NAME"), rs.getTimestamp("START_TIME"),
rs.getTimestamp("END_TIME"), rs.getString("EXIT_MESSAGE"),
new ArrayList<>(0), rs.getString("ERROR_MESSAGE"),
rs.getString("EXTERNAL_EXECUTION_ID"));
return taskExecution;
}
});
List<TaskExecution> rows = jdbcTemplate.query(sql, new RowMapper<TaskExecution>() {
@Override
public TaskExecution mapRow(ResultSet rs, int rownumber) throws SQLException {
TaskExecution taskExecution = new TaskExecution(rs.getLong("TASK_EXECUTION_ID"),
StringUtils.hasText(rs.getString("EXIT_CODE")) ? Integer.valueOf(rs.getString("EXIT_CODE"))
: null,
rs.getString("TASK_NAME"), rs.getTimestamp("START_TIME"), rs.getTimestamp("END_TIME"),
rs.getString("EXIT_MESSAGE"), new ArrayList<>(0), rs.getString("ERROR_MESSAGE"),
rs.getString("EXTERNAL_EXECUTION_ID"));
return taskExecution;
}
});
assertThat(rows.size()).as("only one row should be returned").isEqualTo(1);
TaskExecution taskExecution = rows.get(0);
@@ -101,8 +94,7 @@ public final class TestDBUtils {
* @throws Exception exception thrown if error occurs creating
* {@link PagingQueryProvider}.
*/
public static PagingQueryProvider getPagingQueryProvider(String databaseProductName)
throws Exception {
public static PagingQueryProvider getPagingQueryProvider(String databaseProductName) throws Exception {
return getPagingQueryProvider(databaseProductName, null);
}
@@ -115,8 +107,8 @@ public final class TestDBUtils {
* @throws Exception exception thrown if error occurs creating
* {@link PagingQueryProvider}.
*/
public static PagingQueryProvider getPagingQueryProvider(String databaseProductName,
String whereClause) throws Exception {
public static PagingQueryProvider getPagingQueryProvider(String databaseProductName, String whereClause)
throws Exception {
DataSource dataSource = getMockDataSource(databaseProductName);
Map<String, Order> orderMap = new TreeMap<>();
orderMap.put("START_TIME", Order.DESCENDING);
@@ -147,8 +139,7 @@ public final class TestDBUtils {
* @throws Exception exception thrown if error occurs creating mock
* {@link DataSource}.
*/
public static DataSource getMockDataSource(String databaseProductName)
throws Exception {
public static DataSource getMockDataSource(String databaseProductName) throws Exception {
DatabaseMetaData dmd = mock(DatabaseMetaData.class);
DataSource ds = mock(DataSource.class);
Connection con = mock(Connection.class);
@@ -180,10 +171,9 @@ public final class TestDBUtils {
return incrementerFactory.getIncrementer(databaseType, "TASK_SEQ");
}
private static void populateParamsToDB(DataSource dataSource,
TaskExecution taskExecution) {
String sql = "SELECT * FROM TASK_EXECUTION_PARAMS WHERE TASK_EXECUTION_ID = '"
+ taskExecution.getExecutionId() + "'";
private static void populateParamsToDB(DataSource dataSource, TaskExecution taskExecution) {
String sql = "SELECT * FROM TASK_EXECUTION_PARAMS WHERE TASK_EXECUTION_ID = '" + taskExecution.getExecutionId()
+ "'";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);

View File

@@ -86,11 +86,12 @@ public class TestDefaultConfiguration implements InitializingBean {
@Bean
public TaskLifecycleListener taskHandler(TaskExplorer taskExplorer,
@Autowired(required = false) io.micrometer.core.instrument.MeterRegistry meterRegistry, @Autowired(required = false) ObservationRegistry observationRegistry) {
@Autowired(required = false) io.micrometer.core.instrument.MeterRegistry meterRegistry,
@Autowired(required = false) ObservationRegistry observationRegistry) {
return new TaskLifecycleListener(taskRepository(), taskNameResolver(),
this.applicationArguments, taskExplorer, this.taskProperties,
taskListenerExecutorObjectProvider(this.context), observationRegistry, new TaskObservationCloudKeyValues());
return new TaskLifecycleListener(taskRepository(), taskNameResolver(), this.applicationArguments, taskExplorer,
this.taskProperties, taskListenerExecutorObjectProvider(this.context), observationRegistry,
new TaskObservationCloudKeyValues());
}
@Override

View File

@@ -71,13 +71,11 @@ public final class TestVerifierUtils {
* @param mockAppender The appender that is associated with the test.
* @param logSample The string to search for in the log entry.
*/
public static void verifyLogEntryExists(Appender mockAppender,
final String logSample) {
public static void verifyLogEntryExists(Appender mockAppender, final String logSample) {
verify(mockAppender).doAppend(argThat(new ArgumentMatcher() {
@Override
public boolean matches(final Object argument) {
return ((LoggingEvent) argument).getFormattedMessage()
.contains(logSample);
return ((LoggingEvent) argument).getFormattedMessage().contains(logSample);
}
}));
}
@@ -92,8 +90,7 @@ public final class TestVerifierUtils {
long executionId = randomGenerator.nextLong();
String taskName = UUID.randomUUID().toString();
return new TaskExecution(executionId, null, taskName, startTime, null, null,
new ArrayList<>(), null, null);
return new TaskExecution(executionId, null, taskName, startTime, null, null, new ArrayList<>(), null, null);
}
/**
@@ -109,8 +106,8 @@ public final class TestVerifierUtils {
String taskName = UUID.randomUUID().toString();
String exitMessage = UUID.randomUUID().toString();
return new TaskExecution(executionId, exitCode, taskName, startTime, endTime,
exitMessage, new ArrayList<>(), null, null);
return new TaskExecution(executionId, exitCode, taskName, startTime, endTime, exitMessage, new ArrayList<>(),
null, null);
}
/**
@@ -126,8 +123,7 @@ public final class TestVerifierUtils {
for (int i = 0; i < ARG_SIZE; i++) {
args.add(UUID.randomUUID().toString());
}
return new TaskExecution(executionId, null, taskName, startTime, null, null, args,
null, externalExecutionId);
return new TaskExecution(executionId, null, taskName, startTime, null, null, args, null, externalExecutionId);
}
/**
@@ -135,10 +131,8 @@ public final class TestVerifierUtils {
* @param expectedTaskExecution The expected value for the task execution.
* @param actualTaskExecution The actual value for the task execution.
*/
public static void verifyTaskExecution(TaskExecution expectedTaskExecution,
TaskExecution actualTaskExecution) {
assertThat(actualTaskExecution.getExecutionId())
.as("taskExecutionId must be equal")
public static void verifyTaskExecution(TaskExecution expectedTaskExecution, TaskExecution actualTaskExecution) {
assertThat(actualTaskExecution.getExecutionId()).as("taskExecutionId must be equal")
.isEqualTo(expectedTaskExecution.getExecutionId());
if (actualTaskExecution.getStartTime() != null) {
assertThat(actualTaskExecution.getStartTime()).as("startTime must be equal")
@@ -156,31 +150,26 @@ public final class TestVerifierUtils {
.isEqualTo(expectedTaskExecution.getExitMessage());
assertThat(actualTaskExecution.getErrorMessage()).as("errorMessage must be equal")
.isEqualTo(expectedTaskExecution.getErrorMessage());
assertThat(actualTaskExecution.getExternalExecutionId())
.as("externalExecutionId must be equal")
assertThat(actualTaskExecution.getExternalExecutionId()).as("externalExecutionId must be equal")
.isEqualTo(expectedTaskExecution.getExternalExecutionId());
assertThat(actualTaskExecution.getParentExecutionId())
.as("parentExecutionId must be equal")
assertThat(actualTaskExecution.getParentExecutionId()).as("parentExecutionId must be equal")
.isEqualTo(expectedTaskExecution.getParentExecutionId());
if (expectedTaskExecution.getArguments() != null) {
assertThat(actualTaskExecution.getArguments())
.as("arguments should not be null").isNotNull();
assertThat(actualTaskExecution.getArguments()).as("arguments should not be null").isNotNull();
assertThat(actualTaskExecution.getArguments().size())
.as("arguments result set count should match expected count")
.isEqualTo(expectedTaskExecution.getArguments().size());
}
else {
assertThat(actualTaskExecution.getArguments()).as("arguments should be null")
.isNull();
assertThat(actualTaskExecution.getArguments()).as("arguments should be null").isNull();
}
Set<String> args = new HashSet<>();
for (String param : expectedTaskExecution.getArguments()) {
args.add(param);
}
for (String arg : actualTaskExecution.getArguments()) {
assertThat(args.contains(arg)).as("arg must exist in the repository")
.isTrue();
assertThat(args.contains(arg)).as("arg must exist in the repository").isTrue();
}
}