Java Code Examples for org.flowable.engine.runtime.Execution#getId()

The following examples show how to use org.flowable.engine.runtime.Execution#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: ProcessInstanceMigrationTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { TEST_PROCESS_WITH_PARALLEL_GATEWAY })
public void testSetProcessDefinitionVersionPIIsSubExecution() {
    // start process instance
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("forkJoin");

    Execution execution = runtimeService.createExecutionQuery()
            .activityId("receivePayment")
            .singleResult();
    CommandExecutor commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor();
    SetProcessDefinitionVersionCmd command = new SetProcessDefinitionVersionCmd(execution.getId(), 1);
    try {
        commandExecutor.execute(command);
        fail("ActivitiException expected");
    } catch (ActivitiException ae) {
        assertTextPresent("A process instance id is required, but the provided id '" + execution.getId() + "' points to a child execution of process instance '" + pi.getId() + "'. Please invoke the " + command.getClass().getSimpleName()
                + " with a root execution id.", ae.getMessage());
    }
}
 
Example 2
Source File: BaseExecutionVariableResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void setVariable(Execution execution, 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(execution, name, scope);
    if (isNew && hasVariable) {
        throw new FlowableException("Variable '" + name + "' is already present on execution '" + execution.getId() + "'.");
    }

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

    if (scope == RestVariableScope.LOCAL) {
        runtimeService.setVariableLocal(execution.getId(), name, value);
    } else {
        if (execution.getParentId() != null) {
            runtimeService.setVariable(execution.getParentId(), name, value);
        } else {
            runtimeService.setVariable(execution.getId(), name, value);
        }
    }
}
 
Example 3
Source File: ServiceCacheTask.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {
    ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
    RuntimeService runtimeService = processEngineConfiguration.getRuntimeService();
    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(execution.getProcessInstanceId()).singleResult();
    if (processInstance != null && processInstance.getId().equals(execution.getProcessInstanceId())) {
        processInstanceId = processInstance.getId();
    }
    
    Execution queryExecution = runtimeService.createExecutionQuery().executionId(execution.getId()).singleResult();
    if (queryExecution != null && execution.getId().equals(queryExecution.getId())) {
        executionId = queryExecution.getId();
    }
    
    HistoryService historyService = processEngineConfiguration.getHistoryService();
    HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(execution.getProcessInstanceId()).singleResult();
    if (historicProcessInstance != null && historicProcessInstance.getId().equals(execution.getProcessInstanceId())) {
        historicProcessInstanceId = historicProcessInstance.getId();
    }
}
 
Example 4
Source File: ExecutionVariableResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Delete a variable for an execution", tags = { "Executions" }, nickname = "deletedExecutionVariable")
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Indicates both the execution and variable were found and variable has been deleted."),
        @ApiResponse(code = 404, message = "Indicates the requested execution was not found or the execution does not have a variable with the given name in the requested scope. Status description contains additional information about the error.")
})
@DeleteMapping(value = "/runtime/executions/{executionId}/variables/{variableName}")
public void deleteVariable(@ApiParam(name = "executionId") @PathVariable("executionId") String executionId, @ApiParam(name = "variableName") @PathVariable("variableName") String variableName,
        @RequestParam(value = "scope", required = false) String scope,
        HttpServletResponse response) {

    Execution execution = getExecutionFromRequest(executionId);
    // Determine scope
    RestVariableScope variableScope = RestVariableScope.LOCAL;
    if (scope != null) {
        variableScope = RestVariable.getScopeFromString(scope);
    }

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

    if (variableScope == RestVariableScope.LOCAL) {
        runtimeService.removeVariableLocal(execution.getId(), variableName);
    } else {
        // Safe to use parentId, as the hasVariableOnScope would have
        // stopped a global-var update on a root-execution
        runtimeService.removeVariable(execution.getParentId(), variableName);
    }
    response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example 5
Source File: ProcessInstanceVariableResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Delete a variable", tags = { "Process Instance Variables" }, nickname = "deleteProcessInstanceVariable")
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Indicates the variable was found and has been deleted. Response-body is intentionally empty."),
        @ApiResponse(code = 404, message = "Indicates the requested variable was not found.")
})
@DeleteMapping(value = "/runtime/process-instances/{processInstanceId}/variables/{variableName}")
public void deleteVariable(@ApiParam(name = "processInstanceId") @PathVariable("processInstanceId") String processInstanceId, @ApiParam(name = "variableName") @PathVariable("variableName") String variableName,
        @RequestParam(value = "scope", required = false) String scope, HttpServletResponse response) {

    Execution execution = getProcessInstanceFromRequest(processInstanceId);
    // Determine scope
    RestVariableScope variableScope = RestVariableScope.LOCAL;
    if (scope != null) {
        variableScope = RestVariable.getScopeFromString(scope);
    }

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

    if (variableScope == RestVariableScope.LOCAL) {
        runtimeService.removeVariableLocal(execution.getId(), variableName);
    } else {
        // Safe to use parentId, as the hasVariableOnScope would have
        // stopped a global-var update on a root-execution
        runtimeService.removeVariable(execution.getParentId(), variableName);
    }
    response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example 6
Source File: ProcessInstanceMigrationTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment(resources = { TEST_PROCESS_WITH_PARALLEL_GATEWAY })
public void testSetProcessDefinitionVersionPIIsSubExecution() {
    // start process instance
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("forkJoin");

    Execution execution = runtimeService.createExecutionQuery().activityId("receivePayment").singleResult();
    CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
    SetProcessDefinitionVersionCmd command = new SetProcessDefinitionVersionCmd(execution.getId(), 1);
    assertThatThrownBy(() -> commandExecutor.execute(command))
            .isInstanceOf(FlowableException.class)
            .hasMessage("A process instance id is required, but the provided id '" + execution.getId() + "' points to a child execution of process instance '" + pi.getId() + "'. Please invoke the "
                    + command.getClass().getSimpleName() + " with a root execution id.");
}
 
Example 7
Source File: AsyncTaskTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment
public void testAsyncScript() {
    // start process
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("asyncScript");
    // now there should be one job in the database:
    assertThat(managementService.createJobQuery().count()).isEqualTo(1);
    
    Job job = managementService.createJobQuery().singleResult();
    assertThat(job.getElementId()).isEqualTo("script");
    assertThat(job.getElementName()).isEqualTo("Script");
    
    // the script was not invoked:
    List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).list();
    String eid = null;
    for (Execution e : executions) {
        if (e.getParentId() != null) {
            eid = e.getId();
        }
    }
    assertThat(runtimeService.getVariable(eid, "invoked")).isNull();

    waitForJobExecutorToProcessAllJobs(7000L, 100L);

    // and the job is done
    assertThat(managementService.createJobQuery().count()).isZero();

    // the script was invoked
    assertThat(runtimeService.getVariable(eid, "invoked")).isEqualTo("true");

    runtimeService.trigger(eid);
}
 
Example 8
Source File: DefaultContextAssociationManager.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public String getExecutionId() {
    Execution execution = getExecution();
    if (execution != null) {
        return execution.getId();
    } else {
        return null;
    }
}
 
Example 9
Source File: BaseVariableCollectionResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected Object createExecutionVariable(Execution execution, boolean override, int variableType, HttpServletRequest request, HttpServletResponse response) {

        Object result = null;
        if (request instanceof MultipartHttpServletRequest) {
            result = setBinaryVariable((MultipartHttpServletRequest) request, execution, variableType, 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 (!override && hasVariableOnScope(execution, var.getName(), varScope)) {
                    throw new FlowableConflictException("Variable '" + var.getName() + "' is already present on execution '" + execution.getId() + "'.");
                }

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

            if (!variablesToSet.isEmpty()) {
                if (sharedScope == RestVariableScope.LOCAL) {
                    runtimeService.setVariablesLocal(execution.getId(), variablesToSet);
                } else {
                    if (execution.getParentId() != null) {
                        // Explicitly set on parent, setting non-local variables
                        // on execution itself will override local-variables if
                        // exists
                        runtimeService.setVariables(execution.getParentId(), variablesToSet);
                    } else {
                        // Standalone task, no global variables possible
                        throw new FlowableIllegalArgumentException("Cannot set global variables on execution '" + execution.getId() + "', task is not part of process.");
                    }
                }
            }
        }
        response.setStatus(HttpStatus.CREATED.value());
        return result;
    }
 
Example 10
Source File: BaseExecutionVariableResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public RestVariable getVariableFromRequest(Execution execution, String variableName, String scope, boolean includeBinary) {

        boolean variableFound = false;
        Object value = null;

        if (execution == null) {
            throw new FlowableObjectNotFoundException("Could not find an execution", Execution.class);
        }

        RestVariableScope variableScope = RestVariable.getScopeFromString(scope);
        if (variableScope == null) {
            // First, check local variables (which have precedence when no scope
            // is supplied)
            if (runtimeService.hasVariableLocal(execution.getId(), variableName)) {
                value = runtimeService.getVariableLocal(execution.getId(), variableName);
                variableScope = RestVariableScope.LOCAL;
                variableFound = true;
            } else {
                if (execution.getParentId() != null) {
                    value = runtimeService.getVariable(execution.getParentId(), variableName);
                    variableScope = RestVariableScope.GLOBAL;
                    variableFound = true;
                }
            }
        } else if (variableScope == RestVariableScope.GLOBAL) {
            // Use parent to get variables
            if (execution.getParentId() != null) {
                value = runtimeService.getVariable(execution.getParentId(), variableName);
                variableScope = RestVariableScope.GLOBAL;
                variableFound = true;
            }
        } else if (variableScope == RestVariableScope.LOCAL) {

            value = runtimeService.getVariableLocal(execution.getId(), variableName);
            variableScope = RestVariableScope.LOCAL;
            variableFound = true;
        }

        if (!variableFound) {
            throw new FlowableObjectNotFoundException("Execution '" + execution.getId() + "' does not have a variable with name: '" + variableName + "'.", VariableInstanceEntity.class);
        } else {
            return constructRestVariable(variableName, value, variableScope, execution.getId(), includeBinary);
        }
    }
 
Example 11
Source File: OptimisticLockingExceptionTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@Deployment(resources = { "org/flowable/engine/test/concurrency/CompetingJoinTest.testCompetingJoins.bpmn20.xml" })
public void testOptimisticLockExceptionForConcurrentJoin() throws Exception {

    // The optimistic locking exception should happen for this test to be useful.
    // But with concurrency, you never know. Hence why this test is repeated 10 time to make sure the chance for
    // the optimistic exception happening is as big as possible.

    boolean optimisticLockingExceptionHappenedOnce = false;

    for (int i = 0; i < 10; i++) {

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("CompetingJoinsProcess");
        Execution execution1 = runtimeService.createExecutionQuery().activityId("wait1").processInstanceId(processInstance.getId()).singleResult();
        Execution execution2 = runtimeService.createExecutionQuery().activityId("wait2").processInstanceId(processInstance.getId()).singleResult();

        TestTriggerableThread t1 = new TestTriggerableThread(processEngine, execution1.getId());
        TestTriggerableThread t2 = new TestTriggerableThread(processEngine, execution2.getId());

        // Start the two trigger threads. They will wait at the barrier
        t1.start();
        t2.start();

        // Wait at the barrier, until all threads are at the barrier
        OptimisticLockingTestCommandContextCloseListener.TEST_BARRIER_BEFORE_CLOSE.await();

        long totalWaitTime = 0;
        while (t1.getException() == null && t2.getException() == null && runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).count() == 1) {
            Thread.sleep(250L);
            totalWaitTime += 250L;

            if (totalWaitTime >= 7000L) {
                break;
            }
        }

        // Either the transactions just happened to be aligned perfectly and no problem occurred (process instance ended)
        // Or the process instance wasn't ended and one of the two threads has an exception

        // Optimistic locking exception happened, yay. We can stop the test.
        if ((t1.getException() != null && t1.getException() instanceof FlowableOptimisticLockingException)
                || (t2.getException() != null && t2.getException() instanceof FlowableOptimisticLockingException)) {
            optimisticLockingExceptionHappenedOnce = true;
            break;
        }

        boolean processInstanceEnded = runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).count() == 0;
        Assert.assertTrue(processInstanceEnded);

    }

    Assert.assertTrue(optimisticLockingExceptionHappenedOnce);

}
 
Example 12
Source File: ChangeStateForGatewaysTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@Deployment(resources = { "org/flowable/engine/test/api/parallelSubProcessesMultipleTasks.bpmn20.xml" })
public void testMoveCurrentActivityInParallelSubProcess() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startParallelProcess");
    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    assertThat(task.getTaskDefinitionKey()).isEqualTo("taskBefore");

    taskService.complete(task.getId());

    List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
    assertThat(tasks).hasSize(2);

    List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).onlyChildExecutions().list();
    assertThat(executions).hasSize(4);

    Execution subProcessExecution = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).activityId("subProcess1")
            .singleResult();
    String subProcessExecutionId = subProcessExecution.getId();
    runtimeService.setVariableLocal(subProcessExecutionId, "subProcessVar", "test");

    runtimeService.createChangeActivityStateBuilder()
            .processInstanceId(processInstance.getId())
            .moveActivityIdTo("subtask", "subtask2")
            .changeState();

    tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
    assertThat(tasks).hasSize(2);

    executions = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).onlyChildExecutions().list();
    assertThat(executions).hasSize(4);

    subProcessExecution = runtimeService.createExecutionQuery().executionId(subProcessExecutionId).singleResult();
    assertThat(subProcessExecution).isNotNull();
    assertThat(runtimeService.getVariableLocal(subProcessExecutionId, "subProcessVar")).isEqualTo("test");

    taskService.complete(tasks.get(0).getId());

    tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
    assertThat(tasks).hasSize(1);

    executions = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).onlyChildExecutions().list();
    assertThat(executions).hasSize(3);

    taskService.complete(tasks.get(0).getId());

    task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    assertThat(task.getTaskDefinitionKey()).isEqualTo("taskAfter");
    taskService.complete(task.getId());

    assertProcessEnded(processInstance.getId());
}
 
Example 13
Source File: MessageBoundaryEventTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@Deployment
public void testDoubleBoundaryMessageEvent() {
    runtimeService.startProcessInstanceByKey("process");

    assertThat(runtimeService.createExecutionQuery().count()).isEqualTo(4);

    org.flowable.task.api.Task userTask = taskService.createTaskQuery().singleResult();
    assertThat(userTask).isNotNull();

    // the executions for both messageEventSubscriptionNames are not the same
    Execution execution1 = runtimeService.createExecutionQuery().messageEventSubscriptionName("messageName_1").singleResult();
    assertThat(execution1).isNotNull();

    Execution execution2 = runtimeService.createExecutionQuery().messageEventSubscriptionName("messageName_2").singleResult();
    assertThat(execution2).isNotNull();

    assertThat(execution1.getId()).isNotEqualTo(execution2.getId());

    // /////////////////////////////////////////////////////////////////////////////////
    // 1. first message received cancels the task and the execution and both subscriptions
    runtimeService.messageEventReceived("messageName_1", execution1.getId());

    // this should then throw an exception because execution2 no longer exists
    String execution2Id = execution2.getId();
    assertThatThrownBy(() -> runtimeService.messageEventReceived("messageName_2", execution2Id));

    userTask = taskService.createTaskQuery().singleResult();
    assertThat(userTask).isNotNull();
    assertThat(userTask.getTaskDefinitionKey()).isEqualTo("taskAfterMessage_1");
    taskService.complete(userTask.getId());
    assertThat(runtimeService.createProcessInstanceQuery().count()).isZero();

    // ///////////////////////////////////////////////////////////////////
    // 2. complete the user task cancels the message subscriptions

    runtimeService.startProcessInstanceByKey("process");

    userTask = taskService.createTaskQuery().singleResult();
    assertThat(userTask).isNotNull();
    taskService.complete(userTask.getId());

    execution1 = runtimeService.createExecutionQuery().messageEventSubscriptionName("messageName_1").singleResult();
    assertThat(execution1).isNull();
    execution2 = runtimeService.createExecutionQuery().messageEventSubscriptionName("messageName_2").singleResult();
    assertThat(execution2).isNull();

    userTask = taskService.createTaskQuery().singleResult();
    assertThat(userTask).isNotNull();
    assertThat(userTask.getTaskDefinitionKey()).isEqualTo("taskAfterTask");
    taskService.complete(userTask.getId());
    assertThat(runtimeService.createProcessInstanceQuery().count()).isZero();
}
 
Example 14
Source File: BusinessProcess.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
/**
 * @see #getExecution()
 */
public String getExecutionId() {
    Execution e = getExecution();
    return e != null ? e.getId() : null;
}