Search in sources :

Example 1 with TaskQuery

use of org.activiti.engine.task.TaskQuery in project Activiti by Activiti.

the class CallActivityAdvancedTest method testSubProcessWithDataInputOutput.

/**
   * Test case for handing over process variables to a sub process
   */
@Deployment(resources = { "org/activiti/engine/test/bpmn/callactivity/CallActivity.testSubProcessDataInputOutput.bpmn20.xml", "org/activiti/engine/test/bpmn/callactivity/simpleSubProcess.bpmn20.xml" })
public void testSubProcessWithDataInputOutput() {
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("superVariable", "Hello from the super process.");
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("subProcessDataInputOutput", vars);
    // one task in the subprocess should be active after starting the process instance
    TaskQuery taskQuery = taskService.createTaskQuery();
    Task taskBeforeSubProcess = taskQuery.singleResult();
    assertEquals("Task in subprocess", taskBeforeSubProcess.getName());
    assertEquals("Hello from the super process.", runtimeService.getVariable(taskBeforeSubProcess.getProcessInstanceId(), "subVariable"));
    assertEquals("Hello from the super process.", taskService.getVariable(taskBeforeSubProcess.getId(), "subVariable"));
    runtimeService.setVariable(taskBeforeSubProcess.getProcessInstanceId(), "subVariable", "Hello from sub process.");
    // super variable is unchanged
    assertEquals("Hello from the super process.", runtimeService.getVariable(processInstance.getId(), "superVariable"));
    // Completing this task ends the subprocess which leads to a task in the super process
    taskService.complete(taskBeforeSubProcess.getId());
    // one task in the subprocess should be active after starting the process instance
    Task taskAfterSubProcess = taskQuery.singleResult();
    assertEquals("Task in super process", taskAfterSubProcess.getName());
    assertEquals("Hello from sub process.", runtimeService.getVariable(processInstance.getId(), "superVariable"));
    assertEquals("Hello from sub process.", taskService.getVariable(taskAfterSubProcess.getId(), "superVariable"));
    vars.clear();
    vars.put("x", 5l);
    // Completing this task ends the super process which leads to a task in the super process
    taskService.complete(taskAfterSubProcess.getId(), vars);
    // now we are the second time in the sub process but passed variables via expressions
    Task taskInSecondSubProcess = taskQuery.singleResult();
    assertEquals("Task in subprocess", taskInSecondSubProcess.getName());
    assertEquals(10l, runtimeService.getVariable(taskInSecondSubProcess.getProcessInstanceId(), "y"));
    assertEquals(10l, taskService.getVariable(taskInSecondSubProcess.getId(), "y"));
    // Completing this task ends the subprocess which leads to a task in the super process
    taskService.complete(taskInSecondSubProcess.getId());
    // one task in the subprocess should be active after starting the process instance
    Task taskAfterSecondSubProcess = taskQuery.singleResult();
    assertEquals("Task in super process", taskAfterSecondSubProcess.getName());
    assertEquals(15l, runtimeService.getVariable(taskAfterSecondSubProcess.getProcessInstanceId(), "z"));
    assertEquals(15l, taskService.getVariable(taskAfterSecondSubProcess.getId(), "z"));
    // and end last task in Super process
    taskService.complete(taskAfterSecondSubProcess.getId());
    assertProcessEnded(processInstance.getId());
    assertEquals(0, runtimeService.createExecutionQuery().list().size());
}
Also used : Task(org.activiti.engine.task.Task) HashMap(java.util.HashMap) TaskQuery(org.activiti.engine.task.TaskQuery) HistoricProcessInstance(org.activiti.engine.history.HistoricProcessInstance) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) Deployment(org.activiti.engine.test.Deployment)

Example 2 with TaskQuery

use of org.activiti.engine.task.TaskQuery in project alfresco-remote-api by Alfresco.

the class TasksImpl method update.

@Override
public Task update(String taskId, Task task, Parameters parameters) {
    TaskStateTransition taskAction = null;
    List<String> selectedProperties = parameters.getSelectedProperties();
    if (selectedProperties.contains("state")) {
        taskAction = TaskStateTransition.getTaskActionFromString(task.getState());
    }
    // Fetch the task unfiltered, we check authorization below
    TaskQuery query = activitiProcessEngine.getTaskService().createTaskQuery().taskId(taskId);
    org.activiti.engine.task.Task taskInstance = query.singleResult();
    if (taskInstance == null) {
        // Check if task exists in history, to be able to return appropriate error when trying to update an
        // existing completed task vs. an unexisting task vs. unauthorized
        boolean taskHasExisted = activitiProcessEngine.getHistoryService().createHistoricTaskInstanceQuery().taskId(taskId).count() > 0;
        if (taskHasExisted) {
            throw new UnsupportedResourceOperationException("Task with id: " + taskId + " cannot be updated, it's completed");
        } else {
            throw new EntityNotFoundException(taskId);
        }
    } else {
        String user = AuthenticationUtil.getRunAsUser();
        // Check if user is either assignee, owner or admin
        boolean authorized = authorityService.isAdminAuthority(user) || user.equals(taskInstance.getOwner()) || user.equals(taskInstance.getAssignee());
        Set<String> candidateGroups = new HashSet<String>();
        if (!authorized) {
            // Check if user is initiator of the process this task is involved with
            List<IdentityLink> linksForTask = activitiProcessEngine.getTaskService().getIdentityLinksForTask(taskId);
            // the identity-links, there is no reason why we should check candidate using a DB-query
            for (IdentityLink link : linksForTask) {
                if (user.equals(link.getUserId()) && IdentityLinkType.STARTER.equals(link.getType())) {
                    authorized = true;
                    break;
                }
                // MNT-13276
                if ((taskInstance.getAssignee() == null) && (link.getGroupId() != null) && link.getType().equals(IdentityLinkType.CANDIDATE)) {
                    Set<String> userGroups = authorityService.getAuthoritiesForUser(user);
                    if (userGroups.contains(link.getGroupId())) {
                        authorized = true;
                        break;
                    }
                }
                if (taskAction == TaskStateTransition.CLAIMED && link.getGroupId() != null && link.getType().equals(IdentityLinkType.CANDIDATE)) {
                    candidateGroups.add(link.getGroupId());
                }
                if (taskAction == TaskStateTransition.CLAIMED && link.getUserId() != null && link.getType().equals(IdentityLinkType.CANDIDATE) && user.equals(link.getUserId())) {
                    // User is a direct candidate for the task, authorized to claim
                    authorized = true;
                    break;
                }
            }
        }
        // When claiming, a limited update (set assignee through claim) is allowed
        if (!authorized && taskAction == TaskStateTransition.CLAIMED) {
            Set<String> userGroups = authorityService.getAuthoritiesForUser(user);
            for (String group : candidateGroups) {
                if (userGroups.contains(group)) {
                    authorized = true;
                    break;
                }
            }
        }
        if (!authorized) {
            // None of the above conditions are met, not authorized to update task
            throw new PermissionDeniedException();
        }
    }
    // Update fields if no action is required
    if (taskAction == null) {
        // Only update task in Activiti API if actual properties are changed
        if (updateTaskProperties(selectedProperties, task, taskInstance)) {
            activitiProcessEngine.getTaskService().saveTask(taskInstance);
        }
    } else {
        // Perform actions associated to state transition
        if (taskAction != null) {
            // look for variables submitted with task action
            Map<String, Object> globalVariables = new HashMap<String, Object>();
            Map<String, Object> localVariables = new HashMap<String, Object>();
            if (selectedProperties.contains("variables") && task.getVariables() != null && task.getVariables().size() > 0) {
                for (TaskVariable taskVariable : task.getVariables()) {
                    taskVariable = convertToTypedVariable(taskVariable, taskInstance);
                    if (taskVariable.getVariableScope() == VariableScope.GLOBAL) {
                        globalVariables.put(taskVariable.getName(), taskVariable.getValue());
                    } else {
                        localVariables.put(taskVariable.getName(), taskVariable.getValue());
                    }
                }
            }
            switch(taskAction) {
                case CLAIMED:
                    try {
                        activitiProcessEngine.getTaskService().claim(taskId, AuthenticationUtil.getRunAsUser());
                    } catch (ActivitiTaskAlreadyClaimedException atace) {
                        throw new ConstraintViolatedException("The task is already claimed by another user.");
                    }
                    break;
                case COMPLETED:
                    if (localVariables.size() > 0) {
                        activitiProcessEngine.getTaskService().setVariablesLocal(taskId, localVariables);
                    }
                    setOutcome(taskId);
                    if (globalVariables.size() > 0) {
                        activitiProcessEngine.getTaskService().complete(taskId, globalVariables);
                    } else {
                        activitiProcessEngine.getTaskService().complete(taskId);
                    }
                    break;
                case DELEGATED:
                    if (selectedProperties.contains("assignee") && task.getAssignee() != null) {
                        if (taskInstance.getAssignee() == null || !taskInstance.getAssignee().equals(AuthenticationUtil.getRunAsUser())) {
                            // Alter assignee before delegating to preserve trail of who actually delegated
                            activitiProcessEngine.getTaskService().setAssignee(taskId, AuthenticationUtil.getRunAsUser());
                        }
                        activitiProcessEngine.getTaskService().delegateTask(taskId, task.getAssignee());
                    } else {
                        throw new InvalidArgumentException("When delegating a task, assignee should be selected and provided in the request.");
                    }
                    break;
                case RESOLVED:
                    if (localVariables.size() > 0) {
                        activitiProcessEngine.getTaskService().setVariablesLocal(taskId, localVariables);
                    }
                    setOutcome(taskId);
                    if (globalVariables.size() > 0) {
                        activitiProcessEngine.getTaskService().resolveTask(taskId, globalVariables);
                    } else {
                        activitiProcessEngine.getTaskService().resolveTask(taskId);
                    }
                    break;
                case UNCLAIMED:
                    activitiProcessEngine.getTaskService().setAssignee(taskId, null);
                    break;
            }
        }
    }
    Task responseTask = new Task(activitiProcessEngine.getHistoryService().createHistoricTaskInstanceQuery().taskId(taskId).singleResult());
    // if the task is not ended the task state might be pending or resolved
    if (responseTask.getEndedAt() == null) {
        try {
            org.activiti.engine.task.Task runningTask = activitiProcessEngine.getTaskService().createTaskQuery().taskId(taskId).singleResult();
            if (runningTask != null) {
                if (runningTask.getDelegationState() == DelegationState.PENDING) {
                    responseTask.setState(TaskStateTransition.DELEGATED.name().toLowerCase());
                } else if (runningTask.getDelegationState() == DelegationState.RESOLVED) {
                    responseTask.setState(TaskStateTransition.RESOLVED.name().toLowerCase());
                }
            }
        } catch (Exception e) {
        // ignore the exception
        }
    }
    return responseTask;
}
Also used : Task(org.alfresco.rest.workflow.api.model.Task) TaskStateTransition(org.alfresco.rest.workflow.api.model.TaskStateTransition) UnsupportedResourceOperationException(org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationException) HashMap(java.util.HashMap) TaskVariable(org.alfresco.rest.workflow.api.model.TaskVariable) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) IdentityLink(org.activiti.engine.task.IdentityLink) ConstraintViolatedException(org.alfresco.rest.framework.core.exceptions.ConstraintViolatedException) PermissionDeniedException(org.alfresco.rest.framework.core.exceptions.PermissionDeniedException) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) UnsupportedResourceOperationException(org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationException) ActivitiTaskAlreadyClaimedException(org.activiti.engine.ActivitiTaskAlreadyClaimedException) ConstraintViolatedException(org.alfresco.rest.framework.core.exceptions.ConstraintViolatedException) InvalidQNameException(org.alfresco.service.namespace.InvalidQNameException) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) ActivitiTaskAlreadyClaimedException(org.activiti.engine.ActivitiTaskAlreadyClaimedException) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) TaskQuery(org.activiti.engine.task.TaskQuery) PermissionDeniedException(org.alfresco.rest.framework.core.exceptions.PermissionDeniedException) HashSet(java.util.HashSet)

Example 3 with TaskQuery

use of org.activiti.engine.task.TaskQuery in project alfresco-remote-api by Alfresco.

the class TasksImpl method getValidTask.

/**
 * Get a valid {@link org.activiti.engine.task.Task} based on the given task id. Checks if current logged
 * in user is assignee/owner/involved with the task. In case true was passed for "validIfClaimable",
 * the task is also valid if the current logged in user is a candidate for claiming the task.
 *
 * @throws EntityNotFoundException when the task was not found
 * @throws PermissionDeniedException when the current logged in user isn't allowed to access task.
 */
protected org.activiti.engine.task.Task getValidTask(String taskId) {
    if (taskId == null) {
        throw new InvalidArgumentException("Task id is required.");
    }
    TaskQuery query = activitiProcessEngine.getTaskService().createTaskQuery().taskId(taskId);
    if (authorityService.isAdminAuthority(AuthenticationUtil.getRunAsUser())) {
        // Admin is allowed to read all tasks in the current tenant
        if (tenantService.isEnabled()) {
            query.processVariableValueEquals(ActivitiConstants.VAR_TENANT_DOMAIN, TenantUtil.getCurrentDomain());
        }
    } else {
        // If non-admin user, involvement in the task is required (either owner, assignee or externally involved).
        query.taskInvolvedUser(AuthenticationUtil.getRunAsUser());
    }
    org.activiti.engine.task.Task taskInstance = query.singleResult();
    if (taskInstance == null) {
        // Either the task doesn't exist or the user is not involved directly. We can differentiate by
        // checking if the task exists without applying the additional filtering
        taskInstance = activitiProcessEngine.getTaskService().createTaskQuery().taskId(taskId).singleResult();
        if (taskInstance == null) {
            // Full error message will be "Task with id: 'id' was not found"
            throw new EntityNotFoundException(taskId);
        } else {
            // Task is not yet finished, so potentially claimable. If user is part of a "candidateGroup", the task is accessible to the
            // user regardless of not being involved/owner/assignee
            boolean isTaskClaimable = activitiProcessEngine.getTaskService().createTaskQuery().taskCandidateGroupIn(new ArrayList<String>(authorityService.getAuthoritiesForUser(AuthenticationUtil.getRunAsUser()))).taskId(taskId).count() == 1;
            if (isTaskClaimable == false) {
                throw new PermissionDeniedException();
            }
        }
    }
    return taskInstance;
}
Also used : InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) TaskQuery(org.activiti.engine.task.TaskQuery) ArrayList(java.util.ArrayList) PermissionDeniedException(org.alfresco.rest.framework.core.exceptions.PermissionDeniedException) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException)

Example 4 with TaskQuery

use of org.activiti.engine.task.TaskQuery in project midpoint by Evolveum.

the class TestActivitiQuery method test210TestQueryByIdentityLink.

@Test
public void test210TestQueryByIdentityLink() throws Exception {
    final String TEST_NAME = "test210TestQueryByIdentityLink";
    TestUtil.displayTestTile(this, TEST_NAME);
    login(userAdministrator);
    TaskService taskService = activitiEngine.getTaskService();
    TaskQuery tq = taskService.createTaskQuery();
    org.activiti.engine.task.Task task = tq.singleResult();
    System.out.println("Task = " + task);
    assertNotNull("No task", task);
    final String TASK_NAME = "Approve assigning Role1a to jack";
    List<IdentityLink> linksBefore = taskService.getIdentityLinksForTask(task.getId());
    System.out.println("Identity links (before)" + linksBefore);
    taskService.addUserIdentityLink(task.getId(), "123", CommonProcessVariableNames.MIDPOINT_ASSIGNEE);
    taskService.addUserIdentityLink(task.getId(), "456", CommonProcessVariableNames.MIDPOINT_ASSIGNEE);
    List<IdentityLink> linksAfter = taskService.getIdentityLinksForTask(task.getId());
    System.out.println("Identity links (after)" + linksAfter);
    TaskQuery tq1 = taskService.createTaskQuery().taskInvolvedUser("UserType:" + userLead1Oid).taskName(TASK_NAME);
    assertFound(tq1, "involved user (assignee)");
    assertFound(taskService.createTaskQuery().taskInvolvedUser("123").taskName(TASK_NAME), "involved user (midpoint-assignee 123)");
    assertFound(taskService.createTaskQuery().taskInvolvedUser("456").taskName(TASK_NAME), "involved user (midpoint-assignee 456)");
    assertNotFound(taskService.createTaskQuery().taskInvolvedUser("123xxx").taskName(TASK_NAME), "involved user (wrong user)");
    assertFound(taskService.createTaskQuery().taskInvolvedUser("123;124").taskName(TASK_NAME), "involved user (123 or 124)");
    assertFound(taskService.createTaskQuery().taskInvolvedUser("124;123").taskName(TASK_NAME), "involved user (124 or 123)");
    assertNotFound(taskService.createTaskQuery().taskInvolvedUser("124x;123x").taskName(TASK_NAME), "involved user (124x or 123x)");
    assertFound(taskService.createTaskQuery().or().taskInvolvedUser("123").taskCandidateGroup("xxxxxxx").endOr().taskName(TASK_NAME), "involved user (123 or candidate group xxxxxxx)");
    assertFound(taskService.createTaskQuery().or().taskInvolvedUser("123;124").taskCandidateGroup("xxxxxxx").endOr().taskName(TASK_NAME), "involved user (123 or 124 or candidate group xxxxxxx)");
    assertNotFound(taskService.createTaskQuery().or().taskInvolvedUser("123x;124x").taskCandidateGroup("xxxxxxx").endOr().taskName(TASK_NAME), "involved user (123x or 124x or candidate group xxxxxxx)");
}
Also used : TaskService(org.activiti.engine.TaskService) TaskQuery(org.activiti.engine.task.TaskQuery) IdentityLink(org.activiti.engine.task.IdentityLink) Test(org.testng.annotations.Test)

Example 5 with TaskQuery

use of org.activiti.engine.task.TaskQuery in project midpoint by Evolveum.

the class TestActivitiQuery method test200TestQueryByTaskVariable.

/**
	 * Actually, this mechanism is not used anymore. We use identity links to store information about assignees.
	 * But keeping this test - just in case something like that would be needed later.
	 */
@Test
public void test200TestQueryByTaskVariable() throws Exception {
    final String TEST_NAME = "test200TestQueryByTaskVariable";
    TestUtil.displayTestTile(this, TEST_NAME);
    login(userAdministrator);
    TaskService taskService = activitiEngine.getTaskService();
    TaskQuery tq = taskService.createTaskQuery();
    org.activiti.engine.task.Task task = tq.singleResult();
    System.out.println("Task = " + task);
    assertNotNull("No task", task);
    final String TASK_NAME = "Approve assigning Role1a to jack";
    final String VAR = "someVariable";
    taskService.setVariableLocal(task.getId(), VAR, "[:abc];[:def];[UserType:" + userLead1Oid + "]");
    TaskQuery tq1 = taskService.createTaskQuery().includeTaskLocalVariables().taskVariableValueLike(VAR, "%:def]%").taskName(TASK_NAME);
    assertFound(tq1, "#1");
    TaskQuery tq2 = taskService.createTaskQuery().includeTaskLocalVariables().taskVariableValueLike(VAR, "%:xyz]%");
    org.activiti.engine.task.Task task2 = tq2.singleResult();
    System.out.println("Task2 = " + task2);
    assertNull("Found task2 even if it shouldn't", task2);
    TaskQuery tq3 = taskService.createTaskQuery().includeTaskLocalVariables().taskName(TASK_NAME).or().taskVariableValueLike(VAR, "%:ghi]%").taskVariableValueLike(VAR, "%:xxx]%").taskVariableValueLike(VAR, "%:" + userLead1Oid + "]%").endOr();
    org.activiti.engine.task.Task task3 = tq3.singleResult();
    System.out.println("Task3 = " + task3);
    assertNotNull("No task3", task3);
    TaskQuery tq4 = taskService.createTaskQuery().includeTaskLocalVariables().taskName(TASK_NAME).or().taskVariableValueLike(VAR, "%:" + userLead1Oid + "]%").taskVariableValueLike(VAR, "%:xxx]%").taskAssignee(userLead1Oid).endOr();
    org.activiti.engine.task.Task task4 = tq4.singleResult();
    System.out.println("Task4 = " + task4);
    assertNotNull("No task4", task4);
    TaskQuery tq5 = taskService.createTaskQuery().includeTaskLocalVariables().taskName(TASK_NAME).or().taskVariableValueLike(VAR, "%:" + userLead1Oid + "]%").taskVariableValueLike(VAR, "%:xxx]%").taskAssignee("xxx;" + userLead1Oid).endOr();
    org.activiti.engine.task.Task task5 = tq5.singleResult();
    System.out.println("Task5 = " + task5);
    assertNotNull("No task5", task5);
    TaskQuery tq6 = taskService.createTaskQuery().includeTaskLocalVariables().taskName(TASK_NAME).or().taskVariableValueLike(VAR, "%:xxx]%").taskVariableValueLike(VAR, "%:" + userLead1Oid + "]%").taskAssignee("xxx;yyy").endOr();
    org.activiti.engine.task.Task task6 = tq6.singleResult();
    System.out.println("Task6 = " + task6);
    assertNotNull("No task6", task6);
    TaskQuery tq7 = taskService.createTaskQuery().includeTaskLocalVariables().taskName(TASK_NAME).or().taskVariableValueLike(VAR, "%:xxx]%").taskVariableValueLike(VAR, "%:yyy]%").taskAssignee("xxx;UserType:" + userLead1Oid).endOr();
    org.activiti.engine.task.Task task7 = tq7.singleResult();
    System.out.println("Task7 = " + task7);
    assertNotNull("No task7", task7);
}
Also used : TaskService(org.activiti.engine.TaskService) TaskQuery(org.activiti.engine.task.TaskQuery) Test(org.testng.annotations.Test)

Aggregations

TaskQuery (org.activiti.engine.task.TaskQuery)120 Task (org.activiti.engine.task.Task)47 Deployment (org.activiti.engine.test.Deployment)30 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)21 ActivitiException (org.activiti.engine.ActivitiException)20 ArrayList (java.util.ArrayList)18 ActivitiIllegalArgumentException (org.activiti.engine.ActivitiIllegalArgumentException)12 SimpleDateFormat (java.text.SimpleDateFormat)8 Date (java.util.Date)8 HistoricProcessInstance (org.activiti.engine.history.HistoricProcessInstance)7 HashMap (java.util.HashMap)6 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)4 Test (org.junit.jupiter.api.Test)4 Map (java.util.Map)3 HistoricVariableInstance (org.activiti.engine.history.HistoricVariableInstance)3 HistoricVariableInstanceEntity (org.activiti.engine.impl.persistence.entity.HistoricVariableInstanceEntity)3 Job (org.activiti.engine.runtime.Job)3 IdentityLink (org.activiti.engine.task.IdentityLink)3 HashSet (java.util.HashSet)2 List (java.util.List)2