Checks for invalid ExecutionId in the TaskLifeCycleListener

resolves #115
* Fixes bug where if the user set the environment variable and commandline args a unique constraint would fire.
* Updated docs
* Removed deprecation
* Fixed version number for integration test.

Added integration tests for externally generated task executions
This commit is contained in:
Michael Minella
2016-08-22 12:55:31 -05:00
parent bf0c27dd1a
commit 441bbfe492
21 changed files with 619 additions and 36 deletions

View File

@@ -136,7 +136,8 @@ public class SimpleTaskConfiguration {
this.platformTransactionManager = taskConfigurer.getTransactionManager();
this.taskExplorer = taskConfigurer.getTaskExplorer();
this.taskLifecycleListener = new TaskLifecycleListener(this.taskRepository, taskNameResolver(), this.applicationArguments);
this.taskLifecycleListener = new TaskLifecycleListener(this.taskRepository, taskNameResolver(),
this.applicationArguments, taskExplorer);
initialized = true;
}

View File

@@ -35,6 +35,7 @@ import org.springframework.boot.ExitCodeEvent;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.cloud.task.repository.TaskExplorer;
import org.springframework.cloud.task.repository.TaskNameResolver;
import org.springframework.cloud.task.repository.TaskRepository;
import org.springframework.context.ApplicationEvent;
@@ -75,6 +76,8 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
private final TaskRepository taskRepository;
private final TaskExplorer taskExplorer;
private TaskExecution taskExecution;
private boolean started = false;
@@ -92,18 +95,23 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
@Value("${spring.cloud.task.closecontext.enable:true}")
private Boolean closeContext;
@Value("${spring.cloud.task.executionid:}")
private Integer taskExecutionId;
/**
* @param taskRepository The repository to record executions in.
*/
public TaskLifecycleListener(TaskRepository taskRepository,
TaskNameResolver taskNameResolver,
ApplicationArguments applicationArguments) {
ApplicationArguments applicationArguments, TaskExplorer taskExplorer) {
Assert.notNull(taskRepository, "A taskRepository is required");
Assert.notNull(taskNameResolver, "A taskNameResolver is required");
Assert.notNull(taskExplorer, "A taskExplorer is required");
this.taskRepository = taskRepository;
this.taskNameResolver = taskNameResolver;
this.applicationArguments = applicationArguments;
this.taskExplorer = taskExplorer;
}
/**
@@ -187,9 +195,18 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
if(this.applicationArguments != null) {
args = Arrays.asList(this.applicationArguments.getSourceArgs());
}
this.taskExecution = this.taskRepository.createTaskExecution(
this.taskNameResolver.getTaskName(), new Date(), args);
if(this.taskExecutionId != null) {
TaskExecution taskExecution = taskExplorer.getTaskExecution(this.taskExecutionId);
Assert.notNull(taskExecution, String.format("Invalid TaskExecution, ID %s not found", this.taskExecutionId));
Assert.isNull(taskExecution.getEndTime(), String.format(
"Invalid TaskExecution, ID %s task is already complete", this.taskExecutionId));
this.taskExecution = this.taskRepository.startTaskExecution(this.taskExecutionId,
this.taskNameResolver.getTaskName(), new Date(), args);
}
else {
this.taskExecution = this.taskRepository.createTaskExecution(
this.taskNameResolver.getTaskName(), new Date(), args);
}
}
else {
logger.error("Multiple start events have been received. The first one was " +

View File

@@ -82,13 +82,12 @@ public class TaskExecution {
String errorMessage) {
Assert.notNull(arguments, "arguments must not be null");
Assert.notNull(startTime, "startTime must not be null");
this.executionId = executionId;
this.exitCode = exitCode;
this.taskName = taskName;
this.exitMessage = exitMessage;
this.arguments = new ArrayList<>(arguments);
this.startTime = (Date)startTime.clone();
this.startTime = (startTime != null) ? (Date)startTime.clone() : null;
this.endTime = (endTime != null) ? (Date)endTime.clone() : null;
this.errorMessage = errorMessage;
}

View File

@@ -68,4 +68,26 @@ public interface TaskRepository {
TaskExecution createTaskExecution(String taskName,
Date startTime,List<String> arguments);
/**
* Creates an empty TaskExecution with just an id provided. This is intended to be
* utilized in systems where the request of launching a task is separate from the
* actual start of a task (the underlying system may need to deploy the task prior to
* launching, etc).
*
* @return the initial {@link TaskExecution}
*/
@Transactional
TaskExecution createTaskExecution();
/**
* Notifies the repository that a taskExecution has has started.
* @param executionid to the task execution to be updated.
* @param taskName the name that associated with the task execution.
* @param startTime the time task began.
* @param arguments list of key/value pairs that configure the task.
* @return
*/
@Transactional
TaskExecution startTaskExecution(long executionid, String taskName,
Date startTime,List<String> arguments);
}

View File

@@ -74,6 +74,9 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
private static final String CREATE_TASK_ARGUMENT = "INSERT into "
+ "%PREFIX%EXECUTION_PARAMS(TASK_EXECUTION_ID, TASK_PARAM ) values (?, ?)";
private static final String START_TASK_EXECUTION = "UPDATE %PREFIX%EXECUTION set "
+ "START_TIME = ?, TASK_NAME = ?, LAST_UPDATED = ? where TASK_EXECUTION_ID = ?";
private static final String CHECK_TASK_EXECUTION_EXISTS = "SELECT COUNT(*) FROM "
+ "%PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = ?";
@@ -127,16 +130,31 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
@Override
public TaskExecution createTaskExecution(String taskName,
Date startTime, List<String> arguments) {
long taskExecutionId = getNextExecutionId();
TaskExecution taskExecution = new TaskExecution(taskExecutionId, null, taskName,
long nextExecutionId = getNextExecutionId();
TaskExecution taskExecution = new TaskExecution(nextExecutionId, null, taskName,
startTime, null, null, arguments, null);
Object[] queryParameters = new Object[]{ taskExecutionId, startTime, taskName, new Date()};
Object[] queryParameters = new Object[]{ nextExecutionId, startTime, taskName, new Date()};
jdbcTemplate.update(
getQuery(SAVE_TASK_EXECUTION),
queryParameters,
new int[]{ Types.BIGINT, Types.TIMESTAMP, Types.VARCHAR, Types.TIMESTAMP });
insertTaskArguments(taskExecutionId, arguments);
insertTaskArguments(nextExecutionId, arguments);
return taskExecution;
}
@Override
public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments) {
TaskExecution taskExecution = new TaskExecution(executionId, null, taskName,
startTime, null, null, arguments, null);
Object[] queryParameters = new Object[]{ startTime, taskName, new Date(), executionId};
jdbcTemplate.update(
getQuery(START_TASK_EXECUTION),
queryParameters,
new int[]{ Types.TIMESTAMP, Types.VARCHAR, Types.TIMESTAMP, Types.BIGINT });
insertTaskArguments(executionId, arguments);
return taskExecution;
}
@@ -146,7 +164,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
// Check if given TaskExecution's Id already exists, if none is found
// it is invalid and an exception should be thrown.
if (jdbcTemplate.queryForObject(getQuery(CHECK_TASK_EXECUTION_EXISTS), Integer.class,
new Object[]{ taskExecutionId}) != 1) {
taskExecutionId) != 1) {
throw new IllegalStateException("Invalid TaskExecution, ID " + taskExecutionId + " not found.");
}

View File

@@ -61,8 +61,23 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
return taskExecution;
}
@Override
public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments) {
TaskExecution taskExecution= taskExecutions.get(executionId);
taskExecution.setTaskName(taskName);
taskExecution.setStartTime(startTime);
taskExecution.setArguments(arguments);
return taskExecution;
}
@Override
public void completeTaskExecution(long executionId, Integer exitCode, Date endTime, String exitMessage, String errorMessage) {
if(!this.taskExecutions.containsKey(executionId)) {
throw new IllegalStateException("Invalid TaskExecution, ID " + executionId + " not found.");
}
TaskExecution taskExecution= taskExecutions.get(executionId);
taskExecution.setEndTime(endTime);
taskExecution.setExitCode(exitCode);

View File

@@ -43,7 +43,19 @@ public interface TaskExecutionDao {
Date startTime, List<String> arguments);
/**
* Update and existing {@link TaskExecution}.
* Update and existing {@link TaskExecution} to mark it as started.
*
* @param executionId the id of the taskExecution to be updated.
* @param taskName the name that associated with the task execution.
* @param startTime the time task began.
* @param arguments list of key/value pairs that configure the task.
* @since 1.1.0
*/
TaskExecution startTaskExecution(long executionId, String taskName,
Date startTime, List<String> arguments);
/**
* Update and existing {@link TaskExecution} to mark it as completed.
*
* @param executionId the id of the taskExecution to be updated.
* @param exitCode the status of the task upon completion.

View File

@@ -16,6 +16,7 @@
package org.springframework.cloud.task.repository.support;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -109,6 +110,24 @@ public class SimpleTaskRepository implements TaskRepository {
return taskExecution;
}
@Override
public TaskExecution createTaskExecution() {
initialize();
TaskExecution taskExecution =
taskExecutionDao.createTaskExecution(null, null, new ArrayList<String>(0));
logger.debug("Creating: " + taskExecution.toString());
return taskExecution;
}
@Override
public TaskExecution startTaskExecution(long executionid, String taskName, Date startTime, List<String> arguments) {
initialize();
TaskExecution taskExecution =
taskExecutionDao.startTaskExecution(executionid, taskName, startTime, arguments);
logger.debug("Starting: " + taskExecution.toString());
return taskExecution;
}
/**
* Retrieves the taskExecutionDao associated with this repository.
* @return the taskExecutionDao

View File

@@ -7,8 +7,9 @@ import org.junit.Test;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.OutputCapture;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -28,6 +29,8 @@ public class TaskCoreTests {
private static final String UPDATE_TASK_MESSAGE = "Updating: TaskExecution with executionId=";
private static final String SUCCESS_EXIT_CODE_MESSAGE = "with the following {exitCode=0";
private static final String EXCEPTION_EXIT_CODE_MESSAGE = "with the following {exitCode=1";
private static final String EXCEPTION_INVALID_TASK_EXECUTION_ID =
"java.lang.IllegalArgumentException: Invalid TaskExecution, ID 55 not found";
private static final String ERROR_MESSAGE =
"errorMessage='java.lang.IllegalStateException: Failed to execute CommandLineRunner";
@@ -88,6 +91,27 @@ public class TaskCoreTests {
output.contains(EXCEPTION_MESSAGE));
}
@Test
public void invalidExecutionId() {
boolean exceptionFired = false;
try {
applicationContext = new SpringApplicationBuilder().sources(new Object[]{TaskExceptionConfiguration.class,
PropertyPlaceholderAutoConfiguration.class}).build().run(new String[]{
"--spring.cloud.task.closecontext.enable=false",
"--spring.cloud.task.name=" + TASK_NAME,
"--spring.main.web-environment=false",
"--spring.cloud.task.executionid=55"});
}
catch (ApplicationContextException exception) {
exceptionFired = true;
}
assertTrue("An ApplicationContextException should have been thrown", exceptionFired);
String output = this.outputCapture.toString();
assertTrue("Test results do not show the correct exception message: " + output,
output.contains(EXCEPTION_INVALID_TASK_EXECUTION_ID));
}
@Configuration
@EnableTask
public static class TaskConfiguration {

View File

@@ -35,10 +35,15 @@ import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.cloud.task.repository.TaskExplorer;
import org.springframework.cloud.task.util.TestDefaultConfiguration;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
@@ -139,6 +144,17 @@ public class TaskLifecycleListenerTests {
}
}
@Test(expected = ApplicationContextException.class)
public void testInvalidTaskExecutionId() {
ConfigurableEnvironment environment = new StandardEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
Map myMap = new HashMap();
myMap.put("spring.cloud.task.executionid", "55");
propertySources.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
context.setEnvironment(environment);
context.refresh();
}
private void verifyTaskExecution(int numberOfParams, boolean update, Integer exitCode, Throwable exception) {
Sort sort = new Sort("id");

View File

@@ -16,11 +16,16 @@
package org.springframework.cloud.task.repository.dao;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.UUID;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration;
@@ -56,7 +61,24 @@ public class JdbcTaskExecutionDaoTests {
@Test
@DirtiesContext
public void saveTaskExecution() {
public void testStartTaskExecution() {
TaskExecution expectedTaskExecution = dao.createTaskExecution(null, null,
new ArrayList<String>(0));
expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setStartTime(new Date());
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
TestDBUtils.getTaskExecutionFromDB(dataSource, expectedTaskExecution.getExecutionId()));
}
@Test
@DirtiesContext
public void createTaskExecution() {
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
expectedTaskExecution = dao.createTaskExecution(expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments());
@@ -65,6 +87,16 @@ public class JdbcTaskExecutionDaoTests {
TestDBUtils.getTaskExecutionFromDB(dataSource, expectedTaskExecution.getExecutionId()));
}
@Test
@DirtiesContext
public void createEmptyTaskExecution() {
TaskExecution expectedTaskExecution = dao.createTaskExecution(null, null,
new ArrayList<String>(0));
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
TestDBUtils.getTaskExecutionFromDB(dataSource, expectedTaskExecution.getExecutionId()));
}
@Test
@DirtiesContext
public void completeTaskExecution() {

View File

@@ -16,28 +16,72 @@
package org.springframework.cloud.task.repository.dao;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.cloud.task.util.TestVerifierUtils;
import static org.junit.Assert.assertNotNull;
/**
* Executes unit tests on MapTaskExecutionDaoTests.
* @author Glenn Renfro
*/
public class MapTaskExecutionDaoTests {
private MapTaskExecutionDao dao;
@Before
public void setUp() {
this.dao = new MapTaskExecutionDao();
}
@Test
public void testStartTaskExecution() {
TaskExecution expectedTaskExecution = this.dao.createTaskExecution(null, null, new ArrayList<String>(0));
expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setStartTime(new Date());
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
this.dao.startTaskExecution(expectedTaskExecution.getExecutionId(), expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments());
Map<Long, TaskExecution> taskExecutionMap = this.dao.getTaskExecutions();
assertNotNull("taskExecutionMap must not be null", taskExecutionMap);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));
}
@Test
public void createEmptyTaskExecution() {
TaskExecution expectedTaskExecution = dao.createTaskExecution(null, null,
new ArrayList<String>(0));
Map<Long, TaskExecution> taskExecutionMap = this.dao.getTaskExecutions();
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));
}
@Test(expected = IllegalStateException.class)
public void completeTaskExecutionWithNoCreate() {
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(),
expectedTaskExecution.getExitMessage());
}
@Test
public void saveTaskExecution(){
MapTaskExecutionDao dao = new MapTaskExecutionDao();
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
expectedTaskExecution = dao.createTaskExecution(expectedTaskExecution.getTaskName(),
expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments());
Map<Long, TaskExecution> taskExecutionMap = dao.getTaskExecutions();
Map<Long, TaskExecution> taskExecutionMap = this.dao.getTaskExecutions();
assertNotNull("taskExecutionMap must not be null", taskExecutionMap);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));
@@ -45,14 +89,13 @@ public class MapTaskExecutionDaoTests {
@Test
public void completeTaskExecution(){
MapTaskExecutionDao dao = new MapTaskExecutionDao();
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoArg();
expectedTaskExecution = dao.createTaskExecution(expectedTaskExecution.getTaskName(),
expectedTaskExecution = this.dao.createTaskExecution(expectedTaskExecution.getTaskName(),
expectedTaskExecution.getStartTime(), expectedTaskExecution.getArguments());
dao.completeTaskExecution(expectedTaskExecution.getExecutionId(),
this.dao.completeTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getExitCode(), expectedTaskExecution.getEndTime(),
expectedTaskExecution.getExitMessage());
Map<Long, TaskExecution> taskExecutionMap = dao.getTaskExecutions();
Map<Long, TaskExecution> taskExecutionMap = this.dao.getTaskExecutions();
assertNotNull("taskExecutionMap must not be null", taskExecutionMap);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));

View File

@@ -16,6 +16,7 @@
package org.springframework.cloud.task.repository.support;
import java.util.Collections;
import java.util.Date;
import java.util.UUID;
@@ -61,6 +62,17 @@ public class SimpleTaskRepositoryJdbcTests {
@Autowired
private TaskExplorer taskExplorer;
@Test
@DirtiesContext
public void testCreateEmptyExecution() {
TaskExecution expectedTaskExecution =
TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository);
TaskExecution actualTaskExecution = TestDBUtils.getTaskExecutionFromDB(dataSource,
expectedTaskExecution.getExecutionId());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
actualTaskExecution);
}
@Test
@DirtiesContext
public void testCreateTaskExecutionNoParam() {
@@ -81,6 +93,39 @@ public class SimpleTaskRepositoryJdbcTests {
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@Test
@DirtiesContext
public void startTaskExecutionWithParam() {
TaskExecution expectedTaskExecution =
TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository);
expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setStartTime(new Date());
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@Test
@DirtiesContext
public void startTaskExecutionWithNoParam() {
TaskExecution expectedTaskExecution =
TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository);
expectedTaskExecution.setStartTime(new Date());
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@Test
@DirtiesContext
public void testCompleteTaskExecution() {
@@ -200,7 +245,6 @@ public class SimpleTaskRepositoryJdbcTests {
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@Test(expected=IllegalArgumentException.class)
@DirtiesContext
public void testCreateTaskExecutionNullEndTime(){

View File

@@ -16,8 +16,10 @@
package org.springframework.cloud.task.repository.support;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
@@ -43,6 +45,14 @@ public class SimpleTaskRepositoryMapTests {
this.taskRepository = new SimpleTaskRepository(new TaskExecutionDaoFactoryBean());
}
@Test
public void testCreateEmptyExecution() {
TaskExecution expectedTaskExecution =
TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId()));
}
@Test
public void testCreateTaskExecutionNoParam() {
TaskExecution expectedTaskExecution =
@@ -59,6 +69,37 @@ public class SimpleTaskRepositoryMapTests {
getSingleTaskExecutionFromMapRepository(expectedTaskExecution.getExecutionId()));
}
@Test
public void startTaskExecutionWithParam() {
TaskExecution expectedTaskExecution =
TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository);
expectedTaskExecution.setArguments(Collections.singletonList("foo=" + UUID.randomUUID().toString()));
expectedTaskExecution.setStartTime(new Date());
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@Test
public void startTaskExecutionWithNoParam() {
TaskExecution expectedTaskExecution =
TaskExecutionCreator.createAndStoreEmptyTaskExecution(taskRepository);
expectedTaskExecution.setStartTime(new Date());
expectedTaskExecution.setTaskName(UUID.randomUUID().toString());
TaskExecution actualTaskExecution = this.taskRepository.startTaskExecution(expectedTaskExecution.getExecutionId(),
expectedTaskExecution.getTaskName(), expectedTaskExecution.getStartTime(),
expectedTaskExecution.getArguments());
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution, actualTaskExecution);
}
@Test
public void testCompleteTaskExecution() {
TaskExecution expectedTaskExecution =

View File

@@ -30,6 +30,16 @@ import org.springframework.cloud.task.repository.TaskRepository;
*/
public class TaskExecutionCreator {
/**
* Creates a sample TaskExecution and stores it in the taskRepository.
*
* @param taskRepository the taskRepository where the taskExecution should be stored.
* @return the taskExecution created.
*/
public static TaskExecution createAndStoreEmptyTaskExecution(TaskRepository taskRepository) {
return taskRepository.createTaskExecution();
}
/**
* Creates a sample TaskExecution and stores it in the taskRepository.
*

View File

@@ -69,8 +69,8 @@ public class TestDefaultConfiguration implements InitializingBean {
}
@Bean
public TaskLifecycleListener taskHandler(){
return new TaskLifecycleListener(taskRepository(), taskNameResolver(), applicationArguments);
public TaskLifecycleListener taskHandler(TaskExplorer taskExplorer){
return new TaskLifecycleListener(taskRepository(), taskNameResolver(), applicationArguments, taskExplorer);
}
@Override

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.task.executionid;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.context.annotation.Bean;
/**
* @author Glenn Renfro
*/
@SpringBootApplication
@EnableTask
public class TaskStartApplication {
public static void main(String[] args) {
SpringApplication.run(TaskStartApplication.class, args);
}
@Bean
public CommandLineRunner testCommandLineRunner() {
return new CommandLineRunner() {
@Override
public void run(String... strings) throws Exception {
for(String s : strings)
System.out.println("Test" + s);
}
};
}
}

View File

@@ -0,0 +1,223 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.task.executionid;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.h2.tools.Server;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.cloud.task.repository.TaskExplorer;
import org.springframework.cloud.task.repository.TaskRepository;
import org.springframework.cloud.task.repository.support.SimpleTaskExplorer;
import org.springframework.cloud.task.repository.support.SimpleTaskRepository;
import org.springframework.cloud.task.repository.support.TaskExecutionDaoFactoryBean;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.SocketUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {TaskStartTests.TaskLauncherConfiguration.class})
public class TaskStartTests {
private final static int WAIT_INTERVAL = 500;
private final static int MAX_WAIT_TIME = 5000;
private final static String URL = "maven://io.spring.cloud:"
+ "timestamp-task:jar:1.1.0.BUILD-SNAPSHOT";
private final static String DATASOURCE_URL;
private final static String DATASOURCE_USER_NAME = "SA";
private final static String DATASOURCE_USER_PASSWORD = "";
private final static String DATASOURCE_DRIVER_CLASS_NAME = "org.h2.Driver";
private final static String TASK_NAME = "TASK_LAUNCHER_SINK_TEST";
private static int randomPort;
static {
randomPort = SocketUtils.findAvailableTcpPort();
DATASOURCE_URL = "jdbc:h2:tcp://localhost:" + randomPort + "/mem:dataflow;DB_CLOSE_DELAY=-1;"
+ "DB_CLOSE_ON_EXIT=FALSE";
}
private DataSource dataSource;
private Map<String, String> properties;
private TaskExplorer taskExplorer;
private TaskRepository taskRepository;
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
TaskExecutionDaoFactoryBean factoryBean = new TaskExecutionDaoFactoryBean(dataSource);
taskExplorer = new SimpleTaskExplorer(factoryBean);
taskRepository = new SimpleTaskRepository(factoryBean);
}
@Before
public void setup() {
properties = new HashMap<>();
properties.put("spring.datasource.url", DATASOURCE_URL);
properties.put("spring.datasource.username", DATASOURCE_USER_NAME);
properties.put("spring.datasource.password", DATASOURCE_USER_PASSWORD);
properties.put("spring.datasource.driverClassName", DATASOURCE_DRIVER_CLASS_NAME);
properties.put("spring.application.name",TASK_NAME);
properties.put("spring.cloud.task.initialize.enable", "false");
JdbcTemplate template = new JdbcTemplate(this.dataSource);
template.execute("DROP TABLE IF EXISTS TASK_TASK_BATCH");
template.execute("DROP TABLE IF EXISTS TASK_SEQ");
template.execute("DROP TABLE IF EXISTS TASK_EXECUTION_PARAMS");
template.execute("DROP TABLE IF EXISTS TASK_EXECUTION");
template.execute("DROP TABLE IF EXISTS BATCH_STEP_EXECUTION_SEQ");
template.execute("DROP TABLE IF EXISTS BATCH_STEP_EXECUTION_CONTEXT");
template.execute("DROP TABLE IF EXISTS BATCH_STEP_EXECUTION");
template.execute("DROP TABLE IF EXISTS BATCH_JOB_SEQ");
template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION_SEQ");
template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION_PARAMS");
template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION_CONTEXT");
template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION");
template.execute("DROP TABLE IF EXISTS BATCH_JOB_INSTANCE");
template.execute("DROP SEQUENCE IF EXISTS TASK_SEQ");
DataSourceInitializer initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource);
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScript(new ClassPathResource("/org/springframework/cloud/task/schema-h2.sql"));
initializer.setDatabasePopulator(databasePopulator);
initializer.afterPropertiesSet();
}
@Test
public void testWithGeneratedTaskExecution() throws Exception {
taskRepository.createTaskExecution();
assertEquals("Only one row is expected", 1, taskExplorer.getTaskExecutionCount());
getTaskApplication(1).run(new String[0]);
assertTrue(waitForDBToBePopulated());
Page<TaskExecution> taskExecutions = taskExplorer.findAll(new PageRequest(0, 10));
TaskExecution te = taskExecutions.iterator().next();
assertEquals("Only one row is expected", 1, taskExecutions.getTotalElements());
assertEquals("return code should be 0", 0, taskExecutions.iterator().next().getExitCode().intValue());
}
@Test(expected = ApplicationContextException.class)
public void testWithNoTaskExecution() throws Exception {
getTaskApplication(55).run(new String[0]);
}
@Test(expected = ApplicationContextException.class)
public void testCompletedTaskExecution() throws Exception {
taskRepository.createTaskExecution();
assertEquals("Only one row is expected", 1, taskExplorer.getTaskExecutionCount());
taskRepository.completeTaskExecution(1, 0, new Date(),"");
getTaskApplication(1).run(new String[0]);
}
private SpringApplication getTaskApplication(Integer executionId) {
SpringApplication myapp = new SpringApplication(TaskStartApplication.class);
Map<String,Object> myMap = new HashMap<>();
ConfigurableEnvironment environment = new StandardEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
myMap.put("spring.cloud.task.executionid", executionId);
propertySources.addFirst(new MapPropertySource("EnvrionmentTestPropsource", myMap));
myapp.setEnvironment(environment);
return myapp;
}
private boolean tableExists() throws SQLException {
boolean result;
try (Connection conn = dataSource.getConnection();
ResultSet res = conn.getMetaData().getTables(null, null, "TASK_EXECUTION",
new String[]{"TABLE"})) {
result = res.next();
}
return result;
}
private boolean waitForDBToBePopulated() throws Exception {
boolean isDbPopulated = false;
for (int waitTime = 0; waitTime <= MAX_WAIT_TIME; waitTime += WAIT_INTERVAL) {
Thread.sleep(WAIT_INTERVAL);
if (tableExists() && taskExplorer.getTaskExecutionCount() > 0) {
isDbPopulated = true;
break;
}
}
return isDbPopulated;
}
@Configuration
public static class TaskLauncherConfiguration {
private static Server defaultServer;
@Bean(destroyMethod = "stop")
public Server initH2TCPServer() {
Server server = null;
try {
if(defaultServer == null) {
server = Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort",
String.valueOf(randomPort)).start();
defaultServer = server;
}
}
catch (SQLException e) {
throw new IllegalStateException(e);
}
return server;
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DATASOURCE_DRIVER_CLASS_NAME);
dataSource.setUrl(DATASOURCE_URL);
dataSource.setUsername(DATASOURCE_USER_NAME);
dataSource.setPassword(DATASOURCE_USER_PASSWORD);
return dataSource;
}
}
}

View File

@@ -65,7 +65,7 @@ public class TaskLauncherSinkTests {
private final static int WAIT_INTERVAL = 500;
private final static int MAX_WAIT_TIME = 5000;
private final static String URL = "maven://io.spring.cloud:"
+ "timestamp-task:jar:1.1.0.M1";
+ "timestamp-task:jar:1.1.0.BUILD-SNAPSHOT";
private final static String DATASOURCE_URL;
private final static String DATASOURCE_USER_NAME = "SA";
private final static String DATASOURCE_USER_PASSWORD = "";
@@ -123,6 +123,7 @@ public class TaskLauncherSinkTests {
template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION_CONTEXT");
template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION");
template.execute("DROP TABLE IF EXISTS BATCH_JOB_INSTANCE");
template.execute("DROP SEQUENCE IF EXISTS TASK_SEQ");
DataSourceInitializer initializer = new DataSourceInitializer();

View File

@@ -15,9 +15,6 @@
*/
package org.springframework.cloud.task.listener;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -28,7 +25,7 @@ import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.binder.rabbit.config.RabbitServiceAutoConfiguration;
@@ -39,14 +36,17 @@ import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Michael Minella
* @author Ilayaperumal Gopinathan
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration({TaskEventTests.ListenerBinding.class})
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {TaskEventTests.ListenerBinding.class})
public class TaskEventTests {
@ClassRule

View File

@@ -93,7 +93,7 @@ public class JobConfiguration {
@Bean
public PartitionHandler partitionHandler(TaskLauncher taskLauncher, JobExplorer jobExplorer) throws Exception {
Resource resource = resourceLoader.getResource("maven://io.spring.cloud:partitioned-batch-job:1.1.0.M1");
Resource resource = resourceLoader.getResource("maven://io.spring.cloud:partitioned-batch-job:1.1.0.BUILD-SNAPSHOT");
DeployerPartitionHandler partitionHandler = new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, "workerStep");