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

The following examples show how to use org.flowable.task.api.Task#getScopeId() . 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: PermissionService.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public boolean validateIfUserIsInitiatorAndCanCompleteTask(User user, Task task) {
    boolean canCompleteTask = false;
    if (task.getProcessInstanceId() != null) {
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        if (historicProcessInstance != null && StringUtils.isNotEmpty(historicProcessInstance.getStartUserId())) {
            String processInstanceStartUserId = historicProcessInstance.getStartUserId();
            if (String.valueOf(user.getId()).equals(processInstanceStartUserId)) {
                BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
                FlowElement flowElement = bpmnModel.getFlowElement(task.getTaskDefinitionKey());
                if (flowElement instanceof UserTask) {
                    UserTask userTask = (UserTask) flowElement;
                    List<ExtensionElement> extensionElements = userTask.getExtensionElements().get("initiator-can-complete");
                    if (CollectionUtils.isNotEmpty(extensionElements)) {
                        String value = extensionElements.get(0).getElementText();
                        if (StringUtils.isNotEmpty(value) && Boolean.valueOf(value)) {
                            canCompleteTask = true;
                        }
                    }
                }
            }
        }

    } else if (task.getScopeId() != null) {
        HistoricCaseInstance historicCaseInstance = cmmnHistoryService.createHistoricCaseInstanceQuery().caseInstanceId(task.getScopeId()).singleResult();
        if (historicCaseInstance != null && StringUtils.isNotEmpty(historicCaseInstance.getStartUserId())) {
            String caseInstanceStartUserId = historicCaseInstance.getStartUserId();
            if (String.valueOf(user.getId()).equals(caseInstanceStartUserId)) {
                canCompleteTask = true;
            }
        }
    }
    return canCompleteTask;
}
 
Example 3
Source File: TaskResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Delete a task", tags = { "Tasks" })
@ApiImplicitParams({
        @ApiImplicitParam(name = "cascadeHistory", dataType = "string", value = "Whether or not to delete the HistoricTask instance when deleting the task (if applicable). If not provided, this value defaults to false.", paramType = "query"),
        @ApiImplicitParam(name = "deleteReason", dataType = "string", value = "Reason why the task is deleted. This value is ignored when cascadeHistory is true.", paramType = "query")
})
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Indicates the task was found and has been deleted. Response-body is intentionally empty."),
        @ApiResponse(code = 403, message = "Indicates the requested task cannot be deleted because it’s part of a workflow."),
        @ApiResponse(code = 404, message = "Indicates the requested task was not found.")
})
@DeleteMapping(value = "/cmmn-runtime/tasks/{taskId}")
public void deleteTask(@ApiParam(name = "taskId") @PathVariable String taskId, @ApiParam(hidden = true) @RequestParam(value = "cascadeHistory", required = false) Boolean cascadeHistory,
        @ApiParam(hidden = true) @RequestParam(value = "deleteReason", required = false) String deleteReason, HttpServletResponse response) {

    Task taskToDelete = getTaskFromRequest(taskId);
    if (taskToDelete.getScopeId() != null && ScopeTypes.CMMN.equals(taskToDelete.getScopeType())) {
        // Can't delete a task that is part of a case instance
        throw new FlowableForbiddenException("Cannot delete a task that is part of a case instance.");
    } else if (taskToDelete.getExecutionId() != null) {
        throw new FlowableForbiddenException("Cannot delete a task that is part of a process instance.");
    }
    
    if (restApiInterceptor != null) {
        restApiInterceptor.deleteTask(taskToDelete);
    }

    if (cascadeHistory != null) {
        // Ignore delete-reason since the task-history (where the reason is
        // recorded) will be deleted anyway
        taskService.deleteTask(taskToDelete.getId(), cascadeHistory);
    } else {
        // Delete with delete-reason
        taskService.deleteTask(taskToDelete.getId(), deleteReason);
    }
    response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example 4
Source File: TaskVariableBaseResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public RestVariable getVariableFromRequest(String taskId, String variableName, String scope, boolean includeBinary) {
    Task task = getTaskFromRequest(taskId);
    
    boolean variableFound = false;
    Object value = null;
    RestVariableScope variableScope = RestVariable.getScopeFromString(scope);
    if (variableScope == null) {
        // First, check local variables (which have precedence when no scope is supplied)
        if (taskService.hasVariableLocal(taskId, variableName)) {
            value = taskService.getVariableLocal(taskId, variableName);
            variableScope = RestVariableScope.LOCAL;
            variableFound = true;
        } else {
            // Revert to execution-variable when not present local on the task
            if (ScopeTypes.CMMN.equals(task.getScopeType()) && task.getScopeId() != null && runtimeService.hasVariable(task.getScopeId(), variableName)) {
                value = runtimeService.getVariable(task.getScopeId(), variableName);
                variableScope = RestVariableScope.GLOBAL;
                variableFound = true;
            }
        }

    } else if (variableScope == RestVariableScope.GLOBAL) {
        if (ScopeTypes.CMMN.equals(task.getScopeType()) && task.getScopeId() != null && runtimeService.hasVariable(task.getScopeId(), variableName)) {
            value = runtimeService.getVariable(task.getScopeId(), variableName);
            variableFound = true;
        }

    } else if (variableScope == RestVariableScope.LOCAL) {
        if (taskService.hasVariableLocal(taskId, variableName)) {
            value = taskService.getVariableLocal(taskId, variableName);
            variableFound = true;
        }
    }

    if (!variableFound) {
        throw new FlowableObjectNotFoundException("Task '" + taskId + "' doesn't have a variable with name: '" + variableName + "'.", VariableInstanceEntity.class);
    } else {
        return restResponseFactory.createRestVariable(variableName, value, variableScope, taskId, CmmnRestResponseFactory.VARIABLE_TASK, includeBinary);
    }
}
 
Example 5
Source File: TaskVariableBaseResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected boolean hasVariableOnScope(Task task, String variableName, RestVariableScope scope) {
    boolean variableFound = false;

    if (scope == RestVariableScope.GLOBAL) {
        if (ScopeTypes.CMMN.equals(task.getScopeType()) && task.getScopeId() != null && runtimeService.hasVariable(task.getScopeId(), variableName)) {
            variableFound = true;
        }

    } else if (scope == RestVariableScope.LOCAL) {
        if (taskService.hasVariableLocal(task.getId(), variableName)) {
            variableFound = true;
        }
    }
    return variableFound;
}
 
Example 6
Source File: TaskVariableCollectionResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void addGlobalVariables(Task task, Map<String, RestVariable> variableMap) {
    if (task.getScopeId() != null) {
        Map<String, Object> rawVariables = runtimeService.getVariables(task.getScopeId());
        List<RestVariable> globalVariables = restResponseFactory.createRestVariables(rawVariables, task.getId(), CmmnRestResponseFactory.VARIABLE_TASK, RestVariableScope.GLOBAL);

        // Overlay global variables over local ones. In case they are present the values are not overridden,
        // since local variables get precedence over global ones at all times.
        for (RestVariable var : globalVariables) {
            if (!variableMap.containsKey(var.getName())) {
                variableMap.put(var.getName(), var);
            }
        }
    }
}
 
Example 7
Source File: TaskResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Delete a task", tags = { "Tasks" })
@ApiImplicitParams({
        @ApiImplicitParam(name = "cascadeHistory", dataType = "string", value = "Whether or not to delete the HistoricTask instance when deleting the task (if applicable). If not provided, this value defaults to false.", paramType = "query"),
        @ApiImplicitParam(name = "deleteReason", dataType = "string", value = "Reason why the task is deleted. This value is ignored when cascadeHistory is true.", paramType = "query")
})
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Indicates the task was found and has been deleted. Response-body is intentionally empty."),
        @ApiResponse(code = 403, message = "Indicates the requested task cannot be deleted because it’s part of a workflow."),
        @ApiResponse(code = 404, message = "Indicates the requested task was not found.")
})
@DeleteMapping(value = "/runtime/tasks/{taskId}")
public void deleteTask(@ApiParam(name = "taskId") @PathVariable String taskId, @ApiParam(hidden = true) @RequestParam(value = "cascadeHistory", required = false) Boolean cascadeHistory,
        @ApiParam(hidden = true) @RequestParam(value = "deleteReason", required = false) String deleteReason, HttpServletResponse response) {

    Task taskToDelete = getTaskFromRequest(taskId);
    if (taskToDelete.getExecutionId() != null) {
        // Can not delete a task that is part of a process instance
        throw new FlowableForbiddenException("Cannot delete a task that is part of a process instance.");
    } else if (taskToDelete.getScopeId() != null && ScopeTypes.CMMN.equals(taskToDelete.getScopeType())) {
        throw new FlowableForbiddenException("Cannot delete a task that is part of a case instance.");
    }

    if (restApiInterceptor != null) {
        restApiInterceptor.deleteTask(taskToDelete);
    }

    if (cascadeHistory != null) {
        // Ignore delete-reason since the task-history (where the reason is
        // recorded) will be deleted anyway
        taskService.deleteTask(taskToDelete.getId(), cascadeHistory);
    } else {
        // Delete with delete-reason
        taskService.deleteTask(taskToDelete.getId(), deleteReason);
    }
    response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example 8
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 9
Source File: TaskQueryResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Test querying tasks. GET cmmn-runtime/tasks
 */
public void testQueryTasksWithPaging() throws Exception {
    try {
        Calendar adhocTaskCreate = Calendar.getInstance();
        adhocTaskCreate.set(Calendar.MILLISECOND, 0);

        cmmnEngineConfiguration.getClock().setCurrentTime(adhocTaskCreate.getTime());
        List<String> taskIdList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Task adhocTask = taskService.newTask();
            adhocTask.setAssignee("gonzo");
            adhocTask.setOwner("owner");
            adhocTask.setDelegationState(DelegationState.PENDING);
            adhocTask.setDescription("Description one");
            adhocTask.setName("Name one");
            adhocTask.setDueDate(adhocTaskCreate.getTime());
            adhocTask.setPriority(100);
            taskService.saveTask(adhocTask);
            taskService.addUserIdentityLink(adhocTask.getId(), "misspiggy", IdentityLinkType.PARTICIPANT);
            taskIdList.add(adhocTask.getId());
        }
        Collections.sort(taskIdList);

        // Check filter-less to fetch all tasks
        String url = CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_TASK_QUERY);
        ObjectNode requestNode = objectMapper.createObjectNode();
        String[] taskIds = new String[] { taskIdList.get(0), taskIdList.get(1), taskIdList.get(2) };
        assertResultsPresentInPostDataResponse(url + "?size=3&sort=id&order=asc", requestNode, taskIds);

        taskIds = new String[] { taskIdList.get(4), taskIdList.get(5), taskIdList.get(6), taskIdList.get(7) };
        assertResultsPresentInPostDataResponse(url + "?start=4&size=4&sort=id&order=asc", requestNode, taskIds);

        taskIds = new String[] { taskIdList.get(8), taskIdList.get(9) };
        assertResultsPresentInPostDataResponse(url + "?start=8&size=10&sort=id&order=asc", requestNode, taskIds);

    } finally {
        // Clean adhoc-tasks even if test fails
        List<Task> tasks = taskService.createTaskQuery().list();
        for (Task task : tasks) {
            if (task.getScopeId() == null) {
                taskService.deleteTask(task.getId(), true);
            }
        }
    }
}