getCommandLineArgs(ExecutionContext executionContext);
-
-}
diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandler.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandler.java
deleted file mode 100644
index f50d09c5..00000000
--- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandler.java
+++ /dev/null
@@ -1,401 +0,0 @@
-/*
- * Copyright 2016-2022 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.partition;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.springframework.batch.core.BatchStatus;
-import org.springframework.batch.core.StepExecution;
-import org.springframework.batch.core.explore.JobExplorer;
-import org.springframework.batch.core.partition.PartitionHandler;
-import org.springframework.batch.core.partition.StepExecutionSplitter;
-import org.springframework.batch.poller.DirectPoller;
-import org.springframework.batch.poller.Poller;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.cloud.deployer.spi.task.TaskLauncher;
-import org.springframework.cloud.task.listener.annotation.BeforeTask;
-import org.springframework.cloud.task.repository.TaskExecution;
-import org.springframework.cloud.task.repository.TaskRepository;
-import org.springframework.context.EnvironmentAware;
-import org.springframework.core.env.Environment;
-import org.springframework.core.io.Resource;
-import org.springframework.core.task.SyncTaskExecutor;
-import org.springframework.core.task.TaskExecutor;
-import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
-import org.springframework.util.Assert;
-import org.springframework.util.CollectionUtils;
-
-/**
- *
- * A {@link PartitionHandler} implementation that delegates to a {@link TaskLauncher} for
- * each of the workers. The id of the worker's StepExecution is passed as an environment
- * variable to the worker. The worker, bootstrapped by the
- * {@link DeployerStepExecutionHandler}, looks up the StepExecution in the JobRepository
- * and executes it. This PartitionHandler polls the JobRepository for the results.
- *
- *
- *
- * If the job fails, the partitions will be re-executed per normal batch rules (steps that
- * are complete should do nothing, failed steps should restart based on their
- * configurations).
- *
- *
- *
- * This PartitionHandler and all of the worker processes must share the same JobRepository
- * data store (aka point the same database).
- *
- *
- * @author Michael Minella
- * @author Glenn Renfro
- */
-public class DeployerPartitionHandler implements PartitionHandler, EnvironmentAware, InitializingBean {
-
- /**
- * ID of Spring Cloud Task job execution.
- */
- public static final String SPRING_CLOUD_TASK_JOB_EXECUTION_ID = "spring.cloud.task.job-execution-id";
-
- /**
- * ID of Spring Cloud Task step execution.
- */
- public static final String SPRING_CLOUD_TASK_STEP_EXECUTION_ID = "spring.cloud.task.step-execution-id";
-
- /**
- * Name of Spring Cloud Task step.
- */
- public static final String SPRING_CLOUD_TASK_STEP_NAME = "spring.cloud.task.step-name";
-
- /**
- * ID of Spring Cloud Task parent execution.
- */
- public static final String SPRING_CLOUD_TASK_PARENT_EXECUTION_ID = "spring.cloud.task.parentExecutionId";
-
- /**
- * ID of the Spring Cloud Task execution.
- */
- public static final String SPRING_CLOUD_TASK_EXECUTION_ID = "spring.cloud.task.executionid";
-
- /**
- * Spring Cloud Task name property.
- */
- public static final String SPRING_CLOUD_TASK_NAME = "spring.cloud.task.name";
-
- private static final long DEFAULT_POLL_INTERVAL = 10000;
-
- private int maxWorkers = -1;
-
- private int gridSize = 1;
-
- private int currentWorkers = 0;
-
- private TaskLauncher taskLauncher;
-
- private JobExplorer jobExplorer;
-
- private TaskExecution taskExecution;
-
- private Resource resource;
-
- private String stepName;
-
- private Log logger = LogFactory.getLog(DeployerPartitionHandler.class);
-
- private long pollInterval = DEFAULT_POLL_INTERVAL;
-
- private long timeout = -1;
-
- private Environment environment;
-
- private Map deploymentProperties;
-
- private EnvironmentVariablesProvider environmentVariablesProvider;
-
- private String applicationName;
-
- private CommandLineArgsProvider commandLineArgsProvider;
-
- private boolean defaultArgsAsEnvironmentVars = false;
-
- private TaskExecutor taskExecutor;
-
- @Autowired
- private TaskRepository taskRepository;
-
- /**
- * Constructor initializing the DeployerPartitionHandler instance.
- * @param taskLauncher The
- * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} used to execute
- * partitioned tasks.
- * @param jobExplorer The {@link JobExplorer} to acquire the status of the job.
- * @param resource The {@link Resource} to the app to be launched.
- * @param stepName The name of the step.
- * @param taskExecutor If task launches should occur asynchronously then provide a
- * {@link ThreadPoolTaskExecutor}. Default is null.
- */
- public DeployerPartitionHandler(org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher,
- JobExplorer jobExplorer, Resource resource, String stepName, TaskRepository taskRepository,
- TaskExecutor taskExecutor) {
- Assert.notNull(taskLauncher, "A taskLauncher is required");
- Assert.notNull(jobExplorer, "A jobExplorer is required");
- Assert.notNull(resource, "A resource is required");
- Assert.hasText(stepName, "A step name is required");
- Assert.notNull(taskRepository, "A TaskRepository is required");
-
- this.taskLauncher = taskLauncher;
- this.jobExplorer = jobExplorer;
- this.resource = resource;
- this.stepName = stepName;
- this.taskRepository = taskRepository;
- this.taskExecutor = taskExecutor;
- }
-
- /**
- * Constructor initializing the DeployerPartitionHandler instance.
- * @param taskLauncher The
- * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} used to execute
- * partitioned tasks.
- * @param jobExplorer The {@link JobExplorer} to acquire the status of the job.
- * @param resource The {@link Resource} to the app to be launched.
- * @param stepName The name of the step.
- */
- public DeployerPartitionHandler(org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher,
- JobExplorer jobExplorer, Resource resource, String stepName, TaskRepository taskRepository) {
- this(taskLauncher, jobExplorer, resource, stepName, taskRepository, new SyncTaskExecutor());
- }
-
- /**
- * Used to provide any environment variables to be set on each worker launched.
- * @param environmentVariablesProvider an {@link EnvironmentVariablesProvider}
- */
- public void setEnvironmentVariablesProvider(EnvironmentVariablesProvider environmentVariablesProvider) {
- this.environmentVariablesProvider = environmentVariablesProvider;
- }
-
- /**
- * If set to true, the default args that are used internally by Spring Cloud Task and
- * Spring Batch are passed as environment variables instead of command line arguments.
- * @param defaultArgsAsEnvironmentVars defaults to false
- */
- public void setDefaultArgsAsEnvironmentVars(boolean defaultArgsAsEnvironmentVars) {
- this.defaultArgsAsEnvironmentVars = defaultArgsAsEnvironmentVars;
- }
-
- /**
- * Used to provide any command line arguements to be passed to each worker launched.
- * @param commandLineArgsProvider {@link CommandLineArgsProvider}
- */
- public void setCommandLineArgsProvider(CommandLineArgsProvider commandLineArgsProvider) {
- this.commandLineArgsProvider = commandLineArgsProvider;
- }
-
- /**
- * The maximum number of workers to be executing at once.
- * @param maxWorkers number of workers. Defaults to -1 (unlimited)
- */
- public void setMaxWorkers(int maxWorkers) {
- Assert.isTrue(maxWorkers != 0, "maxWorkers cannot be 0");
- this.maxWorkers = maxWorkers;
- }
-
- /**
- * Approximate size of the pool of worker JVMs available. May be used by the
- * {@link StepExecutionSplitter} to determine how many partitions to create (at the
- * discretion of the
- * {@link org.springframework.batch.core.partition.support.Partitioner}).
- * @param gridSize size of grid. Defaults to 1
- */
- public void setGridSize(int gridSize) {
- this.gridSize = gridSize;
- }
-
- /**
- * The interval to check the job repository for completed steps.
- * @param pollInterval interval. Defaults to 10 seconds
- */
- public void setPollInterval(long pollInterval) {
- this.pollInterval = pollInterval;
- }
-
- /**
- * Timeout for the master step. This is a timeout for all workers to complete.
- * @param timeout timeout. Defaults to none (-1).
- */
- public void setTimeout(long timeout) {
- this.timeout = timeout;
- }
-
- /**
- * Map of deployment properties to be used by the
- * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher}.
- * @param deploymentProperties properties to be used by the
- * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher}
- */
- public void setDeploymentProperties(Map deploymentProperties) {
- this.deploymentProperties = deploymentProperties;
- }
-
- /**
- * The name of the application to be launched. Useful in environments where
- * application deployments are reused (such as CloudFoundry).
- * @param applicationName The name of the application to be launched
- */
- public void setApplicationName(String applicationName) {
- this.applicationName = applicationName;
- }
-
- @BeforeTask
- public void beforeTask(TaskExecution taskExecution) {
- this.taskExecution = taskExecution;
-
- if (this.commandLineArgsProvider == null) {
- SimpleCommandLineArgsProvider provider = new SimpleCommandLineArgsProvider(taskExecution);
- this.commandLineArgsProvider = provider;
-
- }
- }
-
- @Override
- public Collection handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution)
- throws Exception {
-
- final Set tempCandidates = stepSplitter.split(stepExecution, this.gridSize);
-
- // Following two lines due to https://jira.spring.io/browse/BATCH-2490
- final Set candidates = new HashSet<>(tempCandidates.size());
- candidates.addAll(tempCandidates);
-
- int partitions = candidates.size();
-
- this.logger.debug(String.format("%s partitions were returned", partitions));
-
- final Set executed = new HashSet<>(candidates.size());
-
- if (CollectionUtils.isEmpty(candidates)) {
- return Collections.emptySet();
- }
-
- launchWorkers(candidates, executed);
-
- candidates.removeAll(executed);
-
- return pollReplies(stepExecution, executed, candidates, partitions);
- }
-
- private void launchWorkers(Set candidates, Set executed) {
- TaskLauncherHandler taskLauncherHandler = new TaskLauncherHandler(this.commandLineArgsProvider,
- this.taskRepository, this.defaultArgsAsEnvironmentVars, this.stepName, this.taskExecution,
- this.environmentVariablesProvider, this.resource, this.deploymentProperties, this.taskLauncher,
- this.applicationName);
- for (StepExecution execution : candidates) {
- if (this.currentWorkers < this.maxWorkers || this.maxWorkers < 0) {
- if (this.taskExecutor != null) {
- TaskLauncherHandler taskLauncherThread = new TaskLauncherHandler(this.commandLineArgsProvider,
- this.taskRepository, this.defaultArgsAsEnvironmentVars, this.stepName, this.taskExecution,
- this.environmentVariablesProvider, this.resource, this.deploymentProperties,
- this.taskLauncher, this.applicationName, execution);
- this.taskExecutor.execute(taskLauncherThread);
- }
- else {
- taskLauncherHandler.launchWorker(execution);
- }
- this.currentWorkers++;
- executed.add(execution);
- }
- }
- }
-
- private Collection pollReplies(final StepExecution masterStepExecution,
- final Set executed, final Set candidates, final int size) throws Exception {
-
- final Collection result = new ArrayList<>(executed.size());
-
- Callable> callback = new Callable>() {
- @Override
- public Collection call() throws Exception {
- Set newExecuted = new HashSet<>();
-
- for (StepExecution curStepExecution : executed) {
- if (!result.contains(curStepExecution)) {
- StepExecution partitionStepExecution = DeployerPartitionHandler.this.jobExplorer
- .getStepExecution(masterStepExecution.getJobExecutionId(), curStepExecution.getId());
-
- BatchStatus batchStatus = partitionStepExecution.getStatus();
- if (batchStatus != null && isComplete(batchStatus)) {
- result.add(partitionStepExecution);
- DeployerPartitionHandler.this.currentWorkers--;
-
- if (!candidates.isEmpty()) {
-
- launchWorkers(candidates, newExecuted);
- candidates.removeAll(newExecuted);
- }
- }
- }
- }
-
- executed.addAll(newExecuted);
-
- if (result.size() == size) {
- return result;
- }
- else {
- return null;
- }
- }
- };
-
- Poller> poller = new DirectPoller<>(this.pollInterval);
- Future> resultsFuture = poller.poll(callback);
-
- if (this.timeout >= 0) {
- return resultsFuture.get(this.timeout, TimeUnit.MILLISECONDS);
- }
- else {
- return resultsFuture.get();
- }
- }
-
- private boolean isComplete(BatchStatus status) {
- return status.equals(BatchStatus.COMPLETED) || status.isGreaterThan(BatchStatus.STARTED);
- }
-
- @Override
- public void setEnvironment(Environment environment) {
- this.environment = environment;
- }
-
- @Override
- public void afterPropertiesSet() throws Exception {
- if (this.environmentVariablesProvider == null) {
- this.environmentVariablesProvider = new SimpleEnvironmentVariablesProvider(this.environment);
-
- }
- }
-
-}
diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerStepExecutionHandler.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerStepExecutionHandler.java
deleted file mode 100644
index 56124116..00000000
--- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/DeployerStepExecutionHandler.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright 2016-2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.partition;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.springframework.batch.core.BatchStatus;
-import org.springframework.batch.core.JobInterruptedException;
-import org.springframework.batch.core.Step;
-import org.springframework.batch.core.StepExecution;
-import org.springframework.batch.core.explore.JobExplorer;
-import org.springframework.batch.core.repository.JobRepository;
-import org.springframework.batch.core.step.NoSuchStepException;
-import org.springframework.batch.core.step.StepLocator;
-import org.springframework.batch.integration.partition.BeanFactoryStepLocator;
-import org.springframework.beans.factory.BeanFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.CommandLineRunner;
-import org.springframework.core.env.Environment;
-import org.springframework.util.Assert;
-
-/**
- *
- * A {@link CommandLineRunner} used to execute a {@link Step}. No result is provided
- * directly to the associated {@link DeployerPartitionHandler} as it will obtain the step
- * results directly from the shared job repository.
- *
- *
- *
- * The {@link StepExecution} is rehydrated based on the environment variables provided.
- * Specifically, the following variables are required:
- *
- *
- * - {@link DeployerPartitionHandler#SPRING_CLOUD_TASK_JOB_EXECUTION_ID}: The id of the
- * JobExecution.
- * - {@link DeployerPartitionHandler#SPRING_CLOUD_TASK_STEP_EXECUTION_ID}: The id of the
- * StepExecution.
- * - {@link DeployerPartitionHandler#SPRING_CLOUD_TASK_STEP_NAME}: The id of the bean
- * definition for the Step to execute. The id must be found within the provided
- * {@link BeanFactory}
- *
- *
- * @author Michael Minella
- */
-public class DeployerStepExecutionHandler implements CommandLineRunner {
-
- private JobExplorer jobExplorer;
-
- private JobRepository jobRepository;
-
- private Log logger = LogFactory.getLog(DeployerStepExecutionHandler.class);
-
- @Autowired
- private Environment environment;
-
- private StepLocator stepLocator;
-
- public DeployerStepExecutionHandler(BeanFactory beanFactory, JobExplorer jobExplorer, JobRepository jobRepository) {
- Assert.notNull(beanFactory, "A beanFactory is required");
- Assert.notNull(jobExplorer, "A jobExplorer is required");
- Assert.notNull(jobRepository, "A jobRepository is required");
-
- this.stepLocator = new BeanFactoryStepLocator();
- ((BeanFactoryStepLocator) this.stepLocator).setBeanFactory(beanFactory);
-
- this.jobExplorer = jobExplorer;
- this.jobRepository = jobRepository;
- }
-
- @Override
- public void run(String... args) throws Exception {
-
- validateRequest();
-
- Long jobExecutionId = Long
- .parseLong(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID));
- Long stepExecutionId = Long
- .parseLong(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID));
- StepExecution stepExecution = this.jobExplorer.getStepExecution(jobExecutionId, stepExecutionId);
-
- if (stepExecution == null) {
- throw new NoSuchStepException(
- String.format("No StepExecution could be located for step execution id %s within job execution %s",
- stepExecutionId, jobExecutionId));
- }
-
- String stepName = this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME);
- Step step = this.stepLocator.getStep(stepName);
-
- try {
- this.logger.debug(String.format("Executing step %s with step execution id %s and job execution id %s",
- stepExecution.getStepName(), stepExecutionId, jobExecutionId));
-
- step.execute(stepExecution);
- }
- catch (JobInterruptedException e) {
- stepExecution.setStatus(BatchStatus.STOPPED);
- this.jobRepository.update(stepExecution);
- }
- catch (Throwable e) {
- stepExecution.addFailureException(e);
- stepExecution.setStatus(BatchStatus.FAILED);
- this.jobRepository.update(stepExecution);
- }
- }
-
- private void validateRequest() {
- Assert.isTrue(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID),
- "A job execution id is required");
- Assert.isTrue(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID),
- "A step execution id is required");
- Assert.isTrue(this.environment.containsProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME),
- "A step name is required");
-
- Assert.isTrue(
- this.stepLocator.getStepNames()
- .contains(this.environment.getProperty(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME)),
- "The step requested cannot be found in the provided BeanFactory");
- }
-
-}
diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/EnvironmentVariablesProvider.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/EnvironmentVariablesProvider.java
deleted file mode 100644
index c3cf8c51..00000000
--- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/EnvironmentVariablesProvider.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2016-2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.partition;
-
-import java.util.Map;
-
-import org.springframework.batch.item.ExecutionContext;
-
-/**
- * Strategy interface to allow for advanced configuration of environment variables for
- * each worker in a partitioned job.
- *
- * @author Michael Minella
- * @since 1.0.2
- */
-public interface EnvironmentVariablesProvider {
-
- /**
- * Provides a {@link Map} of Strings to be used as environment variables. This method
- * will be called for each worker step. For example, if there are 5 partitions, this
- * method will be called 5 times.
- * @param executionContext the {@link ExecutionContext} associated with the worker's
- * step
- * @return A {@link Map} of values to be used as environment variables
- */
- Map getEnvironmentVariables(ExecutionContext executionContext);
-
-}
diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/NoOpEnvironmentVariablesProvider.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/NoOpEnvironmentVariablesProvider.java
deleted file mode 100644
index bdc696b3..00000000
--- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/NoOpEnvironmentVariablesProvider.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2016-2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.partition;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.springframework.batch.item.ExecutionContext;
-
-/**
- * A simple no-op implementation of the {@link EnvironmentVariablesProvider}. It returns
- * an empty {@link Map}.
- *
- * @author Michael Minella
- * @since 1.0.2
- */
-public class NoOpEnvironmentVariablesProvider implements EnvironmentVariablesProvider {
-
- /**
- * @param executionContext the {@link ExecutionContext} associated with the worker's
- * step
- * @return an empty {@link Map}
- */
- @Override
- public Map getEnvironmentVariables(ExecutionContext executionContext) {
- return Collections.emptyMap();
- }
-
-}
diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/PassThroughCommandLineArgsProvider.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/PassThroughCommandLineArgsProvider.java
deleted file mode 100644
index 5380ce54..00000000
--- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/PassThroughCommandLineArgsProvider.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2016-2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.partition;
-
-import java.util.List;
-
-import org.springframework.batch.item.ExecutionContext;
-import org.springframework.util.Assert;
-
-/**
- * Returns the {@code List} provided.
- *
- * @author Michael Minella
- * @since 1.1.0
- */
-public class PassThroughCommandLineArgsProvider implements CommandLineArgsProvider {
-
- private final List commandLineArgs;
-
- public PassThroughCommandLineArgsProvider(List commandLineArgs) {
- Assert.notNull(commandLineArgs, "commandLineArgs is required");
-
- this.commandLineArgs = commandLineArgs;
- }
-
- @Override
- public List getCommandLineArgs(ExecutionContext executionContext) {
- return this.commandLineArgs;
- }
-
-}
diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleCommandLineArgsProvider.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleCommandLineArgsProvider.java
deleted file mode 100644
index 83dc8e98..00000000
--- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleCommandLineArgsProvider.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2016-2022 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.partition;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.springframework.batch.item.ExecutionContext;
-import org.springframework.cloud.task.listener.TaskExecutionListener;
-import org.springframework.cloud.task.repository.TaskExecution;
-import org.springframework.util.Assert;
-
-/**
- * Returns any command line arguments used with the {@link TaskExecution} provided
- * appended with any additional arguments configured.
- *
- * @author Michael Minella
- * @author Glenn Renfro
- * @since 1.1.0
- */
-public class SimpleCommandLineArgsProvider implements CommandLineArgsProvider, TaskExecutionListener {
-
- private TaskExecution taskExecution;
-
- private List appendedArgs;
-
- public SimpleCommandLineArgsProvider() {
- }
-
- /**
- * @param taskExecution task execution
- */
- public SimpleCommandLineArgsProvider(TaskExecution taskExecution) {
- Assert.notNull(taskExecution, "A taskExecution is required");
-
- this.taskExecution = taskExecution;
- }
-
- @Override
- public void onTaskStartup(TaskExecution taskExecution) {
- this.taskExecution = taskExecution;
- }
-
- /**
- * Additional command line args to be appended.
- * @param appendedArgs list of arguments
- * @since 1.2
- */
- public void setAppendedArgs(List appendedArgs) {
- this.appendedArgs = appendedArgs;
- }
-
- @Override
- public List getCommandLineArgs(ExecutionContext executionContext) {
-
- int listSize = this.taskExecution.getArguments().size()
- + (this.appendedArgs != null ? this.appendedArgs.size() : 0);
-
- List args = new ArrayList<>(listSize);
-
- args.addAll(this.taskExecution.getArguments());
-
- if (this.appendedArgs != null) {
- args.addAll(this.appendedArgs);
- }
-
- return args;
- }
-
-}
diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleEnvironmentVariablesProvider.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleEnvironmentVariablesProvider.java
deleted file mode 100644
index b5f34b85..00000000
--- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/SimpleEnvironmentVariablesProvider.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright 2016-2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.partition;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.springframework.batch.item.ExecutionContext;
-import org.springframework.core.env.AbstractEnvironment;
-import org.springframework.core.env.Environment;
-import org.springframework.core.env.MapPropertySource;
-import org.springframework.core.env.PropertySource;
-
-/**
- * Copies all existing environment variables as made available in the {@link Environment}
- * only if includeCurrentEnvironment is set to true (default). The
- * environmentProperties option provides the ability to override any specific
- * values on an as needed basis.
- *
- * @author Michael Minella
- * @since 1.0.2
- */
-public class SimpleEnvironmentVariablesProvider implements EnvironmentVariablesProvider {
-
- private Environment environment;
-
- private Map environmentProperties = new HashMap<>(0);
-
- private boolean includeCurrentEnvironment = true;
-
- /**
- * @param environment The {@link Environment} for this context
- */
- public SimpleEnvironmentVariablesProvider(Environment environment) {
- this.environment = environment;
- }
-
- /**
- * @param environmentProperties a {@link Map} of properties used to override any
- * values configured in the current {@link Environment}
- */
- public void setEnvironmentProperties(Map environmentProperties) {
- this.environmentProperties = environmentProperties;
- }
-
- /**
- * Establishes if current environment variables will be included as a part of the
- * provider.
- * @param includeCurrentEnvironment true(default) include local environment
- * properties. False do not include current environment properties.
- */
- public void setIncludeCurrentEnvironment(boolean includeCurrentEnvironment) {
- this.includeCurrentEnvironment = includeCurrentEnvironment;
- }
-
- @Override
- public Map getEnvironmentVariables(ExecutionContext executionContext) {
-
- Map environmentProperties = new HashMap<>(this.environmentProperties.size());
-
- if (this.includeCurrentEnvironment) {
- environmentProperties.putAll(getCurrentEnvironmentProperties());
- }
-
- environmentProperties.putAll(this.environmentProperties);
-
- return environmentProperties;
- }
-
- private Map getCurrentEnvironmentProperties() {
- Map currentEnvironment = new HashMap<>();
-
- Set keys = new HashSet<>();
-
- for (PropertySource> propertySource : ((AbstractEnvironment) this.environment).getPropertySources()) {
- if (propertySource instanceof MapPropertySource) {
- keys.addAll(Arrays.asList(((MapPropertySource) propertySource).getPropertyNames()));
- }
- }
-
- for (String key : keys) {
- currentEnvironment.put(key, this.environment.getProperty(key));
- }
-
- return currentEnvironment;
- }
-
-}
diff --git a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/TaskLauncherHandler.java b/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/TaskLauncherHandler.java
deleted file mode 100644
index 4ec6d08d..00000000
--- a/spring-cloud-task-batch/src/main/java/org/springframework/cloud/task/batch/partition/TaskLauncherHandler.java
+++ /dev/null
@@ -1,236 +0,0 @@
-/*
- * Copyright 2022-2022 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.partition;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.springframework.batch.core.StepExecution;
-import org.springframework.batch.item.ExecutionContext;
-import org.springframework.cloud.deployer.spi.core.AppDefinition;
-import org.springframework.cloud.deployer.spi.core.AppDeploymentRequest;
-import org.springframework.cloud.task.repository.TaskExecution;
-import org.springframework.cloud.task.repository.TaskRepository;
-import org.springframework.core.io.Resource;
-import org.springframework.util.StringUtils;
-
-/**
- * Supports the launching of partitions.
- *
- * @author Glenn Renfro
- */
-public class TaskLauncherHandler implements Runnable {
-
- private CommandLineArgsProvider commandLineArgsProvider;
-
- private TaskRepository taskRepository;
-
- private boolean defaultArgsAsEnvironmentVars;
-
- private String stepName;
-
- private TaskExecution taskExecution;
-
- private EnvironmentVariablesProvider environmentVariablesProvider;
-
- private Resource resource;
-
- private Map deploymentProperties;
-
- private org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher;
-
- private String applicationName;
-
- private StepExecution workerStepExecution;
-
- private Log logger = LogFactory.getLog(TaskLauncherHandler.class);
-
- /**
- * @param commandLineArgsProvider The {@link CommandLineArgsProvider} that provides
- * command line arguments passed to each partition's execution.
- * @param taskRepository The {@link TaskRepository} task repository for launching the
- * partition.
- * @param defaultArgsAsEnvironmentVars - If set to true, the default args that are
- * used internally by Spring Cloud Task and Spring Batch are passed as environment
- * variables instead of command line arguments.
- * @param stepName The name of the step.
- * @param taskExecution The {@link TaskExecution} to be associated with the partition.
- * @param environmentVariablesProvider {@link EnvironmentVariablesProvider} that
- * provides the environmennt variables.
- * @param resource The {@link Resource} to be launched.
- * @param deploymentProperties The {@link Map} containing the deployment properties
- * for the partition.
- * @param taskLauncher
- * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} that is used to
- * launch the partition.
- * @param applicationName The name to be associated with task.
- * @param workerStepExecution The {@link StepExecution} for the paritition.
- */
- public TaskLauncherHandler(CommandLineArgsProvider commandLineArgsProvider, TaskRepository taskRepository,
- boolean defaultArgsAsEnvironmentVars, String stepName, TaskExecution taskExecution,
- EnvironmentVariablesProvider environmentVariablesProvider, Resource resource,
- Map deploymentProperties,
- org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher, String applicationName,
- StepExecution workerStepExecution) {
- this.commandLineArgsProvider = commandLineArgsProvider;
- this.taskRepository = taskRepository;
- this.defaultArgsAsEnvironmentVars = defaultArgsAsEnvironmentVars;
- this.stepName = stepName;
- this.taskExecution = taskExecution;
- this.environmentVariablesProvider = environmentVariablesProvider;
- this.resource = resource;
- this.deploymentProperties = deploymentProperties;
- this.taskLauncher = taskLauncher;
- this.applicationName = applicationName;
- this.workerStepExecution = workerStepExecution;
- }
-
- /**
- * @param commandLineArgsProvider The {@link CommandLineArgsProvider} that provides
- * command line arguments passed to each partition's execution.
- * @param taskRepository The {@link TaskRepository} task repository for launching the
- * partition.
- * @param defaultArgsAsEnvironmentVars - If set to true, the default args that are
- * used internally by Spring Cloud Task and Spring Batch are passed as environment
- * variables instead of command line arguments.
- * @param stepName The name of the step.
- * @param taskExecution The {@link TaskExecution} to be associated with the partition.
- * @param environmentVariablesProvider {@link EnvironmentVariablesProvider} that
- * provides the environmennt variables.
- * @param resource The {@link Resource} to be launched.
- * @param deploymentProperties The {@link Map} containing the deployment properties
- * for the partition.
- * @param taskLauncher
- * {@link org.springframework.cloud.deployer.spi.task.TaskLauncher} that is used to
- * launch the partition.
- * @param applicationName The name to be associated with task.
- */
- public TaskLauncherHandler(CommandLineArgsProvider commandLineArgsProvider, TaskRepository taskRepository,
- boolean defaultArgsAsEnvironmentVars, String stepName, TaskExecution taskExecution,
- EnvironmentVariablesProvider environmentVariablesProvider, Resource resource,
- Map deploymentProperties,
- org.springframework.cloud.deployer.spi.task.TaskLauncher taskLauncher, String applicationName) {
- this.commandLineArgsProvider = commandLineArgsProvider;
- this.taskRepository = taskRepository;
- this.defaultArgsAsEnvironmentVars = defaultArgsAsEnvironmentVars;
- this.stepName = stepName;
- this.taskExecution = taskExecution;
- this.environmentVariablesProvider = environmentVariablesProvider;
- this.resource = resource;
- this.deploymentProperties = deploymentProperties;
- this.taskLauncher = taskLauncher;
- this.applicationName = applicationName;
- }
-
- @Override
- public void run() {
- launchWorker(this.workerStepExecution);
- }
-
- /**
- * Launches the partition for the StepExecution.
- * @param workerStepExecution The {@link StepExecution}
- */
- public void launchWorker(StepExecution workerStepExecution) {
- List arguments = new ArrayList<>();
-
- ExecutionContext copyContext = new ExecutionContext(workerStepExecution.getExecutionContext());
-
- arguments.addAll(this.commandLineArgsProvider.getCommandLineArgs(copyContext));
-
- TaskExecution partitionTaskExecution = null;
-
- if (this.taskRepository != null) {
- partitionTaskExecution = this.taskRepository.createTaskExecution();
- }
- else {
- logger.warn("TaskRepository was not set so external execution id will not be recorded.");
- }
-
- if (!this.defaultArgsAsEnvironmentVars) {
- arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID,
- String.valueOf(workerStepExecution.getJobExecution().getId())));
- arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID,
- String.valueOf(workerStepExecution.getId())));
- arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, this.stepName));
- arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_NAME,
- String.format("%s_%s_%s", this.taskExecution.getTaskName(),
- workerStepExecution.getJobExecution().getJobInstance().getJobName(),
- workerStepExecution.getStepName())));
- arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID,
- String.valueOf(this.taskExecution.getExecutionId())));
-
- if (partitionTaskExecution != null) {
- arguments.add(formatArgument(DeployerPartitionHandler.SPRING_CLOUD_TASK_EXECUTION_ID,
- String.valueOf(partitionTaskExecution.getExecutionId())));
- }
- }
-
- copyContext = new ExecutionContext(workerStepExecution.getExecutionContext());
-
- Map environmentVariables = this.environmentVariablesProvider
- .getEnvironmentVariables(copyContext);
-
- if (this.defaultArgsAsEnvironmentVars) {
- environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID,
- String.valueOf(workerStepExecution.getJobExecution().getId()));
- environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID,
- String.valueOf(workerStepExecution.getId()));
- environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, this.stepName);
- environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_NAME,
- String.format("%s_%s_%s", this.taskExecution.getTaskName(),
- workerStepExecution.getJobExecution().getJobInstance().getJobName(),
- workerStepExecution.getStepName()));
- environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID,
- String.valueOf(this.taskExecution.getExecutionId()));
- environmentVariables.put(DeployerPartitionHandler.SPRING_CLOUD_TASK_EXECUTION_ID,
- String.valueOf(partitionTaskExecution.getExecutionId()));
- }
-
- AppDefinition definition = new AppDefinition(resolveApplicationName(), environmentVariables);
-
- AppDeploymentRequest request = new AppDeploymentRequest(definition, this.resource, this.deploymentProperties,
- arguments);
-
- if (logger.isDebugEnabled()) {
- logger.debug("Requesting the launch of the following application: " + request);
- }
- String externalExecutionId = this.taskLauncher.launch(request);
-
- if (this.taskRepository != null) {
- this.taskRepository.updateExternalExecutionId(partitionTaskExecution.getExecutionId(), externalExecutionId);
- }
- }
-
- private String formatArgument(String key, String value) {
- return String.format("--%s=%s", key, value);
- }
-
- private String resolveApplicationName() {
- if (StringUtils.hasText(this.applicationName)) {
- return this.applicationName;
- }
- else {
- return this.taskExecution.getTaskName();
- }
- }
-
-}
diff --git a/spring-cloud-task-batch/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-task-batch/src/main/resources/META-INF/additional-spring-configuration-metadata.json
deleted file mode 100644
index 246cffc2..00000000
--- a/spring-cloud-task-batch/src/main/resources/META-INF/additional-spring-configuration-metadata.json
+++ /dev/null
@@ -1,64 +0,0 @@
-{
- "properties": [
- {
- "defaultValue": true,
- "name": "spring.cloud.task.batch.listener.enabled",
- "description": "This property is used to determine if a task will be linked to the batch jobs that are run.",
- "type": "java.lang.Boolean"
- },
- {
- "defaultValue": false,
- "name": "spring.cloud.task.batch.fail-on-job-failure",
- "description": "This property is used to determine if a task app should return with a non zero exit code if a batch job fails.",
- "type": "java.lang.Boolean"
- },
- {
- "defaultValue": true,
- "name": "spring.cloud.task.batch.events.enabled",
- "description": "This property is used to determine if a task should listen for batch events.",
- "type": "java.lang.Boolean"
- },
- {
- "defaultValue": true,
- "name": "spring.cloud.task.batch.events.chunk.enabled",
- "description": "This property is used to determine if a task should listen for batch chunk events.",
- "type": "java.lang.Boolean"
- },
- {
- "defaultValue": true,
- "name": "spring.cloud.task.batch.events.item-process.enabled",
- "description": "This property is used to determine if a task should listen for batch item processed events.",
- "type": "java.lang.Boolean"
- },
- {
- "defaultValue": true,
- "name": "spring.cloud.task.batch.events.item-read.enabled",
- "description": "This property is used to determine if a task should listen for batch item read events.",
- "type": "java.lang.Boolean"
- },
- {
- "defaultValue": true,
- "name": "spring.cloud.task.batch.events.item-write.enabled",
- "description": "This property is used to determine if a task should listen for batch item write events.",
- "type": "java.lang.Boolean"
- },
- {
- "defaultValue": true,
- "name": "spring.cloud.task.batch.events.job-execution.enabled",
- "description": "This property is used to determine if a task should listen for batch job execution events.",
- "type": "java.lang.Boolean"
- },
- {
- "defaultValue": true,
- "name": "spring.cloud.task.batch.events.skip.enabled",
- "description": "This property is used to determine if a task should listen for batch skip events.",
- "type": "java.lang.Boolean"
- },
- {
- "defaultValue": true,
- "name": "spring.cloud.task.batch.events.step-execution.enabled",
- "description": "This property is used to determine if a task should listen for batch step execution events.",
- "type": "java.lang.Boolean"
- }
- ]
-}
diff --git a/spring-cloud-task-batch/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/spring-cloud-task-batch/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
deleted file mode 100644
index 66fb7f99..00000000
--- a/spring-cloud-task-batch/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
+++ /dev/null
@@ -1,2 +0,0 @@
-org.springframework.cloud.task.batch.configuration.TaskBatchAutoConfiguration
-org.springframework.cloud.task.batch.configuration.TaskJobLauncherAutoConfiguration
diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskBatchTest.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskBatchTest.java
deleted file mode 100644
index 3186ae7f..00000000
--- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskBatchTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright 2018-2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.configuration;
-
-import java.lang.annotation.Documented;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
-
-/**
- * Contains the common configurations to run a unit test for the task batch features of
- * SCT.
- *
- * @author Glenn Renfro
- */
-@Target(ElementType.TYPE)
-@Retention(RetentionPolicy.RUNTIME)
-@Documented
-@ImportAutoConfiguration
-public @interface TaskBatchTest {
-
-}
diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherAutoConfigurationTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherAutoConfigurationTests.java
deleted file mode 100644
index 91d97d62..00000000
--- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/configuration/TaskJobLauncherAutoConfigurationTests.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright 2018-2022 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.configuration;
-
-import org.junit.jupiter.api.Test;
-
-import org.springframework.boot.autoconfigure.AutoConfigurations;
-import org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration;
-import org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner;
-import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
-import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration;
-import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
-import org.springframework.boot.test.context.runner.ApplicationContextRunner;
-import org.springframework.cloud.task.batch.handler.TaskJobLauncherApplicationRunner;
-import org.springframework.cloud.task.batch.listener.TaskBatchExecutionListenerTests;
-import org.springframework.test.util.ReflectionTestUtils;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * @author Glenn Renfro
- */
-public class TaskJobLauncherAutoConfigurationTests {
-
- private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
- .withConfiguration(
- AutoConfigurations.of(BatchAutoConfiguration.class, TaskJobLauncherAutoConfiguration.class))
- .withUserConfiguration(TaskBatchExecutionListenerTests.JobConfiguration.class,
- PropertyPlaceholderAutoConfiguration.class, EmbeddedDataSourceConfiguration.class);
-
- @Test
- public void testAutoBuiltDataSourceWithTaskJobLauncherCLR() {
- this.contextRunner.withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true").run(context -> {
- assertThat(context).hasSingleBean(TaskJobLauncherApplicationRunner.class);
- assertThat(context.getBean(TaskJobLauncherApplicationRunner.class).getOrder()).isEqualTo(0);
- });
- }
-
- @Test
- public void testAutoBuiltDataSourceWithTaskJobLauncherCLROrder() {
- this.contextRunner.withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true",
- "spring.cloud.task.batch.applicationRunnerOrder=100").run(context -> {
- assertThat(context.getBean(TaskJobLauncherApplicationRunner.class).getOrder()).isEqualTo(100);
- });
- }
-
- @Test
- public void testAutoBuiltDataSourceWithBatchJobNames() {
- this.contextRunner.withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true",
- "spring.batch.job.name=job1", "spring.cloud.task.batch.jobName=foobar").run(context -> {
- validateJobNames(context, "job1");
- });
- }
-
- @Test
- public void testAutoBuiltDataSourceWithTaskBatchJobNames() {
- this.contextRunner.withPropertyValues("spring.cloud.task.batch.fail-on-job-failure=true",
- "spring.cloud.task.batch.jobNames=job1,job2").run(context -> {
- validateJobNames(context, "job1,job2");
- });
- }
-
- private void validateJobNames(AssertableApplicationContext context, String jobNames) throws Exception {
- JobLauncherApplicationRunner jobLauncherApplicationRunner = context
- .getBean(TaskJobLauncherApplicationRunner.class);
-
- Object names = ReflectionTestUtils.getField(jobLauncherApplicationRunner, "jobName");
- assertThat(names).isEqualTo(jobNames);
- }
-
- @Test
- public void testAutoBuiltDataSourceWithTaskJobLauncherCLRDisabled() {
- this.contextRunner.run(context -> {
- assertThat(context).hasSingleBean(JobLauncherApplicationRunner.class);
- assertThat(context).doesNotHaveBean(TaskJobLauncherApplicationRunner.class);
- });
- }
-
-}
diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerCoreTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerCoreTests.java
deleted file mode 100644
index 037195a2..00000000
--- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerCoreTests.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * Copyright 2018-2022 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.handler;
-
-import java.util.Arrays;
-import java.util.List;
-
-import javax.sql.DataSource;
-
-import org.junit.jupiter.api.Test;
-
-import org.springframework.batch.core.Job;
-import org.springframework.batch.core.JobExecutionException;
-import org.springframework.batch.core.JobInstance;
-import org.springframework.batch.core.JobParameters;
-import org.springframework.batch.core.JobParametersBuilder;
-import org.springframework.batch.core.Step;
-import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.explore.JobExplorer;
-import org.springframework.batch.core.job.builder.JobBuilder;
-import org.springframework.batch.core.job.builder.SimpleJobBuilder;
-import org.springframework.batch.core.launch.JobLauncher;
-import org.springframework.batch.core.launch.support.RunIdIncrementer;
-import org.springframework.batch.core.repository.JobRepository;
-import org.springframework.batch.core.repository.JobRestartException;
-import org.springframework.batch.core.step.builder.StepBuilder;
-import org.springframework.batch.core.step.tasklet.Tasklet;
-import org.springframework.boot.autoconfigure.AutoConfigurations;
-import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
-import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
-import org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration;
-import org.springframework.boot.jdbc.init.DataSourceScriptDatabaseInitializer;
-import org.springframework.boot.sql.init.DatabaseInitializationSettings;
-import org.springframework.boot.test.context.runner.ApplicationContextRunner;
-import org.springframework.cloud.task.batch.configuration.TaskBatchProperties;
-import org.springframework.cloud.task.listener.TaskException;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.transaction.PlatformTransactionManager;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.assertj.core.api.Assertions.fail;
-
-/**
- * @author Glenn Renfro
- */
-public class TaskJobLauncherApplicationRunnerCoreTests {
-
- private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
- .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class,
- TransactionAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class))
- .withUserConfiguration(BatchConfiguration.class);
-
- @Test
- void basicExecution() {
- this.contextRunner.run((context) -> {
- JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context);
- jobLauncherContext.executeJob(new JobParameters());
- assertThat(jobLauncherContext.jobInstances()).hasSize(1);
- jobLauncherContext.executeJob(new JobParametersBuilder().addLong("id", 1L).toJobParameters());
- assertThat(jobLauncherContext.jobInstances()).hasSize(2);
- });
- }
-
- @Test
- void incrementExistingExecution() {
- this.contextRunner.run((context) -> {
- JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context);
- Job job = jobLauncherContext.configureJob().incrementer(new RunIdIncrementer()).build();
- jobLauncherContext.runner.execute(job, new JobParameters());
- jobLauncherContext.runner.execute(job, new JobParameters());
- assertThat(jobLauncherContext.jobInstances()).hasSize(2);
- });
- }
-
- @Test
- void runDifferentInstances() {
- this.contextRunner.run((context) -> {
- PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class);
- JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context);
- Job job = jobLauncherContext.jobBuilder()
- .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet(), transactionManager).build())
- .build();
- // start a job instance
- JobParameters jobParameters = new JobParametersBuilder().addString("name", "foo").toJobParameters();
- runFailedJob(jobLauncherContext, job, jobParameters);
- assertThat(jobLauncherContext.jobInstances()).hasSize(1);
- // start a different job instance
- JobParameters otherJobParameters = new JobParametersBuilder().addString("name", "bar").toJobParameters();
- runFailedJob(jobLauncherContext, job, otherJobParameters);
-
- assertThat(jobLauncherContext.jobInstances()).hasSize(2);
- });
- }
-
- @Test
- void retryFailedExecutionOnNonRestartableJob() {
- this.contextRunner.run((context) -> {
- PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class);
- JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context);
- Job job = jobLauncherContext.jobBuilder().preventRestart()
- .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet(), transactionManager).build())
- .incrementer(new RunIdIncrementer()).build();
- runFailedJob(jobLauncherContext, job, new JobParameters());
- runFailedJob(jobLauncherContext, job, new JobParameters());
- // A failed job that is not restartable does not re-use the job params of
- // the last execution, but creates a new job instance when running it again.
- assertThat(jobLauncherContext.jobInstances()).hasSize(2);
- assertThatExceptionOfType(JobRestartException.class).isThrownBy(() -> {
- // try to re-run a failed execution
- jobLauncherContext.runner.execute(job,
- new JobParametersBuilder().addLong("run.id", 1L).toJobParameters());
- fail("expected JobRestartException");
- }).withMessageContaining("JobInstance already exists and is not restartable");
- });
- }
-
- @Test
- void retryFailedExecutionWithNonIdentifyingParameters() {
- this.contextRunner.run((context) -> {
- PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class);
- JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context);
- Job job = jobLauncherContext.jobBuilder()
- .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet(), transactionManager).build())
- .incrementer(new RunIdIncrementer()).build();
- JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false).addLong("foo", 2L, false)
- .toJobParameters();
- runFailedJob(jobLauncherContext, job, jobParameters);
- assertThat(jobLauncherContext.jobInstances()).hasSize(1);
- // try to re-run a failed execution with non identifying parameters
- runFailedJob(jobLauncherContext, job,
- new JobParametersBuilder(jobParameters).addLong("run.id", 1L).toJobParameters());
- assertThat(jobLauncherContext.jobInstances()).hasSize(1);
- });
- }
-
- private Tasklet throwingTasklet() {
- return (contribution, chunkContext) -> {
- throw new RuntimeException("Planned");
- };
- }
-
- private void runFailedJob(JobLauncherApplicationRunnerContext jobLauncherContext, Job job,
- JobParameters jobParameters) throws Exception {
- boolean isExceptionThrown = false;
- try {
- jobLauncherContext.runner.execute(job, jobParameters);
- }
- catch (TaskException taskException) {
- isExceptionThrown = true;
- }
- assertThat(isExceptionThrown).isTrue();
- }
-
- static class JobLauncherApplicationRunnerContext {
-
- private final TaskJobLauncherApplicationRunner runner;
-
- private final JobExplorer jobExplorer;
-
- private final JobBuilder jobBuilder;
-
- private final Job job;
-
- private final StepBuilder stepBuilder;
-
- private final Step step;
-
- JobLauncherApplicationRunnerContext(ApplicationContext context) {
- JobLauncher jobLauncher = context.getBean(JobLauncher.class);
- JobRepository jobRepository = context.getBean(JobRepository.class);
- PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class);
- this.stepBuilder = new StepBuilder("step", jobRepository);
- this.step = this.stepBuilder.tasklet((contribution, chunkContext) -> null, transactionManager).build();
- this.jobBuilder = new JobBuilder("job", jobRepository);
- this.job = this.jobBuilder.start(this.step).build();
- this.jobExplorer = context.getBean(JobExplorer.class);
- this.runner = new TaskJobLauncherApplicationRunner(jobLauncher, this.jobExplorer, jobRepository,
- new TaskBatchProperties());
- }
-
- List jobInstances() {
- return this.jobExplorer.getJobInstances("job", 0, 100);
- }
-
- void executeJob(JobParameters jobParameters) throws JobExecutionException {
- this.runner.execute(this.job, jobParameters);
- }
-
- JobBuilder jobBuilder() {
- return this.jobBuilder;
- }
-
- StepBuilder stepBuilder() {
- return this.stepBuilder;
- }
-
- SimpleJobBuilder configureJob() {
- return this.jobBuilder.start(this.step);
- }
-
- }
-
- @EnableBatchProcessing
- @Configuration(proxyBeanMethods = false)
- static class BatchConfiguration {
-
- private final DataSource dataSource;
-
- protected BatchConfiguration(DataSource dataSource) {
- this.dataSource = dataSource;
- }
-
- @Bean
- DataSourceScriptDatabaseInitializer batchDataSourceInitializer() {
- DatabaseInitializationSettings settings = new DatabaseInitializationSettings();
- settings.setSchemaLocations(Arrays.asList("classpath:org/springframework/batch/core/schema-h2.sql"));
- return new DataSourceScriptDatabaseInitializer(this.dataSource, settings);
- }
-
- }
-
-}
diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerTests.java
deleted file mode 100644
index ed5ac327..00000000
--- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/handler/TaskJobLauncherApplicationRunnerTests.java
+++ /dev/null
@@ -1,283 +0,0 @@
-/*
- * Copyright 2018-2023 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.handler;
-
-import java.util.Arrays;
-import java.util.Set;
-
-import javax.sql.DataSource;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.function.Executable;
-
-import org.springframework.batch.core.Job;
-import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.explore.JobExplorer;
-import org.springframework.batch.core.job.builder.JobBuilder;
-import org.springframework.batch.core.repository.JobRepository;
-import org.springframework.batch.core.step.builder.StepBuilder;
-import org.springframework.batch.repeat.RepeatStatus;
-import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
-import org.springframework.beans.factory.NoSuchBeanDefinitionException;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
-import org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration;
-import org.springframework.boot.autoconfigure.batch.BatchProperties;
-import org.springframework.boot.autoconfigure.batch.JobExecutionEvent;
-import org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner;
-import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
-import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration;
-import org.springframework.boot.jdbc.init.DataSourceScriptDatabaseInitializer;
-import org.springframework.boot.sql.init.DatabaseInitializationSettings;
-import org.springframework.cloud.task.batch.configuration.TaskBatchAutoConfiguration;
-import org.springframework.cloud.task.batch.configuration.TaskBatchTest;
-import org.springframework.cloud.task.batch.configuration.TaskJobLauncherAutoConfiguration;
-import org.springframework.cloud.task.configuration.EnableTask;
-import org.springframework.cloud.task.configuration.SimpleTaskAutoConfiguration;
-import org.springframework.cloud.task.configuration.SingleTaskConfiguration;
-import org.springframework.cloud.task.repository.TaskExecution;
-import org.springframework.cloud.task.repository.TaskExplorer;
-import org.springframework.context.ApplicationListener;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Import;
-import org.springframework.data.domain.Page;
-import org.springframework.data.domain.PageRequest;
-import org.springframework.stereotype.Component;
-import org.springframework.transaction.PlatformTransactionManager;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-
-/**
- * @author Glenn Renfro
- */
-public class TaskJobLauncherApplicationRunnerTests {
-
- private static final String DEFAULT_ERROR_MESSAGE = "The following Jobs have failed: \n"
- + "Job jobA failed during execution for job instance id 1 with jobExecutionId of 1 \n";
-
- private ConfigurableApplicationContext applicationContext;
-
- @AfterEach
- public void tearDown() {
- if (this.applicationContext != null && this.applicationContext.isActive()) {
- this.applicationContext.close();
- }
- }
-
- @Test
- public void testTaskJobLauncherCLRSuccessFail() {
- String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true" };
- validateForFail(DEFAULT_ERROR_MESSAGE, TaskJobLauncherApplicationRunnerTests.JobWithFailureConfiguration.class,
- enabledArgs);
- }
-
- /**
- * Verifies that the task will return an exit code other than zero if the job fails
- * with the EnableTask annotation.
- */
- @Test
- public void testTaskJobLauncherCLRSuccessFailWithAnnotation() {
- String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true" };
- validateForFail(DEFAULT_ERROR_MESSAGE,
- TaskJobLauncherApplicationRunnerTests.JobWithFailureAnnotatedConfiguration.class, enabledArgs);
- }
-
- @Test
- public void testTaskJobLauncherCLRSuccessFailWithTaskExecutor() {
- String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true",
- "--spring.cloud.task.batch.failOnJobFailurePollInterval=500" };
- validateForFail(DEFAULT_ERROR_MESSAGE,
- TaskJobLauncherApplicationRunnerTests.JobWithFailureTaskExecutorConfiguration.class, enabledArgs);
- }
-
- @Test
- public void testNoTaskJobLauncher() {
- String[] enabledArgs = new String[] { "--spring.cloud.task.batch.failOnJobFailure=true",
- "--spring.cloud.task.batch.failOnJobFailurePollInterval=500", "--spring.batch.job.enabled=false" };
- this.applicationContext = SpringApplication.run(
- new Class[] { TaskJobLauncherApplicationRunnerTests.JobWithFailureConfiguration.class }, enabledArgs);
- JobExplorer jobExplorer = this.applicationContext.getBean(JobExplorer.class);
- assertThat(jobExplorer.getJobNames().size()).isEqualTo(0);
- }
-
- @Test
- public void testTaskJobLauncherPickOneJob() {
- String[] enabledArgs = new String[] { "--spring.cloud.task.batch.fail-on-job-failure=true",
- "--spring.cloud.task.batch.jobNames=jobSucceed" };
- boolean isExceptionThrown = false;
- try {
- this.applicationContext = SpringApplication.run(
- new Class[] { TaskJobLauncherApplicationRunnerTests.JobWithFailureConfiguration.class },
- enabledArgs);
- }
- catch (IllegalStateException exception) {
- isExceptionThrown = true;
- }
- assertThat(isExceptionThrown).isFalse();
- validateContext();
- }
-
- @Test
- public void testApplicationRunnerSetToFalse() {
- String[] enabledArgs = new String[] {};
- this.applicationContext = SpringApplication
- .run(new Class[] { TaskJobLauncherApplicationRunnerTests.JobConfiguration.class }, enabledArgs);
- validateContext();
- assertThat(this.applicationContext.getBean(JobLauncherApplicationRunner.class)).isNotNull();
-
- Executable executable = () -> this.applicationContext.getBean(TaskJobLauncherApplicationRunner.class);
-
- assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(executable::execute)
- .withMessage("No qualifying bean of type "
- + "'org.springframework.cloud.task.batch.handler.TaskJobLauncherApplicationRunner' available");
- validateContext();
- }
-
- private void validateContext() {
- TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class);
-
- Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1));
-
- Set jobExecutionIds = taskExplorer
- .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId());
-
- assertThat(jobExecutionIds.size()).isEqualTo(1);
- assertThat(taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()).getExecutionId()).isEqualTo(1);
-
- JobExecutionEventListener listener = this.applicationContext.getBean(JobExecutionEventListener.class);
- assertThat(listener.getEventCounter()).isEqualTo(1);
- }
-
- private void validateForFail(String errorMessage, Class> clazz, String[] enabledArgs) {
- Executable executable = () -> this.applicationContext = SpringApplication
- .run(new Class[] { clazz, PropertyPlaceholderAutoConfiguration.class }, enabledArgs);
-
- assertThatExceptionOfType(IllegalStateException.class).isThrownBy(executable::execute).havingCause()
- .withMessage(errorMessage);
- }
-
- @Component
- private static class JobExecutionEventListener implements ApplicationListener {
-
- private int eventCounter = 0;
-
- @Override
- public void onApplicationEvent(JobExecutionEvent event) {
- eventCounter++;
- }
-
- public int getEventCounter() {
- return eventCounter;
- }
-
- }
-
- @TaskBatchTest
- @Import({ EmbeddedDataSourceConfiguration.class, JobExecutionEventListener.class })
- @EnableTask
- public static class JobConfiguration {
-
- @Bean
- public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
- return new JobBuilder("job", jobRepository)
- .start(new StepBuilder("step1", jobRepository).tasklet((contribution, chunkContext) -> {
- System.out.println("Executed");
- return RepeatStatus.FINISHED;
- }, transactionManager).build()).build();
- }
-
- @Bean
- public PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- }
-
- @Configuration(proxyBeanMethods = false)
- @Import(JobExecutionEventListener.class)
- public static class TransactionManagerTestConfiguration {
-
- @Bean
- public PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- @Bean
- public BatchProperties batchProperties() {
- return new BatchProperties();
- }
-
- @Bean
- DataSourceScriptDatabaseInitializer batchDataSourceInitializer(DataSource dataSource) {
- DatabaseInitializationSettings settings = new DatabaseInitializationSettings();
- settings.setSchemaLocations(Arrays.asList("classpath:org/springframework/batch/core/schema-h2.sql"));
- return new DataSourceScriptDatabaseInitializer(dataSource, settings);
- }
-
- }
-
- @EnableBatchProcessing
- @ImportAutoConfiguration({ PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class,
- TaskBatchAutoConfiguration.class, TaskJobLauncherAutoConfiguration.class, SingleTaskConfiguration.class,
- SimpleTaskAutoConfiguration.class, TransactionManagerTestConfiguration.class })
- @Import(EmbeddedDataSourceConfiguration.class)
- @EnableTask
- public static class JobWithFailureConfiguration {
-
- @Autowired
- private JobRepository jobRepository;
-
- @Autowired
- private PlatformTransactionManager transactionManager;
-
- @Bean
- public Job jobFail() {
- return new JobBuilder("jobA", this.jobRepository)
- .start(new StepBuilder("step1", this.jobRepository).tasklet((contribution, chunkContext) -> {
- System.out.println("Executed");
- throw new IllegalStateException("WHOOPS");
- }, transactionManager).build()).build();
- }
-
- @Bean
- public Job jobFun() {
- return new JobBuilder("jobSucceed", this.jobRepository)
- .start(new StepBuilder("step1Succeed", this.jobRepository).tasklet((contribution, chunkContext) -> {
- System.out.println("Executed");
- return RepeatStatus.FINISHED;
- }, transactionManager).build()).build();
- }
-
- }
-
- @EnableTask
- public static class JobWithFailureAnnotatedConfiguration extends JobWithFailureConfiguration {
-
- }
-
- @Import(JobWithFailureConfiguration.class)
- @Configuration
- public static class JobWithFailureTaskExecutorConfiguration {
-
- }
-
-}
diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/PrefixTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/PrefixTests.java
deleted file mode 100644
index 190410c3..00000000
--- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/PrefixTests.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright 2018-2022 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.listener;
-
-import java.util.Set;
-
-import javax.sql.DataSource;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.batch.core.Job;
-import org.springframework.batch.core.job.builder.JobBuilder;
-import org.springframework.batch.core.repository.JobRepository;
-import org.springframework.batch.core.step.builder.StepBuilder;
-import org.springframework.batch.repeat.RepeatStatus;
-import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.AutoConfiguration;
-import org.springframework.cloud.task.batch.configuration.TaskBatchTest;
-import org.springframework.cloud.task.configuration.EnableTask;
-import org.springframework.cloud.task.repository.TaskExplorer;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
-import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
-import org.springframework.transaction.PlatformTransactionManager;
-
-import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
-
-/**
- * @author Glenn Renfro
- */
-public class PrefixTests {
-
- private ConfigurableApplicationContext applicationContext;
-
- @AfterEach
- public void tearDown() {
- if (this.applicationContext != null && this.applicationContext.isActive()) {
- this.applicationContext.close();
- }
- }
-
- @Test
- public void testPrefix() {
- this.applicationContext = SpringApplication.run(JobConfiguration.class, "--spring.cloud.task.tablePrefix=FOO_");
-
- TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class);
-
- Set jobIds = taskExplorer.getJobExecutionIdsByTaskExecutionId(1);
- assertThat(jobIds.size()).isEqualTo(1);
- assertThat(jobIds.contains(1L));
- }
-
- @AutoConfiguration
- @TaskBatchTest
- @EnableTask
- public static class JobConfiguration {
-
- @Bean
- public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
- return new JobBuilder("job", jobRepository)
- .start(new StepBuilder("step1", jobRepository).tasklet((contribution, chunkContext) -> {
- System.out.println("Executed");
- return RepeatStatus.FINISHED;
- }, transactionManager).build()).build();
- }
-
- @Bean
- public DataSource dataSource() {
- return new EmbeddedDatabaseBuilder().addScript("classpath:schema-h2.sql").setType(EmbeddedDatabaseType.H2)
- .build();
- }
-
- @Bean
- PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- }
-
-}
diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/PrimaryKeyTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/PrimaryKeyTests.java
deleted file mode 100644
index 05d67e12..00000000
--- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/PrimaryKeyTests.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright 2022-2022 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.listener;
-
-import java.util.Set;
-
-import javax.sql.DataSource;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.batch.core.Job;
-import org.springframework.batch.core.job.builder.JobBuilder;
-import org.springframework.batch.core.repository.JobRepository;
-import org.springframework.batch.core.step.builder.StepBuilder;
-import org.springframework.batch.repeat.RepeatStatus;
-import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
-import org.springframework.boot.SpringApplication;
-import org.springframework.cloud.task.batch.configuration.TaskBatchTest;
-import org.springframework.cloud.task.configuration.EnableTask;
-import org.springframework.cloud.task.repository.TaskExplorer;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
-import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
-import org.springframework.transaction.PlatformTransactionManager;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * @author Henning Pöttker
- */
-class PrimaryKeyTests {
-
- private ConfigurableApplicationContext applicationContext;
-
- @AfterEach
- void tearDown() {
- if (this.applicationContext != null && this.applicationContext.isActive()) {
- this.applicationContext.close();
- }
- }
-
- @Test
- void testSchemaWithPrimaryKeys() {
- this.applicationContext = SpringApplication.run(JobConfiguration.class);
-
- TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class);
-
- Set jobIds = taskExplorer.getJobExecutionIdsByTaskExecutionId(1);
- assertThat(jobIds).containsExactly(1L);
- }
-
- @Configuration(proxyBeanMethods = false)
- @TaskBatchTest
- @EnableTask
- static class JobConfiguration {
-
- @Bean
- Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
- return new JobBuilder("job", jobRepository)
- .start(new StepBuilder("step1", jobRepository).tasklet((contribution, chunkContext) -> {
- System.out.println("Executed");
- return RepeatStatus.FINISHED;
- }, transactionManager).build()).build();
- }
-
- @Bean
- DataSource dataSource() {
- return new EmbeddedDatabaseBuilder().addScript("classpath:schema-with-primary-keys-h2.sql")
- .setType(EmbeddedDatabaseType.H2).build();
- }
-
- @Bean
- PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- }
-
-}
diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/TaskBatchExecutionListenerTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/TaskBatchExecutionListenerTests.java
deleted file mode 100644
index 0b7b8c40..00000000
--- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/listener/TaskBatchExecutionListenerTests.java
+++ /dev/null
@@ -1,435 +0,0 @@
-/*
- * Copyright 2016-2022 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.listener;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import javax.sql.DataSource;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.Test;
-
-import org.springframework.batch.core.Job;
-import org.springframework.batch.core.StepContribution;
-import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.job.SimpleJob;
-import org.springframework.batch.core.job.builder.JobBuilder;
-import org.springframework.batch.core.repository.JobRepository;
-import org.springframework.batch.core.scope.context.ChunkContext;
-import org.springframework.batch.core.step.builder.StepBuilder;
-import org.springframework.batch.core.step.tasklet.Tasklet;
-import org.springframework.batch.repeat.RepeatStatus;
-import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
-import org.springframework.beans.factory.FactoryBean;
-import org.springframework.beans.factory.NoSuchBeanDefinitionException;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration;
-import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
-import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration;
-import org.springframework.cloud.task.batch.configuration.TaskBatchAutoConfiguration;
-import org.springframework.cloud.task.batch.configuration.TaskBatchExecutionListenerBeanPostProcessor;
-import org.springframework.cloud.task.batch.configuration.TaskBatchTest;
-import org.springframework.cloud.task.configuration.DefaultTaskConfigurer;
-import org.springframework.cloud.task.configuration.EnableTask;
-import org.springframework.cloud.task.configuration.SimpleTaskAutoConfiguration;
-import org.springframework.cloud.task.configuration.SingleTaskConfiguration;
-import org.springframework.cloud.task.configuration.TaskConfigurer;
-import org.springframework.cloud.task.repository.TaskExecution;
-import org.springframework.cloud.task.repository.TaskExplorer;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Import;
-import org.springframework.context.annotation.Primary;
-import org.springframework.data.domain.Page;
-import org.springframework.data.domain.PageRequest;
-import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
-import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
-import org.springframework.transaction.PlatformTransactionManager;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-
-/**
- * @author Michael Minella
- * @author Glenn Renfro
- */
-public class TaskBatchExecutionListenerTests {
-
- private static final String[] ARGS = new String[] {};
-
- private ConfigurableApplicationContext applicationContext;
-
- @AfterEach
- public void tearDown() {
- if (this.applicationContext != null && this.applicationContext.isActive()) {
- this.applicationContext.close();
- }
- }
-
- @Test
- public void testAutobuiltDataSource() {
- this.applicationContext = SpringApplication.run(JobConfiguration.class, ARGS);
- validateContext();
- }
-
- @Test
- public void testNoAutoConfigurationEnabled() {
- this.applicationContext = SpringApplication.run(JobConfiguration.class,
- "--spring.cloud.task.batch.listener.enabled=false");
- assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> {
- validateContext();
- });
- }
-
- @Test
- public void testNoAutoConfigurationEnable() {
- this.applicationContext = SpringApplication.run(JobConfiguration.class,
- "--spring.cloud.task.batch.listener.enable=false");
- assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> {
- validateContext();
- });
- }
-
- @Test
- public void testNoAutoConfigurationBothDisabled() {
- this.applicationContext = SpringApplication.run(JobConfiguration.class,
- "--spring.cloud.task.batch.listener.enable=false --spring.cloud.task.batch.listener.enabled=false");
- assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> {
- validateContext();
- });
- }
-
- @Test
- public void testAutoConfigurationEnable() {
- this.applicationContext = SpringApplication.run(JobConfiguration.class,
- "--spring.cloud.task.batch.listener.enable=true");
- validateContext();
- }
-
- @Test
- public void testAutoConfigurationEnabled() {
- this.applicationContext = SpringApplication.run(JobConfiguration.class,
- "--spring.cloud.task.batch.listener.enabled=true");
- validateContext();
- }
-
- @Test
- public void testFactoryBean() {
- this.applicationContext = SpringApplication.run(JobFactoryBeanConfiguration.class, ARGS);
- validateContext();
- }
-
- private void validateContext() {
- TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class);
-
- Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1));
-
- Set jobExecutionIds = taskExplorer
- .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId());
-
- assertThat(jobExecutionIds.size()).isEqualTo(1);
- assertThat(taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()).getExecutionId()).isEqualTo(1);
-
- }
-
- @Test
- public void testNoListenerIfTaskNotEnabled() {
- this.applicationContext = SpringApplication.run(TaskNotEnabledConfiguration.class, ARGS);
- assertThat(applicationContext.getBean(Job.class)).isNotNull();
- assertThatThrownBy(() -> applicationContext.getBean(TaskBatchExecutionListenerBeanPostProcessor.class))
- .isInstanceOf(NoSuchBeanDefinitionException.class);
- assertThatThrownBy(() -> applicationContext.getBean(TaskBatchExecutionListener.class))
- .isInstanceOf(NoSuchBeanDefinitionException.class);
- }
-
- @Test
- public void testMultipleDataSources() {
- this.applicationContext = SpringApplication.run(JobConfigurationMultipleDataSources.class, ARGS);
-
- TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class);
-
- Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1));
-
- Set jobExecutionIds = taskExplorer
- .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId());
-
- assertThat(jobExecutionIds.size()).isEqualTo(1);
- assertThat(taskExplorer.getTaskExecution(jobExecutionIds.iterator().next()).getExecutionId()).isEqualTo(1);
- }
-
- @Test
- public void testAutobuiltDataSourceNoJob() {
- this.applicationContext = SpringApplication.run(NoJobConfiguration.class, ARGS);
-
- TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class);
-
- Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1));
-
- Set jobExecutionIds = taskExplorer
- .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId());
-
- assertThat(jobExecutionIds.size()).isEqualTo(0);
- }
-
- @Test
- public void testMapBased() {
- this.applicationContext = SpringApplication.run(JobConfiguration.class, ARGS);
-
- TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class);
-
- Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1));
-
- Set jobExecutionIds = taskExplorer
- .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId());
-
- assertThat(jobExecutionIds.size()).isEqualTo(1);
- assertThat((long) taskExplorer.getTaskExecutionIdByJobExecutionId(jobExecutionIds.iterator().next()))
- .isEqualTo(1);
- }
-
- @Test
- public void testMultipleJobs() {
- this.applicationContext = SpringApplication.run(MultipleJobConfiguration.class, "--spring.batch.job.name=job1");
-
- TaskExplorer taskExplorer = this.applicationContext.getBean(TaskExplorer.class);
-
- Page page = taskExplorer.findTaskExecutionsByName("application", PageRequest.of(0, 1));
-
- Set jobExecutionIds = taskExplorer
- .getJobExecutionIdsByTaskExecutionId(page.iterator().next().getExecutionId());
-
- assertThat(jobExecutionIds.size()).isEqualTo(1);
- Iterator jobExecutionIdsIterator = jobExecutionIds.iterator();
- assertThat((long) taskExplorer.getTaskExecutionIdByJobExecutionId(jobExecutionIdsIterator.next())).isEqualTo(1);
-
- }
-
- @Test
- public void testBatchExecutionListenerBeanPostProcessorWithJobNames() {
- List jobNames = new ArrayList<>(3);
- jobNames.add("job1");
- jobNames.add("job2");
- jobNames.add("TESTOBJECT");
-
- TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor = beanPostProcessor(jobNames);
-
- SimpleJob testObject = new SimpleJob();
- SimpleJob bean = (SimpleJob) beanPostProcessor.postProcessBeforeInitialization(testObject, "TESTOBJECT");
- assertThat(bean).isEqualTo(testObject);
- }
-
- @Test
- public void testBatchExecutionListenerBeanPostProcessorWithEmptyJobNames() {
- TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor = beanPostProcessor(Collections.emptyList());
-
- SimpleJob testObject = new SimpleJob();
- SimpleJob bean = (SimpleJob) beanPostProcessor.postProcessBeforeInitialization(testObject, "TESTOBJECT");
- assertThat(bean).isEqualTo(testObject);
- }
-
- @Test
- public void testBatchExecutionListenerBeanPostProcessorNullJobNames() {
- assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
- beanPostProcessor(null);
- });
- }
-
- private TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor(List jobNames) {
- this.applicationContext = SpringApplication.run(new Class[] { JobConfiguration.class,
- PropertyPlaceholderAutoConfiguration.class, EmbeddedDataSourceConfiguration.class,
- BatchAutoConfiguration.class, TaskBatchAutoConfiguration.class, SimpleTaskAutoConfiguration.class,
- SingleTaskConfiguration.class }, ARGS);
-
- TaskBatchExecutionListenerBeanPostProcessor beanPostProcessor = this.applicationContext
- .getBean(TaskBatchExecutionListenerBeanPostProcessor.class);
-
- beanPostProcessor.setJobNames(jobNames);
- return beanPostProcessor;
- }
-
- @EnableBatchProcessing
- @TaskBatchTest
- @Import(EmbeddedDataSourceConfiguration.class)
- @EnableTask
- public static class NoJobConfiguration {
-
- @Bean
- PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- }
-
- @TaskBatchTest
- @EnableTask
- @Import(EmbeddedDataSourceConfiguration.class)
- public static class JobConfiguration {
-
- @Bean
- public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
- return new JobBuilder("job", jobRepository)
- .start(new StepBuilder("step1", jobRepository).tasklet((contribution, chunkContext) -> {
- System.out.println("Executed");
- return RepeatStatus.FINISHED;
- }, transactionManager).build()).build();
- }
-
- @Bean
- PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- }
-
- @EnableBatchProcessing
- @TaskBatchTest
- @Import(EmbeddedDataSourceConfiguration.class)
- public static class TaskNotEnabledConfiguration {
-
- @Bean
- public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
- return new JobBuilder("job", jobRepository)
- .start(new StepBuilder("step1", jobRepository).tasklet((contribution, chunkContext) -> {
- System.out.println("Executed");
- return RepeatStatus.FINISHED;
- }, transactionManager).build()).build();
- }
-
- @Bean
- PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- }
-
- @TaskBatchTest
- @EnableTask
- @Import(EmbeddedDataSourceConfiguration.class)
- public static class JobFactoryBeanConfiguration {
-
- @Bean
- public FactoryBean job(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
- return new FactoryBean() {
- @Override
- public Job getObject() {
- return new JobBuilder("job", jobRepository)
- .start(new StepBuilder("step1", jobRepository).tasklet((contribution, chunkContext) -> {
- System.out.println("Executed");
- return RepeatStatus.FINISHED;
- }, transactionManager).build()).build();
- }
-
- @Override
- public Class> getObjectType() {
- return Job.class;
- }
-
- @Override
- public boolean isSingleton() {
- return true;
- }
- };
- }
-
- @Bean
- PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- }
-
- @TaskBatchTest
- @EnableTask
- @Import(EmbeddedDataSourceConfiguration.class)
- public static class JobConfigurationMultipleDataSources {
-
- @Bean
- public Job job(JobRepository jobRepository) {
- return new JobBuilder("job", jobRepository)
- .start(new StepBuilder("step1", jobRepository).tasklet(new Tasklet() {
- @Override
- public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext)
- throws Exception {
- System.out.println("Executed");
- return RepeatStatus.FINISHED;
- }
- }, new ResourcelessTransactionManager()).build()).build();
- }
-
- @Bean
- @Primary
- public DataSource myDataSource() {
- EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
- .setName("myDataSource");
- return builder.build();
- }
-
- @Bean
- public DataSource incorrectDataSource() {
- EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
- .setName("incorrectDataSource");
- return builder.build();
- }
-
- @Bean
- public TaskConfigurer taskConfigurer() {
- return new DefaultTaskConfigurer(myDataSource());
- }
-
- @Bean
- PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- }
-
- @TaskBatchTest
- @EnableTask
- @Import(EmbeddedDataSourceConfiguration.class)
- public static class MultipleJobConfiguration {
-
- @Bean
- public Job job1(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
- return new JobBuilder("job1", jobRepository)
- .start(new StepBuilder("job1step1", jobRepository).tasklet((contribution, chunkContext) -> {
- System.out.println("Executed job1");
- return RepeatStatus.FINISHED;
- }, transactionManager).build()).build();
- }
-
- @Bean
- public Job job2(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
- return new JobBuilder("job2", jobRepository)
- .start(new StepBuilder("job2step1", jobRepository).tasklet((contribution, chunkContext) -> {
- System.out.println("Executed job2");
- return RepeatStatus.FINISHED;
- }, transactionManager).build()).build();
- }
-
- @Bean
- PlatformTransactionManager transactionManager() {
- return new ResourcelessTransactionManager();
- }
-
- }
-
-}
diff --git a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandlerTests.java b/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandlerTests.java
deleted file mode 100644
index 9fc25ee9..00000000
--- a/spring-cloud-task-batch/src/test/java/org/springframework/cloud/task/batch/partition/DeployerPartitionHandlerTests.java
+++ /dev/null
@@ -1,912 +0,0 @@
-/*
- * Copyright 2016-2022 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.task.batch.partition;
-
-import java.time.LocalDateTime;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.TimeoutException;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-
-import org.springframework.batch.core.BatchStatus;
-import org.springframework.batch.core.JobExecution;
-import org.springframework.batch.core.JobInstance;
-import org.springframework.batch.core.StepExecution;
-import org.springframework.batch.core.explore.JobExplorer;
-import org.springframework.batch.core.partition.StepExecutionSplitter;
-import org.springframework.cloud.deployer.spi.core.AppDefinition;
-import org.springframework.cloud.deployer.spi.core.AppDeploymentRequest;
-import org.springframework.cloud.deployer.spi.task.TaskLauncher;
-import org.springframework.cloud.task.repository.TaskExecution;
-import org.springframework.cloud.task.repository.TaskRepository;
-import org.springframework.core.env.Environment;
-import org.springframework.core.io.Resource;
-import org.springframework.mock.env.MockEnvironment;
-import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-/**
- * @author Michael Minella
- * @author Glenn Renfro
- */
-public class DeployerPartitionHandlerTests {
-
- @Captor
- ArgumentCaptor appDeploymentRequestArgumentCaptor;
-
- @Mock
- private TaskLauncher taskLauncher;
-
- @Mock
- private JobExplorer jobExplorer;
-
- @Mock
- private Resource resource;
-
- @Mock
- private StepExecutionSplitter splitter;
-
- @Mock
- private TaskRepository taskRepository;
-
- private Environment environment;
-
- @BeforeEach
- public void setUp() {
- MockitoAnnotations.openMocks(this);
- this.environment = new MockEnvironment();
- TaskExecution taskExecution = new TaskExecution(2, 0, "name", LocalDateTime.now(), LocalDateTime.now(), "",
- Collections.emptyList(), null, null, null);
- Mockito.lenient().when(taskRepository.createTaskExecution()).thenReturn(taskExecution);
- }
-
- @Test
- public void testDeprecatedConstructorValidation() {
- validateDeprecatedConstructorValidation(null, null, null, null, "A taskLauncher is required");
- validateDeprecatedConstructorValidation(this.taskLauncher, null, null, null, "A jobExplorer is required");
- validateDeprecatedConstructorValidation(this.taskLauncher, this.jobExplorer, null, null,
- "A resource is required");
- validateDeprecatedConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, null,
- "A step name is required");
-
- new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, this.resource, "step-name",
- this.taskRepository);
- }
-
- @Test
- public void testConstructorValidation() {
- validateConstructorValidation(null, null, null, null, null, "A taskLauncher is required");
- validateConstructorValidation(this.taskLauncher, null, null, null, null, "A jobExplorer is required");
- validateConstructorValidation(this.taskLauncher, this.jobExplorer, null, null, null, "A resource is required");
- validateConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, null, null,
- "A step name is required");
- validateConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, null, null,
- "A step name is required");
- validateConstructorValidation(this.taskLauncher, this.jobExplorer, this.resource, "step-name", null,
- "A TaskRepository is required");
- new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer, this.resource, "step-name",
- this.taskRepository);
- }
-
- @Test
- public void testNoPartitions() throws Exception {
- DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer,
- this.resource, "step1", this.taskRepository);
- handler.setEnvironment(this.environment);
-
- StepExecution stepExecution = new StepExecution("step1", new JobExecution(1L));
-
- when(this.splitter.split(stepExecution, 1)).thenReturn(new HashSet<>());
-
- Collection results = handler.handle(this.splitter, stepExecution);
-
- verify(this.taskLauncher, never()).launch((AppDeploymentRequest) any());
- assertThat(results.isEmpty()).isTrue();
- }
-
- @Test
- public void testSinglePartition() throws Exception {
-
- StepExecution masterStepExecution = createMasterStepExecution();
- JobExecution jobExecution = masterStepExecution.getJobExecution();
-
- StepExecution workerStepExecutionStart = getStepExecutionStart(jobExecution, 4L);
- StepExecution workerStepExecutionFinish = getStepExecutionFinish(workerStepExecutionStart,
- BatchStatus.COMPLETED);
-
- DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer,
- this.resource, "step1", this.taskRepository);
- handler.setEnvironment(this.environment);
-
- TaskExecution taskExecution = new TaskExecution();
- taskExecution.setTaskName("partitionedJobTask");
-
- Set stepExecutions = new HashSet<>();
- stepExecutions.add(workerStepExecutionStart);
- when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions);
-
- when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish);
-
- handler.afterPropertiesSet();
-
- handler.beforeTask(taskExecution);
-
- Collection results = handler.handle(this.splitter, masterStepExecution);
-
- verify(this.taskLauncher).launch(this.appDeploymentRequestArgumentCaptor.capture());
-
- AppDeploymentRequest request = this.appDeploymentRequestArgumentCaptor.getValue();
-
- assertThat(request.getResource()).isEqualTo(this.resource);
- assertThat(request.getDeploymentProperties().size()).isEqualTo(0);
-
- AppDefinition appDefinition = request.getDefinition();
-
- assertThat(appDefinition.getName()).isEqualTo("partitionedJobTask");
- assertThat(request.getCommandlineArguments()
- .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID, "1"))).isTrue();
- assertThat(request.getCommandlineArguments()
- .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID, "4"))).isTrue();
- assertThat(request.getCommandlineArguments()
- .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME, "step1"))).isTrue();
- assertThat(request.getCommandlineArguments().contains(formatArgs("spring.cloud.task.executionid", "2")))
- .isTrue();
-
- assertThat(results.size()).isEqualTo(1);
- StepExecution resultStepExecution = results.iterator().next();
- assertThat(resultStepExecution.getStatus()).isEqualTo(BatchStatus.COMPLETED);
- assertThat(resultStepExecution.getStepName()).isEqualTo("step1:partition1");
- }
-
- @Test
- public void testSinglePartitionAsEnvVars() throws Exception {
-
- StepExecution masterStepExecution = createMasterStepExecution();
- JobExecution jobExecution = masterStepExecution.getJobExecution();
-
- StepExecution workerStepExecutionStart = getStepExecutionStart(jobExecution, 4L);
- StepExecution workerStepExecutionFinish = getStepExecutionFinish(workerStepExecutionStart,
- BatchStatus.COMPLETED);
- DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer,
- this.resource, "step1", this.taskRepository);
- handler.setEnvironment(this.environment);
- handler.setDefaultArgsAsEnvironmentVars(true);
-
- TaskExecution taskExecution = new TaskExecution(55, null, null, null, null, null, new ArrayList<>(), null,
- null);
- taskExecution.setTaskName("partitionedJobTask");
-
- Set stepExecutions = new HashSet<>();
- stepExecutions.add(workerStepExecutionStart);
- when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions);
-
- when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish);
-
- handler.afterPropertiesSet();
-
- handler.beforeTask(taskExecution);
-
- Collection results = handler.handle(this.splitter, masterStepExecution);
-
- verify(this.taskLauncher).launch(this.appDeploymentRequestArgumentCaptor.capture());
-
- AppDeploymentRequest request = this.appDeploymentRequestArgumentCaptor.getValue();
-
- assertThat(request.getResource()).isEqualTo(this.resource);
- assertThat(request.getDeploymentProperties().size()).isEqualTo(0);
-
- AppDefinition appDefinition = request.getDefinition();
-
- assertThat(appDefinition.getName()).isEqualTo("partitionedJobTask");
- assertThat(request.getCommandlineArguments().isEmpty()).isTrue();
- assertThat(request.getDefinition().getProperties()
- .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_JOB_EXECUTION_ID)).isEqualTo("1");
- assertThat(request.getDefinition().getProperties()
- .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_EXECUTION_ID)).isEqualTo("4");
- assertThat(request.getDefinition().getProperties().get(DeployerPartitionHandler.SPRING_CLOUD_TASK_STEP_NAME))
- .isEqualTo("step1");
- assertThat(request.getDefinition().getProperties().get(DeployerPartitionHandler.SPRING_CLOUD_TASK_NAME))
- .isEqualTo("partitionedJobTask_partitionedJob_step1:partition1");
- assertThat(request.getDefinition().getProperties()
- .get(DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID)).isEqualTo("55");
- assertThat(request.getDefinition().getProperties().get(DeployerPartitionHandler.SPRING_CLOUD_TASK_EXECUTION_ID))
- .isEqualTo("2");
-
- assertThat(results.size()).isEqualTo(1);
- StepExecution resultStepExecution = results.iterator().next();
- assertThat(resultStepExecution.getStatus()).isEqualTo(BatchStatus.COMPLETED);
- assertThat(resultStepExecution.getStepName()).isEqualTo("step1:partition1");
- }
-
- @Test
- public void testParentExecutionId() throws Exception {
-
- StepExecution masterStepExecution = createMasterStepExecution();
- JobExecution jobExecution = masterStepExecution.getJobExecution();
-
- StepExecution workerStepExecutionStart = getStepExecutionStart(jobExecution, 4L);
- StepExecution workerStepExecutionFinish = getStepExecutionFinish(workerStepExecutionStart,
- BatchStatus.COMPLETED);
-
- DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer,
- this.resource, "step1", this.taskRepository);
- handler.setEnvironment(this.environment);
-
- TaskExecution taskExecution = new TaskExecution(55, null, null, null, null, null, new ArrayList<>(), null,
- null);
-
- taskExecution.setTaskName("partitionedJobTask");
-
- Set stepExecutions = new HashSet<>();
- stepExecutions.add(workerStepExecutionStart);
- when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions);
-
- when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish);
-
- handler.afterPropertiesSet();
-
- handler.beforeTask(taskExecution);
-
- handler.handle(this.splitter, masterStepExecution);
-
- verify(this.taskLauncher).launch(this.appDeploymentRequestArgumentCaptor.capture());
-
- AppDeploymentRequest request = this.appDeploymentRequestArgumentCaptor.getValue();
- assertThat(request.getCommandlineArguments()
- .contains(formatArgs(DeployerPartitionHandler.SPRING_CLOUD_TASK_PARENT_EXECUTION_ID, "55"))).isTrue();
- }
-
- @Test
- public void testThreePartitionsSequential() throws Exception {
- testThreePartitions(null);
- }
-
- @Test
- public void testThreePartitionsAsynchronous() throws Exception {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(4);
- executor.setThreadNamePrefix("default_task_executor_thread");
- executor.setWaitForTasksToCompleteOnShutdown(true);
- executor.initialize();
- testThreePartitions(executor);
- }
-
- private void testThreePartitions(ThreadPoolTaskExecutor threadPoolTaskExecutor) throws Exception {
-
- StepExecution masterStepExecution = createMasterStepExecution();
- JobExecution jobExecution = masterStepExecution.getJobExecution();
-
- StepExecution workerStepExecutionStart1 = getStepExecutionStart(jobExecution, 4L);
- StepExecution workerStepExecutionFinish1 = getStepExecutionFinish(workerStepExecutionStart1,
- BatchStatus.COMPLETED);
-
- StepExecution workerStepExecutionStart2 = getStepExecutionStart(jobExecution, 5L);
- StepExecution workerStepExecutionFinish2 = getStepExecutionFinish(workerStepExecutionStart2,
- BatchStatus.COMPLETED);
-
- StepExecution workerStepExecutionStart3 = getStepExecutionStart(jobExecution, 6L);
- StepExecution workerStepExecutionFinish3 = getStepExecutionFinish(workerStepExecutionStart3,
- BatchStatus.COMPLETED);
-
- DeployerPartitionHandler handler = new DeployerPartitionHandler(this.taskLauncher, this.jobExplorer,
- this.resource, "step1", this.taskRepository, threadPoolTaskExecutor);
- handler.setEnvironment(this.environment);
-
- TaskExecution taskExecution = new TaskExecution();
- taskExecution.setTaskName("partitionedJobTask");
-
- Set stepExecutions = new HashSet<>();
-
- stepExecutions.add(workerStepExecutionStart1);
- stepExecutions.add(workerStepExecutionStart2);
- stepExecutions.add(workerStepExecutionStart3);
-
- when(this.splitter.split(masterStepExecution, 1)).thenReturn(stepExecutions);
-
- when(this.jobExplorer.getStepExecution(1L, 4L)).thenReturn(workerStepExecutionFinish1);
- when(this.jobExplorer.getStepExecution(1L, 5L)).thenReturn(workerStepExecutionFinish2);
- when(this.jobExplorer.getStepExecution(1L, 6L)).thenReturn(workerStepExecutionFinish3);
-
- handler.afterPropertiesSet();
-
- handler.beforeTask(taskExecution);
- Collection results = handler.handle(this.splitter, masterStepExecution);
- Thread.sleep(5000);
- verify(this.taskLauncher, times(3)).launch(this.appDeploymentRequestArgumentCaptor.capture());
-
- List