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

The following examples show how to use org.flowable.task.api.Task#getExecutionId() . 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() + "' 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 2
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 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 = "/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 4
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 (task.getExecutionId() != null && runtimeService.hasVariable(task.getExecutionId(), variableName)) {
            variableFound = true;
        }

    } else if (scope == RestVariableScope.LOCAL) {
        if (taskService.hasVariableLocal(task.getId(), variableName)) {
            variableFound = true;
        }
    }
    return variableFound;
}
 
Example 5
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.getExecutionId() != null) {
        Map<String, Object> rawVariables = runtimeService.getVariables(task.getExecutionId());
        List<RestVariable> globalVariables = restResponseFactory.createRestVariables(rawVariables, task.getId(), RestResponseFactory.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 6
Source File: AttachmentEntityManagerImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteAttachmentsByTaskId(String taskId) {
    checkHistoryEnabled();
    List<AttachmentEntity> attachments = findAttachmentsByTaskId(taskId);
    FlowableEventDispatcher eventDispatcher = getEventDispatcher();
    boolean dispatchEvents = eventDispatcher != null && eventDispatcher.isEnabled();

    String processInstanceId = null;
    String processDefinitionId = null;
    String executionId = null;

    if (dispatchEvents && attachments != null && !attachments.isEmpty()) {
        // Forced to fetch the task to get hold of the process definition
        // for event-dispatching, if available
        Task task = CommandContextUtil.getTaskService().getTask(taskId);
        if (task != null) {
            processDefinitionId = task.getProcessDefinitionId();
            processInstanceId = task.getProcessInstanceId();
            executionId = task.getExecutionId();
        }
    }

    for (Attachment attachment : attachments) {
        String contentId = attachment.getContentId();
        if (contentId != null) {
            getByteArrayEntityManager().deleteByteArrayById(contentId);
        }

        dataManager.delete((AttachmentEntity) attachment);

        if (dispatchEvents) {
            eventDispatcher.dispatchEvent(
                    FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, attachment, executionId, processInstanceId, processDefinitionId));
        }
    }
}
 
Example 7
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 8
Source File: TaskQueryResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Test querying tasks. GET runtime/tasks
 */
@Test
public void testQueryTasksWithPaging() throws Exception {
    try {
        Calendar adhocTaskCreate = Calendar.getInstance();
        adhocTaskCreate.set(Calendar.MILLISECOND, 0);

        processEngineConfiguration.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 = RestUrls.createRelativeResourceUrl(RestUrls.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.getExecutionId() == null) {
                taskService.deleteTask(task.getId(), true);
            }
        }
    }
}