Search in sources :

Example 26 with TasksClient

use of org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient in project alfresco-remote-api by Alfresco.

the class TaskWorkflowApiTest method testDeleteTaskVariableAuthentication.

@Test
public void testDeleteTaskVariableAuthentication() throws Exception {
    RequestContext requestContext = initApiClientWithTestUser();
    String initiator = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId()).getId();
    // Start process by one user and try to access the task variables as the task assignee instead of the process
    // initiator to see if the assignee is authorized to get the task
    ProcessInstance processInstance = startAdhocProcess(initiator, requestContext.getNetworkId(), null);
    try {
        Task task = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertNotNull(task);
        TasksClient tasksClient = publicApiClient.tasksClient();
        activitiProcessEngine.getTaskService().setVariableLocal(task.getId(), "existingVariable", "Value");
        // Try updating task variables when NOT involved in the task
        try {
            tasksClient.deleteTaskVariable(task.getId(), "existingVariable");
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Permission was denied", expected.getHttpResponse());
        }
        assertTrue(activitiProcessEngine.getTaskService().hasVariableLocal(task.getId(), "existingVariable"));
        // Set assignee, task variables should be updatable now
        activitiProcessEngine.getTaskService().setAssignee(task.getId(), requestContext.getRunAsUser());
        tasksClient.deleteTaskVariable(task.getId(), "existingVariable");
        assertFalse(activitiProcessEngine.getTaskService().hasVariableLocal(task.getId(), "existingVariable"));
        activitiProcessEngine.getTaskService().setVariableLocal(task.getId(), "existingVariable", "Value");
        // Updating task variables as admin should be possible
        String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId();
        publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin));
        tasksClient.deleteTaskVariable(task.getId(), "existingVariable");
        assertFalse(activitiProcessEngine.getTaskService().hasVariableLocal(task.getId(), "existingVariable"));
        activitiProcessEngine.getTaskService().setVariableLocal(task.getId(), "existingVariable", "Value");
        // Updating the task variables as a admin from another tenant shouldn't be possible
        TestNetwork anotherNetwork = getOtherNetwork(requestContext.getNetworkId());
        tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + anotherNetwork.getId();
        publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin));
        try {
            tasksClient.deleteTaskVariable(task.getId(), "existingVariable");
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Permission was denied", expected.getHttpResponse());
        }
    } finally {
        cleanupProcessInstance(processInstance);
    }
}
Also used : PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) Task(org.activiti.engine.task.Task) TasksClient(org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient) TestNetwork(org.alfresco.rest.api.tests.RepoService.TestNetwork) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) Test(org.junit.Test)

Example 27 with TasksClient

use of org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient in project alfresco-remote-api by Alfresco.

the class TaskWorkflowApiTest method testAssociationDefinitionExtraction.

/* 
    * Test association definition extraction from the dictionary as per MNT-11472.
    *  
    * We are going to test association definition extraction through dictionary, when one is not retrieved in context.
    * Context doesn't contains all type definitions, because it requires entire history extraction of a process that causes performance implications.   
    * Type definition extraction from the dictionary is quite fast and it doesn't affect performance.
    * 
    */
@Test
@SuppressWarnings("unchecked")
public void testAssociationDefinitionExtraction() throws Exception {
    RequestContext requestContext = initApiClientWithTestUser();
    // The "wbpm:delegatee" custom association is defined in bpmDelegateeModel.xml. This association has "cm:person" target type.
    final String delegatee = "wbpm_delegatee";
    final String user = requestContext.getRunAsUser();
    final String networkId = requestContext.getNetworkId();
    // Get person
    final ActivitiScriptNode person = TenantUtil.runAsUserTenant(new TenantRunAsWork<ActivitiScriptNode>() {

        @Override
        public ActivitiScriptNode doWork() throws Exception {
            return getPersonNodeRef(user);
        }
    }, user, networkId);
    // Start custom process instance
    ProcessInstance processInstance = TenantUtil.runAsUserTenant(new TenantRunAsWork<ProcessInstance>() {

        @Override
        public ProcessInstance doWork() throws Exception {
            deployProcessDefinition("workflow/testCustomDelegatee.bpmn20.xml");
            String processDefinitionKey = "@" + networkId + "@myProcess";
            Map<String, Object> variables = new HashMap<String, Object>();
            variables.put("bpm_assignee", person);
            variables.put("wf_notifyMe", Boolean.FALSE);
            variables.put(WorkflowConstants.PROP_INITIATOR, person);
            return activitiProcessEngine.getRuntimeService().startProcessInstanceByKey(processDefinitionKey, "myProcessKey", variables);
        }
    }, user, networkId);
    // Get task
    Task activeTask = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    assertNotNull(activeTask);
    try {
        TasksClient tasksClient = publicApiClient.tasksClient();
        // Define the "wbpm_delegatee" variable for the taskDefine delegatee user name. POST request will be executed.
        JSONArray variablesArray = new JSONArray();
        JSONObject variableBody = new JSONObject();
        variableBody.put("name", delegatee);
        variableBody.put("value", user);
        variableBody.put("scope", "local");
        variablesArray.add(variableBody);
        try {
            // Set variable for the task.
            JSONObject response = tasksClient.createTaskVariables(activeTask.getId(), variablesArray);
            assertNotNull(response);
            JSONObject variable = (JSONObject) response.get("entry");
            assertEquals(delegatee, variable.get("name"));
            // Check that d:noderef type was returned with appropriate nodeRef Id value.
            assertEquals("d:noderef", variable.get("type"));
            assertEquals(person.getNodeRef().getId(), variable.get("value"));
            // Get process variables. GET request will be executed.
            response = publicApiClient.processesClient().getProcessvariables(processInstance.getId());
            assertNotNull(response);
            assertTrue(delegatee + " variable was not set", response.toJSONString().contains(delegatee));
            JSONArray entries = (JSONArray) response.get("entries");
            // Find "wbpm_delegatee" variable.
            for (Object entry : entries) {
                variable = (JSONObject) ((JSONObject) entry).get("entry");
                if (variable.get("name").equals(delegatee)) {
                    // Check that type corresponds to the target class.
                    // It means that assoc type def was retrieved successfully from the dictionary.
                    assertEquals("cm:person", variable.get("type"));
                    // Value should be an actual user name.
                    assertEquals(user, variable.get("value"));
                }
            }
        } catch (PublicApiException ex) {
            fail("Unexpected result " + ex);
        }
    } finally {
        cleanupProcessInstance(processInstance);
    }
}
Also used : Task(org.activiti.engine.task.Task) TasksClient(org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient) JSONArray(org.json.simple.JSONArray) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) ActivitiScriptNode(org.alfresco.repo.workflow.activiti.ActivitiScriptNode) JSONObject(org.json.simple.JSONObject) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) JSONObject(org.json.simple.JSONObject) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Example 28 with TasksClient

use of org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient in project alfresco-remote-api by Alfresco.

the class TaskWorkflowApiTest method testAddTaskItem.

@Test
@SuppressWarnings("unchecked")
public void testAddTaskItem() throws Exception {
    final RequestContext requestContext = initApiClientWithTestUser();
    String otherPerson = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId()).getId();
    RequestContext otherContext = new RequestContext(requestContext.getNetworkId(), otherPerson);
    String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId();
    RequestContext adminContext = new RequestContext(requestContext.getNetworkId(), tenantAdmin);
    // Create test-document and add to package
    NodeRef[] docNodeRefs = createTestDocuments(requestContext);
    ProcessInfo processInfo = startAdhocProcess(requestContext, null);
    final Task task = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(processInfo.getId()).singleResult();
    assertNotNull(task);
    activitiProcessEngine.getTaskService().setAssignee(task.getId(), null);
    try {
        TasksClient tasksClient = publicApiClient.tasksClient();
        JSONObject createItemObject = new JSONObject();
        createItemObject.put("id", docNodeRefs[0].getId());
        JSONObject result = tasksClient.addTaskItem(task.getId(), createItemObject.toJSONString());
        assertNotNull(result);
        assertEquals(docNodeRefs[0].getId(), result.get("id"));
        assertEquals("Test Doc1", result.get("name"));
        assertEquals("Test Doc1 Title", result.get("title"));
        assertEquals("Test Doc1 Description", result.get("description"));
        assertNotNull(result.get("createdAt"));
        assertEquals(requestContext.getRunAsUser(), result.get("createdBy"));
        assertNotNull(result.get("modifiedAt"));
        assertEquals(requestContext.getRunAsUser(), result.get("modifiedBy"));
        assertNotNull(result.get("size"));
        assertNotNull(result.get("mimeType"));
        JSONObject itemJSON = tasksClient.findTaskItem(task.getId(), docNodeRefs[0].getId());
        assertEquals(docNodeRefs[0].getId(), itemJSON.get("id"));
        tasksClient.deleteTaskItem(task.getId(), docNodeRefs[0].getId());
        try {
            tasksClient.findTaskItem(task.getId(), docNodeRefs[0].getId());
            fail("Expected exception");
        } catch (PublicApiException e) {
            assertEquals(404, e.getHttpResponse().getStatusCode());
        }
        // add item as admin
        publicApiClient.setRequestContext(adminContext);
        result = tasksClient.addTaskItem(task.getId(), createItemObject.toJSONString());
        assertNotNull(result);
        assertEquals(docNodeRefs[0].getId(), result.get("id"));
        assertEquals("Test Doc1", result.get("name"));
        itemJSON = tasksClient.findTaskItem(task.getId(), docNodeRefs[0].getId());
        assertEquals(docNodeRefs[0].getId(), itemJSON.get("id"));
        tasksClient.deleteTaskItem(task.getId(), docNodeRefs[0].getId());
        try {
            tasksClient.findTaskItem(task.getId(), docNodeRefs[0].getId());
            fail("Expected exception");
        } catch (PublicApiException e) {
            assertEquals(404, e.getHttpResponse().getStatusCode());
        }
        // add item with candidate user
        activitiProcessEngine.getTaskService().addCandidateUser(task.getId(), otherPerson);
        publicApiClient.setRequestContext(otherContext);
        result = tasksClient.addTaskItem(task.getId(), createItemObject.toJSONString());
        assertNotNull(result);
        assertEquals(docNodeRefs[0].getId(), result.get("id"));
        assertEquals("Test Doc1", result.get("name"));
        itemJSON = tasksClient.findTaskItem(task.getId(), docNodeRefs[0].getId());
        assertEquals(docNodeRefs[0].getId(), itemJSON.get("id"));
        tasksClient.deleteTaskItem(task.getId(), docNodeRefs[0].getId());
        try {
            tasksClient.findTaskItem(task.getId(), docNodeRefs[0].getId());
            fail("Expected exception");
        } catch (PublicApiException e) {
            assertEquals(404, e.getHttpResponse().getStatusCode());
        }
        // add item with not involved user
        activitiProcessEngine.getTaskService().deleteCandidateUser(task.getId(), otherPerson);
        publicApiClient.setRequestContext(otherContext);
        try {
            tasksClient.addTaskItem(task.getId(), createItemObject.toJSONString());
            fail("Expected exception");
        } catch (PublicApiException e) {
            assertEquals(403, e.getHttpResponse().getStatusCode());
        }
        // add item with user from candidate group with no assignee
        List<MemberOfSite> memberships = getTestFixture().getNetwork(otherContext.getNetworkId()).getSiteMemberships(otherContext.getRunAsUser());
        assertTrue(memberships.size() > 0);
        MemberOfSite memberOfSite = memberships.get(0);
        String group = "GROUP_site_" + memberOfSite.getSiteId() + "_" + memberOfSite.getRole().name();
        activitiProcessEngine.getTaskService().deleteCandidateUser(task.getId(), otherContext.getRunAsUser());
        activitiProcessEngine.getTaskService().addCandidateGroup(task.getId(), group);
        publicApiClient.setRequestContext(otherContext);
        result = tasksClient.addTaskItem(task.getId(), createItemObject.toJSONString());
        assertNotNull(result);
        assertEquals(docNodeRefs[0].getId(), result.get("id"));
        assertEquals("Test Doc1", result.get("name"));
        itemJSON = tasksClient.findTaskItem(task.getId(), docNodeRefs[0].getId());
        assertEquals(docNodeRefs[0].getId(), itemJSON.get("id"));
        tasksClient.deleteTaskItem(task.getId(), docNodeRefs[0].getId());
        try {
            tasksClient.findTaskItem(task.getId(), docNodeRefs[0].getId());
            fail("Expected exception");
        } catch (PublicApiException e) {
            assertEquals(404, e.getHttpResponse().getStatusCode());
        }
        // add item with user from candidate group with assignee
        activitiProcessEngine.getTaskService().setAssignee(task.getId(), requestContext.getRunAsUser());
        publicApiClient.setRequestContext(otherContext);
        try {
            tasksClient.addTaskItem(task.getId(), createItemObject.toJSONString());
            fail("Expected exception");
        } catch (PublicApiException e) {
            assertEquals(403, e.getHttpResponse().getStatusCode());
        }
        // invalid task id
        publicApiClient.setRequestContext(requestContext);
        try {
            tasksClient.addTaskItem("fakeid", createItemObject.toJSONString());
            fail("Expected exception");
        } catch (PublicApiException e) {
            assertEquals(404, e.getHttpResponse().getStatusCode());
        }
        // invalid item id
        createItemObject = new JSONObject();
        createItemObject.put("id", "fakeid");
        try {
            tasksClient.addTaskItem(task.getId(), createItemObject.toJSONString());
            fail("Expected exception");
        } catch (PublicApiException e) {
            assertEquals(404, e.getHttpResponse().getStatusCode());
        }
        // add item to completed task
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {

            @Override
            public Void doWork() throws Exception {
                activitiProcessEngine.getTaskService().complete(task.getId());
                return null;
            }
        }, requestContext.getRunAsUser(), requestContext.getNetworkId());
        createItemObject = new JSONObject();
        createItemObject.put("id", docNodeRefs[0].getId());
        try {
            tasksClient.addTaskItem(task.getId(), createItemObject.toJSONString());
            fail("Expected exception");
        } catch (PublicApiException e) {
            assertEquals(404, e.getHttpResponse().getStatusCode());
        }
    } finally {
        cleanupProcessInstance(processInfo.getId());
    }
}
Also used : Task(org.activiti.engine.task.Task) TasksClient(org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient) MemberOfSite(org.alfresco.rest.api.tests.client.data.MemberOfSite) ProcessInfo(org.alfresco.rest.workflow.api.model.ProcessInfo) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) JSONObject(org.json.simple.JSONObject) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) Test(org.junit.Test)

Example 29 with TasksClient

use of org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient in project alfresco-remote-api by Alfresco.

the class TaskWorkflowApiTest method testGetTasksWithParams.

@Test
public void testGetTasksWithParams() throws Exception {
    RequestContext requestContext = initApiClientWithTestUser();
    String otherPerson = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId()).getId();
    RequestContext otherContext = new RequestContext(requestContext.getNetworkId(), otherPerson);
    Calendar taskCreated = Calendar.getInstance();
    taskCreated.set(Calendar.MILLISECOND, 0);
    String businessKey = UUID.randomUUID().toString();
    ProcessInstance processInstance = startAdhocProcess(requestContext.getRunAsUser(), requestContext.getNetworkId(), businessKey);
    ProcessInfo otherInstance = startReviewPooledProcess(otherContext);
    try {
        // Complete the adhoc task
        final Task completedTask = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertNotNull(completedTask);
        // Find the review pooled task
        final Task reviewPooledTask = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(otherInstance.getId()).singleResult();
        assertNotNull(reviewPooledTask);
        // MNT-12221 case, due date should be set as task property, not as variable!!!
        assertNotNull("Due date was not set for review pooled task.", reviewPooledTask.getDueDate());
        String anotherUserId = UUID.randomUUID().toString();
        Calendar completedTaskDue = Calendar.getInstance();
        completedTaskDue.add(Calendar.HOUR, 1);
        completedTaskDue.set(Calendar.MILLISECOND, 0);
        completedTask.setOwner(requestContext.getRunAsUser());
        completedTask.setPriority(3);
        completedTask.setDueDate(completedTaskDue.getTime());
        completedTask.setAssignee(anotherUserId);
        completedTask.setName("Another task name");
        completedTask.setDescription("This is another test description");
        activitiProcessEngine.getTaskService().saveTask(completedTask);
        // Complete task in correct tenant
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {

            @Override
            public Void doWork() throws Exception {
                activitiProcessEngine.getTaskService().complete(completedTask.getId());
                return null;
            }
        }, requestContext.getRunAsUser(), requestContext.getNetworkId());
        // Active task is the second task in the adhoc-process (Verify task completed)
        Task activeTask = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertNotNull(activeTask);
        Calendar activeTaskDue = Calendar.getInstance();
        activeTaskDue.add(Calendar.HOUR, 2);
        activeTaskDue.set(Calendar.MILLISECOND, 0);
        activeTask.setDueDate(activeTaskDue.getTime());
        activeTask.setName("Task name");
        activeTask.setDescription("This is a test description");
        activeTask.setOwner(requestContext.getRunAsUser());
        activeTask.setPriority(2);
        activeTask.setAssignee(requestContext.getRunAsUser());
        activitiProcessEngine.getTaskService().saveTask(activeTask);
        activitiProcessEngine.getTaskService().addCandidateUser(activeTask.getId(), anotherUserId);
        activitiProcessEngine.getTaskService().addCandidateGroup(activeTask.getId(), "sales");
        activitiProcessEngine.getTaskService().setVariableLocal(activeTask.getId(), "numberVar", 10);
        final Task otherTask = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(otherInstance.getId()).singleResult();
        TasksClient tasksClient = publicApiClient.tasksClient();
        // Test status filtering - active
        Map<String, String> params = new HashMap<String, String>();
        params.put("where", "(status = 'active' AND processId = '" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, false, activeTask.getId());
        // Test status filtering - completed
        params.clear();
        params.put("where", "(status = 'completed' AND processId = '" + processInstance.getId() + "')");
        params.put("orderBy", "dueAt DESC");
        assertTasksPresentInTaskQuery(params, tasksClient, false, completedTask.getId());
        // Test status filtering - any
        params.clear();
        params.put("where", "(status = 'any' AND processId = '" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, false, activeTask.getId(), completedTask.getId());
        // Test status filtering - no value should default to 'active'
        params.clear();
        params.put("where", "(processId = '" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, false, activeTask.getId());
        // Test status filtering - illegal status
        params.clear();
        params.put("where", "(status = 'alfrescorocks')");
        try {
            tasksClient.findTasks(params);
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.BAD_REQUEST.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Invalid status parameter: alfrescorocks", expected.getHttpResponse());
        }
        // Next, we test all filtering for active, complete and any tasks
        // Assignee filtering
        params.clear();
        params.put("where", "(status = 'active' AND assignee = '" + requestContext.getRunAsUser() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.put("where", "(status = 'completed' AND assignee = '" + anotherUserId + "')");
        params.put("orderBy", "endedAt");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        params.put("where", "(status = 'any' AND assignee = '" + anotherUserId + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        // Owner filtering
        params.clear();
        params.put("where", "(status = 'active' AND owner = '" + requestContext.getRunAsUser() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.put("where", "(status = 'completed' AND owner = '" + requestContext.getRunAsUser() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        params.put("where", "(status = 'any' AND owner = '" + requestContext.getRunAsUser() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId(), completedTask.getId());
        // Candidate user filtering, only available for active tasks. When used with completed/any 400 is returned
        params.clear();
        params.put("where", "(status = 'active' AND candidateUser = '" + anotherUserId + "')");
        // No tasks expected since assignee is set
        assertEquals(0L, getResultSizeForTaskQuery(params, tasksClient));
        // Clear assignee
        activitiProcessEngine.getTaskService().setAssignee(activeTask.getId(), null);
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        // Candidate user with candidate group
        params.clear();
        params.put("where", "(status = 'active' AND candidateUser = '" + otherContext.getRunAsUser() + "')");
        // No tasks expected since assignee is set
        assertEquals(1L, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(status = 'completed' AND candidateUser = '" + anotherUserId + "')");
        try {
            tasksClient.findTasks(params);
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.BAD_REQUEST.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Filtering on candidateUser is only allowed in combination with status-parameter 'active'", expected.getHttpResponse());
        }
        params.clear();
        params.put("where", "(status = 'any' AND candidateUser = '" + anotherUserId + "')");
        try {
            tasksClient.findTasks(params);
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.BAD_REQUEST.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Filtering on candidateUser is only allowed in combination with status-parameter 'active'", expected.getHttpResponse());
        }
        // Candidate group filtering, only available for active tasks. When used with completed/any 400 is returned
        params.clear();
        params.put("where", "(status = 'active' AND candidateGroup = 'sales' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(status = 'completed' AND candidateGroup = 'sales' AND processId='" + processInstance.getId() + "')");
        try {
            tasksClient.findTasks(params);
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.BAD_REQUEST.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Filtering on candidateGroup is only allowed in combination with status-parameter 'active'", expected.getHttpResponse());
        }
        params.clear();
        params.put("where", "(status = 'any' AND candidateGroup = 'sales' AND processId='" + processInstance.getId() + "')");
        try {
            tasksClient.findTasks(params);
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.BAD_REQUEST.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Filtering on candidateGroup is only allowed in combination with status-parameter 'active'", expected.getHttpResponse());
        }
        // Name filtering
        params.clear();
        params.put("where", "(status = 'active' AND name = 'Task name' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(status = 'completed' AND name = 'Another task name' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        params.clear();
        params.put("where", "(status = 'any' AND name = 'Another task name' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        // Description filtering
        params.clear();
        params.put("where", "(status = 'active' AND description = 'This is a test description' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(status = 'completed' AND description = 'This is another test description' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        params.clear();
        params.put("where", "(status = 'any' AND description = 'This is another test description' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        // Priority filtering
        params.clear();
        params.put("where", "(status = 'active' AND priority = 2 AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.put("where", "(status = 'completed' AND priority = 3 AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        params.put("where", "(status = 'any' AND priority = 3 AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        // Process instance business-key filtering
        params.clear();
        params.put("where", "(status = 'active' AND processBusinessKey = '" + businessKey + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(status = 'completed' AND processBusinessKey = '" + businessKey + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        params.clear();
        params.put("where", "(status = 'any' AND processBusinessKey = '" + businessKey + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId(), activeTask.getId());
        params.clear();
        params.put("where", "(status = 'any' AND processBusinessKey MATCHES('" + businessKey + "'))");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId(), activeTask.getId());
        params.clear();
        params.put("where", "(status = 'any' AND processBusinessKey MATCHES('" + businessKey.substring(0, businessKey.length() - 2) + "%'))");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId(), activeTask.getId());
        // Activity definition id filtering
        params.clear();
        params.put("where", "(status = 'active' AND activityDefinitionId = 'verifyTaskDone' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(status = 'completed' AND activityDefinitionId = 'adhocTask' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        params.clear();
        params.put("where", "(status = 'any' AND activityDefinitionId = 'adhocTask' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        // Process definition id filtering
        params.clear();
        params.put("where", "(status = 'active' AND processDefinitionId = '" + processInstance.getProcessDefinitionId() + "' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(status = 'completed' AND processDefinitionId = '" + processInstance.getProcessDefinitionId() + "' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        params.clear();
        params.put("where", "(status = 'any' AND processDefinitionId = '" + processInstance.getProcessDefinitionId() + "' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId(), completedTask.getId());
        // Process definition name filtering
        params.clear();
        params.put("where", "(status = 'active' AND processDefinitionName = 'Adhoc Activiti Process' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(status = 'completed' AND processDefinitionName = 'Adhoc Activiti Process' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        params.clear();
        params.put("where", "(status = 'any' AND processDefinitionName = 'Adhoc Activiti Process' AND processId='" + processInstance.getId() + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId(), completedTask.getId());
        // Due date filtering
        params.clear();
        params.put("where", "(status = 'active' AND dueAt = '" + ISO8601DateFormat.format(activeTaskDue.getTime()) + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(status = 'completed' AND dueAt = '" + ISO8601DateFormat.format(completedTaskDue.getTime()) + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        params.clear();
        params.put("where", "(status = 'any' AND dueAt = '" + ISO8601DateFormat.format(completedTaskDue.getTime()) + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        // Started filtering
        Calendar compareCal = Calendar.getInstance();
        compareCal.set(Calendar.MILLISECOND, 0);
        compareCal.add(Calendar.DAY_OF_YEAR, -1);
        params.clear();
        params.put("where", "(status = 'active' AND startedAt > '" + ISO8601DateFormat.format(compareCal.getTime()) + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId(), otherTask.getId());
        params.clear();
        params.put("where", "(status = 'completed' AND startedAt > '" + ISO8601DateFormat.format(compareCal.getTime()) + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId());
        params.clear();
        params.put("where", "(status = 'any' AND startedAt > '" + ISO8601DateFormat.format(compareCal.getTime()) + "')");
        assertTasksPresentInTaskQuery(params, tasksClient, completedTask.getId(), activeTask.getId(), otherTask.getId());
        params.clear();
        params.put("where", "(status = 'any' AND startedAt < '" + ISO8601DateFormat.format(compareCal.getTime()) + "')");
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(variables/local/numberVar > 'd:int 5')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(variables/local/numberVar > 'd:int 10')");
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(variables/local/numberVar >= 'd_int 10')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(variables/local/numberVar >= 'd:int 11')");
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(variables/local/numberVar <= 'd:int 10')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(variables/local/numberVar <= 'd:int 9')");
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(variables/local/numberVar < 'd_int 15')");
        assertTasksPresentInTaskQuery(params, tasksClient, activeTask.getId());
        params.clear();
        params.put("where", "(variables/local/numberVar < 'd:int 10')");
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(variables/global/numberVar > 'd:int 5')");
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(variables/numberVar > 'd:int 5')");
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(variables/bpm_dueDate = 'd:datetime " + ISO8601DateFormat.format(new Date()) + "')");
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(variables/bpm_dueDate = 'd:datetime 2013-09-15T12:22:31.866+0000')");
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(variables/bpm_dueDate > 'd:datetime 2013-09-15T12:22:31.866+0000')");
        // MNT-12221 fix, due date is not saved as variable for review pooled workflow, so nothing should be found
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(dueAt = '" + ISO8601DateFormat.format(reviewPooledTask.getDueDate()) + "')");
        assertEquals(1, getResultSizeForTaskQuery(params, tasksClient));
        params.clear();
        params.put("where", "(variables/bpm_comment MATCHES ('test%'))");
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
        // test with OR operator
        params.clear();
        params.put("where", "(status = 'any' OR candidateGroup = 'sales')");
        try {
            tasksClient.findTasks(params);
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.BAD_REQUEST.value(), expected.getHttpResponse().getStatusCode());
        }
        params.clear();
        params.put("where", "(status = 'completed' AND processDefinitionName = 'Adhoc Activiti Process')");
        JSONObject response = publicApiClient.processesClient().getTasks(processInstance.getId(), params);
        assertNotNull(response);
        JSONObject paginationJSON = (JSONObject) response.get("pagination");
        assertEquals(1l, paginationJSON.get("count"));
        params.clear();
        params.put("where", "(status = 'any' AND variables/numberVar < 'd:int 5')");
        assertEquals(0, getResultSizeForTaskQuery(params, tasksClient));
    } finally {
        cleanupProcessInstance(processInstance.getId(), otherInstance.getId());
    }
}
Also used : Task(org.activiti.engine.task.Task) HashMap(java.util.HashMap) Calendar(java.util.Calendar) TasksClient(org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient) ProcessInfo(org.alfresco.rest.workflow.api.model.ProcessInfo) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) Date(java.util.Date) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) JSONObject(org.json.simple.JSONObject) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) Test(org.junit.Test)

Example 30 with TasksClient

use of org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient in project alfresco-remote-api by Alfresco.

the class TaskWorkflowApiTest method testUpdateTask.

@Test
@SuppressWarnings("unchecked")
public void testUpdateTask() throws Exception {
    RequestContext requestContext = initApiClientWithTestUser();
    String otherPerson = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId()).getId();
    RequestContext otherContext = new RequestContext(requestContext.getNetworkId(), otherPerson);
    String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId();
    RequestContext adminContext = new RequestContext(requestContext.getNetworkId(), tenantAdmin);
    ProcessInstance processInstance = startAdhocProcess(requestContext.getRunAsUser(), requestContext.getNetworkId(), null);
    try {
        Task task = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        TasksClient tasksClient = publicApiClient.tasksClient();
        Calendar dueDateCal = Calendar.getInstance();
        dueDateCal.set(Calendar.MILLISECOND, 0);
        dueDateCal.add(Calendar.DAY_OF_YEAR, 1);
        Date dueDate = dueDateCal.getTime();
        JSONObject taskBody = new JSONObject();
        taskBody.put("name", "Updated name");
        taskBody.put("description", "Updated description");
        taskBody.put("dueAt", formatDate(dueDate));
        taskBody.put("priority", 1234);
        taskBody.put("assignee", "john");
        taskBody.put("owner", "james");
        List<String> selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "name", "description", "dueAt", "priority", "assignee", "owner" }));
        JSONObject result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals("Updated name", result.get("name"));
        assertEquals("Updated description", result.get("description"));
        assertEquals(1234, Integer.valueOf(result.get("priority").toString()).intValue());
        assertEquals("john", result.get("assignee"));
        assertEquals("james", result.get("owner"));
        assertEquals(dueDate, parseDate(result, "dueAt"));
        task = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertNotNull(task);
        assertEquals("Updated name", task.getName());
        assertEquals("Updated description", task.getDescription());
        assertEquals(1234, task.getPriority());
        assertEquals("john", task.getAssignee());
        assertEquals("james", task.getOwner());
        assertEquals(dueDate, task.getDueDate());
        // update owner with admin user id
        taskBody = new JSONObject();
        taskBody.put("owner", adminContext.getRunAsUser());
        selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "owner" }));
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals(adminContext.getRunAsUser(), result.get("owner"));
        // update owner with initiator user id
        taskBody = new JSONObject();
        taskBody.put("owner", requestContext.getRunAsUser());
        selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "owner" }));
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals(requestContext.getRunAsUser(), result.get("owner"));
        // update owner with other user id
        taskBody = new JSONObject();
        taskBody.put("owner", otherContext.getRunAsUser());
        selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "owner" }));
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals(otherContext.getRunAsUser(), result.get("owner"));
        // update due date to date more in the future
        dueDateCal.add(Calendar.DAY_OF_YEAR, 1);
        dueDate = dueDateCal.getTime();
        taskBody = new JSONObject();
        taskBody.put("dueAt", formatDate(dueDate));
        selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "dueAt" }));
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals(dueDate, parseDate(result, "dueAt"));
        // update due date to date a day less in the future
        dueDateCal.add(Calendar.DAY_OF_YEAR, -1);
        dueDate = dueDateCal.getTime();
        taskBody = new JSONObject();
        taskBody.put("dueAt", formatDate(dueDate));
        selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "dueAt" }));
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals(dueDate, parseDate(result, "dueAt"));
        // update due date to current time
        dueDateCal = Calendar.getInstance();
        dueDateCal.set(Calendar.MILLISECOND, 0);
        dueDate = dueDateCal.getTime();
        taskBody = new JSONObject();
        taskBody.put("dueAt", formatDate(dueDate));
        selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "dueAt" }));
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals(dueDate, parseDate(result, "dueAt"));
    } finally {
        cleanupProcessInstance(processInstance);
    }
}
Also used : Task(org.activiti.engine.task.Task) JSONObject(org.json.simple.JSONObject) TasksClient(org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) Date(java.util.Date) Test(org.junit.Test)

Aggregations

TasksClient (org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient)41 Test (org.junit.Test)41 RequestContext (org.alfresco.rest.api.tests.client.RequestContext)39 Task (org.activiti.engine.task.Task)38 JSONObject (org.json.simple.JSONObject)36 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)32 PublicApiException (org.alfresco.rest.api.tests.client.PublicApiException)22 ArrayList (java.util.ArrayList)17 JSONArray (org.json.simple.JSONArray)14 HashMap (java.util.HashMap)9 ProcessInfo (org.alfresco.rest.workflow.api.model.ProcessInfo)8 Calendar (java.util.Calendar)5 Date (java.util.Date)5 TestNetwork (org.alfresco.rest.api.tests.RepoService.TestNetwork)5 MemberOfSite (org.alfresco.rest.api.tests.client.data.MemberOfSite)5 NodeRef (org.alfresco.service.cmr.repository.NodeRef)4 HistoricTaskInstance (org.activiti.engine.history.HistoricTaskInstance)3 HashSet (java.util.HashSet)2 TaskService (org.activiti.engine.TaskService)2 Clock (org.activiti.engine.runtime.Clock)2