TSK-252: Bulk-Transfer for Task

This commit is contained in:
Marcel Lengl 2018-02-07 12:45:06 +01:00
parent 91a949f842
commit 8b0bdb94b5
8 changed files with 293 additions and 37 deletions

View File

@ -531,4 +531,11 @@ public interface TaskQuery extends BaseQuery<TaskSummary> {
* @return the query
*/
TaskQuery orderByCustom10(SortDirection sortDirection);
/*
* Filter for summaries which are containing one of the given taskIds.
* @param taskIds
* @return the taskQuery
*/
TaskQuery idIn(String... taskIds);
}

View File

@ -12,7 +12,9 @@ import pro.taskana.exceptions.InvalidWorkbasketException;
import pro.taskana.exceptions.NotAuthorizedException;
import pro.taskana.exceptions.TaskAlreadyExistException;
import pro.taskana.exceptions.TaskNotFoundException;
import pro.taskana.exceptions.TaskanaException;
import pro.taskana.exceptions.WorkbasketNotFoundException;
import pro.taskana.impl.BulkOperationResults;
import pro.taskana.model.TaskState;
/**
@ -236,4 +238,23 @@ public interface TaskService {
Task updateTask(Task task) throws InvalidArgumentException, TaskNotFoundException, ConcurrencyException,
WorkbasketNotFoundException, ClassificationNotFoundException, InvalidWorkbasketException,
NotAuthorizedException, AttachmentPersistenceException;
/**
* Transfers a list of tasks to an other workbasket. Exceptions will be thrown if the caller got no permissions on
* the target or it doesn´t exist. Other Exceptions will be stored and returned in the end.
*
* @param destinationWorkbasketKey
* target workbasket key
* @param taskIds
* source task which will be moved
* @return Bulkresult with ID and Error in it for failed transactions.
* @throws NotAuthorizedException
* if the caller hasn´t permissions on tarket WB.
* @throws InvalidArgumentException
* if the method paramesters are EMPTY or NULL.
* @throws WorkbasketNotFoundException
* if the target WB can´t be found.
*/
BulkOperationResults<String, TaskanaException> transferBulk(String destinationWorkbasketKey, List<String> taskIds)
throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException;
}

View File

@ -0,0 +1,90 @@
package pro.taskana.impl;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Returning type for a bulk db interaction with errors. This wrapper is storing them with a matching object ID.
*
* @param <K>
* unique keys for the logs.
* @param <V>
* type of the stored informations
*/
public class BulkOperationResults<K, V> {
private Optional<Map<K, V>> errorMap = Optional.of(new HashMap<K, V>());
private static final Logger LOGGER = LoggerFactory.getLogger(BulkOperationResults.class);
/**
* Returning a list of current errors as map. If there are no errors the result will be empty.
*
* @return map of errors which can´t be null.
*/
public Map<K, V> getErrorMap() {
return this.errorMap.get();
}
/**
* Adding an appearing error to the map and list them by a unique ID as key. NULL keys will be ignored.
*
* @param objectId
* unique key of a entity.
* @param error
* occurred error of a interaction with the entity
* @return status of adding the values.
*/
public boolean addError(K objectId, V error) {
boolean status = false;
try {
if (objectId != null) {
this.errorMap.get().put(objectId, error);
status = true;
}
} catch (Exception e) {
LOGGER.warn(
"Can´t add bulkoperation-error, because of a map failure. ID={}, error={} and current failure={}",
objectId, error, e);
}
return status;
}
/**
* Returning the status of a bulk-error-log.
*
* @return true if there are logged errors.
*/
public boolean containErrors() {
boolean isContainingErrors = false;
if (!this.errorMap.get().isEmpty()) {
isContainingErrors = true;
}
return isContainingErrors;
}
/**
* Returns the stored error for a unique ID or NULL if there is no error stored or ID invalid.
*
* @param idKey
* which is mapped with an error
* @return stored error for ID
*/
public V getErrorForId(K idKey) {
V result = null;
if (idKey != null) {
result = this.errorMap.get().get(idKey);
}
return result;
}
/**
* Clearing the map - all entries will be removed.
*/
public void clearErrors() {
this.errorMap.get().clear();
}
}

View File

@ -30,6 +30,7 @@ public class TaskQueryImpl implements TaskQuery {
private TaskanaEngineImpl taskanaEngineImpl;
private TaskServiceImpl taskService;
private String[] name;
private String[] taskIds;
private String description;
private String note;
private int[] priority;
@ -59,6 +60,12 @@ public class TaskQueryImpl implements TaskQuery {
this.orderBy = new ArrayList<>();
}
@Override
public TaskQuery idIn(String... taskIds) {
this.taskIds = taskIds;
return this;
}
@Override
public TaskQuery nameIn(String... names) {
this.name = names;
@ -302,6 +309,10 @@ public class TaskQueryImpl implements TaskQuery {
this.taskanaEngineImpl = taskanaEngine;
}
public String[] getTaskIds() {
return taskIds;
}
public String[] getName() {
return name;
}

View File

@ -36,6 +36,7 @@ import pro.taskana.exceptions.NotAuthorizedException;
import pro.taskana.exceptions.SystemException;
import pro.taskana.exceptions.TaskAlreadyExistException;
import pro.taskana.exceptions.TaskNotFoundException;
import pro.taskana.exceptions.TaskanaException;
import pro.taskana.exceptions.WorkbasketNotFoundException;
import pro.taskana.impl.util.IdGenerator;
import pro.taskana.impl.util.LoggerUtils;
@ -268,6 +269,7 @@ public class TaskServiceImpl implements TaskService {
task.setDomain(destinationWorkbasket.getDomain());
task.setModified(Instant.now());
task.setState(TaskState.READY);
task.setOwner(null);
taskMapper.update(task);
LOGGER.debug("Method transfer() transferred Task '{}' to destination workbasket {}", taskId,
destinationWorkbasketKey);
@ -278,6 +280,91 @@ public class TaskServiceImpl implements TaskService {
}
}
@Override
public BulkOperationResults<String, TaskanaException> transferBulk(String destinationWorkbasketKey,
List<String> taskIds) throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException {
try {
taskanaEngineImpl.openConnection();
LOGGER.debug("entry to transferBulk(targetWbKey = {}, taskIds = {})", destinationWorkbasketKey, taskIds);
// Check pre-conditions with trowing Exceptions
if (destinationWorkbasketKey == null || taskIds == null) {
throw new InvalidArgumentException(
"DestinationWorkbasketKey or TaskIds can´t be used as NULL-Parameter.");
}
Workbasket destinationWorkbasket = workbasketService.getWorkbasketByKey(destinationWorkbasketKey);
BulkOperationResults<String, TaskanaException> bulkLog = new BulkOperationResults<>();
// check tasks exist and Ids valid - log and remove
List<TaskSummary> taskSummaries = this.createTaskQuery().idIn(taskIds.toArray(new String[0])).list();
Iterator<String> taskIdIterator = taskIds.iterator();
while (taskIdIterator.hasNext()) {
String currentTaskId = taskIdIterator.next();
if (currentTaskId == null || currentTaskId.equals("")) {
bulkLog.addError("",
new InvalidArgumentException("IDs with EMPTY or NULL value are not allowed."));
taskIdIterator.remove();
} else if (!taskSummaries.stream()
.filter(taskSummary -> currentTaskId.equals(taskSummary.getTaskId()))
.findFirst()
.isPresent()) {
bulkLog.addError(currentTaskId, new TaskNotFoundException(currentTaskId));
taskIdIterator.remove();
}
}
// check source WB (read)+transfer
Set<String> workbasketKeys = new HashSet<>();
taskSummaries.stream().forEach(t -> workbasketKeys.add(t.getWorkbasketSummary().getKey()));
List<WorkbasketSummary> sourceWorkbaskets = workbasketService.createWorkbasketQuery()
.callerHasPermission(WorkbasketAuthorization.TRANSFER)
.keyIn(workbasketKeys.toArray(new String[0]))
.list();
taskIdIterator = taskIds.iterator();
while (taskIdIterator.hasNext()) {
String currentTaskId = taskIdIterator.next();
TaskSummary taskSummary = taskSummaries.stream()
.filter(t -> currentTaskId.equals(t.getTaskId()))
.findFirst()
.orElse(null);
if (taskSummaries != null) {
if (!sourceWorkbaskets.stream()
.filter(wb -> taskSummary.getWorkbasketSummary().getKey().equals(wb.getKey()))
.findFirst()
.isPresent()) {
bulkLog.addError(currentTaskId,
new NotAuthorizedException(
"The workbasket of this task got not TRANSFER permissions. TaskId=" + currentTaskId));
taskIdIterator.remove();
}
}
}
// filter taskSummaries and update values
taskSummaries = taskSummaries.stream().filter(ts -> taskIds.contains(ts.getTaskId())).collect(
Collectors.toList());
if (!taskSummaries.isEmpty()) {
Instant now = Instant.now();
List<TaskSummaryImpl> updateObjects = new ArrayList<>();
for (TaskSummary ts : taskSummaries) {
TaskSummaryImpl taskSummary = (TaskSummaryImpl) ts;
taskSummary.setRead(false);
taskSummary.setTransferred(true);
taskSummary.setWorkbasketSummary(destinationWorkbasket.asSummary());
taskSummary.setDomain(destinationWorkbasket.getDomain());
taskSummary.setModified(now);
taskSummary.setState(TaskState.READY);
taskSummary.setOwner(null);
updateObjects.add(taskSummary);
}
taskMapper.updateTransfered(taskIds, updateObjects.get(0));
}
return bulkLog;
} finally {
LOGGER.debug("exit from transferBulk(targetWbKey = {}, taskIds = {})", destinationWorkbasketKey, taskIds);
taskanaEngineImpl.returnConnection();
}
}
@Override
public Task setTaskRead(String taskId, boolean isRead)
throws TaskNotFoundException {

View File

@ -28,6 +28,7 @@ public interface QueryMapper {
@Select("<script>SELECT t.ID, t.CREATED, t.CLAIMED, t.COMPLETED, t.MODIFIED, t.PLANNED, t.DUE, t.NAME, t.DESCRIPTION, t.NOTE, t.PRIORITY, t.STATE, t.CLASSIFICATION_KEY, t.DOMAIN, t.WORKBASKET_KEY, t.BUSINESS_PROCESS_ID, t.PARENT_BUSINESS_PROCESS_ID, t.OWNER, t.POR_COMPANY, t.POR_SYSTEM, t.POR_INSTANCE, t.POR_TYPE, t.POR_VALUE, t.IS_READ, t.IS_TRANSFERRED, t.CUSTOM_1, t.CUSTOM_2, t.CUSTOM_3, t.CUSTOM_4, t.CUSTOM_5, t.CUSTOM_6, t.CUSTOM_7, t.CUSTOM_8, t.CUSTOM_9, t.CUSTOM_10 "
+ "FROM TASK t "
+ "<where>"
+ "<if test='taskIds != null'>AND t.ID IN(<foreach item='item' collection='taskIds' separator=',' >#{item}</foreach>)</if> "
+ "<if test='name != null'>AND t.NAME IN(<foreach item='item' collection='name' separator=',' >#{item}</foreach>)</if> "
+ "<if test='description != null'>AND t.DESCRIPTION like #{description}</if> "
+ "<if test='note != null'>AND t.NOTE like #{note}</if> "

View File

@ -171,4 +171,11 @@ public interface TaskMapper {
@Result(property = "custom9", column = "CUSTOM_9"),
@Result(property = "custom10", column = "CUSTOM_10")})
List<TaskSummaryImpl> findTaskSummariesByWorkbasketKey(@Param("workbasketKey") String workbasketKey);
@Update("<script>"
+ " UPDATE TASK SET MODIFIED = #{referencetask.modified}, STATE = #{referencetask.state}, WORKBASKET_KEY = #{referencetask.workbasketSummary.key}, DOMAIN = #{referencetask.domain}, OWNER = #{referencetask.owner}, IS_READ = #{referencetask.isRead}, IS_TRANSFERRED = #{referencetask.isTransferred}"
+ " WHERE ID IN <foreach item='taskId' index='index' separator=',' open='(' close=')' collection='taskIds'>#{taskId}</foreach>"
+ "</script>")
void updateTransfered(@Param("taskIds") List<String> taskIds,
@Param("referencetask") TaskSummaryImpl referencetask);
}

View File

@ -1,23 +1,27 @@
package acceptance.task;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.sql.SQLException;
import java.time.Instant;
import java.util.ArrayList;
import org.h2.store.fs.FileUtils;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import acceptance.AbstractAccTest;
import pro.taskana.Task;
import pro.taskana.TaskService;
import pro.taskana.Workbasket;
import pro.taskana.exceptions.ClassificationNotFoundException;
import pro.taskana.exceptions.InvalidArgumentException;
import pro.taskana.exceptions.InvalidOwnerException;
@ -26,7 +30,9 @@ import pro.taskana.exceptions.InvalidWorkbasketException;
import pro.taskana.exceptions.NotAuthorizedException;
import pro.taskana.exceptions.TaskAlreadyExistException;
import pro.taskana.exceptions.TaskNotFoundException;
import pro.taskana.exceptions.TaskanaException;
import pro.taskana.exceptions.WorkbasketNotFoundException;
import pro.taskana.impl.BulkOperationResults;
import pro.taskana.model.TaskState;
import pro.taskana.security.JAASRunner;
import pro.taskana.security.WithAccessId;
@ -106,7 +112,6 @@ public class TransferTaskAccTest extends AbstractAccTest {
taskService.transfer(task.getId(), "USER_1_1");
}
@Ignore
@WithAccessId(
userName = "teamlead_1",
groupNames = {"group_1"})
@ -115,55 +120,82 @@ public class TransferTaskAccTest extends AbstractAccTest {
throws SQLException, NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException,
WorkbasketNotFoundException, TaskAlreadyExistException, InvalidWorkbasketException, TaskNotFoundException,
InvalidStateException, InvalidOwnerException {
Instant before = Instant.now();
TaskService taskService = taskanaEngine.getTaskService();
ArrayList<String> taskIdList = new ArrayList<>();
taskIdList.add("TKI:000000000000000000000000000000000004");
taskIdList.add("TKI:000000000000000000000000000000000005");
// BulkOperationsResults results = taskService.transfer(taskIdList, "USER_1_1");
//
// assertFalse(results.containsErrors());
// Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000004");
// assertNotNull(transferredTask);
// assertTrue(transferredTask.isTransferred());
// assertFalse(transferredTask.isRead());
// assertEquals(TaskState.READY, transferredTask.getState());
// transferredTask = taskService.getTask("TKI:000000000000000000000000000000000005");
// assertNotNull(transferredTask);
// assertTrue(transferredTask.isTransferred());
// assertFalse(transferredTask.isRead());
// assertEquals(TaskState.READY, transferredTask.getState());
BulkOperationResults<String, TaskanaException> results = taskService.transferBulk("USER_1_1", taskIdList);
assertFalse(results.containErrors());
Workbasket wb = taskanaEngine.getWorkbasketService().getWorkbasketByKey("USER_1_1");
Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000004");
assertNotNull(transferredTask);
assertTrue(transferredTask.isTransferred());
assertFalse(transferredTask.isRead());
assertEquals(TaskState.READY, transferredTask.getState());
assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey()));
assertThat(transferredTask.getDomain(), equalTo(wb.getDomain()));
assertTrue(transferredTask.getModified().isAfter(before));
assertThat(transferredTask.getOwner(), equalTo(null));
transferredTask = taskService.getTask("TKI:000000000000000000000000000000000005");
assertNotNull(transferredTask);
assertTrue(transferredTask.isTransferred());
assertFalse(transferredTask.isRead());
assertEquals(TaskState.READY, transferredTask.getState());
assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey()));
assertThat(transferredTask.getDomain(), equalTo(wb.getDomain()));
assertTrue(transferredTask.getModified().isAfter(before));
assertThat(transferredTask.getOwner(), equalTo(null));
}
@Ignore
@WithAccessId(
userName = "teamlead_1")
@WithAccessId(userName = "teamlead_1", groupNames = {"group_1"})
@Test
public void testBulkTransferTaskWithException()
public void testBulkTransferTaskWithExceptions()
throws SQLException, NotAuthorizedException, InvalidArgumentException, ClassificationNotFoundException,
WorkbasketNotFoundException, TaskAlreadyExistException, InvalidWorkbasketException, TaskNotFoundException,
InvalidStateException, InvalidOwnerException {
TaskService taskService = taskanaEngine.getTaskService();
Workbasket wb = taskanaEngine.getWorkbasketService().getWorkbasketByKey("USER_1_1");
Instant before = Instant.now();
ArrayList<String> taskIdList = new ArrayList<>();
taskIdList.add("TKI:000000000000000000000000000000000006");
taskIdList.add("TKI:000000000000000000000000000000000002");
taskIdList.add("TKI:000000000000000000000000000000000006"); // working
taskIdList.add("TKI:000000000000000000000000000000000002"); // NotAuthorized
taskIdList.add(""); // InvalidArgument
taskIdList.add(null); // InvalidArgument (added with ""), duplicate
taskIdList.add("TKI:000000000000000000000000000000000099"); // TaskNotFound
// BulkOperationsResults results = taskService.transfer(taskIdList, "USER_1_1");
//
// assertTrue(results.containsErrors());
// for (results.getErrorMap().keys()) {
// assertEquals("TKI:000000000000000000000000000000000002", key);
// assertTrue(results.getErrorForId(key) instanceOf NotAuthorizedException.class);
// }
// Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000006");
// assertNotNull(transferredTask);
// assertTrue(transferredTask.isTransferred());
// assertFalse(transferredTask.isRead());
// assertEquals(TaskState.READY, transferredTask.getState());
// transferredTask = taskService.getTask("TKI:000000000000000000000000000000000002");
// assertNotNull(transferredTask);
// assertFalse(transferredTask.isTransferred());
// assertEquals("GPK_B_KSC", transferredTask.getWorkbasketKey());
BulkOperationResults<String, TaskanaException> results = taskService.transferBulk("USER_1_1", taskIdList);
assertTrue(results.containErrors());
assertThat(results.getErrorMap().values().size(), equalTo(3));
// react to result
for (String taskId : results.getErrorMap().keySet()) {
TaskanaException ex = results.getErrorForId(taskId);
if (ex instanceof NotAuthorizedException) {
System.out.println("NotAuthorizedException on bulkTransfer for taskId=" + taskId);
} else if (ex instanceof InvalidArgumentException) {
System.out.println("InvalidArgumentException on bulkTransfer for EMPTY/NULL taskId='" + taskId + "'");
} else if (ex instanceof TaskNotFoundException) {
System.out.println("TaskNotFoundException on bulkTransfer for taskId=" + taskId);
} else {
fail("Impossible failure Entry registered");
}
}
Task transferredTask = taskService.getTask("TKI:000000000000000000000000000000000006");
assertNotNull(transferredTask);
assertTrue(transferredTask.isTransferred());
assertFalse(transferredTask.isRead());
assertEquals(TaskState.READY, transferredTask.getState());
assertThat(transferredTask.getWorkbasketKey(), equalTo(wb.getKey()));
assertThat(transferredTask.getDomain(), equalTo(wb.getDomain()));
assertTrue(transferredTask.getModified().isAfter(before));
assertThat(transferredTask.getOwner(), equalTo(null));
transferredTask = taskService.getTask("TKI:000000000000000000000000000000000002");
assertNotNull(transferredTask);
assertFalse(transferredTask.isTransferred());
assertEquals("GPK_B_KSC", transferredTask.getWorkbasketKey());
}
@AfterClass