Java Code Examples for org.activiti.engine.impl.persistence.entity.ExecutionEntity#getCurrentFlowElement()

The following examples show how to use org.activiti.engine.impl.persistence.entity.ExecutionEntity#getCurrentFlowElement() . 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: CallActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
public void completing(DelegateExecution execution, DelegateExecution subProcessInstance) throws Exception {
  // only data. no control flow available on this execution.

  ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager();

  // copy process variables
  ExecutionEntity executionEntity = (ExecutionEntity) execution;
  CallActivity callActivity = (CallActivity) executionEntity.getCurrentFlowElement();
  for (IOParameter ioParameter : callActivity.getOutParameters()) {
    Object value = null;
    if (StringUtils.isNotEmpty(ioParameter.getSourceExpression())) {
      Expression expression = expressionManager.createExpression(ioParameter.getSourceExpression().trim());
      value = expression.getValue(subProcessInstance);

    } else {
      value = subProcessInstance.getVariable(ioParameter.getSource());
    }
    execution.setVariable(ioParameter.getTarget(), value);
  }
}
 
Example 2
Source File: AbstractEventHandler.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected void dispatchExecutionCancelled(EventSubscriptionEntity eventSubscription, ExecutionEntity execution, CommandContext commandContext) {
  // subprocesses
  for (ExecutionEntity subExecution : execution.getExecutions()) {
    dispatchExecutionCancelled(eventSubscription, subExecution, commandContext);
  }

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

  // activity with message/signal boundary events
  FlowElement flowElement = execution.getCurrentFlowElement();
  if (flowElement instanceof BoundaryEvent) {
    BoundaryEvent boundaryEvent = (BoundaryEvent) flowElement;
    if (boundaryEvent.getAttachedToRef() != null) {
      dispatchActivityCancelled(eventSubscription, execution, boundaryEvent.getAttachedToRef(), commandContext);
    }
  }
}
 
Example 3
Source File: AbstractEventHandler.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected void dispatchActivityCancelledForChildExecution(EventSubscriptionEntity eventSubscription,
    ExecutionEntity parentExecutionEntity, ExecutionEntity boundaryEventExecution, CommandContext commandContext) {

  List<ExecutionEntity> executionEntities = commandContext.getExecutionEntityManager().findChildExecutionsByParentExecutionId(parentExecutionEntity.getId());
  for (ExecutionEntity childExecution : executionEntities) {

    if (!boundaryEventExecution.getId().equals(childExecution.getId())
        && childExecution.getCurrentFlowElement() != null
        && childExecution.getCurrentFlowElement() instanceof FlowNode) {

      FlowNode flowNode = (FlowNode) childExecution.getCurrentFlowElement();
      commandContext.getEventDispatcher().dispatchEvent(
          ActivitiEventBuilder.createActivityCancelledEvent(flowNode.getId(), flowNode.getName(), childExecution.getId(),
              childExecution.getProcessInstanceId(), childExecution.getProcessDefinitionId(),
              parseActivityType(flowNode), eventSubscription));

      if (childExecution.isScope()) {
        dispatchActivityCancelledForChildExecution(eventSubscription, childExecution, boundaryEventExecution, commandContext);
      }

    }

  }

}
 
Example 4
Source File: CompleteAdhocSubProcessCmd.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
public Void execute(CommandContext commandContext) {
  ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
  ExecutionEntity execution = executionEntityManager.findById(executionId);
  if (execution == null) {
    throw new ActivitiObjectNotFoundException("No execution found for id '" + executionId + "'", ExecutionEntity.class);
  }

  if (execution.getCurrentFlowElement() instanceof AdhocSubProcess == false) {
    throw new ActivitiException("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 ActivitiException("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);

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

  return null;
}
 
Example 5
Source File: DefaultHistoryManager.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
public void recordActivityStart(ExecutionEntity executionEntity) {
  if (isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
    if (executionEntity.getActivityId() != null && executionEntity.getCurrentFlowElement() != null) {
      
      HistoricActivityInstanceEntity historicActivityInstanceEntity = null;
      
      // Historic activity instance could have been created (but only in cache, never persisted)
      // for example when submitting form properties
      HistoricActivityInstanceEntity historicActivityInstanceEntityFromCache = 
          getHistoricActivityInstanceFromCache(executionEntity.getId(), executionEntity.getActivityId(), true);
      if (historicActivityInstanceEntityFromCache != null) {
        historicActivityInstanceEntity = historicActivityInstanceEntityFromCache;
      } else {
        historicActivityInstanceEntity = createHistoricActivityInstanceEntity(executionEntity);
      }
      
      // Fire event
      ActivitiEventDispatcher activitiEventDispatcher = getEventDispatcher();
      if (activitiEventDispatcher != null && activitiEventDispatcher.isEnabled()) {
        activitiEventDispatcher.dispatchEvent(
            ActivitiEventBuilder.createEntityEvent(ActivitiEventType.HISTORIC_ACTIVITY_INSTANCE_CREATED, historicActivityInstanceEntity));
      }
      
    }
  }
}
 
Example 6
Source File: AbstractOperation.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to match the activityId of an execution with a FlowElement of the process definition referenced by the execution.
 */
protected FlowElement getCurrentFlowElement(final ExecutionEntity execution) {
  if (execution.getCurrentFlowElement() != null) {
    return execution.getCurrentFlowElement();
  } else if (execution.getCurrentActivityId() != null) {
    String processDefinitionId = execution.getProcessDefinitionId();
    org.activiti.bpmn.model.Process process = ProcessDefinitionUtil.getProcess(processDefinitionId);
    String activityId = execution.getCurrentActivityId();
    FlowElement currentFlowElement = process.getFlowElement(activityId, true);
    return currentFlowElement;
  }
  return null;
}
 
Example 7
Source File: BoundaryEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected void deleteChildExecutions(ExecutionEntity parentExecution, ExecutionEntity notToDeleteExecution, CommandContext commandContext) {

    // TODO: would be good if this deleteChildExecutions could be removed and the one on the executionEntityManager is used
    // The problem however, is that the 'notToDeleteExecution' is passed here.
    // This could be solved by not reusing an execution, but creating a new

    // Delete all child executions
    ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
    Collection<ExecutionEntity> childExecutions = executionEntityManager.findChildExecutionsByParentExecutionId(parentExecution.getId());
    if (CollectionUtil.isNotEmpty(childExecutions)) {
      for (ExecutionEntity childExecution : childExecutions) {
        if (childExecution.getId().equals(notToDeleteExecution.getId()) == false) {
          deleteChildExecutions(childExecution, notToDeleteExecution, commandContext);
        }
      }
    }

    String deleteReason = DeleteReason.BOUNDARY_EVENT_INTERRUPTING + " (" + notToDeleteExecution.getCurrentActivityId() + ")";
    if (parentExecution.getCurrentFlowElement() instanceof CallActivity) {
      ExecutionEntity subProcessExecution = executionEntityManager.findSubProcessInstanceBySuperExecutionId(parentExecution.getId());
      if (subProcessExecution != null) {
        executionEntityManager.deleteProcessInstanceExecutionEntity(subProcessExecution.getId(),
            subProcessExecution.getCurrentActivityId(), deleteReason, true, true);
      }
    }

    executionEntityManager.deleteExecutionAndRelatedData(parentExecution, deleteReason, false);
  }
 
Example 8
Source File: ErrorPropagation.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public static boolean mapException(Exception e, ExecutionEntity execution, List<MapExceptionEntry> exceptionMap) {
  String errorCode = findMatchingExceptionMapping(e, exceptionMap);
  if (errorCode != null) {
    propagateError(errorCode, execution);
    return true;
  } else {
    ExecutionEntity callActivityExecution = null;
    ExecutionEntity parentExecution = execution.getParent();
    while (parentExecution != null && callActivityExecution == null) {
      if (parentExecution.getId().equals(parentExecution.getProcessInstanceId())) {
        if (parentExecution.getSuperExecution() != null) {
          callActivityExecution = parentExecution.getSuperExecution();
        } else {
          parentExecution = null;
        }
      } else {
        parentExecution = parentExecution.getParent();
      }
    }

    if (callActivityExecution != null) {
      CallActivity callActivity = (CallActivity) callActivityExecution.getCurrentFlowElement();
      if (CollectionUtil.isNotEmpty(callActivity.getMapExceptions())) {
        errorCode = findMatchingExceptionMapping(e, callActivity.getMapExceptions());
        if (errorCode != null) {
          propagateError(errorCode, callActivityExecution);
          return true;
        }
      }
    }

    return false;
  }
}
 
Example 9
Source File: ExecuteActivityForAdhocSubProcessCmd.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public Execution execute(CommandContext commandContext) {
  ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(executionId);
  if (execution == null) {
    throw new ActivitiObjectNotFoundException("No execution found for id '" + executionId + "'", ExecutionEntity.class);
  }

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

  FlowNode foundNode = null;
  AdhocSubProcess adhocSubProcess = (AdhocSubProcess) execution.getCurrentFlowElement();

  // if sequential ordering, only one child execution can be active
  if (adhocSubProcess.hasSequentialOrdering()) {
    if (execution.getExecutions().size() > 0) {
      throw new ActivitiException("Sequential ad-hoc sub process already has an active execution");
    }
  }

  for (FlowElement flowElement : adhocSubProcess.getFlowElements()) {
    if (activityId.equals(flowElement.getId()) && flowElement instanceof FlowNode) {
      FlowNode flowNode = (FlowNode) flowElement;
      if (flowNode.getIncomingFlows().size() == 0) {
        foundNode = flowNode;
      }
    }
  }

  if (foundNode == null) {
    throw new ActivitiException("The requested activity with id " + activityId + " can not be enabled");
  }

  ExecutionEntity activityExecution = Context.getCommandContext().getExecutionEntityManager().createChildExecution(execution);
  activityExecution.setCurrentFlowElement(foundNode);
  Context.getAgenda().planContinueProcessOperation(activityExecution);

  return activityExecution;
}
 
Example 10
Source File: TriggerTimerEventJobHandler.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void execute(JobEntity job, String configuration, ExecutionEntity execution, CommandContext commandContext) {

    Context.getAgenda().planTriggerExecutionOperation(execution);

    if (commandContext.getEventDispatcher().isEnabled()) {
      commandContext.getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TIMER_FIRED, job));
    }

    if (execution.getCurrentFlowElement() instanceof BoundaryEvent) {
      List<String> processedElements = new ArrayList<String>();
      dispatchExecutionTimeOut(job, execution, processedElements, commandContext);
    }
  }
 
Example 11
Source File: EndExecutionOperation.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected int getNumberOfActiveChildExecutionsForExecution(ExecutionEntityManager executionEntityManager, String executionId) {
  List<ExecutionEntity> executions = executionEntityManager.findChildExecutionsByParentExecutionId(executionId);
  int activeExecutions = 0;

  // Filter out the boundary events
  for (ExecutionEntity activeExecution : executions) {
    if (!(activeExecution.getCurrentFlowElement() instanceof BoundaryEvent)) {
      activeExecutions++;
    }
  }

  return activeExecutions;
}
 
Example 12
Source File: EndExecutionOperation.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected boolean isEndEventInMultiInstanceSubprocess(ExecutionEntity executionEntity) {
  if (executionEntity.getCurrentFlowElement() instanceof EndEvent) {
    SubProcess subProcess = ((EndEvent) execution.getCurrentFlowElement()).getSubProcess();
    return !executionEntity.getParent().isProcessInstanceType()
        && subProcess != null
        && subProcess.getLoopCharacteristics() != null
        && subProcess.getBehavior() instanceof MultiInstanceActivityBehavior;
  }
  return false;
}
 
Example 13
Source File: DefaultHistoryManager.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected HistoricActivityInstanceEntity createHistoricActivityInstanceEntity(ExecutionEntity execution) {
  IdGenerator idGenerator = getProcessEngineConfiguration().getIdGenerator();
  
  String processDefinitionId = execution.getProcessDefinitionId();
  String processInstanceId = execution.getProcessInstanceId();
    
  HistoricActivityInstanceEntity historicActivityInstance = getHistoricActivityInstanceEntityManager().create();
  historicActivityInstance.setId(idGenerator.getNextId());
  historicActivityInstance.setProcessDefinitionId(processDefinitionId);
  historicActivityInstance.setProcessInstanceId(processInstanceId);
  historicActivityInstance.setExecutionId(execution.getId());
  historicActivityInstance.setActivityId(execution.getActivityId());
  if (execution.getCurrentFlowElement() != null) {
    historicActivityInstance.setActivityName(execution.getCurrentFlowElement().getName());
    historicActivityInstance.setActivityType(parseActivityType(execution.getCurrentFlowElement()));
  }
  Date now = getClock().getCurrentTime();
  historicActivityInstance.setStartTime(now);
 
  // Inherit tenant id (if applicable)
  if (execution.getTenantId() != null) {
    historicActivityInstance.setTenantId(execution.getTenantId());
  }
  
  getHistoricActivityInstanceEntityManager().insert(historicActivityInstance);
  return historicActivityInstance;
}
 
Example 14
Source File: TakeOutgoingSequenceFlowsOperation.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected void cleanupExecutions(FlowElement currentFlowElement) {
  if (execution.getParentId() != null && execution.isScope()) {

    // If the execution is a scope (and not a process instance), the scope must first be
    // destroyed before we can continue and follow the sequence flow

    Context.getAgenda().planDestroyScopeOperation(execution);

  } else if (currentFlowElement instanceof Activity) {

    // If the current activity is an activity, we need to remove any currently active boundary events

    Activity activity = (Activity) currentFlowElement;
    if (CollectionUtil.isNotEmpty(activity.getBoundaryEvents())) {

      // Cancel events are not removed
      List<String> notToDeleteEvents = new ArrayList<String>();
      for (BoundaryEvent event : activity.getBoundaryEvents()) {
        if (CollectionUtil.isNotEmpty(event.getEventDefinitions()) &&
            event.getEventDefinitions().get(0) instanceof CancelEventDefinition) {
          notToDeleteEvents.add(event.getId());
        }
      }

      // Delete all child executions
      Collection<ExecutionEntity> childExecutions = commandContext.getExecutionEntityManager().findChildExecutionsByParentExecutionId(execution.getId());
      for (ExecutionEntity childExecution : childExecutions) {
        if (childExecution.getCurrentFlowElement() == null || !notToDeleteEvents.contains(childExecution.getCurrentFlowElement().getId())) {
          commandContext.getExecutionEntityManager().deleteExecutionAndRelatedData(childExecution, null, false);
        }
      }
    }
  }
}
 
Example 15
Source File: DefaultHistoryManager.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public HistoricActivityInstanceEntity findActivityInstance(ExecutionEntity execution, String activityId, boolean createOnNotFound, boolean endTimeMustBeNull) {
  
  // No use looking for the HistoricActivityInstance when no activityId is provided.
  if (activityId == null) {
    return null;
  }
  
  String executionId = execution.getId();

  // Check the cache
  HistoricActivityInstanceEntity historicActivityInstanceEntityFromCache = 
      getHistoricActivityInstanceFromCache(executionId, activityId, endTimeMustBeNull);
  if (historicActivityInstanceEntityFromCache != null) {
    return historicActivityInstanceEntityFromCache;
  }
  
  // If the execution was freshly created, there is no need to check the database, 
  // there can never be an entry for a historic activity instance with this execution id.
  if (!execution.isInserted() && !execution.isProcessInstanceType()) {

    // Check the database
    List<HistoricActivityInstanceEntity> historicActivityInstances = getHistoricActivityInstanceEntityManager()
        .findUnfinishedHistoricActivityInstancesByExecutionAndActivityId(executionId, activityId); 

    if (historicActivityInstances.size() > 0) {
      return historicActivityInstances.get(0);
    }
    
  }
  
  if (execution.getParentId() != null) {
    HistoricActivityInstanceEntity historicActivityInstanceFromParent 
      = findActivityInstance((ExecutionEntity) execution.getParent(), activityId, false, endTimeMustBeNull); // always false for create, we only check if it can be found
    if (historicActivityInstanceFromParent != null) {
      return historicActivityInstanceFromParent;
    }
  }
  
  if (createOnNotFound 
      && activityId != null
      && ( (execution.getCurrentFlowElement() != null && execution.getCurrentFlowElement() instanceof FlowNode) || execution.getCurrentFlowElement() == null)) {
    return createHistoricActivityInstanceEntity(execution);
  }

  return null;
}
 
Example 16
Source File: JobRetryCmd.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public Object execute(CommandContext commandContext) {
  JobEntity job = commandContext.getJobEntityManager().findById(jobId);
  if (job == null) {
    return null;
  }

  ProcessEngineConfiguration processEngineConfig = commandContext.getProcessEngineConfiguration();

  ExecutionEntity executionEntity = fetchExecutionEntity(commandContext, job.getExecutionId());
  FlowElement currentFlowElement = executionEntity != null ? executionEntity.getCurrentFlowElement() : null;

  String failedJobRetryTimeCycleValue = null;
  if (currentFlowElement instanceof ServiceTask) {
    failedJobRetryTimeCycleValue = ((ServiceTask) currentFlowElement).getFailedJobRetryTimeCycleValue();
  }

  AbstractJobEntity newJobEntity = null;
  if (currentFlowElement == null || failedJobRetryTimeCycleValue == null) {

    log.debug("activity or FailedJobRetryTimerCycleValue is null in job " + jobId + ". only decrementing retries.");
    
    if (job.getRetries() <= 1) {
      newJobEntity = commandContext.getJobManager().moveJobToDeadLetterJob(job);
    } else {
      newJobEntity = commandContext.getJobManager().moveJobToTimerJob(job);
    }
    
    newJobEntity.setRetries(job.getRetries() - 1);
    if (job.getDuedate() == null || JobEntity.JOB_TYPE_MESSAGE.equals(job.getJobType())) {
      // add wait time for failed async job
      newJobEntity.setDuedate(calculateDueDate(commandContext, processEngineConfig.getAsyncFailedJobWaitTime(), null));
    } else {
      // add default wait time for failed job
      newJobEntity.setDuedate(calculateDueDate(commandContext, processEngineConfig.getDefaultFailedJobWaitTime(), job.getDuedate()));
    }

  } else {
    try {
      DurationHelper durationHelper = new DurationHelper(failedJobRetryTimeCycleValue, processEngineConfig.getClock());
      int jobRetries = job.getRetries();
      if (job.getExceptionMessage() == null) {
        // change default retries to the ones configured
        jobRetries = durationHelper.getTimes();
      }
      
      if (jobRetries <= 1) {
        newJobEntity = commandContext.getJobManager().moveJobToDeadLetterJob(job);
      } else {
        newJobEntity = commandContext.getJobManager().moveJobToTimerJob(job);
      }
      
      newJobEntity.setDuedate(durationHelper.getDateAfter());

      if (job.getExceptionMessage() == null) { // is it the first exception
        log.debug("Applying JobRetryStrategy '" + failedJobRetryTimeCycleValue + "' the first time for job " + 
            job.getId() + " with " + durationHelper.getTimes() + " retries");

      } else {
        log.debug("Decrementing retries of JobRetryStrategy '" + failedJobRetryTimeCycleValue + "' for job " + job.getId());
      }
      
      newJobEntity.setRetries(jobRetries - 1);

    } catch (Exception e) {
      throw new ActivitiException("failedJobRetryTimeCylcle has wrong format:" + failedJobRetryTimeCycleValue, exception);
    }
  }
  
  if (exception != null) {
    newJobEntity.setExceptionMessage(exception.getMessage());
    newJobEntity.setExceptionStacktrace(getExceptionStacktrace());
  }

  // Dispatch both an update and a retry-decrement event
  ActivitiEventDispatcher eventDispatcher = commandContext.getEventDispatcher();
  if (eventDispatcher.isEnabled()) {
    eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, newJobEntity));
    eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_RETRIES_DECREMENTED, newJobEntity));
  }

  return null;
}
 
Example 17
Source File: DebugInfoExecutionCreated.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public DebugInfoExecutionCreated(ExecutionEntity executionEntity) {
  this.executionEntity = executionEntity;
  this.flowElementId = executionEntity.getCurrentFlowElement() != null ? executionEntity.getCurrentFlowElement().getId() : null;
}
 
Example 18
Source File: ErrorPropagation.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
protected static void executeCatch(Map<String, List<Event>> eventMap, DelegateExecution delegateExecution, String errorId) {
  Event matchingEvent = null;
  ExecutionEntity currentExecution = (ExecutionEntity) delegateExecution;
  ExecutionEntity parentExecution = null;

  if (eventMap.containsKey(currentExecution.getActivityId())) {
    matchingEvent = eventMap.get(currentExecution.getActivityId()).get(0);

    // Check for multi instance
    if (currentExecution.getParentId() != null && currentExecution.getParent().isMultiInstanceRoot()) {
      parentExecution = currentExecution.getParent();
    } else {
      parentExecution = currentExecution;
    }

  } else {
    parentExecution = currentExecution.getParent();

    // Traverse parents until one is found that is a scope and matches the activity the boundary event is defined on
    while (matchingEvent == null && parentExecution != null) {
      FlowElementsContainer currentContainer = null;
      if (parentExecution.getCurrentFlowElement() instanceof FlowElementsContainer) {
        currentContainer = (FlowElementsContainer) parentExecution.getCurrentFlowElement();
      } else if (parentExecution.getId().equals(parentExecution.getProcessInstanceId())) {
        currentContainer = ProcessDefinitionUtil.getProcess(parentExecution.getProcessDefinitionId());
      }

      for (String refId : eventMap.keySet()) {
        List<Event> events = eventMap.get(refId);
        if (CollectionUtil.isNotEmpty(events) && events.get(0) instanceof StartEvent) {
          if (currentContainer.getFlowElement(refId) != null) {
            matchingEvent = events.get(0);
          }
        }
      }

      if (matchingEvent == null) {
        if (eventMap.containsKey(parentExecution.getActivityId())) {
          matchingEvent = eventMap.get(parentExecution.getActivityId()).get(0);

          // Check for multi instance
          if (parentExecution.getParentId() != null && parentExecution.getParent().isMultiInstanceRoot()) {
            parentExecution = parentExecution.getParent();
          }

        } else if (StringUtils.isNotEmpty(parentExecution.getParentId())) {
          parentExecution = parentExecution.getParent();
        } else {
          parentExecution = null;
        }
      }
    }
  }

  if (matchingEvent != null && parentExecution != null) {
    executeEventHandler(matchingEvent, parentExecution, currentExecution, errorId);
  } else {
    throw new ActivitiException("No matching parent execution for error code " + errorId + " found");
  }
}
 
Example 19
Source File: BoundaryCompensateEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {
  ExecutionEntity executionEntity = (ExecutionEntity) execution;
  BoundaryEvent boundaryEvent = (BoundaryEvent) execution.getCurrentFlowElement();
  
  Process process = ProcessDefinitionUtil.getProcess(execution.getProcessDefinitionId());
  if (process == null) {
    throw new ActivitiException("Process model (id = " + execution.getId() + ") could not be found");
  }
  
  Activity compensationActivity = null;
  List<Association> associations = process.findAssociationsWithSourceRefRecursive(boundaryEvent.getId());
  for (Association association : associations) {
    FlowElement targetElement = process.getFlowElement(association.getTargetRef(), true);
    if (targetElement instanceof Activity) {
      Activity activity = (Activity) targetElement;
      if (activity.isForCompensation()) {
        compensationActivity = activity;
        break;
      }
    }
  }
  
  if (compensationActivity == null) {
    throw new ActivitiException("Compensation activity could not be found (or it is missing 'isForCompensation=\"true\"'");
  }
  
  // find SubProcess or Process instance execution
  ExecutionEntity scopeExecution = null;
  ExecutionEntity parentExecution = executionEntity.getParent();
  while (scopeExecution == null && parentExecution != null) {
    if (parentExecution.getCurrentFlowElement() instanceof SubProcess) {
      scopeExecution = parentExecution;
      
    } else if (parentExecution.isProcessInstanceType()) {
      scopeExecution = parentExecution;
    } else {
      parentExecution = parentExecution.getParent();
    }
  }
  
  if (scopeExecution == null) {
    throw new ActivitiException("Could not find a scope execution for compensation boundary event " + boundaryEvent.getId());
  }
  
  Context.getCommandContext().getEventSubscriptionEntityManager().insertCompensationEvent(
      scopeExecution, compensationActivity.getId());
}
 
Example 20
Source File: BoundaryCancelEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@Override
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
  BoundaryEvent boundaryEvent = (BoundaryEvent) execution.getCurrentFlowElement();
  
  CommandContext commandContext = Context.getCommandContext();
  ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
  
  ExecutionEntity subProcessExecution = null;
  // TODO: this can be optimized. A full search in the all executions shouldn't be needed
  List<ExecutionEntity> processInstanceExecutions = executionEntityManager.findChildExecutionsByProcessInstanceId(execution.getProcessInstanceId());
  for (ExecutionEntity childExecution : processInstanceExecutions) {
    if (childExecution.getCurrentFlowElement() != null 
        && childExecution.getCurrentFlowElement().getId().equals(boundaryEvent.getAttachedToRefId())) {
      subProcessExecution = childExecution;
      break;
    }
  }
  
  if (subProcessExecution == null) {
    throw new ActivitiException("No execution found for sub process of boundary cancel event " + boundaryEvent.getId());
  }
  
  EventSubscriptionEntityManager eventSubscriptionEntityManager = commandContext.getEventSubscriptionEntityManager();
  List<CompensateEventSubscriptionEntity> eventSubscriptions = eventSubscriptionEntityManager.findCompensateEventSubscriptionsByExecutionId(subProcessExecution.getParentId());

  if (eventSubscriptions.isEmpty()) {
    leave(execution);
  } else {
    
    String deleteReason = DeleteReason.BOUNDARY_EVENT_INTERRUPTING + "(" + boundaryEvent.getId() + ")";
    
    // cancel boundary is always sync
    ScopeUtil.throwCompensationEvent(eventSubscriptions, execution, false);
    executionEntityManager.deleteExecutionAndRelatedData(subProcessExecution, deleteReason, false);
    if (subProcessExecution.getCurrentFlowElement() instanceof Activity) {
      Activity activity = (Activity) subProcessExecution.getCurrentFlowElement();
      if (activity.getLoopCharacteristics() != null) {
        ExecutionEntity miExecution = subProcessExecution.getParent();
        List<ExecutionEntity> miChildExecutions = executionEntityManager.findChildExecutionsByParentExecutionId(miExecution.getId());
        for (ExecutionEntity miChildExecution : miChildExecutions) {
          if (subProcessExecution.getId().equals(miChildExecution.getId()) == false && activity.getId().equals(miChildExecution.getCurrentActivityId())) {
            executionEntityManager.deleteExecutionAndRelatedData(miChildExecution, deleteReason, false);
          }
        }
      }
    }
    leave(execution);
  }
}