TaskExecution should use long id

* Replace String executionId with a long executionId
* Add externalExecutionID that is a String

resolves spring-cloud/spring-cloud-task#47
This commit is contained in:
Glenn Renfro
2016-01-06 12:14:01 -05:00
committed by Michael Minella
parent 1c3bb94bbd
commit 584cfb90f5
29 changed files with 330 additions and 190 deletions

View File

@@ -17,8 +17,8 @@ package org.springframework.cloud.task.listener;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -142,13 +142,10 @@ public class TaskLifecycleListener implements ApplicationListener<ApplicationEve
private void doTaskStart() {
if(!started) {
this.taskExecution = new TaskExecution(this.taskRepository.getNextExecutionId(),
0, this.taskNameResolver.getTaskName(), new Date(), null, null, null,
new ArrayList<String>(0), null);
String executionId = UUID.randomUUID().toString();
this.taskExecution = new TaskExecution();
this.taskExecution.setTaskName(taskNameResolver.getTaskName());
this.taskExecution.setStartTime(new Date());
this.taskExecution.setExecutionId(executionId);
this.taskRepository.createTaskExecution(this.taskExecution);
}
else {

View File

@@ -32,7 +32,12 @@ public class TaskExecution {
/**
* The unique id associated with the task execution.
*/
private String executionId;
private long executionId;
/**
* Id provided by an external system for the given task execution.
*/
private String externalExecutionID;
/**
* The recorded exit code for the task.
@@ -73,14 +78,15 @@ public class TaskExecution {
parameters = new ArrayList<>();
}
public TaskExecution(String executionId, int exitCode, String taskName,
public TaskExecution(long executionId, int exitCode, String taskName,
Date startTime, Date endTime, String statusCode,
String exitMessage, List<String> parameters) {
String exitMessage, List<String> parameters,
String externalExecutionID) {
Assert.hasText(executionId, "executionId must not be null nor empty");
Assert.notNull(parameters, "parameters must not be null");
Assert.notNull(startTime, "startTime must not be null");
this.executionId = executionId;
this.externalExecutionID = externalExecutionID;
this.exitCode = exitCode;
this.taskName = taskName;
this.statusCode = statusCode;
@@ -90,14 +96,10 @@ public class TaskExecution {
setEndTime(endTime);
}
public String getExecutionId() {
public long getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public int getExitCode() {
return exitCode;
}
@@ -154,10 +156,19 @@ public class TaskExecution {
this.parameters = parameters;
}
public String getExternalExecutionID() {
return externalExecutionID;
}
public void setExternalExecutionID(String externalExecutionID) {
this.externalExecutionID = externalExecutionID;
}
@Override
public String toString() {
return "TaskExecution{" +
"executionId='" + executionId + '\'' +
"executionId=" + executionId +
", externalExecutionID='" + externalExecutionID + '\'' +
", exitCode=" + exitCode +
", taskName='" + taskName + '\'' +
", startTime=" + startTime +

View File

@@ -35,7 +35,7 @@ public interface TaskExplorer {
* @param executionId the task execution id
* @return the {@link TaskExecution} with this id, or null if not found
*/
public TaskExecution getTaskExecution(String executionId);
public TaskExecution getTaskExecution(long executionId);
/**

View File

@@ -40,4 +40,10 @@ public interface TaskRepository {
*/
@Transactional
public void createTaskExecution(TaskExecution taskExecution);
/**
* Retrieves the next available execution id for a task execution.
* @return long containing the executionId.
*/
public long getNextExecutionId();
}

View File

@@ -41,6 +41,7 @@ import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -52,15 +53,16 @@ import org.springframework.util.StringUtils;
public class JdbcTaskExecutionDao implements TaskExecutionDao {
public static String SELECT_CLAUSE = "TASK_EXECUTION_ID, "
public static String SELECT_CLAUSE = "TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, "
+ "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, "
+ "EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE ";
public static String FROM_CLAUSE = "%PREFIX%EXECUTION";
private static final String SAVE_TASK_EXECUTION = "INSERT into %PREFIX%EXECUTION"
+ "(TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, EXIT_CODE, "
+ "EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE) values (?, ?, ?, ?, ?, ?, ?, ?)";
+ "(TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, START_TIME, END_TIME, "
+ "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE)"
+ "values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String CREATE_TASK_PARAMETER = "INSERT into "
+ "%PREFIX%EXECUTION_PARAMS(TASK_EXECUTION_ID, TASK_PARAM ) values (?, ?)";
@@ -70,12 +72,12 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
private static final String UPDATE_TASK_EXECUTION = "UPDATE %PREFIX%EXECUTION set "
+ "START_TIME = ?, END_TIME = ?, TASK_NAME = ?, EXIT_CODE = ?, "
+ "EXIT_MESSAGE = ?, LAST_UPDATED = ?, STATUS_CODE = ? "
+ "where TASK_EXECUTION_ID = ?";
+ "EXIT_MESSAGE = ?, LAST_UPDATED = ?, STATUS_CODE = ?, "
+ "TASK_EXTERNAL_EXECUTION_ID = ? where TASK_EXECUTION_ID = ?";
private static final String GET_EXECUTION_BY_ID = "SELECT TASK_EXECUTION_ID, " +
"START_TIME, END_TIME, TASK_NAME, EXIT_CODE, "
+ "EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE "
+ "EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE, TASK_EXTERNAL_EXECUTION_ID "
+ "from %PREFIX%EXECUTION where TASK_EXECUTION_ID = ?";
private static final String FIND_PARAMS_FROM_ID = "SELECT TASK_EXECUTION_ID, "
@@ -89,13 +91,13 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
private static final String FIND_RUNNING_TASK_EXECUTIONS = "SELECT TASK_EXECUTION_ID, "
+ "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, "
+ "EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE "
+ "EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE, TASK_EXTERNAL_EXECUTION_ID "
+ "from %PREFIX%EXECUTION where TASK_NAME = ? AND END_TIME IS NULL "
+ "order by TASK_EXECUTION_ID";
private static final String FIND_TASK_EXECUTIONS_BY_NAME = "SELECT TASK_EXECUTION_ID, "
+ "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, "
+ "EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE "
+ "EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE, TASK_EXTERNAL_EXECUTION_ID "
+ "from %PREFIX%EXECUTION where TASK_NAME = ? "
+ "order by TASK_EXECUTION_ID "
+ "LIMIT ? OFFSET ?";
@@ -110,7 +112,9 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
private DataSource dataSource;
Map<String, Order> orderMap;
private Map<String, Order> orderMap;
private DataFieldMaxValueIncrementer taskIncrementer;
public JdbcTaskExecutionDao(DataSource dataSource) {
Assert.notNull(dataSource);
@@ -119,12 +123,12 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
orderMap = new TreeMap<>();
orderMap.put("START_TIME", Order.DESCENDING);
orderMap.put("TASK_EXECUTION_ID", Order.DESCENDING);
}
@Override
public void saveTaskExecution(TaskExecution taskExecution) {
Object[] parameters = new Object[]{ taskExecution.getExecutionId(),
taskExecution.getExternalExecutionID(),
taskExecution.getStartTime(), taskExecution.getEndTime(),
taskExecution.getTaskName(), taskExecution.getExitCode(),
taskExecution.getExitMessage(), new Date(),
@@ -132,8 +136,9 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
jdbcTemplate.update(
getQuery(SAVE_TASK_EXECUTION),
parameters,
new int[]{ Types.VARCHAR, Types.TIMESTAMP, Types.TIMESTAMP, Types.VARCHAR,
Types.INTEGER, Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR });
new int[]{ Types.BIGINT, Types.VARCHAR, Types.TIMESTAMP, Types.TIMESTAMP,
Types.VARCHAR, Types.INTEGER, Types.VARCHAR, Types.TIMESTAMP,
Types.VARCHAR });
insertTaskParameters(taskExecution.getExecutionId(), taskExecution.getParameters());
}
@@ -149,12 +154,13 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
Object[] parameters = new Object[]{ taskExecution.getStartTime(), taskExecution.getEndTime(),
taskExecution.getTaskName(), taskExecution.getExitCode(),
taskExecution.getExitMessage(), new Date(), taskExecution.getStatusCode(),
taskExecution.getExecutionId() };
taskExecution.getExternalExecutionID(), taskExecution.getExecutionId()};
jdbcTemplate.update(
getQuery(UPDATE_TASK_EXECUTION),
parameters,
new int[]{ Types.TIMESTAMP, Types.TIMESTAMP, Types.VARCHAR, Types.INTEGER,
Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR, Types.VARCHAR });
Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR, Types.VARCHAR,
Types.BIGINT});
}
/**
@@ -169,7 +175,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
}
@Override
public TaskExecution getTaskExecution(String executionId) {
public TaskExecution getTaskExecution(long executionId) {
try {
TaskExecution taskExecution = jdbcTemplate.queryForObject(getQuery(GET_EXECUTION_BY_ID),
new TaskExecutionRowMapper(), executionId);
@@ -248,6 +254,14 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
return new PageImpl<TaskExecution>(resultList, pageable, getTaskExecutionCount());
}
public void setTaskIncrementer(DataFieldMaxValueIncrementer taskIncrementer) {
this.taskIncrementer = taskIncrementer;
}
public long getNextExecutionId(){
return taskIncrementer.nextLongValue();
}
private String getQuery(String base) {
return StringUtils.replace(base, "%PREFIX%", tablePrefix);
}
@@ -259,7 +273,7 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
* @param executionId The executionId to which the params are associated.
* @param taskParameters The parameters to be stored.
*/
private void insertTaskParameters(String executionId, List<String> taskParameters) {
private void insertTaskParameters(long executionId, List<String> taskParameters) {
for (String param : taskParameters) {
insertParameter(executionId, param);
}
@@ -269,13 +283,13 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
* Convenience method that inserts an individual records into the
* TASK_EXECUTION_PARAMS table.
*/
private void insertParameter(String executionId, String param) {
private void insertParameter(long executionId, String param) {
int[] argTypes = new int[]{ Types.VARCHAR, Types.VARCHAR };
Object[] args = new Object[]{ executionId, param };
jdbcTemplate.update(getQuery(CREATE_TASK_PARAMETER), args, argTypes);
}
private List<String> getTaskParameters(String executionId){
private List<String> getTaskParameters(long executionId){
final List<String> params= new ArrayList<>();
RowCallbackHandler handler = new RowCallbackHandler() {
@Override
@@ -287,7 +301,6 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
jdbcTemplate.query(getQuery(FIND_PARAMS_FROM_ID), new Object[] { executionId },
handler);
return params;
}
/**
* Re-usable mapper for {@link TaskExecution} instances.
@@ -300,16 +313,16 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {
@Override
public TaskExecution mapRow(ResultSet rs, int rowNum) throws SQLException {
String id = rs.getString("TASK_EXECUTION_ID");
TaskExecution taskExecution=new TaskExecution();
taskExecution.setExecutionId(id);
taskExecution.setStartTime(rs.getTimestamp("START_TIME"));
taskExecution.setEndTime(rs.getTimestamp("END_TIME"));
taskExecution.setExitCode(rs.getInt("EXIT_CODE"));
taskExecution.setExitMessage(rs.getString("EXIT_MESSAGE"));
taskExecution.setStatusCode(rs.getString("STATUS_CODE"));
taskExecution.setTaskName(rs.getString("TASK_NAME"));
taskExecution.setParameters(getTaskParameters(id));
long id = rs.getLong("TASK_EXECUTION_ID");
TaskExecution taskExecution=new TaskExecution(id,
rs.getInt("EXIT_CODE"),
rs.getString("TASK_NAME"),
rs.getTimestamp("START_TIME"),
rs.getTimestamp("END_TIME"),
rs.getString("STATUS_CODE"),
rs.getString("EXIT_MESSAGE"),
getTaskParameters(id),
rs.getString("TASK_EXTERNAL_EXECUTION_ID"));
return taskExecution;
}
}

View File

@@ -25,6 +25,7 @@ import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.data.domain.Page;
@@ -38,7 +39,9 @@ import org.springframework.data.domain.Pageable;
*/
public class MapTaskExecutionDao implements TaskExecutionDao {
private ConcurrentMap<String, TaskExecution> taskExecutions;
private ConcurrentMap<Long, TaskExecution> taskExecutions;
private final AtomicLong currentId = new AtomicLong(0L);
public MapTaskExecutionDao() {
taskExecutions = new ConcurrentHashMap<>();
@@ -55,14 +58,14 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
}
@Override
public TaskExecution getTaskExecution(String executionId) {
public TaskExecution getTaskExecution(long executionId) {
return taskExecutions.get(executionId);
}
@Override
public long getTaskExecutionCountByTaskName(String taskName) {
int count = 0;
for (Map.Entry<String, TaskExecution> entry : taskExecutions.entrySet()) {
for (Map.Entry<Long, TaskExecution> entry : taskExecutions.entrySet()) {
if (entry.getValue().getTaskName().equals(taskName)) {
count++;
}
@@ -78,7 +81,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
@Override
public Set<TaskExecution> findRunningTaskExecutions(String taskName) {
Set<TaskExecution> result = getTaskExecutionTreeSet();
for (Map.Entry<String, TaskExecution> entry : taskExecutions.entrySet()) {
for (Map.Entry<Long, TaskExecution> entry : taskExecutions.entrySet()) {
if (entry.getValue().getTaskName().equals(taskName) &&
entry.getValue().getEndTime() == null) {
result.add(entry.getValue());
@@ -91,7 +94,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
public List<TaskExecution> getTaskExecutionsByName(String taskName, int start, int count) {
List<TaskExecution> result = new ArrayList<>();
Set<TaskExecution> filteredSet = getTaskExecutionTreeSet();
for (Map.Entry<String, TaskExecution> entry : taskExecutions.entrySet()) {
for (Map.Entry<Long, TaskExecution> entry : taskExecutions.entrySet()) {
if (entry.getValue().getTaskName().equals(taskName)) {
filteredSet.add(entry.getValue());
}
@@ -103,7 +106,7 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
@Override
public List<String> getTaskNames() {
Set<String> result = new TreeSet<>();
for (Map.Entry<String, TaskExecution> entry : taskExecutions.entrySet()) {
for (Map.Entry<Long, TaskExecution> entry : taskExecutions.entrySet()) {
result.add(entry.getValue().getTaskName());
}
return new ArrayList<String>(result);
@@ -122,21 +125,24 @@ public class MapTaskExecutionDao implements TaskExecutionDao {
getTaskExecutionCount());
}
public Map<String, TaskExecution> getTaskExecutions() {
public Map<Long, TaskExecution> getTaskExecutions() {
return Collections.unmodifiableMap(taskExecutions);
}
public long getNextExecutionId(){
return currentId.getAndIncrement();
}
private TreeSet<TaskExecution> getTaskExecutionTreeSet() {
return new TreeSet<TaskExecution>(new Comparator<TaskExecution>() {
@Override
public int compare(TaskExecution e1, TaskExecution e2) {
int result = e1.getStartTime().compareTo(e2.getStartTime());
if (result == 0){
result = e1.getExecutionId().compareTo(e2.getExecutionId());
result = Long.valueOf(e1.getExecutionId()).compareTo(e2.getExecutionId());
}
return result;
}
});
}
}

View File

@@ -47,10 +47,10 @@ public interface TaskExecutionDao {
/**
* Retrieves a task execution from the task repository.
*
* @param executionId the uuid associated with the task execution.
* @param executionId the id associated with the task execution.
* @return a fully qualified TaskExecution instance.
*/
TaskExecution getTaskExecution(String executionId);
TaskExecution getTaskExecution(long executionId);
/**
* Retrieves current number of task executions for a taskName.
@@ -100,4 +100,10 @@ public interface TaskExecutionDao {
*/
public Page<TaskExecution> findAll(Pageable pageable);
/**
* Retrieves the next available execution id for a task execution.
* @return long containing the executionId.
*/
public long getNextExecutionId();
}

View File

@@ -20,10 +20,13 @@ import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.item.database.support.DataFieldMaxValueIncrementerFactory;
import org.springframework.batch.item.database.support.DefaultDataFieldMaxValueIncrementerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.cloud.task.repository.TaskRepository;
import org.springframework.cloud.task.repository.dao.JdbcTaskExecutionDao;
import org.springframework.cloud.task.repository.dao.TaskExecutionDao;
import org.springframework.jdbc.support.MetaDataAccessException;
/**
* Automates the creation of a {@link SimpleTaskRepository} which will persist task
@@ -42,6 +45,8 @@ public class JdbcTaskRepositoryFactoryBean implements FactoryBean<TaskRepository
private String tablePrefix = DEFAULT_TABLE_PREFIX;
private DataFieldMaxValueIncrementerFactory incrementerFactory;
public JdbcTaskRepositoryFactoryBean(){
}
@@ -50,6 +55,7 @@ public class JdbcTaskRepositoryFactoryBean implements FactoryBean<TaskRepository
if(dataSource != null) {
this.dataSource = dataSource;
}
incrementerFactory = new DefaultDataFieldMaxValueIncrementerFactory(dataSource);
}
/**
@@ -82,9 +88,18 @@ public class JdbcTaskRepositoryFactoryBean implements FactoryBean<TaskRepository
return true;
}
private TaskExecutionDao createJdbcTaskExecutionDao() {
private TaskExecutionDao createJdbcTaskExecutionDao() {
JdbcTaskExecutionDao dao = new JdbcTaskExecutionDao(dataSource);
String databaseType = null;
try {
databaseType = org.springframework.batch.support.DatabaseType.fromMetaData(dataSource).name();
}
catch (MetaDataAccessException e) {
throw new IllegalStateException(e);
}
dao.setTaskIncrementer(incrementerFactory.getIncrementer(databaseType, tablePrefix + "SEQ"));
dao.setTablePrefix(tablePrefix);
return dao;
}
}

View File

@@ -41,7 +41,7 @@ public class SimpleTaskExplorer implements TaskExplorer{
}
@Override
public TaskExecution getTaskExecution(String executionId) {
public TaskExecution getTaskExecution(long executionId) {
return taskExecutionDao.getTaskExecution(executionId);
}

View File

@@ -32,7 +32,7 @@ public class SimpleTaskRepository implements TaskRepository {
public static final int MAX_EXIT_MESSAGE_SIZE = 2500;
public static final int MAX_TASK_NAME_SIZE = 100;
public static final int MAX_STATUS_CODE_SIZE = 10;
public static final int MAX_EXECUTION_ID_SIZE = 100;
public static final int MAX_EXTERNAL_EXECUTION_ID_SIZE = 100;
private final static Logger logger = LoggerFactory.getLogger(SimpleTaskRepository.class);
@@ -56,6 +56,10 @@ public class SimpleTaskRepository implements TaskRepository {
logger.info("Creating: " + taskExecution.toString());
}
@Override
public long getNextExecutionId() {
return taskExecutionDao.getNextExecutionId();
}
/**
* Retrieves the taskExecutionDao associated with this repository.
@@ -72,7 +76,6 @@ public class SimpleTaskRepository implements TaskRepository {
*/
private void validateTaskExecution(TaskExecution taskExecution) {
Assert.notNull(taskExecution, "taskExecution should not be null");
Assert.hasText(taskExecution.getExecutionId(), "taskExecutionId should not be null");
Assert.notNull(taskExecution.getStartTime(), "TaskExecution start time cannot be null.");
if (taskExecution.getTaskName() != null &&
@@ -85,9 +88,10 @@ public class SimpleTaskRepository implements TaskRepository {
throw new IllegalArgumentException("StatusCode length exceeds "
+ MAX_STATUS_CODE_SIZE + " characters");
}
if (taskExecution.getExecutionId().length() > MAX_EXECUTION_ID_SIZE) {
throw new IllegalArgumentException("ExecutionID length exceeds "
+ MAX_EXECUTION_ID_SIZE + " characters");
if (taskExecution.getExternalExecutionID() != null &&
taskExecution.getExternalExecutionID().length() > MAX_EXTERNAL_EXECUTION_ID_SIZE) {
throw new IllegalArgumentException("externalExecutionID length exceeds "
+ MAX_EXTERNAL_EXECUTION_ID_SIZE + " characters");
}
//Trim the exit message
if(taskExecution.getExitMessage() != null &&

View File

@@ -1,6 +1,7 @@
CREATE TABLE TASK_EXECUTION (
TASK_EXECUTION_ID VARCHAR(100) NOT NULL PRIMARY KEY ,
TASK_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY ,
TASK_EXTERNAL_EXECUTION_ID VARCHAR(100) ,
START_TIME TIMESTAMP DEFAULT NULL ,
END_TIME TIMESTAMP DEFAULT NULL ,
TASK_NAME VARCHAR(100) ,
@@ -11,8 +12,12 @@ CREATE TABLE TASK_EXECUTION (
);
CREATE TABLE TASK_EXECUTION_PARAMS (
TASK_EXECUTION_ID VARCHAR(100) NOT NULL ,
TASK_EXECUTION_ID BIGINT NOT NULL ,
TASK_PARAM VARCHAR(250) ,
constraint TASK_EXEC_PARAMS_FK foreign key (TASK_EXECUTION_ID)
references TASK_EXECUTION(TASK_EXECUTION_ID)
) ;
CREATE TABLE TASK_SEQ (
ID BIGINT IDENTITY
);

View File

@@ -1,6 +1,7 @@
CREATE TABLE TASK_EXECUTION (
TASK_EXECUTION_ID VARCHAR(100) NOT NULL PRIMARY KEY ,
TASK_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY ,
TASK_EXTERNAL_EXECUTION_ID VARCHAR(100),
START_TIME DATETIME DEFAULT NULL ,
END_TIME DATETIME DEFAULT NULL ,
TASK_NAME VARCHAR(100) ,
@@ -11,8 +12,17 @@ CREATE TABLE TASK_EXECUTION (
);
CREATE TABLE TASK_EXECUTION_PARAMS (
TASK_EXECUTION_ID VARCHAR(100) NOT NULL ,
TASK_EXECUTION_ID BIGINT NOT NULL ,
TASK_PARAM VARCHAR(250) ,
constraint TASK_EXEC_PARAMS_FK foreign key (TASK_EXECUTION_ID)
references TASK_EXECUTION(TASK_EXECUTION_ID)
) ;
CREATE TABLE TASK_SEQ (
ID BIGINT NOT NULL,
UNIQUE_KEY CHAR(1) NOT NULL,
constraint UNIQUE_KEY_UN unique (UNIQUE_KEY)
) ENGINE=InnoDB;
INSERT INTO TASK_SEQ (ID, UNIQUE_KEY) select * from (select 0 as ID, '0' as UNIQUE_KEY) as tmp;

View File

@@ -1,6 +1,7 @@
CREATE TABLE TASK_EXECUTION (
TASK_EXECUTION_ID VARCHAR2(100) NOT NULL PRIMARY KEY ,
TASK_EXECUTION_ID NUMBER NOT NULL PRIMARY KEY ,
TASK_EXTERNAL_EXECUTION_ID VARCHAR2(100),
START_TIME TIMESTAMP DEFAULT NULL ,
END_TIME TIMESTAMP DEFAULT NULL ,
TASK_NAME VARCHAR2(100) ,
@@ -11,8 +12,10 @@ CREATE TABLE TASK_EXECUTION (
);
CREATE TABLE TASK_EXECUTION_PARAMS (
TASK_EXECUTION_ID VARCHAR2(100) NOT NULL ,
TASK_EXECUTION_ID NUMBER NOT NULL ,
TASK_PARAM VARCHAR2(250) ,
constraint TASK_EXEC_PARAMS_FK foreign key (TASK_EXECUTION_ID)
references TASK_EXECUTION(TASK_EXECUTION_ID)
) ;
CREATE SEQUENCE TASK_SEQ START WITH 0 MINVALUE 0 MAXVALUE 9223372036854775807 NOCYCLE;

View File

@@ -1,6 +1,7 @@
CREATE TABLE TASK_EXECUTION (
TASK_EXECUTION_ID VARCHAR(100) NOT NULL PRIMARY KEY ,
TASK_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY ,
TASK_EXTERNAL_EXECUTION_ID VARCHAR(100) ,
START_TIME TIMESTAMP DEFAULT NULL ,
END_TIME TIMESTAMP DEFAULT NULL ,
TASK_NAME VARCHAR(100) ,
@@ -11,8 +12,10 @@ CREATE TABLE TASK_EXECUTION (
);
CREATE TABLE TASK_EXECUTION_PARAMS (
TASK_EXECUTION_ID VARCHAR(100) NOT NULL ,
TASK_EXECUTION_ID BIGINT NOT NULL ,
TASK_PARAM VARCHAR(250) ,
constraint TASK_EXEC_PARAMS_FK foreign key (TASK_EXECUTION_ID)
references TASK_EXECUTION(TASK_EXECUTION_ID)
) ;
CREATE SEQUENCE TASK_SEQ MAXVALUE 9223372036854775807 NO CYCLE;

View File

@@ -64,7 +64,7 @@ public class TaskLifecycleListenerTests {
context.refresh();
this.listener = context.getBean(TaskLifecycleListener.class);
TestVerifierUtils.verifyLogEntryExists(mockAppender,
"Creating: TaskExecution{executionId='" +
"Creating: TaskExecution{executionId=" +
listener.getTaskExecution().getExecutionId());
assertEquals("Create should report that exit code is zero",
0, listener.getTaskExecution().getExitCode());
@@ -78,7 +78,7 @@ public class TaskLifecycleListenerTests {
this.listener = context.getBean(TaskLifecycleListener.class);
this.listener.onApplicationEvent(new ContextClosedEvent(context));
TestVerifierUtils.verifyLogEntryExists(mockAppender,
"Updating: TaskExecution{executionId='" +
"Updating: TaskExecution{executionId=" +
listener.getTaskExecution().getExecutionId());
assertEquals("Update should report that exit code is zero",
0, listener.getTaskExecution().getExitCode());
@@ -91,7 +91,7 @@ public class TaskLifecycleListenerTests {
this.listener = context.getBean(TaskLifecycleListener.class);
listener.onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[]{}, context, new RuntimeException("This was expected")));
TestVerifierUtils.verifyLogEntryExists(mockAppender,
"Updating: TaskExecution{executionId='" +
"Updating: TaskExecution{executionId=" +
listener.getTaskExecution().getExecutionId());
assertEquals("Update should report that exit code is one",
1, listener.getTaskExecution().getExitCode());

View File

@@ -18,9 +18,9 @@ package org.springframework.cloud.task.repository.dao;
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;
@@ -28,7 +28,6 @@ import org.springframework.cloud.task.configuration.TestConfiguration;
import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.cloud.task.util.TestDBUtils;
import org.springframework.cloud.task.util.TestVerifierUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -47,10 +46,17 @@ public class JdbcTaskExecutionDaoTests {
@Autowired
private DataSource dataSource;
private JdbcTaskExecutionDao dao;
@Before
public void setup(){
dao = new JdbcTaskExecutionDao(dataSource);
dao.setTaskIncrementer(TestDBUtils.getIncrementer(dataSource));
}
@Test
@DirtiesContext
public void saveTaskExecution() {
JdbcTaskExecutionDao dao = new JdbcTaskExecutionDao(dataSource);
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoParam();
dao.saveTaskExecution(expectedTaskExecution);
@@ -58,20 +64,9 @@ public class JdbcTaskExecutionDaoTests {
TestDBUtils.getTaskExecutionFromDB(dataSource, expectedTaskExecution.getExecutionId()));
}
@Test(expected = DuplicateKeyException.class)
@DirtiesContext
public void duplicateSaveTaskExecution() {
JdbcTaskExecutionDao dao = new JdbcTaskExecutionDao(dataSource);
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoParam();
dao.saveTaskExecution(expectedTaskExecution);
dao.saveTaskExecution(expectedTaskExecution);
}
@Test
@DirtiesContext
public void updateTaskExecution() {
JdbcTaskExecutionDao dao = new JdbcTaskExecutionDao(dataSource);
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoParam();
dao.saveTaskExecution(expectedTaskExecution);
dao.updateTaskExecution(expectedTaskExecution);

View File

@@ -36,7 +36,7 @@ public class MapTaskExecutionDaoTests {
MapTaskExecutionDao dao = new MapTaskExecutionDao();
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoParam();
dao.saveTaskExecution(expectedTaskExecution);
Map<String, TaskExecution> taskExecutionMap = dao.getTaskExecutions();
Map<Long, TaskExecution> taskExecutionMap = dao.getTaskExecutions();
assertNotNull("taskExecutionMap must not be null", taskExecutionMap);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));
@@ -48,7 +48,7 @@ public class MapTaskExecutionDaoTests {
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoParam();
dao.saveTaskExecution(expectedTaskExecution);
dao.updateTaskExecution(expectedTaskExecution);
Map<String, TaskExecution> taskExecutionMap = dao.getTaskExecutions();
Map<Long, TaskExecution> taskExecutionMap = dao.getTaskExecutions();
assertNotNull("taskExecutionMap must not be null", taskExecutionMap);
TestVerifierUtils.verifyTaskExecution(expectedTaskExecution,
taskExecutionMap.get(expectedTaskExecution.getExecutionId()));

View File

@@ -41,24 +41,24 @@ public class FindAllPagingQueryProviderTests {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
{"Oracle", "SELECT TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "(SELECT TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE, ROWNUM as "
+ "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, START_TIME, "
+ "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, START_TIME, "
+ "END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, LAST_UPDATED, "
+ "STATUS_CODE FROM %PREFIX%EXECUTION ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC)) WHERE TMP_ROW_NUM >= 1 AND "
+ "TMP_ROW_NUM < 11"},
{"HSQL Database Engine","SELECT LIMIT 0 10 TASK_EXECUTION_ID, "
{"HSQL Database Engine","SELECT LIMIT 0 10 TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, "
+ "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, "
+ "LAST_UPDATED, STATUS_CODE FROM %PREFIX%EXECUTION ORDER BY "
+ "START_TIME DESC, TASK_EXECUTION_ID DESC"},
{"PostgreSQL","SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, "
{"PostgreSQL","SELECT TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, START_TIME, END_TIME, "
+ "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE "
+ "FROM %PREFIX%EXECUTION ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC LIMIT 10 OFFSET 0"},
{"MySQL","SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
{"MySQL","SELECT TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE FROM "
+ "%PREFIX%EXECUTION ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC LIMIT 0, 10"}

View File

@@ -42,27 +42,27 @@ public class WhereClausePagingQueryProviderTests {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"Oracle", "SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
{"Oracle", "SELECT TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE FROM "
+ "(SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "(SELECT TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE, ROWNUM as "
+ "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, START_TIME, "
+ "TMP_ROW_NUM FROM (SELECT TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, START_TIME, "
+ "END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, LAST_UPDATED, "
+ "STATUS_CODE FROM %PREFIX%EXECUTION "
+ "WHERE TASK_EXECUTION_ID = '0000' ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC)) WHERE TMP_ROW_NUM >= 1 AND "
+ "TMP_ROW_NUM < 11"},
{"HSQL Database Engine","SELECT LIMIT 0 10 TASK_EXECUTION_ID, "
+ "START_TIME, END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, "
+ "TASK_EXTERNAL_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, EXIT_CODE, EXIT_MESSAGE, "
+ "LAST_UPDATED, STATUS_CODE FROM %PREFIX%EXECUTION "
+ "WHERE TASK_EXECUTION_ID = '0000' ORDER BY "
+ "START_TIME DESC, TASK_EXECUTION_ID DESC"},
{"PostgreSQL","SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, "
{"PostgreSQL","SELECT TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, START_TIME, END_TIME, "
+ "TASK_NAME, EXIT_CODE, EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE "
+ "FROM %PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = '0000' "
+ "ORDER BY START_TIME DESC, "
+ "TASK_EXECUTION_ID DESC LIMIT 10 OFFSET 0"},
{"MySQL","SELECT TASK_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
{"MySQL","SELECT TASK_EXECUTION_ID, TASK_EXTERNAL_EXECUTION_ID, START_TIME, END_TIME, TASK_NAME, "
+ "EXIT_CODE, EXIT_MESSAGE, LAST_UPDATED, STATUS_CODE FROM "
+ "%PREFIX%EXECUTION WHERE TASK_EXECUTION_ID = '0000' "
+ "ORDER BY START_TIME DESC, "

View File

@@ -16,20 +16,16 @@
package org.springframework.cloud.task.repository.support;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.cloud.task.repository.support.DatabaseType.HSQL;
import static org.springframework.cloud.task.repository.support.DatabaseType.MYSQL;
import static org.springframework.cloud.task.repository.support.DatabaseType.ORACLE;
import static org.springframework.cloud.task.repository.support.DatabaseType.POSTGRES;
import static org.springframework.cloud.task.repository.support.DatabaseType.fromProductName;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.cloud.task.util.TestDBUtils;
/**
* Tests that the correct database names are selected from datasource metadata.
@@ -56,41 +52,26 @@ public class DatabaseTypeTests {
@Test
public void testFromMetaDataForHsql() throws Exception {
DataSource ds = getMockDataSource("HSQL Database Engine");
DataSource ds = TestDBUtils.getMockDataSource("HSQL Database Engine");
assertEquals(HSQL, DatabaseType.fromMetaData(ds));
}
@Test
public void testFromMetaDataForOracle() throws Exception {
DataSource ds = getMockDataSource("Oracle");
DataSource ds = TestDBUtils.getMockDataSource("Oracle");
assertEquals(ORACLE, DatabaseType.fromMetaData(ds));
}
@Test
public void testFromMetaDataForPostgres() throws Exception {
DataSource ds = getMockDataSource("PostgreSQL");
DataSource ds = TestDBUtils.getMockDataSource("PostgreSQL");
assertEquals(POSTGRES, DatabaseType.fromMetaData(ds));
}
@Test
public void testFromMetaDataForMySQL() throws Exception {
DataSource ds = getMockDataSource("MySQL");
DataSource ds = TestDBUtils.getMockDataSource("MySQL");
assertEquals(MYSQL, DatabaseType.fromMetaData(ds));
}
public DataSource getMockDataSource(String databaseProductName) throws Exception {
DatabaseMetaData dmd = mock(DatabaseMetaData.class);
DataSource ds = mock(DataSource.class);
Connection con = mock(Connection.class);
when(ds.getConnection()).thenReturn(con);
when(con.getMetaData()).thenReturn(dmd);
when(dmd.getDatabaseProductName()).thenReturn(databaseProductName);
return ds;
}
public DataSource getMockDataSource(Exception e) throws Exception {
DataSource ds = mock(DataSource.class);
when(ds.getConnection()).thenReturn(null);
return ds;
}
}

View File

@@ -33,7 +33,8 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
@@ -50,7 +51,9 @@ import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfigurati
import org.springframework.cloud.task.configuration.TestConfiguration;
import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.cloud.task.repository.TaskExplorer;
import org.springframework.cloud.task.repository.dao.JdbcTaskExecutionDao;
import org.springframework.cloud.task.repository.dao.TaskExecutionDao;
import org.springframework.cloud.task.util.TestDBUtils;
import org.springframework.cloud.task.util.TestVerifierUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.domain.Page;
@@ -71,6 +74,9 @@ public class SimpleTaskExplorerTests {
@Autowired
private TaskExplorer taskExplorer;
@Autowired(required = false)
private DataSource dataSource;
private DaoType testType;
@Parameterized.Parameters
@@ -91,6 +97,9 @@ public class SimpleTaskExplorerTests {
if (testType == DaoType.jdbc) {
initializeJdbcExplorerTest();
dao = new JdbcTaskExecutionDao(dataSource);
((JdbcTaskExecutionDao)dao).
setTaskIncrementer(TestDBUtils.getIncrementer(dataSource));
}
else {
initializeMapExplorerTest();
@@ -108,8 +117,8 @@ public class SimpleTaskExplorerTests {
@Test
public void getTaskExecution() {
Map<String, TaskExecution> expectedResults = createSampleDataSet(5);
for (String taskExecutionId : expectedResults.keySet()) {
Map<Long, TaskExecution> expectedResults = createSampleDataSet(5);
for (Long taskExecutionId : expectedResults.keySet()) {
TaskExecution actualTaskExecution =
taskExplorer.getTaskExecution(taskExecutionId);
assertNotNull(String.format(
@@ -122,10 +131,10 @@ public class SimpleTaskExplorerTests {
@Test
public void taskExecutionNotFound() {
Map<String, TaskExecution> expectedResults = createSampleDataSet(5);
Map< Long, TaskExecution> expectedResults = createSampleDataSet(5);
TaskExecution actualTaskExecution =
taskExplorer.getTaskExecution("NO_EXECUTION_PRESENT");
taskExplorer.getTaskExecution(-5);
assertNull(String.format(
"expected null for actualTaskExecution %s", testType),
actualTaskExecution);
@@ -133,8 +142,8 @@ public class SimpleTaskExplorerTests {
@Test
public void getTaskCountByTaskName() {
Map<String, TaskExecution> expectedResults = createSampleDataSet(5);
for (Map.Entry<String, TaskExecution> entry : expectedResults.entrySet()) {
Map<Long, TaskExecution> expectedResults = createSampleDataSet(5);
for (Map.Entry<Long, TaskExecution> entry : expectedResults.entrySet()) {
String taskName = entry.getValue().getTaskName();
assertEquals(String.format(
"task count for task name did not match expected result for testType %s",
@@ -145,7 +154,7 @@ public class SimpleTaskExplorerTests {
@Test
public void getTaskCount() {
Map<String, TaskExecution> expectedResults = createSampleDataSet(33);
Map<Long, TaskExecution> expectedResults = createSampleDataSet(33);
assertEquals(String.format(
"task count did not match expected result for test Type %s",
testType),
@@ -158,17 +167,15 @@ public class SimpleTaskExplorerTests {
final int COMPLETE_COUNT = 5;
final String TASK_NAME = "FOOBAR";
Map<String, TaskExecution> expectedResults = new HashMap<>();
Map<Long, TaskExecution> expectedResults = new HashMap<>();
//Store completed jobs
for (int i = 0; i < COMPLETE_COUNT; i++) {
createAndSaveTaskExecution();
int i = 0;
for (; i < COMPLETE_COUNT; i++) {
createAndSaveTaskExecution(i);
}
for (int i = 0; i < TEST_COUNT; i++) {
TaskExecution expectedTaskExecution = new TaskExecution();
expectedTaskExecution.setStartTime(new Date());
expectedTaskExecution.setExecutionId(UUID.randomUUID().toString());
expectedTaskExecution.setTaskName(TASK_NAME);
for (; i < (COMPLETE_COUNT + TEST_COUNT); i++) {
TaskExecution expectedTaskExecution = new TaskExecution(i, 0, TASK_NAME, new Date(), null, null, null, new ArrayList<String>(0), null);
dao.saveTaskExecution(expectedTaskExecution);
expectedResults.put(expectedTaskExecution.getExecutionId(), expectedTaskExecution);
}
@@ -194,10 +201,10 @@ public class SimpleTaskExplorerTests {
final int RESULT_SET_SIZE = 3;
final String TASK_NAME = "FOOBAR";
Map<String, TaskExecution> expectedResults = new HashMap<>();
Map<Long, TaskExecution> expectedResults = new HashMap<>();
//Store completed jobs
for (int i = 0; i < COMPLETE_COUNT; i++) {
createAndSaveTaskExecution();
createAndSaveTaskExecution(i);
}
for (int i = 0; i < TEST_COUNT; i++) {
@@ -226,7 +233,7 @@ public class SimpleTaskExplorerTests {
final int TEST_COUNT = 5;
Set<String> expectedResults = new HashSet<>();
for (int i = 0; i < TEST_COUNT; i++) {
TaskExecution expectedTaskExecution = createAndSaveTaskExecution();
TaskExecution expectedTaskExecution = createAndSaveTaskExecution(i);
expectedResults.add(expectedTaskExecution.getTaskName());
}
List<String> actualTaskNames = taskExplorer.getTaskNames();
@@ -261,9 +268,9 @@ public class SimpleTaskExplorerTests {
}
private void verifyPageResults(Pageable pageable, int totalNumberOfExecs) {
Map<String, TaskExecution> expectedResults = createSampleDataSet(totalNumberOfExecs);
List<String> sortedExecIds = getSortedOfTaskExecIds(expectedResults);
Iterator<String> expectedTaskExecutionIter = sortedExecIds.iterator();
Map<Long, TaskExecution> expectedResults = createSampleDataSet(totalNumberOfExecs);
List<Long> sortedExecIds = getSortedOfTaskExecIds(expectedResults);
Iterator<Long> expectedTaskExecutionIter = sortedExecIds.iterator();
//Verify pageable totals
Page taskPage = taskExplorer.findAll(pageable);
int pagesExpected = (int) Math.ceil(totalNumberOfExecs / ((double) pageable.getPageSize()));
@@ -291,7 +298,7 @@ public class SimpleTaskExplorerTests {
pageNumber), expectedPageSize, actualTaskExecutions.size());
for (TaskExecution actualExecution : actualTaskExecutions) {
assertEquals(String.format("Element on page %n did not match expected",
pageNumber), expectedTaskExecutionIter.next(),
pageNumber), (long)expectedTaskExecutionIter.next(),
actualExecution.getExecutionId());
TestVerifierUtils.verifyTaskExecution(
expectedResults.get(actualExecution.getExecutionId()),
@@ -306,8 +313,8 @@ public class SimpleTaskExplorerTests {
assertEquals("Elements processed did not equal expected,", totalNumberOfExecs, elementCount);
}
private TaskExecution createAndSaveTaskExecution() {
TaskExecution taskExecution = TestVerifierUtils.createSampleTaskExecution();
private TaskExecution createAndSaveTaskExecution(int i) {
TaskExecution taskExecution = TestVerifierUtils.createSampleTaskExecution(i);
dao.saveTaskExecution(taskExecution);
return taskExecution;
}
@@ -333,18 +340,18 @@ public class SimpleTaskExplorerTests {
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
}
private Map<String, TaskExecution> createSampleDataSet(int count){
Map<String, TaskExecution> expectedResults = new HashMap<>();
private Map<Long, TaskExecution> createSampleDataSet(int count){
Map<Long, TaskExecution> expectedResults = new HashMap<>();
for (int i = 0; i < count; i++) {
TaskExecution expectedTaskExecution = createAndSaveTaskExecution();
TaskExecution expectedTaskExecution = createAndSaveTaskExecution(i);
expectedResults.put(expectedTaskExecution.getExecutionId(),
expectedTaskExecution);
}
return expectedResults;
}
private List<String> getSortedOfTaskExecIds(Map<String, TaskExecution> taskExecutionMap){
List<String> sortedExecIds = new ArrayList<>(taskExecutionMap.size());
private List<Long> getSortedOfTaskExecIds(Map<Long, TaskExecution> taskExecutionMap){
List<Long> sortedExecIds = new ArrayList<>(taskExecutionMap.size());
TreeSet sortedSet = getTreeSet();
sortedSet.addAll(taskExecutionMap.values());
Iterator <TaskExecution> iterator = sortedSet.descendingIterator();
@@ -360,7 +367,7 @@ public class SimpleTaskExplorerTests {
public int compare(TaskExecution e1, TaskExecution e2) {
int result = e1.getStartTime().compareTo(e2.getStartTime());
if (result == 0){
result = e1.getExecutionId().compareTo(e2.getExecutionId());
result = Long.valueOf(e1.getExecutionId()).compareTo(e2.getExecutionId());
}
return result;
}

View File

@@ -116,9 +116,10 @@ public class SimpleTaskRepositoryJdbcTests {
}
@Test(expected=IllegalArgumentException.class)
public void testCreateTaskExecutionNoParamMaxExecutionId(){
public void testCreateTaskExecutionNoParamMaxExternalExecutionId(){
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoParam();
expectedTaskExecution.setExecutionId(new String(new char[SimpleTaskRepository.MAX_EXECUTION_ID_SIZE+1]));
expectedTaskExecution.setExternalExecutionID(
new String(new char[SimpleTaskRepository.MAX_EXTERNAL_EXECUTION_ID_SIZE+1]));
taskRepository.createTaskExecution(expectedTaskExecution);
}
}

View File

@@ -45,7 +45,7 @@ public class SimpleTaskRepositoryLoggerTests {
TaskExecution expectedTaskExecution =
TaskExecutionCreator.createAndStoreTaskExecutionNoParams(taskRepository);
TestVerifierUtils.verifyLogEntryExists(mockAppender,
"Creating: TaskExecution{executionId='" + expectedTaskExecution.getExecutionId());
"Creating: TaskExecution{executionId=" + expectedTaskExecution.getExecutionId());
}
@Test
@@ -56,7 +56,7 @@ public class SimpleTaskRepositoryLoggerTests {
TaskExecutionCreator.updateTaskExecution(taskRepository,
expectedTaskExecution.getExecutionId());
TestVerifierUtils.verifyLogEntryExists(mockAppender,
"Updating: TaskExecution{executionId='"
"Updating: TaskExecution{executionId="
+ expectedTaskExecution.getExecutionId());
}

View File

@@ -73,8 +73,8 @@ public class SimpleTaskRepositoryMapTests {
}
private TaskExecution getSingleTaskExecutionFromMapRepository(
TaskRepository repository, String taskExecutionId){
Map<String, TaskExecution> taskMap = ((MapTaskExecutionDao)
TaskRepository repository, long taskExecutionId){
Map<Long, TaskExecution> taskMap = ((MapTaskExecutionDao)
((SimpleTaskRepository)taskRepository).getTaskExecutionDao()).getTaskExecutions();
assertTrue("taskExecutionId must be in MapTaskExecutionRepository",
taskMap.containsKey(taskExecutionId));

View File

@@ -18,7 +18,6 @@ package org.springframework.cloud.task.repository.support;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import javax.sql.DataSource;
@@ -26,6 +25,7 @@ import org.junit.Test;
import org.springframework.cloud.task.repository.TaskRepository;
import org.springframework.cloud.task.repository.dao.JdbcTaskExecutionDao;
import org.springframework.cloud.task.repository.dao.MapTaskExecutionDao;
import org.springframework.cloud.task.util.TestDBUtils;
/**
* Tests that the TaskRepositoryFactoryBeans produce the correct repositories.
@@ -36,8 +36,8 @@ import org.springframework.cloud.task.repository.dao.MapTaskExecutionDao;
public class TaskRepositoryFactoryBeanTests {
@Test
public void testJdbcTaskRepositoryFactoryBean() {
DataSource dataSource = mock(DataSource.class);
public void testJdbcTaskRepositoryFactoryBean() throws Exception{
DataSource dataSource = TestDBUtils.getMockDataSource("HSQL Database Engine");
JdbcTaskRepositoryFactoryBean factory = new JdbcTaskRepositoryFactoryBean(dataSource);
TaskRepository repository = factory.getObject();
assertThat(repository, instanceOf(SimpleTaskRepository.class));

View File

@@ -65,9 +65,8 @@ public class TaskExecutionCreator {
* @return the taskExecution created.
*/
public static TaskExecution updateTaskExecution(TaskRepository taskRepository,
String taskExecutionId) {
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoParam();
expectedTaskExecution.setExecutionId(taskExecutionId);
long taskExecutionId) {
TaskExecution expectedTaskExecution = TestVerifierUtils.createSampleTaskExecutionNoParam(taskExecutionId);
taskRepository.update(expectedTaskExecution);
return expectedTaskExecution;
}

View File

@@ -32,12 +32,17 @@ import java.util.TreeMap;
import javax.sql.DataSource;
import org.springframework.batch.item.database.Order;
import org.springframework.batch.item.database.support.DataFieldMaxValueIncrementerFactory;
import org.springframework.batch.item.database.support.DefaultDataFieldMaxValueIncrementerFactory;
import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.cloud.task.repository.dao.JdbcTaskExecutionDao;
import org.springframework.cloud.task.repository.database.PagingQueryProvider;
import org.springframework.cloud.task.repository.database.support.SqlPagingQueryProviderFactoryBean;
import org.springframework.cloud.task.repository.support.DatabaseType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.MetaDataAccessException;
import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer;
/**
* Provides a suite of tools that allow tests the ability to retrieve results from a
@@ -49,13 +54,12 @@ public class TestDBUtils {
/**
* Retrieves the TaskExecution from the datasource.
*
* @param dataSource The datasource from which to retrieve the taskExecution.
* @param dataSource The datasource from which to retrieve the taskExecution.
* @param taskExecutionId The id of the task to search.
* @return taskExecution
* @return taskExecution retrieved from the database.
*/
public static TaskExecution getTaskExecutionFromDB(DataSource dataSource,
String taskExecutionId) {
long taskExecutionId) {
String sql = "SELECT * FROM TASK_EXECUTION WHERE "
+ "TASK_EXECUTION_ID = '"
+ taskExecutionId + "'";
@@ -64,14 +68,15 @@ public class TestDBUtils {
List<TaskExecution> rows = jdbcTemplate.query(sql, new RowMapper<TaskExecution>(){
@Override
public TaskExecution mapRow(ResultSet rs, int rownumber) throws SQLException {
TaskExecution taskExecution=new TaskExecution();
taskExecution.setExecutionId(rs.getString(1));
taskExecution.setStartTime(rs.getTimestamp("START_TIME"));
taskExecution.setEndTime(rs.getTimestamp("END_TIME"));
taskExecution.setExitCode(rs.getInt("EXIT_CODE"));
taskExecution.setExitMessage(rs.getString("EXIT_MESSAGE"));
taskExecution.setStatusCode(rs.getString("STATUS_CODE"));
taskExecution.setTaskName(rs.getString("TASK_NAME"));
TaskExecution taskExecution=new TaskExecution(rs.getLong("TASK_EXECUTION_ID"),
rs.getInt("EXIT_CODE"),
rs.getString("TASK_NAME"),
rs.getTimestamp("START_TIME"),
rs.getTimestamp("END_TIME"),
rs.getString("STATUS_CODE"),
rs.getString("EXIT_MESSAGE"),
new ArrayList<String>(0),
rs.getString("TASK_EXTERNAL_EXECUTION_ID"));
return taskExecution;
}
});
@@ -124,6 +129,12 @@ public class TestDBUtils {
return pagingQueryProvider;
}
/**
* Creates a mock DataSource for use in testing.
* @param databaseProductName the name of the database type to mock.
* @return a mock DataSource.
* @throws Exception
*/
public static DataSource getMockDataSource(String databaseProductName) throws Exception {
DatabaseMetaData dmd = mock(DatabaseMetaData.class);
DataSource ds = mock(DataSource.class);
@@ -134,6 +145,25 @@ public class TestDBUtils {
return ds;
}
/**
* Creates a incrementer for the DataSource.
* @param dataSource the datasource that the incrementer will use to record current id.
* @return a DataFieldMaxValueIncrementer object.
*/
public static DataFieldMaxValueIncrementer getIncrementer(DataSource dataSource){
DataFieldMaxValueIncrementerFactory incrementerFactory =
new DefaultDataFieldMaxValueIncrementerFactory(dataSource);
String databaseType = null;
try {
databaseType = DatabaseType.fromMetaData(dataSource).name();
}
catch (MetaDataAccessException e) {
throw new IllegalStateException(e);
}
return incrementerFactory.getIncrementer(databaseType,
"TASK_SEQ");
}
private static void populateParamsToDB(DataSource dataSource, TaskExecution taskExecution) {
String sql = "SELECT * FROM TASK_EXECUTION_PARAMS WHERE TASK_EXECUTION_ID = '"
+ taskExecution.getExecutionId() + "'";

View File

@@ -82,19 +82,63 @@ public class TestVerifierUtils {
*
* @return
*/
public static TaskExecution createSampleTaskExecutionNoParam() {
public static TaskExecution createSampleTaskExecutionNoParam(long executionId) {
Random randomGenerator = new Random();
int exitCode = randomGenerator.nextInt();
Date startTime = new Date();
Date endTime = new Date();
String executionId = UUID.randomUUID().toString();
String externalTaskExecutionID = UUID.randomUUID().toString();
String taskName = UUID.randomUUID().toString();
String exitMessage = UUID.randomUUID().toString();
String statusCode = UUID.randomUUID().toString().substring(0, 9);
return new TaskExecution(executionId, exitCode, taskName,
startTime, endTime, statusCode,
exitMessage, new ArrayList<String>());
exitMessage, new ArrayList<String>(), externalTaskExecutionID);
}
/**
* Creates a fully populated TaskExecution (except params) for testing.
*
* @return
*/
public static TaskExecution createSampleTaskExecutionNoParam() {
Random randomGenerator = new Random();
int exitCode = randomGenerator.nextInt();
Date startTime = new Date();
Date endTime = new Date();
long executionId = randomGenerator.nextLong();
String externalTaskExecutionID = UUID.randomUUID().toString();
String taskName = UUID.randomUUID().toString();
String exitMessage = UUID.randomUUID().toString();
String statusCode = UUID.randomUUID().toString().substring(0, 9);
return new TaskExecution(executionId, exitCode, taskName,
startTime, endTime, statusCode,
exitMessage, new ArrayList<String>(), externalTaskExecutionID);
}
/**
* Creates a fully populated TaskExecution for testing.
*
* @return
*/
public static TaskExecution createSampleTaskExecution(long executionId) {
Random randomGenerator = new Random();
int exitCode = randomGenerator.nextInt();
Date startTime = new Date();
Date endTime = new Date();
String externalExecutionId = UUID.randomUUID().toString();
String taskName = UUID.randomUUID().toString();
String exitMessage = UUID.randomUUID().toString();
String statusCode = UUID.randomUUID().toString().substring(0, 9);
List<String> params = new ArrayList<>(PARAM_SIZE);
for (int i = 0 ; i < PARAM_SIZE ; i++){
params.add(UUID.randomUUID().toString());
}
return new TaskExecution(executionId, exitCode, taskName,
startTime, endTime, statusCode,
exitMessage, params, externalExecutionId);
}
/**
@@ -105,9 +149,10 @@ public class TestVerifierUtils {
public static TaskExecution createSampleTaskExecution() {
Random randomGenerator = new Random();
int exitCode = randomGenerator.nextInt();
long executionId = randomGenerator.nextLong();
Date startTime = new Date();
Date endTime = new Date();
String executionId = UUID.randomUUID().toString();
String externalExecutionId = UUID.randomUUID().toString();
String taskName = UUID.randomUUID().toString();
String exitMessage = UUID.randomUUID().toString();
String statusCode = UUID.randomUUID().toString().substring(0, 9);
@@ -117,7 +162,7 @@ public class TestVerifierUtils {
}
return new TaskExecution(executionId, exitCode, taskName,
startTime, endTime, statusCode,
exitMessage, params);
exitMessage, params, externalExecutionId);
}
/**
@@ -130,6 +175,9 @@ public class TestVerifierUtils {
TaskExecution actualTaskExecution) {
assertEquals("taskExecutionId must be equal", expectedTaskExecution.getExecutionId(),
actualTaskExecution.getExecutionId());
assertEquals("taskExternalExecutionId must be equal",
expectedTaskExecution.getExternalExecutionID(),
actualTaskExecution.getExternalExecutionID());
assertEquals("startTime must be equal",
expectedTaskExecution.getStartTime(),
actualTaskExecution.getStartTime());

View File

@@ -40,8 +40,8 @@ public class TaskApplicationTests {
@Test
public void testTimeStampApp() throws Exception {
final String TEST_DATE_DOTS = ".......";
final String CREATE_TASK_MESSAGE = "Creating: TaskExecution{executionId='";
final String UPDATE_TASK_MESSAGE = "Updating: TaskExecution{executionId='";
final String CREATE_TASK_MESSAGE = "Creating: TaskExecution{executionId=";
final String UPDATE_TASK_MESSAGE = "Updating: TaskExecution{executionId=";
String[] args = { "--format=yyyy" + TEST_DATE_DOTS };
assertEquals(0, SpringApplication.exit(SpringApplication