Java Code Examples for org.flowable.engine.impl.util.CommandContextUtil#getExecutionEntityManager()

The following examples show how to use org.flowable.engine.impl.util.CommandContextUtil#getExecutionEntityManager() . 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: InjectParallelEmbeddedSubProcessCmd.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
protected void updateExecutions(CommandContext commandContext, ProcessDefinitionEntity processDefinitionEntity,
                                ExecutionEntity processInstance, List<ExecutionEntity> childExecutions) {

    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);

    TaskEntity taskEntity = CommandContextUtil.getTaskService().getTask(taskId);
    ExecutionEntity executionAtTask = executionEntityManager.findById(taskEntity.getExecutionId());
    
    BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(processDefinitionEntity.getId());
    FlowElement taskElement = bpmnModel.getFlowElement(executionAtTask.getCurrentActivityId());
    FlowElement subProcessElement = bpmnModel.getFlowElement(((SubProcess) taskElement.getParentContainer()).getId());
    ExecutionEntity subProcessExecution = executionEntityManager.createChildExecution(executionAtTask.getParent());
    subProcessExecution.setScope(true);
    subProcessExecution.setCurrentFlowElement(subProcessElement);
    CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(subProcessExecution);
    
    executionAtTask.setParent(subProcessExecution);
   
    ExecutionEntity execution = executionEntityManager.createChildExecution(subProcessExecution);
    FlowElement newSubProcess = bpmnModel.getMainProcess().getFlowElement(dynamicEmbeddedSubProcessBuilder.getDynamicSubProcessId(), true);
    execution.setCurrentFlowElement(newSubProcess);

    CommandContextUtil.getAgenda().planContinueProcessOperation(execution);
}
 
Example 2
Source File: MultiInstanceActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void cleanupMiRoot(DelegateExecution execution) {
    // Delete multi instance root and all child executions.
    // Create a fresh execution to continue
    
    ExecutionEntity multiInstanceRootExecution = (ExecutionEntity) getMultiInstanceRootExecution(execution);
    FlowElement flowElement = multiInstanceRootExecution.getCurrentFlowElement();
    ExecutionEntity parentExecution = multiInstanceRootExecution.getParent();
    
    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager();
    Collection<String> executionIdsNotToSendCancelledEventsFor = execution.isMultiInstanceRoot() ? null : Collections.singletonList(execution.getId());
    executionEntityManager.deleteChildExecutions(multiInstanceRootExecution, null, executionIdsNotToSendCancelledEventsFor, DELETE_REASON_END, true, flowElement);
    executionEntityManager.deleteRelatedDataForExecution(multiInstanceRootExecution, DELETE_REASON_END);
    executionEntityManager.delete(multiInstanceRootExecution);

    ExecutionEntity newExecution = executionEntityManager.createChildExecution(parentExecution);
    newExecution.setCurrentFlowElement(flowElement);
    super.leave(newExecution);
}
 
Example 3
Source File: CompleteAdhocSubProcessCmd.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Void execute(CommandContext commandContext) {
    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    ExecutionEntity execution = executionEntityManager.findById(executionId);
    if (execution == null) {
        throw new FlowableObjectNotFoundException("No execution found for id '" + executionId + "'", ExecutionEntity.class);
    }

    if (!(execution.getCurrentFlowElement() instanceof AdhocSubProcess)) {
        throw new FlowableException("The current flow element of the requested execution is not an ad-hoc sub process");
    }

    List<? extends ExecutionEntity> childExecutions = execution.getExecutions();
    if (childExecutions.size() > 0) {
        throw new FlowableException("Ad-hoc sub process has running child executions that need to be completed first");
    }

    ExecutionEntity outgoingFlowExecution = executionEntityManager.createChildExecution(execution.getParent());
    outgoingFlowExecution.setCurrentFlowElement(execution.getCurrentFlowElement());

    executionEntityManager.deleteExecutionAndRelatedData(execution, null, false);

    CommandContextUtil.getAgenda().planTakeOutgoingSequenceFlowsOperation(outgoingFlowExecution, true);

    return null;
}
 
Example 4
Source File: AddIdentityLinkForProcessInstanceCmd.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Void execute(CommandContext commandContext) {

    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    ExecutionEntity processInstance = executionEntityManager.findById(processInstanceId);

    if (processInstance == null) {
        throw new FlowableObjectNotFoundException("Cannot find process instance with id " + processInstanceId, ExecutionEntity.class);
    }

    if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, processInstance.getProcessDefinitionId())) {
        Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
        compatibilityHandler.addIdentityLinkForProcessInstance(processInstanceId, userId, groupId, type);
        return null;
    }

    IdentityLinkUtil.createProcessInstanceIdentityLink(processInstance, userId, groupId, type);
    CommandContextUtil.getHistoryManager(commandContext).createProcessInstanceIdentityLinkComment(processInstance, userId, groupId, type, true);

    return null;

}
 
Example 5
Source File: DestroyScopeOperation.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {

    // Find the actual scope that needs to be destroyed.
    // This could be the incoming execution, or the first parent execution where isScope = true

    // Find parent scope execution
    ExecutionEntity scopeExecution = execution.isScope() ? execution : findFirstParentScopeExecution(execution);

    if (scopeExecution == null) {
        throw new FlowableException("Programmatic error: no parent scope execution found for boundary event");
    }

    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);

    // Delete all child executions
    executionEntityManager.deleteChildExecutions(scopeExecution, execution.getDeleteReason(), true);
    executionEntityManager.deleteExecutionAndRelatedData(scopeExecution, execution.getDeleteReason(), false, true, null);

    if (scopeExecution.isActive()) {
        CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityEnd(scopeExecution, scopeExecution.getDeleteReason());
    }
    executionEntityManager.delete(scopeExecution);
}
 
Example 6
Source File: ParallelMultiInstanceBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void lockFirstParentScope(DelegateExecution execution) {

        ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager();

        boolean found = false;
        ExecutionEntity parentScopeExecution = null;
        ExecutionEntity currentExecution = (ExecutionEntity) execution;
        while (!found && currentExecution != null && currentExecution.getParentId() != null) {
            parentScopeExecution = executionEntityManager.findById(currentExecution.getParentId());
            if (parentScopeExecution != null && parentScopeExecution.isScope()) {
                found = true;
            }
            currentExecution = parentScopeExecution;
        }

        parentScopeExecution.forceUpdate();
    }
 
Example 7
Source File: ExecutionEntityManagerImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void dispatchExecutionCancelled(ExecutionEntity execution, FlowElement cancelActivity) {

        ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager();

        // subprocesses
        for (ExecutionEntity subExecution : executionEntityManager.findChildExecutionsByParentExecutionId(execution.getId())) {
            dispatchExecutionCancelled(subExecution, cancelActivity);
        }

        // call activities
        ExecutionEntity subProcessInstance = CommandContextUtil.getExecutionEntityManager().findSubProcessInstanceBySuperExecutionId(execution.getId());
        if (subProcessInstance != null) {
            dispatchExecutionCancelled(subProcessInstance, cancelActivity);
        }

        // activity with message/signal boundary events
        FlowElement currentFlowElement = execution.getCurrentFlowElement();
        if (currentFlowElement instanceof FlowNode) {

            if (execution.isMultiInstanceRoot()) {
                dispatchMultiInstanceActivityCancelled(execution, cancelActivity);
            }
            else {
                dispatchActivityCancelled(execution, cancelActivity);
            }
        }
    }
 
Example 8
Source File: InjectEmbeddedSubProcessInProcessInstanceCmd.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
protected void updateExecutions(CommandContext commandContext, ProcessDefinitionEntity processDefinitionEntity,
                                ExecutionEntity processInstance, List<ExecutionEntity> childExecutions) {

    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    
    BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(processDefinitionEntity.getId());
    SubProcess subProcess = (SubProcess) bpmnModel.getFlowElement(dynamicEmbeddedSubProcessBuilder.getDynamicSubProcessId());
    ExecutionEntity subProcessExecution = executionEntityManager.createChildExecution(processInstance);
    subProcessExecution.setScope(true);
    subProcessExecution.setCurrentFlowElement(subProcess);
    CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(subProcessExecution);
    
    ExecutionEntity childExecution = executionEntityManager.createChildExecution(subProcessExecution);
    
    StartEvent initialEvent = null;
    for (FlowElement subElement : subProcess.getFlowElements()) {
        if (subElement instanceof StartEvent) {
            StartEvent startEvent = (StartEvent) subElement;
            if (startEvent.getEventDefinitions().size() == 0) {
                initialEvent = startEvent;
                break;
            }
        }
    }
    
    if (initialEvent == null) {
        throw new FlowableException("Could not find a none start event in dynamic sub process");
    }
    
    childExecution.setCurrentFlowElement(initialEvent);
    
    Context.getAgenda().planContinueProcessOperation(childExecution);
}
 
Example 9
Source File: IntermediateCatchEventActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void deleteOtherEventsRelatedToEventBasedGateway(DelegateExecution execution, EventGateway eventGateway) {

        // To clean up the other events behind the event based gateway, we must gather the
        // activity ids of said events and check the _sibling_ executions of the incoming execution.
        // Note that it can happen that there are multiple such execution in those activity ids,
        // (for example a parallel gw going twice to the event based gateway, kinda silly, but valid)
        // so we only take _one_ result of such a query for deletion.

        // Gather all activity ids for the events after the event based gateway that need to be destroyed
        List<SequenceFlow> outgoingSequenceFlows = eventGateway.getOutgoingFlows();
        Set<String> eventActivityIds = new HashSet<>(outgoingSequenceFlows.size() - 1); // -1, the event being triggered does not need to be deleted
        for (SequenceFlow outgoingSequenceFlow : outgoingSequenceFlows) {
            if (outgoingSequenceFlow.getTargetFlowElement() != null
                    && !outgoingSequenceFlow.getTargetFlowElement().getId().equals(execution.getCurrentActivityId())) {
                eventActivityIds.add(outgoingSequenceFlow.getTargetFlowElement().getId());
            }
        }

        if (!eventActivityIds.isEmpty()) {
            CommandContext commandContext = Context.getCommandContext();
            ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    
            // Find the executions
            List<ExecutionEntity> executionEntities = executionEntityManager
                    .findExecutionsByParentExecutionAndActivityIds(execution.getParentId(), eventActivityIds);
    
            // Execute the cancel behaviour of the IntermediateCatchEvent
            for (ExecutionEntity executionEntity : executionEntities) {
                if (eventActivityIds.contains(executionEntity.getActivityId()) && execution.getCurrentFlowElement() instanceof IntermediateCatchEvent) {
                    IntermediateCatchEvent intermediateCatchEvent = (IntermediateCatchEvent) execution.getCurrentFlowElement();
                    if (intermediateCatchEvent.getBehavior() instanceof IntermediateCatchEventActivityBehavior) {
                        ((IntermediateCatchEventActivityBehavior) intermediateCatchEvent.getBehavior()).eventCancelledByEventGateway(executionEntity);
                        eventActivityIds.remove(executionEntity.getActivityId()); // We only need to delete ONE execution at the event.
                    }
                }
            }
        }
    }
 
Example 10
Source File: ContinueProcessOperation.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected ExecutionEntity createMultiInstanceRootExecution(ExecutionEntity execution) {
    ExecutionEntity parentExecution = execution.getParent();
    FlowElement flowElement = execution.getCurrentFlowElement();
    
    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager();
    executionEntityManager.deleteRelatedDataForExecution(execution, null);
    executionEntityManager.delete(execution);
    
    ExecutionEntity multiInstanceRootExecution = executionEntityManager.createChildExecution(parentExecution);
    multiInstanceRootExecution.setCurrentFlowElement(flowElement);
    multiInstanceRootExecution.setMultiInstanceRoot(true);
    multiInstanceRootExecution.setActive(false);
    return multiInstanceRootExecution;
}
 
Example 11
Source File: BoundaryEventActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void executeNonInterruptingBehavior(ExecutionEntity executionEntity, CommandContext commandContext) {
    // Non-interrupting: the current execution is given the first parent
    // scope (which isn't its direct parent)
    //
    // Why? Because this execution does NOT have anything to do with
    // the current parent execution (the one where the boundary event is on): when it is deleted or whatever,
    // this does not impact this new execution at all, it is completely independent in that regard.

    // Note: if the parent of the parent does not exists, this becomes a concurrent execution in the process instance!

    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);

    ExecutionEntity parentExecutionEntity = executionEntityManager.findById(executionEntity.getParentId());

    ExecutionEntity scopeExecution = null;
    ExecutionEntity currentlyExaminedExecution = executionEntityManager.findById(parentExecutionEntity.getParentId());
    while (currentlyExaminedExecution != null && scopeExecution == null) {
        if (currentlyExaminedExecution.isScope()) {
            scopeExecution = currentlyExaminedExecution;
        } else {
            currentlyExaminedExecution = executionEntityManager.findById(currentlyExaminedExecution.getParentId());
        }
    }

    if (scopeExecution == null) {
        throw new FlowableException("Programmatic error: no parent scope execution found for boundary event");
    }

    CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityEnd(executionEntity, null);

    ExecutionEntity nonInterruptingExecution = executionEntityManager.createChildExecution(scopeExecution);
    nonInterruptingExecution.setActive(false);
    nonInterruptingExecution.setCurrentFlowElement(executionEntity.getCurrentFlowElement());

    CommandContextUtil.getAgenda(commandContext).planTakeOutgoingSequenceFlowsOperation(nonInterruptingExecution, true);
}
 
Example 12
Source File: ProcessInstanceMigrationManagerImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void migrateProcessInstance(String processInstanceId, ProcessInstanceMigrationDocument document, CommandContext commandContext) {
    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    ExecutionEntity processExecution = executionEntityManager.findById(processInstanceId);
    if (processExecution == null) {
        throw new FlowableException("Cannot find the process to migrate, with id" + processInstanceId);
    }

    ProcessDefinition procDefToMigrateTo = resolveProcessDefinition(document, commandContext);
    doMigrateProcessInstance(processExecution, procDefToMigrateTo, document, commandContext);
}
 
Example 13
Source File: DefaultDynamicStateManager.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, List<ExecutionEntity>> resolveActiveEmbeddedSubProcesses(String processInstanceId, CommandContext commandContext) {
    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    List<ExecutionEntity> childExecutions = executionEntityManager.findChildExecutionsByProcessInstanceId(processInstanceId);

    Map<String, List<ExecutionEntity>> activeSubProcessesByActivityId = childExecutions.stream()
        .filter(ExecutionEntity::isActive)
        .filter(executionEntity -> executionEntity.getCurrentFlowElement() instanceof SubProcess)
        .collect(Collectors.groupingBy(ExecutionEntity::getActivityId));
    return activeSubProcessesByActivityId;
}
 
Example 14
Source File: CaseTaskTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public Void execute(CommandContext commandContext) {
    List<Execution> query = new ExecutionQueryImpl(commandContext.getCurrentEngineConfiguration().getCommandExecutor())
            .list();
    ExecutionEntityManager entityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    for (Execution execution : query) {
        ExecutionEntity executionEntity = (ExecutionEntity) execution;
        executionEntity.setReferenceId(null);
        executionEntity.setReferenceType(null);
        entityManager.update(executionEntity);
    }

    return null;
}
 
Example 15
Source File: ParallelGatewayActivityBehavior.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {

    // First off all, deactivate the execution
    execution.inactivate();

    // Join
    FlowElement flowElement = execution.getCurrentFlowElement();
    ParallelGateway parallelGateway = null;
    if (flowElement instanceof ParallelGateway) {
        parallelGateway = (ParallelGateway) flowElement;
    } else {
        throw new FlowableException("Programmatic error: parallel gateway behaviour can only be applied" + " to a ParallelGateway instance, but got an instance of " + flowElement);
    }

    lockFirstParentScope(execution);

    DelegateExecution multiInstanceExecution = null;
    if (hasMultiInstanceParent(parallelGateway)) {
        multiInstanceExecution = findMultiInstanceParentExecution(execution);
    }

    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager();
    Collection<ExecutionEntity> joinedExecutions = executionEntityManager.findInactiveExecutionsByActivityIdAndProcessInstanceId(execution.getCurrentActivityId(), execution.getProcessInstanceId());
    if (multiInstanceExecution != null) {
        joinedExecutions = cleanJoinedExecutions(joinedExecutions, multiInstanceExecution);
    }

    int nbrOfExecutionsToJoin = parallelGateway.getIncomingFlows().size();
    int nbrOfExecutionsCurrentlyJoined = joinedExecutions.size();

    // Fork

    // Is needed to set the endTime for all historic activity joins
    CommandContextUtil.getActivityInstanceEntityManager().recordActivityEnd((ExecutionEntity) execution, null);

    if (nbrOfExecutionsCurrentlyJoined == nbrOfExecutionsToJoin) {

        // Fork
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("parallel gateway '{}' ({}) activates: {} of {} joined", execution.getCurrentActivityId(), 
                    execution.getId(), nbrOfExecutionsCurrentlyJoined, nbrOfExecutionsToJoin);
        }

        if (parallelGateway.getIncomingFlows().size() > 1) {

            // All (now inactive) children are deleted.
            for (ExecutionEntity joinedExecution : joinedExecutions) {

                // The current execution will be reused and not deleted
                if (!joinedExecution.getId().equals(execution.getId())) {
                    executionEntityManager.deleteRelatedDataForExecution(joinedExecution, null);
                    executionEntityManager.delete(joinedExecution);
                }

            }
        }

        // TODO: potential optimization here: reuse more then 1 execution, only 1 currently
        CommandContextUtil.getAgenda().planTakeOutgoingSequenceFlowsOperation((ExecutionEntity) execution, false); // false -> ignoring conditions on parallel gw

    } else if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("parallel gateway '{}' ({}) does not activate: {} of {} joined", execution.getCurrentActivityId(), 
                execution.getId(), nbrOfExecutionsCurrentlyJoined, nbrOfExecutionsToJoin);
    }

}
 
Example 16
Source File: ProcessInstanceMigrationManagerImpl.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected void doMigrateProcessInstance(ProcessInstance processInstance, ProcessDefinition procDefToMigrateTo, ProcessInstanceMigrationDocument document, CommandContext commandContext) {
    LOGGER.debug("Start migration of process instance with Id:'{}' to process definition identified by {}", processInstance.getId(),
        printProcessDefinitionIdentifierMessage(document));

    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);

    if (document.getPreUpgradeScript() != null) {
        LOGGER.debug("Execute pre upgrade process instance script");
        executeScript(processInstance, procDefToMigrateTo, document.getPreUpgradeScript(), commandContext);
    }

    if (document.getPreUpgradeJavaDelegate() != null) {
        LOGGER.debug("Execute pre upgrade process instance script");
        executeJavaDelegate(processInstance, procDefToMigrateTo, document.getPreUpgradeJavaDelegate(), commandContext);
    }

    if (document.getPreUpgradeJavaDelegateExpression() != null) {
        LOGGER.debug("Execute pre upgrade process instance script");
        executeExpression(processInstance, procDefToMigrateTo, document.getPreUpgradeJavaDelegateExpression(), commandContext);
    }

    List<ChangeActivityStateBuilderImpl> changeActivityStateBuilders = prepareChangeStateBuilders((ExecutionEntity) processInstance, procDefToMigrateTo,
        document, commandContext);

    LOGGER.debug("Updating Process definition reference of process root execution with id:'{}' to '{}'", processInstance.getId(), procDefToMigrateTo.getId());
    ((ExecutionEntity) processInstance).setProcessDefinitionId(procDefToMigrateTo.getId());

    LOGGER.debug("Resolve activity executions to migrate");
    List<MoveExecutionEntityContainer> moveExecutionEntityContainerList = new ArrayList<>();
    for (ChangeActivityStateBuilderImpl builder : changeActivityStateBuilders) {
        moveExecutionEntityContainerList.addAll(
            resolveMoveExecutionEntityContainers(builder, Optional.of(procDefToMigrateTo.getId()), document.getProcessInstanceVariables(), commandContext));
    }

    ProcessInstanceChangeState processInstanceChangeState = new ProcessInstanceChangeState()
        .setProcessInstanceId(processInstance.getId())
        .setProcessDefinitionToMigrateTo(procDefToMigrateTo)
        .setMoveExecutionEntityContainers(moveExecutionEntityContainerList)
        .setProcessInstanceVariables(document.getProcessInstanceVariables())
        .setLocalVariables(document.getActivitiesLocalVariables());

    doMoveExecutionState(processInstanceChangeState, commandContext);

    LOGGER.debug("Updating Process definition of unchanged call activity");
    List<ExecutionEntity> callActivities = executionEntityManager.findChildExecutionsByProcessInstanceId(processInstance.getId()).stream()
        .filter(executionEntity -> executionEntity.getCurrentFlowElement() instanceof CallActivity)
        .collect(Collectors.toList());
    callActivities.forEach(executionEntity -> executionEntity.setProcessDefinitionId(procDefToMigrateTo.getId()));

    LOGGER.debug("Updating process definition reference in activity instances");
    CommandContextUtil.getActivityInstanceEntityManager().updateActivityInstancesProcessDefinitionId(procDefToMigrateTo.getId(), processInstance.getId());

    LOGGER.debug("Updating Process definition reference in history");
    changeProcessDefinitionReferenceOfHistory(processInstance, procDefToMigrateTo, commandContext);

    if (document.getPostUpgradeScript() != null) {
        LOGGER.debug("Execute post upgrade process instance script");
        executeScript(processInstance, procDefToMigrateTo, document.getPostUpgradeScript(), commandContext);
    }

    if (document.getPostUpgradeJavaDelegate() != null) {
        LOGGER.debug("Execute post upgrade process instance script");
        executeJavaDelegate(processInstance, procDefToMigrateTo, document.getPostUpgradeJavaDelegate(), commandContext);
    }

    if (document.getPostUpgradeJavaDelegateExpression() != null) {
        LOGGER.debug("Execute post upgrade process instance script");
        executeExpression(processInstance, procDefToMigrateTo, document.getPostUpgradeJavaDelegateExpression(), commandContext);
    }

    LOGGER.debug("Process migration ended for process instance with Id:'{}'", processInstance.getId());
}
 
Example 17
Source File: AbstractDynamicStateManager.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected ExecutionEntity createEmbeddedSubProcessHierarchy(SubProcess subProcess, ExecutionEntity defaultParentExecution, Map<String, SubProcess> subProcessesToCreate, Set<String> movingExecutionIds, ProcessInstanceChangeState processInstanceChangeState, CommandContext commandContext) {
    if (processInstanceChangeState.getProcessInstanceActiveEmbeddedExecutions().containsKey(subProcess.getId())) {
        return processInstanceChangeState.getProcessInstanceActiveEmbeddedExecutions().get(subProcess.getId()).get(0);
    }

    if (processInstanceChangeState.getCreatedEmbeddedSubProcesses().containsKey(subProcess.getId())) {
        return processInstanceChangeState.getCreatedEmbeddedSubProcesses().get(subProcess.getId());
    }

    //Create the parent, if needed
    ExecutionEntity parentSubProcess = defaultParentExecution;
    if (subProcess.getSubProcess() != null) {
        parentSubProcess = createEmbeddedSubProcessHierarchy(subProcess.getSubProcess(), defaultParentExecution, subProcessesToCreate, movingExecutionIds, processInstanceChangeState, commandContext);
        processInstanceChangeState.getCreatedEmbeddedSubProcesses().put(subProcess.getSubProcess().getId(), parentSubProcess);
    }
    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);

    ExecutionEntity subProcessExecution = executionEntityManager.createChildExecution(parentSubProcess);
    subProcessExecution.setCurrentFlowElement(subProcess);
    subProcessExecution.setScope(true);

    FlowableEventDispatcher eventDispatcher = CommandContextUtil.getEventDispatcher();
    if (eventDispatcher != null && eventDispatcher.isEnabled()) {
        eventDispatcher.dispatchEvent(
            FlowableEventBuilder.createActivityEvent(FlowableEngineEventType.ACTIVITY_STARTED, subProcess.getId(), subProcess.getName(), subProcessExecution.getId(),
                subProcessExecution.getProcessInstanceId(), subProcessExecution.getProcessDefinitionId(), subProcess));
    }

    subProcessExecution.setVariablesLocal(processDataObjects(subProcess.getDataObjects()));

    CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(subProcessExecution);

    List<BoundaryEvent> boundaryEvents = subProcess.getBoundaryEvents();
    if (CollectionUtil.isNotEmpty(boundaryEvents)) {
        executeBoundaryEvents(boundaryEvents, subProcessExecution);
    }

    if (subProcess instanceof EventSubProcess) {
        processCreatedEventSubProcess((EventSubProcess) subProcess, subProcessExecution, movingExecutionIds, commandContext);
    }

    ProcessInstanceHelper processInstanceHelper = CommandContextUtil.getProcessEngineConfiguration(commandContext).getProcessInstanceHelper();

    //Process containing child Event SubProcesses not contained in this creation hierarchy
    List<EventSubProcess> childEventSubProcesses = subProcess.findAllSubFlowElementInFlowMapOfType(EventSubProcess.class);
    childEventSubProcesses.stream()
        .filter(childEventSubProcess -> !subProcessesToCreate.containsKey(childEventSubProcess.getId()))
        .forEach(childEventSubProcess -> processInstanceHelper.processEventSubProcess(subProcessExecution, childEventSubProcess, commandContext));

    return subProcessExecution;
}
 
Example 18
Source File: EventSubProcessMessageStartEventActivityBehavior.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
    CommandContext commandContext = Context.getCommandContext();
    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    ExecutionEntity executionEntity = (ExecutionEntity) execution;

    StartEvent startEvent = (StartEvent) execution.getCurrentFlowElement();
    if (startEvent.isInterrupting()) {
        List<ExecutionEntity> childExecutions = executionEntityManager.collectChildren(executionEntity.getParent());
        for (int i = childExecutions.size() - 1; i >= 0; i--) {
            ExecutionEntity childExecutionEntity = childExecutions.get(i);
            if (!childExecutionEntity.isEnded() && !childExecutionEntity.getId().equals(executionEntity.getId())) {
                executionEntityManager.deleteExecutionAndRelatedData(childExecutionEntity,
                        DeleteReason.EVENT_SUBPROCESS_INTERRUPTING + "(" + startEvent.getId() + ")", false);
            }
        }

        EventSubscriptionService eventSubscriptionService = CommandContextUtil.getEventSubscriptionService(commandContext);
        List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions();

        String messageName = EventDefinitionExpressionUtil.determineMessageName(commandContext, messageEventDefinition, execution);
        for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
            if (eventSubscription instanceof MessageEventSubscriptionEntity && eventSubscription.getEventName().equals(messageName)) {

                eventSubscriptionService.deleteEventSubscription(eventSubscription);
                CountingEntityUtil.handleDeleteEventSubscriptionEntityCount(eventSubscription);
            }
        }
    }

    ExecutionEntity newSubProcessExecution = executionEntityManager.createChildExecution(executionEntity.getParent());
    newSubProcessExecution.setCurrentFlowElement((SubProcess) executionEntity.getCurrentFlowElement().getParentContainer());
    newSubProcessExecution.setEventScope(false);
    newSubProcessExecution.setScope(true);

    CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(newSubProcessExecution);

    ExecutionEntity outgoingFlowExecution = executionEntityManager.createChildExecution(newSubProcessExecution);
    outgoingFlowExecution.setCurrentFlowElement(startEvent);

    CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(outgoingFlowExecution);

    leave(outgoingFlowExecution);
}
 
Example 19
Source File: EventSubProcessSignalStartEventActivityBehavior.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
    CommandContext commandContext = Context.getCommandContext();
    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    ExecutionEntity executionEntity = (ExecutionEntity) execution;

    String eventName = EventDefinitionExpressionUtil.determineSignalName(commandContext, signalEventDefinition,
        ProcessDefinitionUtil.getBpmnModel(execution.getProcessDefinitionId()), execution);

    StartEvent startEvent = (StartEvent) execution.getCurrentFlowElement();
    if (startEvent.isInterrupting()) {
        List<ExecutionEntity> childExecutions = executionEntityManager.collectChildren(executionEntity.getParent());
        for (int i = childExecutions.size() - 1; i >= 0; i--) {
            ExecutionEntity childExecutionEntity = childExecutions.get(i);
            if (!childExecutionEntity.isEnded() && !childExecutionEntity.getId().equals(executionEntity.getId())) {
                executionEntityManager.deleteExecutionAndRelatedData(childExecutionEntity,
                        DeleteReason.EVENT_SUBPROCESS_INTERRUPTING + "(" + startEvent.getId() + ")", false);
            }
        }

        EventSubscriptionService eventSubscriptionService = CommandContextUtil.getEventSubscriptionService(commandContext);
        List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions();

        for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
            if (eventSubscription instanceof SignalEventSubscriptionEntity && eventSubscription.getEventName().equals(eventName)) {

                eventSubscriptionService.deleteEventSubscription(eventSubscription);
                CountingEntityUtil.handleDeleteEventSubscriptionEntityCount(eventSubscription);
            }
        }
    }
    
    ExecutionEntity newSubProcessExecution = executionEntityManager.createChildExecution(executionEntity.getParent());
    newSubProcessExecution.setCurrentFlowElement((SubProcess) executionEntity.getCurrentFlowElement().getParentContainer());
    newSubProcessExecution.setEventScope(false);
    newSubProcessExecution.setScope(true);

    CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(newSubProcessExecution);

    ExecutionEntity outgoingFlowExecution = executionEntityManager.createChildExecution(newSubProcessExecution);
    outgoingFlowExecution.setCurrentFlowElement(startEvent);

    CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(outgoingFlowExecution);

    leave(outgoingFlowExecution);
}
 
Example 20
Source File: InclusiveGatewayActivityBehavior.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected void executeInclusiveGatewayLogic(ExecutionEntity execution, boolean inactiveCheck) {
    CommandContext commandContext = Context.getCommandContext();
    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);

    lockFirstParentScope(execution);

    Collection<ExecutionEntity> allExecutions = executionEntityManager.findChildExecutionsByProcessInstanceId(execution.getProcessInstanceId());
    Iterator<ExecutionEntity> executionIterator = allExecutions.iterator();
    boolean oneExecutionCanReachGatewayInstance = false;
    while (!oneExecutionCanReachGatewayInstance && executionIterator.hasNext()) {
        ExecutionEntity executionEntity = executionIterator.next();
        if (!executionEntity.getActivityId().equals(execution.getCurrentActivityId())) {
            if (ExecutionGraphUtil.isReachable(execution.getProcessDefinitionId(), executionEntity.getActivityId(), execution.getCurrentActivityId())) {
                //Now check if they are in the same "execution path"
                if (executionEntity.getParentId().equals(execution.getParentId())) {
                    oneExecutionCanReachGatewayInstance = true;
                    break;
                }
            }
        } else if (executionEntity.getId().equals(execution.getId()) && executionEntity.isActive()) {
            // Special case: the execution has reached the inc gw, but the operation hasn't been executed yet for that execution
            oneExecutionCanReachGatewayInstance = true;
            break;
        }
    }

    // Is needed to set the endTime for all historic activity joins
    if (!inactiveCheck || !oneExecutionCanReachGatewayInstance) {
        CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityEnd(execution, null);
    }

    // If no execution can reach the gateway, the gateway activates and executes fork behavior
    if (!oneExecutionCanReachGatewayInstance) {

        LOGGER.debug("Inclusive gateway cannot be reached by any execution and is activated");

        // Kill all executions here (except the incoming)
        Collection<ExecutionEntity> executionsInGateway = executionEntityManager
            .findInactiveExecutionsByActivityIdAndProcessInstanceId(execution.getCurrentActivityId(), execution.getProcessInstanceId());
        for (ExecutionEntity executionEntityInGateway : executionsInGateway) {
            if (!executionEntityInGateway.getId().equals(execution.getId()) && executionEntityInGateway.getParentId().equals(execution.getParentId())) {

                if (!Objects.equals(executionEntityInGateway.getActivityId(), execution.getActivityId())) {
                    CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityEnd(executionEntityInGateway, null);
                }

                executionEntityManager.deleteExecutionAndRelatedData(executionEntityInGateway, null, false);
            }
        }

        // Leave
        CommandContextUtil.getAgenda(commandContext).planTakeOutgoingSequenceFlowsOperation(execution, true);
    }
}