Java Code Examples for org.flowable.task.api.Task#getId()

The following examples show how to use org.flowable.task.api.Task#getId() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TaskVariableBaseResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void setVariable(Task task, String name, Object value, RestVariableScope scope, boolean isNew) {
    // Create can only be done on new variables. Existing variables should
    // be updated using PUT
    boolean hasVariable = hasVariableOnScope(task, name, scope);
    if (isNew && hasVariable) {
        throw new FlowableException("Variable '" + name + "' is already present on task '" + task.getId() + "'.");
    }

    if (!isNew && !hasVariable) {
        throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' doesn't have a variable with name: '" + name + "'.", null);
    }

    if (scope == RestVariableScope.LOCAL) {
        taskService.setVariableLocal(task.getId(), name, value);
    } else {
        if (ScopeTypes.CMMN.equals(task.getScopeType()) && task.getScopeId() != null) {
            // Explicitly set on execution, setting non-local variable on
            // task will override local-variable if exists
            runtimeService.setVariable(task.getScopeId(), name, value);
        } else {
            // Standalone task, no global variables possible
            throw new FlowableIllegalArgumentException("Cannot set global variable '" + name + "' on task '" + task.getId() + "', task is not part of process.");
        }
    }
}
 
Example 2
Source File: TaskAttachmentResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Delete an attachment on a task", tags = { "Task Attachments"})
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Indicates the task and attachment were found and the attachment is deleted. Response body is left empty intentionally."),
        @ApiResponse(code = 404, message = "Indicates the requested task was not found or the tasks does not have a attachment with the given ID.")
})
@DeleteMapping(value = "/runtime/tasks/{taskId}/attachments/{attachmentId}")
public void deleteAttachment(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "attachmentId") @PathVariable("attachmentId") String attachmentId, HttpServletResponse response) {

    Task task = getTaskFromRequest(taskId);

    Attachment attachment = taskService.getAttachment(attachmentId);
    if (attachment == null || !task.getId().equals(attachment.getTaskId())) {
        throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have an attachment with id '" + attachmentId + "'.", Comment.class);
    }

    taskService.deleteAttachment(attachmentId);
    response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example 3
Source File: TaskEventResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Delete an event on a task", tags = { "Tasks" })
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Indicates the task was found and the events are returned."),
        @ApiResponse(code = 404, message = "Indicates the requested task was not found or the task does not have the requested event.")
})
@DeleteMapping(value = "/runtime/tasks/{taskId}/events/{eventId}")
public void deleteEvent(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "eventId") @PathVariable("eventId") String eventId, HttpServletResponse response) {

    // Check if task exists
    Task task = getTaskFromRequest(taskId);

    Event event = taskService.getEvent(eventId);
    if (event == null || event.getTaskId() == null || !event.getTaskId().equals(task.getId())) {
        throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have an event with id '" + event + "'.", Event.class);
    }

    taskService.deleteComment(eventId);
    response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example 4
Source File: TaskCommentResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Delete a comment on a task", tags = { "Task Comments" }, nickname = "deleteTaskComment")
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Indicates the task and comment were found and the comment is deleted. Response body is left empty intentionally."),
        @ApiResponse(code = 404, message = "Indicates the requested task was not found or the tasks does not have a comment with the given ID.")
})
@DeleteMapping(value = "/runtime/tasks/{taskId}/comments/{commentId}")
public void deleteComment(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "commentId") @PathVariable("commentId") String commentId, HttpServletResponse response) {

    // Check if task exists
    Task task = getTaskFromRequest(taskId);

    Comment comment = taskService.getComment(commentId);
    if (comment == null || comment.getTaskId() == null || !comment.getTaskId().equals(task.getId())) {
        throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have a comment with id '" + commentId + "'.", Comment.class);
    }

    taskService.deleteComment(commentId);
    response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example 5
Source File: TaskVariableBaseResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void setVariable(Task task, String name, Object value, RestVariableScope scope, boolean isNew) {
    // Create can only be done on new variables. Existing variables should
    // be updated using PUT
    boolean hasVariable = hasVariableOnScope(task, name, scope);
    if (isNew && hasVariable) {
        throw new FlowableException("Variable '" + name + "' is already present on task '" + task.getId() + "'.");
    }

    if (!isNew && !hasVariable) {
        throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have a variable with name: '" + name + "'.", null);
    }

    if (scope == RestVariableScope.LOCAL) {
        taskService.setVariableLocal(task.getId(), name, value);
    } else {
        if (task.getExecutionId() != null) {
            // Explicitly set on execution, setting non-local variable on
            // task will override local-variable if exists
            runtimeService.setVariable(task.getExecutionId(), name, value);
        } else {
            // Standalone task, no global variables possible
            throw new FlowableIllegalArgumentException("Cannot set global variable '" + name + "' on task '" + task.getId() + "', task is not part of process.");
        }
    }
}
 
Example 6
Source File: FlowableTaskActionService.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void assignTask(User currentUser, Task task, String assigneeIdString) {
    try {
        String oldAssignee = task.getAssignee();
        taskService.setAssignee(task.getId(), assigneeIdString);

        // If the old assignee user wasn't part of the involved users yet, make it so
        addIdentiyLinkForUser(task, oldAssignee, IdentityLinkType.PARTICIPANT);

        // If the current user wasn't part of the involved users yet, make it so
        String currentUserIdString = String.valueOf(currentUser.getId());
        addIdentiyLinkForUser(task, currentUserIdString, IdentityLinkType.PARTICIPANT);

    } catch (FlowableException e) {
        throw new BadRequestException("Task " + task.getId() + " can't be assigned", e);
    }
}
 
Example 7
Source File: TaskVariableResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Delete a variable on a task", tags = { "Task Variables" }, nickname = "deleteTaskInstanceVariable")
@ApiImplicitParams(@ApiImplicitParam(name = "scope", dataType = "string", value = "Scope of variable to be returned. When local, only task-local variable value is returned. When global, only variable value from the task’s parent execution-hierarchy are returned. When the parameter is omitted, a local variable will be returned if it exists, otherwise a global variable.", paramType = "query"))
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Indicates the task variable was found and has been deleted. Response-body is intentionally empty."),
        @ApiResponse(code = 404, message = "Indicates the requested task was not found or the task does not have a variable with the given name. Status message contains additional information about the error.")
})
@DeleteMapping(value = "/runtime/tasks/{taskId}/variables/{variableName}")
public void deleteVariable(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId,
        @ApiParam(name = "variableName") @PathVariable("variableName") String variableName,
        @ApiParam(hidden = true) @RequestParam(value = "scope", required = false) String scopeString,
        HttpServletResponse response) {

    Task task = getTaskFromRequest(taskId);

    // Determine scope
    RestVariableScope scope = RestVariableScope.LOCAL;
    if (scopeString != null) {
        scope = RestVariable.getScopeFromString(scopeString);
    }

    if (!hasVariableOnScope(task, variableName, scope)) {
        throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have a variable '" + variableName + "' in scope " + scope.name().toLowerCase(), VariableInstanceEntity.class);
    }

    if (scope == RestVariableScope.LOCAL) {
        taskService.removeVariableLocal(task.getId(), variableName);
    } else {
        // Safe to use executionId, as the hasVariableOnScope would have
        // stopped a global-var update on standalone task
        runtimeService.removeVariable(task.getExecutionId(), variableName);
    }
    response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example 8
Source File: TaskVariableResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Delete a variable on a task", tags = { "Task Variables" }, nickname = "deleteTaskInstanceVariable")
@ApiImplicitParams(@ApiImplicitParam(name = "scope", dataType = "string", value = "Scope of variable to be returned. When local, only task-local variable value is returned. When global, only variable value from the task’s parent execution-hierarchy are returned. When the parameter is omitted, a local variable will be returned if it exists, otherwise a global variable.", paramType = "query"))
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Indicates the task variable was found and has been deleted. Response-body is intentionally empty."),
        @ApiResponse(code = 404, message = "Indicates the requested task was not found or the task does not have a variable with the given name. Status message contains additional information about the error.")
})
@DeleteMapping(value = "/cmmn-runtime/tasks/{taskId}/variables/{variableName}")
public void deleteVariable(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId,
        @ApiParam(name = "variableName") @PathVariable("variableName") String variableName,
        @ApiParam(hidden = true) @RequestParam(value = "scope", required = false) String scopeString,
        HttpServletResponse response) {

    Task task = getTaskFromRequest(taskId);

    // Determine scope
    RestVariableScope scope = RestVariableScope.LOCAL;
    if (scopeString != null) {
        scope = RestVariable.getScopeFromString(scopeString);
    }

    if (!hasVariableOnScope(task, variableName, scope)) {
        throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' doesn't have a variable '" + variableName + "' in scope " + scope.name().toLowerCase(), VariableInstanceEntity.class);
    }

    if (scope == RestVariableScope.LOCAL) {
        taskService.removeVariableLocal(task.getId(), variableName);
    } else {
        // Safe to use scope id, as the hasVariableOnScope would have
        // stopped a global-var update on standalone task
        runtimeService.removeVariable(task.getScopeId(), variableName);
    }
    response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example 9
Source File: CacheTaskListener.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void notify(DelegateTask delegateTask) {
    CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration();
    CmmnTaskService taskService = cmmnEngineConfiguration.getCmmnTaskService();
    Task task = taskService.createTaskQuery().taskId(delegateTask.getId()).singleResult();
    if (task != null && task.getId().equals(delegateTask.getId())) {
        taskId = task.getId();
    }
    
    CmmnHistoryService historyService = cmmnEngineConfiguration.getCmmnHistoryService();
    HistoricTaskInstance historicTask = historyService.createHistoricTaskInstanceQuery().taskId(delegateTask.getId()).singleResult();
    if (historicTask != null && historicTask.getId().equals(delegateTask.getId())) {
        historicTaskId = historicTask.getId();
    }
}
 
Example 10
Source File: HistoricTaskInstanceResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/runtime/oneHumanTaskWithFormCase.cmmn",
        "org/flowable/cmmn/rest/service/api/runtime/simple.form" })
public void testCompletedTaskForm() throws Exception {
    if (cmmnEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {
        CaseDefinition caseDefinition = repositoryService.createCaseDefinitionQuery().caseDefinitionKey("oneHumanTaskCase").singleResult();
        try {
            FormDefinition formDefinition = formRepositoryService.createFormDefinitionQuery().formDefinitionKey("form1").singleResult();
            assertThat(formDefinition).isNotNull();

            CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").start();
            Task task = taskService.createTaskQuery().scopeId(caseInstance.getId()).singleResult();
            String taskId = task.getId();

            String url = CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_HISTORIC_TASK_INSTANCE_FORM, taskId);
            CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);
            JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
            closeResponse(response);
            assertThatJson(responseNode)
                    .when(Option.IGNORING_EXTRA_FIELDS)
                    .isEqualTo("{"
                            + " id: '" + formDefinition.getId() + "',"
                            + " key: '" + formDefinition.getKey() + "',"
                            + " name: '" + formDefinition.getName() + "'"
                            + "}");

            assertThat(responseNode.get("fields")).hasSize(2);

            Map<String, Object> variables = new HashMap<>();
            variables.put("user", "First value");
            variables.put("number", 789);
            taskService.completeTaskWithForm(taskId, formDefinition.getId(), null, variables);

            assertThat(taskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult()).isNull();

            response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);
            responseNode = objectMapper.readTree(response.getEntity().getContent());
            closeResponse(response);
            assertThatJson(responseNode)
                    .when(Option.IGNORING_EXTRA_FIELDS)
                    .isEqualTo("{"
                            + " id: '" + formDefinition.getId() + "',"
                            + " key: '" + formDefinition.getKey() + "',"
                            + " name: '" + formDefinition.getName() + "'"
                            + "}");

            assertThat(responseNode.get("fields")).hasSize(2);

            JsonNode fields = responseNode.get("fields");
            assertThatJson(fields)
                    .when(Option.IGNORING_EXTRA_FIELDS)
                    .isEqualTo("["
                            + "  {"
                            + "    id: 'user',"
                            + "    value: 'First value'"
                            + "  },"
                            + "  {"
                            + "    id: 'number',"
                            + "    value: 789"
                            + "  }"
                            + "]");

        } finally {
            formEngineFormService.deleteFormInstancesByScopeDefinition(caseDefinition.getId());

            List<FormDeployment> formDeployments = formRepositoryService.createDeploymentQuery().list();
            for (FormDeployment formDeployment : formDeployments) {
                formRepositoryService.deleteDeployment(formDeployment.getId(), true);
            }
        }
    }
}
 
Example 11
Source File: HistoricTaskInstanceIdentityLinkCollectionResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Test querying historic task instance. GET cmmn-history/historic-task-instances/{taskId}/identitylinks
 */
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/repository/twoHumanTaskCase.cmmn" })
public void testGetIdentityLinks() throws Exception {
    HashMap<String, Object> caseVariables = new HashMap<>();
    caseVariables.put("stringVar", "Azerty");
    caseVariables.put("intVar", 67890);
    caseVariables.put("booleanVar", false);

    CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder().caseDefinitionKey("myCase").variables(caseVariables).start();
    Task task = taskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
    taskService.complete(task.getId());
    task = taskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
    taskService.setAssignee(task.getId(), "fozzie");
    taskService.setOwner(task.getId(), "test");

    String url = CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_HISTORIC_TASK_INSTANCE_IDENTITY_LINKS, task.getId());

    // Do the actual call
    CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);

    // Check status and size
    JsonNode linksArray = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    String taskId = task.getId();
    assertThatJson(linksArray)
        .when(Option.IGNORING_ARRAY_ORDER)
        .isEqualTo("["
            + "  {"
            + "    type: 'assignee',"
            + "    userId: 'fozzie',"
            + "    groupId: null,"
            + "    taskId: '" + taskId + "',"
            + "    taskUrl: '${json-unit.any-string}',"
            + "    caseInstanceId: null,"
            + "    caseInstanceUrl: null"
            + "  },"
            + "  {"
            + "    type: 'owner',"
            + "    userId: 'test',"
            + "    groupId: null,"
            + "    taskId: '" + taskId + "',"
            + "    taskUrl: '${json-unit.any-string}',"
            + "    caseInstanceId: null,"
            + "    caseInstanceUrl: null"
            + "  },"
            + "  {"
            + "    type: 'candidate',"
            + "    userId: 'test',"
            + "    groupId: null,"
            + "    taskId: '" + taskId + "',"
            + "    taskUrl: '${json-unit.any-string}',"
            + "    caseInstanceId: null,"
            + "    caseInstanceUrl: null"
            + "  },"
            + "  {"
            + "    type: 'candidate',"
            + "    userId: 'test2',"
            + "    groupId: null,"
            + "    taskId: '" + taskId + "',"
            + "    taskUrl: '${json-unit.any-string}',"
            + "    caseInstanceId: null,"
            + "    caseInstanceUrl: null"
            + "  },"
            + "  {"
            + "    type: 'candidate',"
            + "    userId: null,"
            + "    groupId: 'test',"
            + "    taskId: '" + taskId + "',"
            + "    taskUrl: '${json-unit.any-string}',"
            + "    caseInstanceId: null,"
            + "    caseInstanceUrl: null"
            + "  }"
            + "]");
}
 
Example 12
Source File: TaskResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/runtime/oneHumanTaskWithFormCase.cmmn",
        "org/flowable/cmmn/rest/service/api/runtime/simple.form" })
public void testCompleteTaskWithForm() throws Exception {
    CaseDefinition caseDefinition = repositoryService.createCaseDefinitionQuery().caseDefinitionKey("oneHumanTaskCase").singleResult();
    try {
        FormDefinition formDefinition = formRepositoryService.createFormDefinitionQuery().formDefinitionKey("form1").singleResult();
        assertThat(formDefinition).isNotNull();

        CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").start();
        Task task = taskService.createTaskQuery().scopeId(caseInstance.getId()).singleResult();
        String taskId = task.getId();

        String url = CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_TASK_FORM, taskId);
        CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertThatJson(responseNode)
                .when(Option.IGNORING_EXTRA_FIELDS)
                .isEqualTo("{"
                        + " id: '" + formDefinition.getId() + "',"
                        + " key: '" + formDefinition.getKey() + "',"
                        + " name: '" + formDefinition.getName() + "'"
                        + "}");
        assertThat(responseNode.get("fields")).hasSize(2);

        ObjectNode requestNode = objectMapper.createObjectNode();
        ArrayNode variablesNode = objectMapper.createArrayNode();
        requestNode.put("action", "complete");
        requestNode.put("formDefinitionId", formDefinition.getId());
        requestNode.set("variables", variablesNode);

        ObjectNode var1 = objectMapper.createObjectNode();
        variablesNode.add(var1);
        var1.put("name", "user");
        var1.put("value", "First value");
        ObjectNode var2 = objectMapper.createObjectNode();
        variablesNode.add(var2);
        var2.put("name", "number");
        var2.put("value", 789);

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_TASK, taskId));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_OK));

        task = taskService.createTaskQuery().taskId(taskId).singleResult();
        assertThat(task).isNull();

        FormInstance formInstance = formEngineFormService.createFormInstanceQuery().taskId(taskId).singleResult();
        assertThat(formInstance).isNotNull();
        byte[] valuesBytes = formEngineFormService.getFormInstanceValues(formInstance.getId());
        assertThat(valuesBytes).isNotNull();
        JsonNode instanceNode = objectMapper.readTree(valuesBytes);
        JsonNode valuesNode = instanceNode.get("values");
        assertThatJson(valuesNode)
                .when(Option.IGNORING_EXTRA_FIELDS)
                .isEqualTo("{"
                        + " user: 'First value',"
                        + " number: '789'"
                        + "}");

        if (cmmnEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {
            HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
            assertThat(historicTaskInstance).isNotNull();
            List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).list();
            assertThat(variables).isNotNull();
            assertThat(variables)
                    .extracting(HistoricVariableInstance::getVariableName, HistoricVariableInstance::getValue)
                    .containsExactlyInAnyOrder(
                            tuple("user", "First value"),
                            tuple("number", 789)
                    );
        }

    } finally {
        formEngineFormService.deleteFormInstancesByScopeDefinition(caseDefinition.getId());

        List<FormDeployment> formDeployments = formRepositoryService.createDeploymentQuery().list();
        for (FormDeployment formDeployment : formDeployments) {
            formRepositoryService.deleteDeployment(formDeployment.getId(), true);
        }
    }
}
 
Example 13
Source File: TaskVariableCollectionResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@ApiOperation(value = "Create new variables on a task", tags = { "Tasks", "Task Variables" },
        notes = "This endpoint can be used in 2 ways: By passing a JSON Body (RestVariable or an Array of RestVariable) or by passing a multipart/form-data Object.\n"
                + "It is possible to create simple (non-binary) variable or list of variables or new binary variable \n"
                + "Any number of variables can be passed into the request body array.\n"
                + "NB: Swagger V2 specification does not support this use case that is why this endpoint might be buggy/incomplete if used with other tools.")
@ApiImplicitParams({
        @ApiImplicitParam(name = "body", type = "org.flowable.rest.service.api.engine.variable.RestVariable", value = "Create a variable on a task", paramType = "body", example = "{\n" +
                "    \"name\":\"intProcVar\"\n" +
                "    \"type\":\"integer\"\n" +
                "    \"value\":123,\n" +
                " }"),
        @ApiImplicitParam(name = "name", value = "Required name of the variable", dataType = "string", paramType = "form", example = "Simple content item"),
        @ApiImplicitParam(name = "type", value = "Type of variable that is created. If omitted, reverts to raw JSON-value type (string, boolean, integer or double)",dataType = "string", paramType = "form", example = "integer"),
        @ApiImplicitParam(name = "scope",value = "Scope of variable that is created. If omitted, local is assumed.", dataType = "string",  paramType = "form", example = "local")
})
@ApiResponses(value = {
        @ApiResponse(code = 201, message = "Indicates the variables were created and the result is returned."),
        @ApiResponse(code = 400, message = "Indicates the name of a variable to create was missing or that an attempt is done to create a variable on a standalone task (without a process associated) with scope global or an empty array of variables was included in the request or request did not contain an array of variables. Status message provides additional information."),
        @ApiResponse(code = 404, message = "Indicates the requested task was not found."),
        @ApiResponse(code = 409, message = "Indicates the task already has a variable with the given name. Use the PUT method to update the task variable instead."),
        @ApiResponse(code = 415, message = "Indicates the serializable data contains an object for which no class is present in the JVM running the Flowable engine and therefore cannot be deserialized.")
})
@PostMapping(value = "/cmmn-runtime/tasks/{taskId}/variables", produces = "application/json", consumes = {"text/plain", "application/json", "multipart/form-data"})
public Object createTaskVariable(@ApiParam(name = "taskId") @PathVariable String taskId, HttpServletRequest request, HttpServletResponse response) {

    Task task = getTaskFromRequest(taskId);

    Object result = null;
    if (request instanceof MultipartHttpServletRequest) {
        result = setBinaryVariable((MultipartHttpServletRequest) request, task, true);
    } else {

        List<RestVariable> inputVariables = new ArrayList<>();
        List<RestVariable> resultVariables = new ArrayList<>();
        result = resultVariables;

        try {
            @SuppressWarnings("unchecked")
            List<Object> variableObjects = (List<Object>) objectMapper.readValue(request.getInputStream(), List.class);
            for (Object restObject : variableObjects) {
                RestVariable restVariable = objectMapper.convertValue(restObject, RestVariable.class);
                inputVariables.add(restVariable);
            }
            
        } catch (Exception e) {
            throw new FlowableIllegalArgumentException("Failed to serialize to a RestVariable instance", e);
        }

        if (inputVariables == null || inputVariables.size() == 0) {
            throw new FlowableIllegalArgumentException("Request didn't contain a list of variables to create.");
        }

        RestVariableScope sharedScope = null;
        RestVariableScope varScope = null;
        Map<String, Object> variablesToSet = new HashMap<>();

        for (RestVariable var : inputVariables) {
            // Validate if scopes match
            varScope = var.getVariableScope();
            if (var.getName() == null) {
                throw new FlowableIllegalArgumentException("Variable name is required");
            }

            if (varScope == null) {
                varScope = RestVariableScope.LOCAL;
            }
            if (sharedScope == null) {
                sharedScope = varScope;
            }
            if (varScope != sharedScope) {
                throw new FlowableIllegalArgumentException("Only allowed to update multiple variables in the same scope.");
            }

            if (hasVariableOnScope(task, var.getName(), varScope)) {
                throw new FlowableConflictException("Variable '" + var.getName() + "' is already present on task '" + task.getId() + "'.");
            }

            Object actualVariableValue = restResponseFactory.getVariableValue(var);
            variablesToSet.put(var.getName(), actualVariableValue);
            resultVariables.add(restResponseFactory.createRestVariable(var.getName(), actualVariableValue, varScope, task.getId(), CmmnRestResponseFactory.VARIABLE_TASK, false));
        }

        if (!variablesToSet.isEmpty()) {
            if (sharedScope == RestVariableScope.LOCAL) {
                taskService.setVariablesLocal(task.getId(), variablesToSet);
            } else {
                if (task.getScopeId() != null) {
                    // Explicitly set on case, setting non-local
                    // variables on task will override local-variables if exists
                    runtimeService.setVariables(task.getScopeId(), variablesToSet);
                } else {
                    // Standalone task, no global variables possible
                    throw new FlowableIllegalArgumentException("Cannot set global variables on task '" + task.getId() + "', task is not part of process.");
                }
            }
        }
    }

    response.setStatus(HttpStatus.CREATED.value());
    return result;
}
 
Example 14
Source File: TaskVariableCollectionResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@ApiOperation(value = "Create new variables on a task", tags = { "Tasks", "Task Variables" },
        notes = "This endpoint can be used in 2 ways: By passing a JSON Body (RestVariable or an Array of RestVariable) or by passing a multipart/form-data Object.\n"
                + "It is possible to create simple (non-binary) variable or list of variables or new binary variable \n"
                + "Any number of variables can be passed into the request body array.\n"
                + "NB: Swagger V2 specification does not support this use case that is why this endpoint might be buggy/incomplete if used with other tools.")
@ApiImplicitParams({
        @ApiImplicitParam(name = "body", type = "org.flowable.rest.service.api.engine.variable.RestVariable", value = "Create a variable on a task", paramType = "body", example = "{\n" +
                "    \"name\":\"intProcVar\"\n" +
                "    \"type\":\"integer\"\n" +
                "    \"value\":123,\n" +
                " }"),
        @ApiImplicitParam(name = "name", value = "Required name of the variable", dataType = "string", paramType = "form", example = "Simple content item"),
        @ApiImplicitParam(name = "type", value = "Type of variable that is created. If omitted, reverts to raw JSON-value type (string, boolean, integer or double)",dataType = "string", paramType = "form", example = "integer"),
        @ApiImplicitParam(name = "scope",value = "Scope of variable that is created. If omitted, local is assumed.", dataType = "string",  paramType = "form", example = "local")
})
@ApiResponses(value = {
        @ApiResponse(code = 201, message = "Indicates the variables were created and the result is returned."),
        @ApiResponse(code = 400, message = "Indicates the name of a variable to create was missing or that an attempt is done to create a variable on a standalone task (without a process associated) with scope global or an empty array of variables was included in the request or request did not contain an array of variables. Status message provides additional information."),
        @ApiResponse(code = 404, message = "Indicates the requested task was not found."),
        @ApiResponse(code = 409, message = "Indicates the task already has a variable with the given name. Use the PUT method to update the task variable instead."),
        @ApiResponse(code = 415, message = "Indicates the serializable data contains an object for which no class is present in the JVM running the Flowable engine and therefore cannot be deserialized.")
})
@PostMapping(value = "/runtime/tasks/{taskId}/variables", produces = "application/json", consumes = {"application/json", "multipart/form-data"})
public Object createTaskVariable(@ApiParam(name = "taskId") @PathVariable String taskId, HttpServletRequest request, HttpServletResponse response) {

    Task task = getTaskFromRequest(taskId);

    Object result = null;
    if (request instanceof MultipartHttpServletRequest) {
        result = setBinaryVariable((MultipartHttpServletRequest) request, task, true);
    } else {

        List<RestVariable> inputVariables = new ArrayList<>();
        List<RestVariable> resultVariables = new ArrayList<>();
        result = resultVariables;

        try {
            @SuppressWarnings("unchecked")
            List<Object> variableObjects = (List<Object>) objectMapper.readValue(request.getInputStream(), List.class);
            for (Object restObject : variableObjects) {
                RestVariable restVariable = objectMapper.convertValue(restObject, RestVariable.class);
                inputVariables.add(restVariable);
            }
        } catch (Exception e) {
            throw new FlowableIllegalArgumentException("Failed to serialize to a RestVariable instance", e);
        }

        if (inputVariables == null || inputVariables.size() == 0) {
            throw new FlowableIllegalArgumentException("Request did not contain a list of variables to create.");
        }

        RestVariableScope sharedScope = null;
        RestVariableScope varScope = null;
        Map<String, Object> variablesToSet = new HashMap<>();

        for (RestVariable var : inputVariables) {
            // Validate if scopes match
            varScope = var.getVariableScope();
            if (var.getName() == null) {
                throw new FlowableIllegalArgumentException("Variable name is required");
            }

            if (varScope == null) {
                varScope = RestVariableScope.LOCAL;
            }
            if (sharedScope == null) {
                sharedScope = varScope;
            }
            if (varScope != sharedScope) {
                throw new FlowableIllegalArgumentException("Only allowed to update multiple variables in the same scope.");
            }

            if (hasVariableOnScope(task, var.getName(), varScope)) {
                throw new FlowableConflictException("Variable '" + var.getName() + "' is already present on task '" + task.getId() + "'.");
            }

            Object actualVariableValue = restResponseFactory.getVariableValue(var);
            variablesToSet.put(var.getName(), actualVariableValue);
            resultVariables.add(restResponseFactory.createRestVariable(var.getName(), actualVariableValue, varScope, task.getId(), RestResponseFactory.VARIABLE_TASK, false));
        }

        if (!variablesToSet.isEmpty()) {
            if (sharedScope == RestVariableScope.LOCAL) {
                taskService.setVariablesLocal(task.getId(), variablesToSet);
            } else {
                if (task.getExecutionId() != null) {
                    // Explicitly set on execution, setting non-local
                    // variables on task will override local-variables if
                    // exists
                    runtimeService.setVariables(task.getExecutionId(), variablesToSet);
                } else {
                    // Standalone task, no global variables possible
                    throw new FlowableIllegalArgumentException("Cannot set global variables on task '" + task.getId() + "', task is not part of process.");
                }
            }
        }
    }

    response.setStatus(HttpStatus.CREATED.value());
    return result;
}
 
Example 15
Source File: TaskResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@Deployment
public void testCompleteTaskWithForm() throws Exception {
    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").singleResult();
    try {
        formRepositoryService.createDeployment().addClasspathResource("org/flowable/rest/service/api/runtime/simple.form").deploy();

        FormDefinition formDefinition = formRepositoryService.createFormDefinitionQuery().formDefinitionKey("form1").singleResult();
        assertThat(formDefinition).isNotNull();

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        String taskId = task.getId();

        String url = RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_FORM, taskId);
        CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertThatJson(responseNode)
                .when(Option.IGNORING_EXTRA_FIELDS)
                .isEqualTo("{"
                        + "id : '" + formDefinition.getId() + "',"
                        + "key: '" + formDefinition.getKey() + "',"
                        + "name: '" + formDefinition.getName() + "'"
                        + "}");
        assertThat(responseNode.get("fields")).hasSize(2);

        ObjectNode requestNode = objectMapper.createObjectNode();
        ArrayNode variablesNode = objectMapper.createArrayNode();
        requestNode.put("action", "complete");
        requestNode.put("formDefinitionId", formDefinition.getId());
        requestNode.set("variables", variablesNode);

        ObjectNode var1 = objectMapper.createObjectNode();
        variablesNode.add(var1);
        var1.put("name", "user");
        var1.put("value", "First value");
        ObjectNode var2 = objectMapper.createObjectNode();
        variablesNode.add(var2);
        var2.put("name", "number");
        var2.put("value", 789);

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK, taskId));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_OK));

        task = taskService.createTaskQuery().taskId(taskId).singleResult();
        assertThat(task).isNull();

        FormInstance formInstance = formEngineFormService.createFormInstanceQuery().taskId(taskId).singleResult();
        assertThat(formInstance).isNotNull();
        byte[] valuesBytes = formEngineFormService.getFormInstanceValues(formInstance.getId());
        assertThat(valuesBytes).isNotNull();
        JsonNode instanceNode = objectMapper.readTree(valuesBytes);
        JsonNode valuesNode = instanceNode.get("values");
        assertThatJson(valuesNode)
                .isEqualTo("{"
                        + "  user: 'First value',"
                        + "  number: '789'"
                        + "}");

        if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {
            HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
            assertThat(historicTaskInstance).isNotNull();
            List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId())
                    .list();
            assertThat(variables).isNotNull();

            assertThat(variables)
                    .extracting(HistoricVariableInstance::getVariableName, HistoricVariableInstance::getValue)
                    .containsExactlyInAnyOrder(
                            tuple("user", "First value"),
                            tuple("number", 789));
        }

    } finally {
        formEngineFormService.deleteFormInstancesByProcessDefinition(processDefinition.getId());

        List<FormDeployment> formDeployments = formRepositoryService.createDeploymentQuery().list();
        for (FormDeployment formDeployment : formDeployments) {
            formRepositoryService.deleteDeployment(formDeployment.getId(), true);
        }
    }
}
 
Example 16
Source File: HistoricTaskInstanceResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@Deployment
public void testCompletedTaskForm() throws Exception {
    if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").singleResult();
        try {
            formRepositoryService.createDeployment().addClasspathResource("org/flowable/rest/service/api/runtime/simple.form").deploy();

            FormDefinition formDefinition = formRepositoryService.createFormDefinitionQuery().formDefinitionKey("form1").singleResult();
            assertThat(formDefinition).isNotNull();

            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
            Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
            String taskId = task.getId();

            String url = RestUrls.createRelativeResourceUrl(RestUrls.URL_HISTORIC_TASK_INSTANCE_FORM, taskId);
            CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);
            JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
            closeResponse(response);
            assertThatJson(responseNode)
                    .when(Option.IGNORING_EXTRA_FIELDS, Option.IGNORING_EXTRA_ARRAY_ITEMS)
                    .isEqualTo("{"
                            + "id: '" + formDefinition.getId() + "',"
                            + "name: '" + formDefinition.getName() + "',"
                            + "key: '" + formDefinition.getKey() + "',"
                            + "fields: [ {  },"
                            + "          {  }"
                            + "        ]"
                            + "}");

            Map<String, Object> variables = new HashMap<>();
            variables.put("user", "First value");
            variables.put("number", 789);
            taskService.completeTaskWithForm(taskId, formDefinition.getId(), null, variables);

            assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult()).isNull();

            response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);
            responseNode = objectMapper.readTree(response.getEntity().getContent());
            closeResponse(response);
            assertThatJson(responseNode)
                    .when(Option.IGNORING_EXTRA_FIELDS, Option.IGNORING_EXTRA_ARRAY_ITEMS)
                    .isEqualTo("{"
                            + "id: '" + formDefinition.getId() + "',"
                            + "name: '" + formDefinition.getName() + "',"
                            + "key: '" + formDefinition.getKey() + "',"
                            + "fields: [ { "
                            + "            id: 'user',"
                            + "            value: 'First value'"
                            + "          },"
                            + "          { "
                            + "            id: 'number',"
                            + "            value: '789'"
                            + "          }"
                            + "        ]"
                            + "}");

        } finally {
            formEngineFormService.deleteFormInstancesByProcessDefinition(processDefinition.getId());

            List<FormDeployment> formDeployments = formRepositoryService.createDeploymentQuery().list();
            for (FormDeployment formDeployment : formDeployments) {
                formRepositoryService.deleteDeployment(formDeployment.getId(), true);
            }
        }
    }
}
 
Example 17
Source File: HumanTaskTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@CmmnDeployment
public void testHumanTask() {
    Authentication.setAuthenticatedUserId("JohnDoe");

    CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
                    .caseDefinitionKey("myCase")
                    .start();
    assertThat(caseInstance).isNotNull();

    Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(task.getName()).isEqualTo("Task One");
    assertThat(task.getAssignee()).isEqualTo("JohnDoe");
    String task1Id = task.getId();
    
    List<EntityLink> entityLinks = cmmnRuntimeService.getEntityLinkChildrenForCaseInstance(caseInstance.getId());
    assertThat(entityLinks).hasSize(1);
    EntityLink entityLink = entityLinks.get(0);
    assertThat(entityLink.getLinkType()).isEqualTo(EntityLinkType.CHILD);
    assertThat(entityLink.getCreateTime()).isNotNull();
    assertThat(entityLink.getScopeId()).isEqualTo(caseInstance.getId());
    assertThat(entityLink.getScopeType()).isEqualTo(ScopeTypes.CMMN);
    assertThat(entityLink.getScopeDefinitionId()).isNull();
    assertThat(entityLink.getReferenceScopeId()).isEqualTo(task.getId());
    assertThat(entityLink.getReferenceScopeType()).isEqualTo(ScopeTypes.TASK);
    assertThat(entityLink.getReferenceScopeDefinitionId()).isNull();
    assertThat(entityLink.getHierarchyType()).isEqualTo(HierarchyType.ROOT);

    assertThat(cmmnTaskService.getIdentityLinksForTask(task1Id))
        .extracting(IdentityLink::getType, IdentityLink::getUserId, IdentityLink::getGroupId)
        .containsExactlyInAnyOrder(
            tuple("assignee", "JohnDoe", null)
        );

    cmmnTaskService.complete(task.getId());

    task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(task.getName()).isEqualTo("Task Two");
    assertThat(task.getAssignee()).isNull();
    String task2Id = task.getId();

    task = cmmnTaskService.createTaskQuery().taskCandidateGroup("test").caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(task.getName()).isEqualTo("Task Two");

    task = cmmnTaskService.createTaskQuery().taskCandidateUser("test2").caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(task.getName()).isEqualTo("Task Two");

    assertThat(cmmnTaskService.getIdentityLinksForTask(task2Id))
        .extracting(IdentityLink::getType, IdentityLink::getUserId, IdentityLink::getGroupId)
        .containsExactlyInAnyOrder(
            tuple("candidate", "test", null),
            tuple("candidate", "test2", null),
            tuple("candidate", null, "test")
        );

    cmmnTaskService.complete(task.getId());

    assertThat(cmmnRuntimeService.createCaseInstanceQuery().count()).isZero();

    if (cmmnEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {
        assertThat(cmmnHistoryService.createHistoricVariableInstanceQuery()
                .caseInstanceId(caseInstance.getId())
                .variableName("var1")
                .singleResult().getValue()).isEqualTo("JohnDoe");
        
        List<HistoricEntityLink> historicEntityLinks = cmmnHistoryService.getHistoricEntityLinkChildrenForCaseInstance(caseInstance.getId());
        for (HistoricEntityLink historicEntityLink : historicEntityLinks) {
            assertThat(historicEntityLink.getLinkType()).isEqualTo(EntityLinkType.CHILD);
            assertThat(historicEntityLink.getCreateTime()).isNotNull();
            assertThat(historicEntityLink.getScopeId()).isEqualTo(caseInstance.getId());
            assertThat(historicEntityLink.getScopeType()).isEqualTo(ScopeTypes.CMMN);
            assertThat(historicEntityLink.getScopeDefinitionId()).isNull();
            assertThat(historicEntityLink.getReferenceScopeType()).isEqualTo(ScopeTypes.TASK);
            assertThat(historicEntityLink.getReferenceScopeDefinitionId()).isNull();
            assertThat(entityLink.getHierarchyType()).isEqualTo(HierarchyType.ROOT);
        }

        assertThat(historicEntityLinks)
                .extracting(HistoricEntityLink::getReferenceScopeId)
                .containsExactlyInAnyOrder(task1Id, task2Id);

        assertThat(cmmnHistoryService.getHistoricIdentityLinksForTask(task1Id))
            .extracting(HistoricIdentityLink::getType, HistoricIdentityLink::getUserId, HistoricIdentityLink::getGroupId)
            .containsExactlyInAnyOrder(
                tuple("assignee", "JohnDoe", null)
            );

        assertThat(cmmnHistoryService.getHistoricIdentityLinksForTask(task2Id))
            .extracting(HistoricIdentityLink::getType, HistoricIdentityLink::getUserId, HistoricIdentityLink::getGroupId)
            .containsExactlyInAnyOrder(
                tuple("candidate", "test", null),
                tuple("candidate", "test2", null),
                tuple("candidate", null, "test")
            );
    }

    Authentication.setAuthenticatedUserId(null);
}
 
Example 18
Source File: SubTaskTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
public void testSubTask() {
    Task gonzoTask = taskService.newTask();
    gonzoTask.setName("gonzoTask");
    taskService.saveTask(gonzoTask);

    Task subTaskOne = taskService.newTask();
    subTaskOne.setName("subtask one");
    String gonzoTaskId = gonzoTask.getId();
    subTaskOne.setParentTaskId(gonzoTaskId);
    taskService.saveTask(subTaskOne);

    Task subTaskTwo = taskService.newTask();
    subTaskTwo.setName("subtask two");
    subTaskTwo.setParentTaskId(gonzoTaskId);
    taskService.saveTask(subTaskTwo);
    
    String subTaskId = subTaskOne.getId();
    assertTrue(taskService.getSubTasks(subTaskId).isEmpty());
    assertTrue(historyService.createHistoricTaskInstanceQuery().taskParentTaskId(subTaskId).list().isEmpty());

    List<Task> subTasks = taskService.getSubTasks(gonzoTaskId);
    Set<String> subTaskNames = new HashSet<>();
    for (Task subTask : subTasks) {
        subTaskNames.add(subTask.getName());
    }

    if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.AUDIT, processEngineConfiguration)) {
        Set<String> expectedSubTaskNames = new HashSet<>();
        expectedSubTaskNames.add("subtask one");
        expectedSubTaskNames.add("subtask two");

        assertEquals(expectedSubTaskNames, subTaskNames);

        List<HistoricTaskInstance> historicSubTasks = historyService.createHistoricTaskInstanceQuery().taskParentTaskId(gonzoTaskId).list();

        subTaskNames = new HashSet<>();
        for (HistoricTaskInstance historicSubTask : historicSubTasks) {
            subTaskNames.add(historicSubTask.getName());
        }

        assertEquals(expectedSubTaskNames, subTaskNames);
    }

    taskService.deleteTask(gonzoTaskId, true);
}
 
Example 19
Source File: TestCacheTaskListener.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void notify(DelegateTask delegateTask) {
    ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
    TaskService taskService = processEngineConfiguration.getTaskService();
    Task task = taskService.createTaskQuery().taskId(delegateTask.getId()).singleResult();
    if (task != null && task.getId().equals(delegateTask.getId())) {
        TASK_ID = task.getId();
    }
    
    HistoryService historyService = processEngineConfiguration.getHistoryService();
    HistoricTaskInstance historicTask = historyService.createHistoricTaskInstanceQuery().taskId(delegateTask.getId()).singleResult();
    if (historicTask != null && historicTask.getId().equals(delegateTask.getId())) {
        HISTORIC_TASK_ID = historicTask.getId();
    }

    delegateTask.setVariable("varFromTheListener", "valueFromTheListener");
    delegateTask.setVariableLocal("localVar", "localValue");

    // Used in CacheTaskTest#testTaskQueryWithIncludeVariables
    ProcessInstance processInstance = processEngineConfiguration.getRuntimeService().createProcessInstanceQuery()
        .processInstanceId(task.getProcessInstanceId())
        .includeProcessVariables()
        .singleResult();
    PROCESS_VARIABLES = processInstance.getProcessVariables();

    HistoricProcessInstance historicProcessInstance = processEngineConfiguration.getHistoryService().createHistoricProcessInstanceQuery()
        .processInstanceId(task.getProcessInstanceId())
        .includeProcessVariables()
        .singleResult();
    HISTORIC_PROCESS_VARIABLES = historicProcessInstance.getProcessVariables();

    // Used in CacheTaskTest#testTaskQueryWithIncludeVariables
    Task taskFromQuery = processEngineConfiguration.getTaskService().createTaskQuery()
        .taskId(delegateTask.getId())
        .includeProcessVariables()
        .includeTaskLocalVariables()
        .singleResult();
    TASK_PROCESS_VARIABLES = taskFromQuery.getProcessVariables();
    TASK_LOCAL_VARIABLES = taskFromQuery.getTaskLocalVariables();

    HistoricTaskInstance historicTaskFromQuery = processEngineConfiguration.getHistoryService().createHistoricTaskInstanceQuery()
        .taskId(delegateTask.getId())
        .includeProcessVariables()
        .includeTaskLocalVariables()
        .singleResult();
    HISTORIC_TASK_PROCESS_VARIABLES = historicTaskFromQuery.getProcessVariables();
    HISTORIC_TASK_LOCAL_VARIABLES = historicTaskFromQuery.getTaskLocalVariables();

}
 
Example 20
Source File: BusinessProcess.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the id of the task associated with the current conversation or 'null'.
 */
public String getTaskId() {
    Task task = getTask();
    return task != null ? task.getId() : null;
}