Java Code Examples for org.flowable.engine.repository.ProcessDefinition#getId()

The following examples show how to use org.flowable.engine.repository.ProcessDefinition#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: FlowableProcessDefinitionService.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected FormInfo getStartForm(ProcessDefinition processDefinition) {
    FormInfo formInfo = null;
    BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
    Process process = bpmnModel.getProcessById(processDefinition.getKey());
    FlowElement startElement = process.getInitialFlowElement();
    if (startElement instanceof StartEvent) {
        StartEvent startEvent = (StartEvent) startElement;
        if (StringUtils.isNotEmpty(startEvent.getFormKey())) {
            Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(processDefinition.getDeploymentId()).singleResult();
            formInfo = formRepositoryService.getFormModelByKeyAndParentDeploymentId(startEvent.getFormKey(), deployment.getParentDeploymentId(), 
                            processDefinition.getTenantId(), processEngineConfiguration.isFallbackToDefaultTenant());
        }
    }

    if (formInfo == null) {
        // Definition found, but no form attached
        throw new NotFoundException("Process definition does not have a form defined: " + processDefinition.getId());
    }

    return formInfo;
}
 
Example 2
Source File: FlowableProcessInstanceService.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public ProcessInstanceRepresentation startNewProcessInstance(CreateProcessInstanceRepresentation startRequest) {
    if (StringUtils.isEmpty(startRequest.getProcessDefinitionId())) {
        throw new BadRequestException("Process definition id is required");
    }

    ProcessDefinition processDefinition = repositoryService.getProcessDefinition(startRequest.getProcessDefinitionId());

    if (!permissionService.canStartProcess(SecurityUtils.getCurrentUserObject(), processDefinition)) {
        throw new NotPermittedException("User is not listed as potential starter for process definition with id: " + processDefinition.getId());
    }

    ProcessInstance processInstance = runtimeService.startProcessInstanceWithForm(startRequest.getProcessDefinitionId(),
            startRequest.getOutcome(), startRequest.getValues(), startRequest.getName());

    User user = null;
    if (processInstance.getStartUserId() != null) {
        CachedUser cachedUser = userCache.getUser(processInstance.getStartUserId());
        if (cachedUser != null && cachedUser.getUser() != null) {
            user = cachedUser.getUser();
        }
    }
    return new ProcessInstanceRepresentation(processInstance, processDefinition,
            ((ProcessDefinitionEntity) processDefinition).isGraphicalNotationDefined(), user);

}
 
Example 3
Source File: ProcessDefinitionImageResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Get a process definition image", tags = { "Process Definitions" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Indicates request was successful and the process-definitions are returned"),
        @ApiResponse(code = 404, message = "Indicates the requested process definition was not found.")
})
@GetMapping(value = "/repository/process-definitions/{processDefinitionId}/image", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<byte[]> getModelResource(@ApiParam(name = "processDefinitionId") @PathVariable String processDefinitionId) {
    ProcessDefinition processDefinition = getProcessDefinitionFromRequest(processDefinitionId);
    InputStream imageStream = repositoryService.getProcessDiagram(processDefinition.getId());

    if (imageStream != null) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", MediaType.IMAGE_PNG_VALUE);
        try {
            return new ResponseEntity<>(IOUtils.toByteArray(imageStream), responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            throw new FlowableException("Error reading image stream", e);
        }
    } else {
        throw new FlowableIllegalArgumentException("Process definition with id '" + processDefinition.getId() + "' has no image.");
    }
}
 
Example 4
Source File: ProcessDefinitionResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected FormInfo getStartForm(ProcessDefinition processDefinition) {
    FormInfo formInfo = null;
    BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
    Process process = bpmnModel.getProcessById(processDefinition.getKey());
    FlowElement startElement = process.getInitialFlowElement();
    if (startElement instanceof StartEvent) {
        StartEvent startEvent = (StartEvent) startElement;
        if (StringUtils.isNotEmpty(startEvent.getFormKey())) {
            if (startEvent.isSameDeployment()) {
                Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(processDefinition.getDeploymentId()).singleResult();
                formInfo = formRepositoryService.getFormModelByKeyAndParentDeploymentId(startEvent.getFormKey(),
                                deployment.getParentDeploymentId(), processDefinition.getTenantId(), processEngineConfiguration.isFallbackToDefaultTenant());
            } else {
                formInfo = formRepositoryService.getFormModelByKey(startEvent.getFormKey(), processDefinition.getTenantId(),
                        processEngineConfiguration.isFallbackToDefaultTenant());
            }
        }
    }

    if (formInfo == null) {
        // Definition found, but no form attached
        throw new FlowableObjectNotFoundException("Process definition does not have a form defined: " + processDefinition.getId());
    }
    
    return formInfo;
}
 
Example 5
Source File: DeploymentManager.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public ProcessDefinitionCacheEntry resolveProcessDefinition(ProcessDefinition processDefinition) {
    String processDefinitionId = processDefinition.getId();
    String deploymentId = processDefinition.getDeploymentId();
    ProcessDefinitionCacheEntry cachedProcessDefinition = processDefinitionCache.get(processDefinitionId);
    if (cachedProcessDefinition == null) {
        DeploymentEntity deployment = Context
                .getCommandContext()
                .getDeploymentEntityManager()
                .findDeploymentById(deploymentId);
        deployment.setNew(false);
        deploy(deployment, null);
        cachedProcessDefinition = processDefinitionCache.get(processDefinitionId);

        if (cachedProcessDefinition == null) {
            throw new ActivitiException("deployment '" + deploymentId + "' didn't put process definition '" + processDefinitionId + "' in the cache");
        }
    }
    return cachedProcessDefinition;
}
 
Example 6
Source File: DeploymentManager.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Resolving the process definition will fetch the BPMN 2.0, parse it and store the {@link BpmnModel} in memory.
 */
public ProcessDefinitionCacheEntry resolveProcessDefinition(ProcessDefinition processDefinition) {
    String processDefinitionId = processDefinition.getId();
    String deploymentId = processDefinition.getDeploymentId();

    ProcessDefinitionCacheEntry cachedProcessDefinition = processDefinitionCache.get(processDefinitionId);

    if (cachedProcessDefinition == null) {
        if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, processEngineConfiguration)) {
            return Flowable5Util.getFlowable5CompatibilityHandler().resolveProcessDefinition(processDefinition);
        }

        DeploymentEntity deployment = deploymentEntityManager.findById(deploymentId);
        deployment.setNew(false);
        deploy(deployment, null);
        cachedProcessDefinition = processDefinitionCache.get(processDefinitionId);

        if (cachedProcessDefinition == null) {
            throw new FlowableException("deployment '" + deploymentId + "' didn't put process definition '" + processDefinitionId + "' in the cache");
        }
    }
    return cachedProcessDefinition;
}
 
Example 7
Source File: SignalsResourceTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment(resources = { "org/flowable/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml" })
public void testQueryEventSubscriptions() throws Exception {
    Calendar hourAgo = Calendar.getInstance();
    hourAgo.add(Calendar.HOUR, -1);

    Calendar inAnHour = Calendar.getInstance();
    inAnHour.add(Calendar.HOUR, 1);

    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();

    EventSubscription eventSubscription = runtimeService.createEventSubscriptionQuery().singleResult();

    String url = RestUrls.createRelativeResourceUrl(RestUrls.URL_EVENT_SUBSCRIPTION_COLLECTION);
    assertResultsPresentInDataResponse(url, eventSubscription.getId());

    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_EVENT_SUBSCRIPTION_COLLECTION) + "?eventType=signal";
    assertResultsPresentInDataResponse(url, eventSubscription.getId());

    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_EVENT_SUBSCRIPTION_COLLECTION) + "?eventName=" + encode("The Signal");
    assertResultsPresentInDataResponse(url, eventSubscription.getId());

    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_EVENT_SUBSCRIPTION_COLLECTION) + "?activityId=theStart";
    assertResultsPresentInDataResponse(url, eventSubscription.getId());

    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_EVENT_SUBSCRIPTION_COLLECTION) + "?activityId=nonexisting";
    assertEmptyResultsPresentInDataResponse(url);

    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_EVENT_SUBSCRIPTION_COLLECTION) + "?processDefinitionId=" + processDefinition.getId();
    assertResultsPresentInDataResponse(url, eventSubscription.getId());

    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_EVENT_SUBSCRIPTION_COLLECTION) + "?processDefinitionId=nonexisting";
    assertEmptyResultsPresentInDataResponse(url);

    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_EVENT_SUBSCRIPTION_COLLECTION) + "?createdBefore=" + getISODateString(inAnHour.getTime());
    assertResultsPresentInDataResponse(url, eventSubscription.getId());

    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_EVENT_SUBSCRIPTION_COLLECTION) + "?createdAfter=" + getISODateString(hourAgo.getTime());
    assertResultsPresentInDataResponse(url, eventSubscription.getId());
}
 
Example 8
Source File: OneTaskProcessTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public String deployTestProcess(BpmnModel bpmnModel) {
    org.flowable.engine.repository.Deployment deployment = repositoryService.createDeployment().addBpmnModel("oneTasktest.bpmn20.xml", bpmnModel).deploy();

    deploymentIdsForAutoCleanup.add(deployment.getId()); // For auto-cleanup

    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
    return processDefinition.getId();
}
 
Example 9
Source File: TaskFormsTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment(resources = { "org/flowable/examples/taskforms/VacationRequest_deprecated_forms.bpmn20.xml", "org/flowable/examples/taskforms/approve.form",
        "org/flowable/examples/taskforms/request.form", "org/flowable/examples/taskforms/adjustRequest.form" })
public void testTaskFormsWithVacationRequestProcess() {

    // Get start form
    String procDefId = repositoryService.createProcessDefinitionQuery().singleResult().getId();
    Object startForm = formService.getRenderedStartForm(procDefId);
    assertThat(startForm).isNotNull();

    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
    String processDefinitionId = processDefinition.getId();
    assertThat(formService.getStartFormData(processDefinitionId).getFormKey()).isEqualTo("org/flowable/examples/taskforms/request.form");

    // Define variables that would be filled in through the form
    Map<String, String> formProperties = new HashMap<>();
    formProperties.put("employeeName", "kermit");
    formProperties.put("numberOfDays", "4");
    formProperties.put("vacationMotivation", "I'm tired");
    formService.submitStartFormData(procDefId, formProperties);

    // Management should now have a task assigned to them
    org.flowable.task.api.Task task = taskService.createTaskQuery().taskCandidateGroup("management").singleResult();
    assertThat(task.getDescription()).isEqualTo("Vacation request by kermit");
    Object taskForm = formService.getRenderedTaskForm(task.getId());
    assertThat(taskForm).isNotNull();

    // Rejecting the task should put the process back to first task
    taskService.complete(task.getId(), CollectionUtil.singletonMap("vacationApproved", "false"));
    task = taskService.createTaskQuery().singleResult();
    assertThat(task.getName()).isEqualTo("Adjust vacation request");
}
 
Example 10
Source File: SetProcessDefinitionVersionCmd.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public Void execute(CommandContext commandContext) {
    // check that the new process definition is just another version of the same
    // process definition that the process instance is using
    ExecutionEntityManager executionManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    ExecutionEntity processInstance = executionManager.findById(processInstanceId);
    if (processInstance == null) {
        throw new FlowableObjectNotFoundException("No process instance found for id = '" + processInstanceId + "'.", ProcessInstance.class);
    } else if (!processInstance.isProcessInstanceType()) {
        throw new FlowableIllegalArgumentException("A process instance id is required, but the provided id " + "'" + processInstanceId + "' " + "points to a child execution of process instance " + "'"
                + processInstance.getProcessInstanceId() + "'. " + "Please invoke the " + getClass().getSimpleName() + " with a root execution id.");
    }

    DeploymentManager deploymentCache = CommandContextUtil.getProcessEngineConfiguration(commandContext).getDeploymentManager();
    ProcessDefinition currentProcessDefinition = deploymentCache.findDeployedProcessDefinitionById(processInstance.getProcessDefinitionId());

    ProcessDefinition newProcessDefinition = deploymentCache
            .findDeployedProcessDefinitionByKeyAndVersionAndTenantId(currentProcessDefinition.getKey(), processDefinitionVersion, currentProcessDefinition.getTenantId());

    if (Flowable5Util.isFlowable5ProcessDefinition(currentProcessDefinition, commandContext) && !Flowable5Util
        .isFlowable5ProcessDefinition(newProcessDefinition, commandContext)) {
        throw new FlowableIllegalArgumentException("The current process definition (id = '" + currentProcessDefinition.getId() + "') is a v5 definition."
            + " However the new process definition (id = '" + newProcessDefinition.getId() + "') is not a v5 definition.");
    }

    validateAndSwitchVersionOfExecution(commandContext, processInstance, newProcessDefinition);

    // switch the historic process instance to the new process definition version
    CommandContextUtil.getHistoryManager(commandContext).recordProcessDefinitionChange(processInstanceId, newProcessDefinition.getId());

    // switch all sub-executions of the process instance to the new process definition version
    Collection<ExecutionEntity> childExecutions = executionManager.findChildExecutionsByProcessInstanceId(processInstanceId);
    for (ExecutionEntity executionEntity : childExecutions) {
        validateAndSwitchVersionOfExecution(commandContext, executionEntity, newProcessDefinition);
    }

    return null;
}
 
Example 11
Source File: AbstractFlowableTestCase.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public String deployTwoTasksTestProcess() {
    BpmnModel bpmnModel = createTwoTasksTestProcess();
    Deployment deployment = repositoryService.createDeployment().addBpmnModel("twoTasksTestProcess.bpmn20.xml", bpmnModel).deploy();

    deploymentIdsForAutoCleanup.add(deployment.getId()); // For auto-cleanup

    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
    return processDefinition.getId();
}
 
Example 12
Source File: AbstractFlowableTestCase.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public String deployOneTaskTestProcessWithCandidateStarterGroup() {
    BpmnModel bpmnModel = createOneTaskTestProcessWithCandidateStarterGroup();
    Deployment deployment = repositoryService.createDeployment().addBpmnModel("oneTasktest.bpmn20.xml", bpmnModel).deploy();

    deploymentIdsForAutoCleanup.add(deployment.getId()); // For auto-cleanup

    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
    return processDefinition.getId();
}
 
Example 13
Source File: ProcessInstanceHelper.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public ProcessInstance createProcessInstance(ProcessDefinition processDefinition, String businessKey, String processInstanceName,
                String overrideDefinitionTenantId, String predefinedProcessInstanceId, Map<String, Object> variables, Map<String, Object> transientVariables, 
                String callbackId, String callbackType, String referenceId, String referenceType, String stageInstanceId, boolean startProcessInstance) {

    CommandContext commandContext = Context.getCommandContext();
    if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, commandContext)) {
        Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
        return compatibilityHandler.startProcessInstance(processDefinition.getKey(), processDefinition.getId(),
                variables, transientVariables, businessKey, processDefinition.getTenantId(), processInstanceName);
    }

    // Do not start process a process instance if the process definition is suspended
    if (ProcessDefinitionUtil.isProcessDefinitionSuspended(processDefinition.getId())) {
        throw new FlowableException("Cannot start process instance. Process definition " + processDefinition.getName() + " (id = " + processDefinition.getId() + ") is suspended");
    }

    // Get model from cache
    Process process = ProcessDefinitionUtil.getProcess(processDefinition.getId());
    if (process == null) {
        throw new FlowableException("Cannot start process instance. Process model " + processDefinition.getName() + " (id = " + processDefinition.getId() + ") could not be found");
    }

    FlowElement initialFlowElement = process.getInitialFlowElement();
    if (initialFlowElement == null) {
        throw new FlowableException("No start element found for process definition " + processDefinition.getId());
    }

    return createAndStartProcessInstanceWithInitialFlowElement(processDefinition, businessKey, processInstanceName, overrideDefinitionTenantId, 
                    predefinedProcessInstanceId, initialFlowElement, process, variables, transientVariables, 
                    callbackId, callbackType, referenceId, referenceType, stageInstanceId, startProcessInstance);
}
 
Example 14
Source File: AbstractFlowableTestCase.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and deploys the one task process. See {@link #createOneTaskTestProcess()}.
 * 
 * @return The process definition id (NOT the process definition key) of deployed one task process.
 */
public String deployOneTaskTestProcess() {
    BpmnModel bpmnModel = createOneTaskTestProcess();
    Deployment deployment = repositoryService.createDeployment()
            .addBpmnModel("oneTasktest.bpmn20.xml", bpmnModel).deploy();

    deploymentIdsForAutoCleanup.add(deployment.getId()); // For auto-cleanup

    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
            .deploymentId(deployment.getId()).singleResult();
    return processDefinition.getId();
}
 
Example 15
Source File: ProcessDefinitionResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected ProcessDefinitionResponse suspendProcessDefinition(ProcessDefinition processDefinition, boolean suspendInstances, Date date) {

        if (repositoryService.isProcessDefinitionSuspended(processDefinition.getId())) {
            throw new FlowableConflictException("Process definition with id '" + processDefinition.getId() + " ' is already suspended");
        }
        repositoryService.suspendProcessDefinitionById(processDefinition.getId(), suspendInstances, date);

        ProcessDefinitionResponse response = restResponseFactory.createProcessDefinitionResponse(processDefinition);

        // No need to re-fetch the ProcessDefinition, just alter the suspended
        // state of the result-object
        response.setSuspended(true);
        return response;
    }
 
Example 16
Source File: ProcessDefinitionResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected ProcessDefinitionResponse activateProcessDefinition(ProcessDefinition processDefinition, boolean suspendInstances, Date date) {

        if (!repositoryService.isProcessDefinitionSuspended(processDefinition.getId())) {
            throw new FlowableConflictException("Process definition with id '" + processDefinition.getId() + " ' is already active");
        }
        repositoryService.activateProcessDefinitionById(processDefinition.getId(), suspendInstances, date);

        ProcessDefinitionResponse response = restResponseFactory.createProcessDefinitionResponse(processDefinition);

        // No need to re-fetch the ProcessDefinition, just alter the suspended
        // state of the result-object
        response.setSuspended(false);
        return response;
    }
 
Example 17
Source File: NeedsActiveProcessDefinitionCmd.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public T execute(CommandContext commandContext) {
    DeploymentManager deploymentManager = commandContext.getProcessEngineConfiguration().getDeploymentManager();
    ProcessDefinition processDefinition = deploymentManager.findDeployedProcessDefinitionById(processDefinitionId);

    if (deploymentManager.isProcessDefinitionSuspended(processDefinitionId)) {
        throw new ActivitiException("Cannot execute operation because process definition '"
                + processDefinition.getName() + "' (id=" + processDefinition.getId() + ") is suspended");
    }

    return execute(commandContext, processDefinition);
}
 
Example 18
Source File: TaskFormsTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Deployment(resources = {
        "org/activiti/examples/taskforms/VacationRequest_deprecated_forms.bpmn20.xml",
        "org/activiti/examples/taskforms/approve.form",
        "org/activiti/examples/taskforms/request.form",
        "org/activiti/examples/taskforms/adjustRequest.form" })
public void testTaskFormsWithVacationRequestProcess() {

    // Get start form
    String procDefId = repositoryService.createProcessDefinitionQuery().singleResult().getId();
    Object startForm = formService.getRenderedStartForm(procDefId);
    assertNotNull(startForm);

    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
    String processDefinitionId = processDefinition.getId();
    assertEquals("org/activiti/examples/taskforms/request.form", formService.getStartFormData(processDefinitionId).getFormKey());

    // Define variables that would be filled in through the form
    Map<String, String> formProperties = new HashMap<String, String>();
    formProperties.put("employeeName", "kermit");
    formProperties.put("numberOfDays", "4");
    formProperties.put("vacationMotivation", "I'm tired");
    formService.submitStartFormData(procDefId, formProperties);

    // Management should now have a task assigned to them
    org.flowable.task.api.Task task = taskService.createTaskQuery().taskCandidateGroup("management").singleResult();
    assertEquals("Vacation request by kermit", task.getDescription());
    Object taskForm = formService.getRenderedTaskForm(task.getId());
    assertNotNull(taskForm);

    // Rejecting the task should put the process back to first task
    taskService.complete(task.getId(), CollectionUtil.singletonMap("vacationApproved", "false"));
    task = taskService.createTaskQuery().singleResult();
    assertEquals("Adjust vacation request", task.getName());
}
 
Example 19
Source File: AbstractFlowableTestCase.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public String deployTwoTasksTestProcess() {
    BpmnModel bpmnModel = createTwoTasksTestProcess();
    Deployment deployment = repositoryService.createDeployment()
            .addBpmnModel("twoTasksTestProcess.bpmn20.xml", bpmnModel).deploy();

    deploymentIdsForAutoCleanup.add(deployment.getId()); // For auto-cleanup

    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
            .deploymentId(deployment.getId()).singleResult();
    return processDefinition.getId();
}
 
Example 20
Source File: ProcessInstanceHelper.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public ProcessInstance createAndStartProcessInstanceByMessage(ProcessDefinition processDefinition, String messageName, String businessKey, 
        Map<String, Object> variables, Map<String, Object> transientVariables,
        String callbackId, String callbackType, String referenceId, String referenceType) {

    CommandContext commandContext = Context.getCommandContext();
    if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, commandContext)) {
        return CommandContextUtil.getProcessEngineConfiguration(commandContext).getFlowable5CompatibilityHandler().startProcessInstanceByMessage(
                messageName, variables, transientVariables, businessKey, processDefinition.getTenantId());
    }

    // Do not start process a process instance if the process definition is suspended
    if (ProcessDefinitionUtil.isProcessDefinitionSuspended(processDefinition.getId())) {
        throw new FlowableException("Cannot start process instance. Process definition " + processDefinition.getName() + " (id = " + processDefinition.getId() + ") is suspended");
    }

    // Get model from cache
    Process process = ProcessDefinitionUtil.getProcess(processDefinition.getId());
    if (process == null) {
        throw new FlowableException("Cannot start process instance. Process model " + processDefinition.getName() + " (id = " + processDefinition.getId() + ") could not be found");
    }

    FlowElement initialFlowElement = null;
    for (FlowElement flowElement : process.getFlowElements()) {
        if (flowElement instanceof StartEvent) {
            StartEvent startEvent = (StartEvent) flowElement;
            if (CollectionUtil.isNotEmpty(startEvent.getEventDefinitions()) && startEvent.getEventDefinitions().get(0) instanceof MessageEventDefinition) {

                MessageEventDefinition messageEventDefinition = (MessageEventDefinition) startEvent.getEventDefinitions().get(0);
                String actualMessageName = EventDefinitionExpressionUtil.determineMessageName(commandContext, messageEventDefinition, null);
                if (Objects.equals(actualMessageName, messageName)) {
                    initialFlowElement = flowElement;
                    break;
                }
            }
        }
    }
    if (initialFlowElement == null) {
        throw new FlowableException("No message start event found for process definition " + processDefinition.getId() + " and message name " + messageName);
    }

    return createAndStartProcessInstanceWithInitialFlowElement(processDefinition, businessKey, null, null, null, initialFlowElement, 
                    process, variables, transientVariables, callbackId, callbackType, referenceId, referenceType, null, true);
}