Java Code Examples for org.activiti.engine.impl.context.Context#getCommandContext()

The following examples show how to use org.activiti.engine.impl.context.Context#getCommandContext() . 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: CachingAndArtifactsManager.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures that the process definition is cached in the appropriate places, including the
 * deployment's collection of deployed artifacts and the deployment manager's cache, as well
 * as caching any ProcessDefinitionInfos.
 */
public void updateCachingAndArtifacts(ParsedDeployment parsedDeployment) {
  CommandContext commandContext = Context.getCommandContext();
  final ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
  DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache 
    = processEngineConfiguration.getDeploymentManager().getProcessDefinitionCache();
  DeploymentEntity deployment = parsedDeployment.getDeployment();

  for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
    BpmnModel bpmnModel = parsedDeployment.getBpmnModelForProcessDefinition(processDefinition);
    Process process = parsedDeployment.getProcessModelForProcessDefinition(processDefinition);
    ProcessDefinitionCacheEntry cacheEntry = new ProcessDefinitionCacheEntry(processDefinition, bpmnModel, process);
    processDefinitionCache.add(processDefinition.getId(), cacheEntry);
    addDefinitionInfoToCache(processDefinition, processEngineConfiguration, commandContext);
  
    // Add to deployment for further usage
    deployment.addDeployedArtifact(processDefinition);
  }
}
 
Example 2
Source File: IntermediateCatchMessageEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
public void execute(DelegateExecution execution) {
  CommandContext commandContext = Context.getCommandContext();
  ExecutionEntity executionEntity = (ExecutionEntity) execution;
  
  String messageName = null;
  if (StringUtils.isNotEmpty(messageEventDefinition.getMessageRef())) {
    messageName = messageEventDefinition.getMessageRef();
  } else {
    Expression messageExpression = commandContext.getProcessEngineConfiguration().getExpressionManager()
        .createExpression(messageEventDefinition.getMessageExpression());
    messageName = messageExpression.getValue(execution).toString();
  }
  
  commandContext.getEventSubscriptionEntityManager().insertMessageEvent(messageName, executionEntity);
  
  if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
      commandContext.getProcessEngineConfiguration().getEventDispatcher()
              .dispatchEvent(ActivitiEventBuilder.createMessageEvent(ActivitiEventType.ACTIVITY_MESSAGE_WAITING, executionEntity.getActivityId(), messageName,
                      null, executionEntity.getId(), executionEntity.getProcessInstanceId(), executionEntity.getProcessDefinitionId()));
    }
}
 
Example 3
Source File: TaskEntity.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void setOwner(String owner, boolean dispatchUpdateEvent) {
    if (owner == null && this.owner == null) {
        return;
    }
    // if (owner!=null && owner.equals(this.owner)) {
    // return;
    // }
    this.owner = owner;

    CommandContext commandContext = Context.getCommandContext();
    if (commandContext != null) {
        commandContext
                .getHistoryManager()
                .recordTaskOwnerChange(id, owner);

        if (owner != null && processInstanceId != null) {
            getProcessInstance().involveUser(owner, IdentityLinkType.PARTICIPANT);
        }

        if (dispatchUpdateEvent && commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
            if (dispatchUpdateEvent) {
                commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
                        ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, this));
            }
        }
    }
}
 
Example 4
Source File: ExecutionEntity.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
protected VariableInstanceEntity getSpecificVariable(String variableName) {

    CommandContext commandContext = Context.getCommandContext();
    if (commandContext == null) {
        throw new ActivitiException("lazy loading outside command context");
    }
    VariableInstanceEntity variableInstance = commandContext
            .getVariableInstanceEntityManager()
            .findVariableInstanceByExecutionAndName(id, variableName);

    return variableInstance;
}
 
Example 5
Source File: ExecutionEntityManager.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private void deleteProcessInstanceCascade(ExecutionEntity execution, String deleteReason, boolean deleteHistory) {
    CommandContext commandContext = Context.getCommandContext();

    ProcessInstanceQueryImpl processInstanceQuery = new ProcessInstanceQueryImpl(commandContext);
    List<ProcessInstance> subProcesses = processInstanceQuery.superProcessInstanceId(execution.getProcessInstanceId()).list();
    for (ProcessInstance subProcess : subProcesses) {
        deleteProcessInstanceCascade((ExecutionEntity) subProcess, deleteReason, deleteHistory);
    }

    commandContext
            .getTaskEntityManager()
            .deleteTasksByProcessInstanceId(execution.getId(), deleteReason, deleteHistory);

    // fill default reason if none provided
    if (deleteReason == null) {
        deleteReason = "ACTIVITY_DELETED";
    }

    if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
        commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
                ActivitiEventBuilder.createCancelledEvent(execution.getProcessInstanceId(),
                        execution.getProcessInstanceId(), execution.getProcessDefinitionId(), deleteReason));
    }

    // delete the execution BEFORE we delete the history, otherwise we will produce orphan HistoricVariableInstance instances
    execution.deleteCascade(deleteReason);

    if (deleteHistory) {
        commandContext
                .getHistoricProcessInstanceEntityManager()
                .deleteHistoricProcessInstanceById(execution.getId());
    }
}
 
Example 6
Source File: IntermediateThrowSignalEventActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {

    CommandContext commandContext = Context.getCommandContext();

    List<SignalEventSubscriptionEntity> subscriptionEntities = null;
    if (processInstanceScope) {
        subscriptionEntities = commandContext
                .getEventSubscriptionEntityManager()
                .findSignalEventSubscriptionsByProcessInstanceAndEventName(execution.getProcessInstanceId(), signalDefinition.getEventName());
    } else {
        subscriptionEntities = commandContext
                .getEventSubscriptionEntityManager()
                .findSignalEventSubscriptionsByEventName(signalDefinition.getEventName(), execution.getTenantId());
    }

    for (SignalEventSubscriptionEntity signalEventSubscriptionEntity : subscriptionEntities) {
        ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition(signalEventSubscriptionEntity.getProcessDefinitionId());
        if (Flowable5Util.isVersion5Tag(processDefinition.getEngineVersion())) {
            signalEventSubscriptionEntity.eventReceived(null, signalDefinition.isAsync());
            
        } else {
            EventSubscriptionService eventSubscriptionService = CommandContextUtil.getEventSubscriptionService();
            EventSubscriptionEntity flowable6EventSubscription = eventSubscriptionService.findById(signalEventSubscriptionEntity.getId());
            EventSubscriptionUtil.eventReceived(flowable6EventSubscription, null, signalDefinition.isAsync());
        }
    }

    ActivityExecution activityExecution = (ActivityExecution) execution;
    if (activityExecution.getActivity() != null) { // don't continue if process has already finished
        leave(activityExecution);
    }
}
 
Example 7
Source File: TaskEntityImpl.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
protected List<VariableInstanceEntity> getSpecificVariables(Collection<String> variableNames) {
  CommandContext commandContext = Context.getCommandContext();
  if (commandContext == null) {
    throw new ActivitiException("lazy loading outside command context");
  }
  return commandContext.getVariableInstanceEntityManager().findVariableInstancesByTaskAndNames(id, variableNames);
}
 
Example 8
Source File: BoundaryEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {

  ExecutionEntity executionEntity = (ExecutionEntity) execution;

  CommandContext commandContext = Context.getCommandContext();

  if (interrupting) {
    executeInterruptingBehavior(executionEntity, commandContext);
  } else {
    executeNonInterruptingBehavior(executionEntity, commandContext);
  }
}
 
Example 9
Source File: TaskEntity.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
protected List<VariableInstanceEntity> getSpecificVariables(Collection<String> variableNames) {
    CommandContext commandContext = Context.getCommandContext();
    if (commandContext == null) {
        throw new ActivitiException("lazy loading outside command context");
    }
    return commandContext
            .getVariableInstanceEntityManager()
            .findVariableInstancesByTaskAndNames(id, variableNames);
}
 
Example 10
Source File: TaskEntity.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void setFormKey(String formKey) {
    this.formKey = formKey;

    CommandContext commandContext = Context.getCommandContext();
    if (commandContext != null) {
        commandContext
                .getHistoryManager()
                .recordTaskFormKeyChange(id, formKey);
    }
}
 
Example 11
Source File: BusinessProcess.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
protected void validateValidUsage() {
  if (Context.getCommandContext() != null) {
    throw new ActivitiCdiException("Cannot use this method of the BusinessProcess bean within an activiti command.");
  }
}
 
Example 12
Source File: CommandContextInterceptor.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T execute(CommandConfig config, Command<T> command) {
    CommandContext context = Context.getCommandContext();

    boolean contextReused = false;
    // We need to check the exception, because the transaction can be in a rollback state,
    // and some other command is being fired to compensate (eg. decrementing job retries)
    if (!config.isContextReusePossible() || context == null || context.getException() != null) {
        context = commandContextFactory.createCommandContext(command);
    } else {
        LOGGER.debug("Valid context found. Reusing it for the current command '{}'", command.getClass().getCanonicalName());
        contextReused = true;
    }

    try {
        // Push on stack
        Context.setCommandContext(context);
        Context.setProcessEngineConfiguration(processEngineConfiguration);
        Flowable5CompatibilityContext.setFallbackFlowable5CompatibilityHandler(processEngineConfiguration.getFlowable5CompatibilityHandler());

        return next.execute(config, command);

    } catch (Exception e) {

        context.exception(e);

    } finally {
        try {
            if (!contextReused) {
                context.close();
            }
        } finally {
            // Pop from stack
            Context.removeCommandContext();
            Context.removeProcessEngineConfiguration();
            Context.removeBpmnOverrideContext();
            // don't remove the fallback because it's needed in Activiti 6 code like the Camel module
            // org.activiti.engine.impl.context.Context.removeFallbackcompatibilityHandler();
        }
    }

    return null;
}
 
Example 13
Source File: ProcessInstanceHelper.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public ProcessInstance createAndStartProcessInstanceByMessage(ProcessDefinition processDefinition, String messageName,
    Map<String, Object> variables, Map<String, Object> transientVariables) {

  CommandContext commandContext = Context.getCommandContext();
  if (processDefinition.getEngineVersion() != null) {
    if (Activiti5CompatibilityHandler.ACTIVITI_5_ENGINE_TAG.equals(processDefinition.getEngineVersion())) {
      Activiti5CompatibilityHandler activiti5CompatibilityHandler = commandContext.getProcessEngineConfiguration().getActiviti5CompatibilityHandler();

      if (activiti5CompatibilityHandler == null) {
        throw new ActivitiException("Found Activiti 5 process definition, but no compatibility handler on the classpath");
      }

      return activiti5CompatibilityHandler.startProcessInstanceByMessage(messageName, variables, null, processDefinition.getTenantId());

    } else {
      throw new ActivitiException("Invalid 'engine' for process definition " + processDefinition.getId() + " : " + processDefinition.getEngineVersion());
    }
  }

  // Do not start process a process instance if the process definition is suspended
  if (ProcessDefinitionUtil.isProcessDefinitionSuspended(processDefinition.getId())) {
    throw new ActivitiException("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 ActivitiException("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);
        if (messageEventDefinition.getMessageRef().equals(messageName)) {
          initialFlowElement = flowElement;
          break;
        }
      }
    }
  }
  if (initialFlowElement == null) {
    throw new ActivitiException("No message start event found for process definition " + processDefinition.getId() + " and message name " + messageName);
  }

  return createAndStartProcessInstanceWithInitialFlowElement(processDefinition, null, null, initialFlowElement, process, variables, transientVariables, true);
}
 
Example 14
Source File: ActivitiWorkflowEngine.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
* {@inheritDoc}
*/
public WorkflowPath startWorkflow(String workflowDefinitionId, Map<QName, Serializable> parameters)
{
    try
    {
        String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
        Authentication.setAuthenticatedUserId(currentUserName);
        
        String processDefId = createLocalId(workflowDefinitionId);
        
        // Set start task properties. This should be done before instance is started, since it's id will be used
        Map<String, Object> variables = propertyConverter.getStartVariables(processDefId, parameters);
        variables.put(WorkflowConstants.PROP_CANCELLED, Boolean.FALSE);
        
        // Add company home
        Object companyHome = nodeConverter.convertNode(getCompanyHome());
        variables.put(WorkflowConstants.PROP_COMPANY_HOME, companyHome);
         
        // Add the initiator
        NodeRef initiator = getPersonNodeRef(currentUserName);
        if (initiator != null)
        {
            variables.put(WorkflowConstants.PROP_INITIATOR, nodeConverter.convertNode(initiator));
            // Also add the initiator home reference, if one exists
            NodeRef initiatorHome = (NodeRef) nodeService.getProperty(initiator, ContentModel.PROP_HOMEFOLDER);
            if (initiatorHome != null)
            {
                variables.put(WorkflowConstants.PROP_INITIATOR_HOME, nodeConverter.convertNode(initiatorHome));
            }
        }
        
        // Start the process-instance
        CommandContext context = Context.getCommandContext();
        boolean isContextSuspended = false;
        if (context != null && context.getException() == null)
        {
            // MNT-11926: push null context to stack to avoid context reusage when new instance is not flushed
            Context.setCommandContext(null);
            isContextSuspended = true;
        }
        try
        {
            ProcessInstance instance = runtimeService.startProcessInstanceById(processDefId, variables);
            if (instance.isEnded())
            {
                return typeConverter.buildCompletedPath(instance.getId(), instance.getId());
            }
            else
            {
                WorkflowPath path = typeConverter.convert((Execution) instance);
                endStartTaskAutomatically(path, instance);
                return path;
            }
        }
        finally
        {
            if (isContextSuspended)
            {
                // pop null context out of stack
                Context.removeCommandContext();
            }
        }
    }
    catch (ActivitiException ae)
    {
        String msg = messageService.getMessage(ERR_START_WORKFLOW, workflowDefinitionId);
        if(logger.isDebugEnabled())
        {
        	logger.debug(msg, ae);
        }
        throw new WorkflowException(msg, ae);
    }
}
 
Example 15
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);
  }
}
 
Example 16
Source File: BpmnDeployer.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected boolean localizeFlowElements(Collection<FlowElement> flowElements, ObjectNode infoNode) {
    boolean localizationValuesChanged = false;

    if (flowElements == null)
        return localizationValuesChanged;

    CommandContext commandContext = Context.getCommandContext();
    DynamicBpmnService dynamicBpmnService = commandContext.getProcessEngineConfiguration().getDynamicBpmnService();

    for (FlowElement flowElement : flowElements) {
        if (flowElement instanceof UserTask || flowElement instanceof SubProcess) {
            List<ExtensionElement> localizationElements = flowElement.getExtensionElements().get("localization");
            if (localizationElements != null) {
                for (ExtensionElement localizationElement : localizationElements) {
                    if (BpmnXMLConstants.FLOWABLE_EXTENSIONS_PREFIX.equals(localizationElement.getNamespacePrefix()) ||
                            BpmnXMLConstants.ACTIVITI_EXTENSIONS_PREFIX.equals(localizationElement.getNamespacePrefix())) {

                        String locale = localizationElement.getAttributeValue(null, "locale");
                        String name = localizationElement.getAttributeValue(null, "name");
                        String documentation = null;
                        List<ExtensionElement> documentationElements = localizationElement.getChildElements().get("documentation");
                        if (documentationElements != null) {
                            for (ExtensionElement documentationElement : documentationElements) {
                                documentation = StringUtils.trimToNull(documentationElement.getElementText());
                                break;
                            }
                        }

                        String flowElementId = flowElement.getId();
                        if (!isEqualToCurrentLocalizationValue(locale, flowElementId, "name", name, infoNode)) {
                            dynamicBpmnService.changeLocalizationName(locale, flowElementId, name, infoNode);
                            localizationValuesChanged = true;
                        }

                        if (documentation != null && !isEqualToCurrentLocalizationValue(locale, flowElementId, "description", documentation, infoNode)) {
                            dynamicBpmnService.changeLocalizationDescription(locale, flowElementId, documentation, infoNode);
                            localizationValuesChanged = true;
                        }
                    }
                }
            }

            if (flowElement instanceof SubProcess) {
                SubProcess subprocess = (SubProcess) flowElement;
                boolean isFlowElementLocalizationChanged = localizeFlowElements(subprocess.getFlowElements(), infoNode);
                boolean isDataObjectLocalizationChanged = localizeDataObjectElements(subprocess.getDataObjects(), infoNode);
                if (isFlowElementLocalizationChanged || isDataObjectLocalizationChanged) {
                    localizationValuesChanged = true;
                }
            }
        }
    }

    return localizationValuesChanged;
}
 
Example 17
Source File: DefaultContextAssociationManager.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public Task getTask() {
  if (Context.getCommandContext() != null) {
    throw new ActivitiCdiException("Cannot work with tasks in an activiti command.");
  }
  return getScopedAssociation().getTask();
}
 
Example 18
Source File: HistoricTaskInstanceEntity.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public List<HistoricVariableInstanceEntity> getQueryVariables() {
    if (queryVariables == null && Context.getCommandContext() != null) {
        queryVariables = new HistoricVariableInitializingList();
    }
    return queryVariables;
}
 
Example 19
Source File: ExecutionEntity.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public List<VariableInstanceEntity> getQueryVariables() {
    if (queryVariables == null && Context.getCommandContext() != null) {
        queryVariables = new VariableInitializingList();
    }
    return queryVariables;
}
 
Example 20
Source File: HistoricProcessInstanceEntity.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public List<HistoricVariableInstanceEntity> getQueryVariables() {
    if (queryVariables == null && Context.getCommandContext() != null) {
        queryVariables = new HistoricVariableInitializingList();
    }
    return queryVariables;
}