org.activiti.engine.impl.context.Context Java Examples

The following examples show how to use org.activiti.engine.impl.context.Context. 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: BpmnDeployer.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates new diagrams for process definitions if the deployment is new, the process definition in
 * question supports it, and the engine is configured to make new diagrams.  
 * 
 * When this method creates a new diagram, it also persists it via the ResourceEntityManager 
 * and adds it to the resources of the deployment.
 */
protected void createAndPersistNewDiagramsIfNeeded(ParsedDeployment parsedDeployment) {
  
  final ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
  final DeploymentEntity deploymentEntity = parsedDeployment.getDeployment();
  
  final ResourceEntityManager resourceEntityManager = processEngineConfiguration.getResourceEntityManager();
  
  for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
    if (processDefinitionDiagramHelper.shouldCreateDiagram(processDefinition, deploymentEntity)) {
      ResourceEntity resource = processDefinitionDiagramHelper.createDiagramForProcessDefinition(
          processDefinition, parsedDeployment.getBpmnParseForProcessDefinition(processDefinition));
      if (resource != null) {
        resourceEntityManager.insert(resource, false);
        deploymentEntity.addResource(resource);  // now we'll find it if we look for the diagram name later.
      }
    }
  }
}
 
Example #2
Source File: CheckWithdrawTaskCmd.java    From lemon with Apache License 2.0 6 votes vote down vote up
public HistoricActivityInstanceEntity getHistoricActivityInstanceEntity(
        String historyTaskId) {
    logger.info("historyTaskId : {}", historyTaskId);

    JdbcTemplate jdbcTemplate = ApplicationContextHelper
            .getBean(JdbcTemplate.class);
    String historicActivityInstanceId = jdbcTemplate.queryForObject(
            "select id_ from ACT_HI_ACTINST where task_id_=?",
            String.class, historyTaskId);
    logger.info("historicActivityInstanceId : {}",
            historicActivityInstanceId);

    HistoricActivityInstanceQueryImpl historicActivityInstanceQueryImpl = new HistoricActivityInstanceQueryImpl();
    historicActivityInstanceQueryImpl
            .activityInstanceId(historicActivityInstanceId);

    HistoricActivityInstanceEntity historicActivityInstanceEntity = (HistoricActivityInstanceEntity) Context
            .getCommandContext()
            .getHistoricActivityInstanceEntityManager()
            .findHistoricActivityInstancesByQueryCriteria(
                    historicActivityInstanceQueryImpl, new Page(0, 1))
            .get(0);

    return historicActivityInstanceEntity;
}
 
Example #3
Source File: ExecutionEntityManager.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void deleteProcessInstancesByProcessDefinition(String processDefinitionId, String deleteReason, boolean cascade) {
    List<String> processInstanceIds = getDbSqlSession()
            .selectList("selectProcessInstanceIdsByProcessDefinitionId", processDefinitionId);

    for (String processInstanceId : processInstanceIds) {
        deleteProcessInstance(processInstanceId, deleteReason, cascade);
    }

    if (cascade) {
        Context
                .getCommandContext()
                .getHistoricProcessInstanceEntityManager()
                .deleteHistoricProcessInstanceByProcessDefinitionId(processDefinitionId);
    }
}
 
Example #4
Source File: ExecutionEntity.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
private void removeTasks(String reason) {
    if (reason == null) {
        reason = TaskEntity.DELETE_REASON_DELETED;
    }
    for (TaskEntity task : getTasks()) {
        if (replacedBy != null) {
            if (task.getExecution() == null || task.getExecution() != replacedBy) {
                // All tasks should have been moved when "replacedBy" has been set. Just in case tasks where added,
                // wo do an additional check here and move it
                task.setExecution(replacedBy);
                this.replacedBy.addTask(task);
            }
        } else {
            Context.getCommandContext()
                    .getTaskEntityManager()
                    .deleteTask(task, reason, false);
        }
    }
}
 
Example #5
Source File: RollbackCmd.java    From lemon with Apache License 2.0 6 votes vote down vote up
public HumanTaskDTO createHumanTask(DelegateTask delegateTask,
        HistoricTaskInstanceEntity historicTaskInstanceEntity)
        throws Exception {
    HumanTaskConnector humanTaskConnector = ApplicationContextHelper
            .getBean(HumanTaskConnector.class);
    HumanTaskDTO humanTaskDto = new HumanTaskBuilder().setDelegateTask(
            delegateTask).build();

    if ("发起流程".equals(historicTaskInstanceEntity.getDeleteReason())) {
        humanTaskDto.setCatalog(HumanTaskConstants.CATALOG_START);
    }

    HistoricProcessInstance historicProcessInstance = Context
            .getCommandContext()
            .getHistoricProcessInstanceEntityManager()
            .findHistoricProcessInstance(
                    delegateTask.getProcessInstanceId());
    humanTaskDto
            .setProcessStarter(historicProcessInstance.getStartUserId());
    humanTaskDto = humanTaskConnector.saveHumanTask(humanTaskDto);

    return humanTaskDto;
}
 
Example #6
Source File: FunctionEventListener.java    From lemon with Apache License 2.0 6 votes vote down vote up
public void onActivityEnd(ActivitiActivityEvent event) {
    logger.debug("activity end {}", event);

    String processInstanceId = event.getProcessInstanceId();
    ExecutionEntity executionEntity = Context.getCommandContext()
            .getExecutionEntityManager()
            .findExecutionById(processInstanceId);
    String businessKey = executionEntity.getBusinessKey();
    String processDefinitionId = event.getProcessDefinitionId();
    String activityId = event.getActivityId();
    String activityName = this.findActivityName(activityId,
            processDefinitionId);
    int eventCode = 1;
    String eventName = "end";
    String userId = Authentication.getAuthenticatedUserId();
    this.invokeExpression(eventCode, eventName, businessKey, userId,
            activityId, activityName);
}
 
Example #7
Source File: CommandContext.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public void performOperation(AtomicOperation executionOperation, InterpretableExecution execution) {
    nextOperations.add(executionOperation);
    if (nextOperations.size() == 1) {
        try {
            Context.setExecutionContext(execution);
            while (!nextOperations.isEmpty()) {
                AtomicOperation currentOperation = nextOperations.removeFirst();
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("AtomicOperation: {} on {}", currentOperation, this);
                }
                if (execution.getReplacedBy() == null) {
                    currentOperation.execute(execution);
                } else {
                    currentOperation.execute(execution.getReplacedBy());
                }
            }
        } finally {
            Context.removeExecutionContext();
        }
    }
}
 
Example #8
Source File: BpmnDeploymentHelper.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the persisted version of the already-deployed process definition.  Note that this is
 * different from {@link #getMostRecentVersionOfProcessDefinition} as it looks specifically for
 * a process definition that is already persisted and attached to a particular deployment,
 * rather than the latest version across all deployments.
 */
public ProcessDefinitionEntity getPersistedInstanceOfProcessDefinition(ProcessDefinitionEntity processDefinition) {
  String deploymentId = processDefinition.getDeploymentId();
  if (StringUtils.isEmpty(processDefinition.getDeploymentId())) {
    throw new IllegalStateException("Provided process definition must have a deployment id.");
  }

  ProcessDefinitionEntityManager processDefinitionManager 
    = Context.getCommandContext().getProcessEngineConfiguration().getProcessDefinitionEntityManager();
  ProcessDefinitionEntity persistedProcessDefinition = null;
  if (processDefinition.getTenantId() == null || ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
    persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey());
  } else {
    persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKeyAndTenantId(deploymentId, processDefinition.getKey(), processDefinition.getTenantId());
  }

  return persistedProcessDefinition;
}
 
Example #9
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 #10
Source File: TaskQueryImpl.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void localize(Task task) {
    task.setLocalizedName(null);
    task.setLocalizedDescription(null);

    if (locale != null) {
        String processDefinitionId = task.getProcessDefinitionId();
        if (processDefinitionId != null) {
            ObjectNode languageNode = Context.getLocalizationElementProperties(locale, task.getTaskDefinitionKey(), processDefinitionId, withLocalizationFallback);
            if (languageNode != null) {
                JsonNode languageNameNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_NAME);
                if (languageNameNode != null && !languageNameNode.isNull()) {
                    task.setLocalizedName(languageNameNode.asText());
                }

                JsonNode languageDescriptionNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_DESCRIPTION);
                if (languageDescriptionNode != null && !languageDescriptionNode.isNull()) {
                    task.setLocalizedDescription(languageDescriptionNode.asText());
                }
            }
        }
    }
}
 
Example #11
Source File: TerminateEndEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected void endAllHistoricActivities(String processInstanceId, String deleteReason) {

    if (!Context.getProcessEngineConfiguration().getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {
      return;
    }

    List<HistoricActivityInstanceEntity> historicActivityInstances = Context.getCommandContext().getHistoricActivityInstanceEntityManager()
      .findUnfinishedHistoricActivityInstancesByProcessInstanceId(processInstanceId);

    for (HistoricActivityInstanceEntity historicActivityInstance : historicActivityInstances) {
      historicActivityInstance.markEnded(deleteReason);

      // Fire event
      ProcessEngineConfigurationImpl config = Context.getProcessEngineConfiguration();
      if (config != null && config.getEventDispatcher().isEnabled()) {
        config.getEventDispatcher().dispatchEvent(
            ActivitiEventBuilder.createEntityEvent(ActivitiEventType.HISTORIC_ACTIVITY_INSTANCE_ENDED, historicActivityInstance));
      }
    }

  }
 
Example #12
Source File: BpmnDeployer.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void removeObsoleteTimers(ProcessDefinitionEntity processDefinition) {

        List<Job> jobsToDelete = null;

        if (processDefinition.getTenantId() != null && !ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
            jobsToDelete = Context.getCommandContext().getTimerJobEntityManager().findTimerJobsByTypeAndProcessDefinitionKeyAndTenantId(
                    TimerStartEventJobHandler.TYPE, processDefinition.getKey(), processDefinition.getTenantId());
        } else {
            jobsToDelete = Context.getCommandContext().getTimerJobEntityManager()
                    .findTimerJobsByTypeAndProcessDefinitionKeyNoTenantId(TimerStartEventJobHandler.TYPE, processDefinition.getKey());
        }

        if (jobsToDelete != null) {
            for (Job job : jobsToDelete) {
                new CancelJobsCmd(job.getId()).execute(Context.getCommandContext());
            }
        }
    }
 
Example #13
Source File: ExecutionEntity.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public PvmProcessInstance createSubProcessInstance(PvmProcessDefinition processDefinition) {
    ExecutionEntity subProcessInstance = newExecution();

    // manage bidirectional super-subprocess relation
    subProcessInstance.setSuperExecution(this);
    this.setSubProcessInstance(subProcessInstance);

    // Initialize the new execution
    subProcessInstance.setProcessDefinition((ProcessDefinitionImpl) processDefinition);
    subProcessInstance.setProcessInstance(subProcessInstance);

    Context.getCommandContext().getHistoryManager()
            .recordSubProcessInstanceStart(this, subProcessInstance);

    if (Context.getProcessEngineConfiguration() != null && Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
        Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
                ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_CREATED, subProcessInstance));
    }
    return subProcessInstance;
}
 
Example #14
Source File: JobEntity.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public void insert() {
    Context.getCommandContext()
            .getDbSqlSession()
            .insert(this);

    // add link to execution
    if (executionId != null) {
        ExecutionEntity execution = Context.getCommandContext()
                .getExecutionEntityManager()
                .findExecutionById(executionId);
        execution.addJob(this);

        // Inherit tenant if (if applicable)
        if (execution.getTenantId() != null) {
            setTenantId(execution.getTenantId());
        }
    }

    if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
        Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
                ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_CREATED, this));
        Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
                ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_INITIALIZED, this));
    }
}
 
Example #15
Source File: SkipTaskListener.java    From lemon with Apache License 2.0 6 votes vote down vote up
public void processPosition(DelegateTask delegateTask, String value) {
    String processInstanceId = delegateTask.getProcessInstanceId();
    HistoricProcessInstanceEntity historicProcessInstanceEntity = Context
            .getCommandContext().getHistoricProcessInstanceEntityManager()
            .findHistoricProcessInstance(processInstanceId);
    String initiator = historicProcessInstanceEntity.getStartUserId();
    OrgConnector orgConnector = (OrgConnector) ApplicationContextHelper
            .getBean(OrgConnector.class);

    // 获得发起人的职位
    int initiatorLevel = orgConnector.getJobLevelByUserId(initiator);

    // 获得审批人的职位
    int assigneeLevel = orgConnector.getJobLevelByUserId(delegateTask
            .getAssignee());

    // 比较
    if (initiatorLevel >= assigneeLevel) {
        logger.info("skip task : {}", delegateTask.getId());
        logger.info("initiatorLevel : {}, assigneeLevel : {}",
                initiatorLevel, assigneeLevel);
        new CompleteTaskWithCommentCmd(delegateTask.getId(),
                Collections.<String, Object> emptyMap(), "高级职位自动跳过")
                .execute(Context.getCommandContext());
    }
}
 
Example #16
Source File: ActivitiHistoryGraphBuilder.java    From lemon with Apache License 2.0 6 votes vote down vote up
public void fetchHistoricActivityInstances() {
    HistoricActivityInstanceQueryImpl historicActivityInstanceQueryImpl = new HistoricActivityInstanceQueryImpl();
    // historicActivityInstanceQueryImpl.processInstanceId(processInstanceId)
    // .orderByHistoricActivityInstanceStartTime().asc();
    // TODO: 如果用了uuid会造成这样排序出问题
    // 但是如果用startTime,可能出现因为处理速度太快,时间一样,导致次序颠倒的问题
    historicActivityInstanceQueryImpl.processInstanceId(processInstanceId)
            .orderByHistoricActivityInstanceId().asc();

    Page page = new Page(0, 100);
    historicActivityInstances = Context
            .getCommandContext()
            .getHistoricActivityInstanceEntityManager()
            .findHistoricActivityInstancesByQueryCriteria(
                    historicActivityInstanceQueryImpl, page);
}
 
Example #17
Source File: WebServiceActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected AbstractDataAssociation createDataInputAssociation(DataAssociation dataAssociationElement) {
  if (dataAssociationElement.getAssignments().isEmpty()) {
    return new MessageImplicitDataInputAssociation(dataAssociationElement.getSourceRef(), dataAssociationElement.getTargetRef());
  } else {
    SimpleDataInputAssociation dataAssociation = new SimpleDataInputAssociation(dataAssociationElement.getSourceRef(), dataAssociationElement.getTargetRef());
    ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager();
    
    for (org.activiti.bpmn.model.Assignment assignmentElement : dataAssociationElement.getAssignments()) {
      if (StringUtils.isNotEmpty(assignmentElement.getFrom()) && StringUtils.isNotEmpty(assignmentElement.getTo())) {
        Expression from = expressionManager.createExpression(assignmentElement.getFrom());
        Expression to = expressionManager.createExpression(assignmentElement.getTo());
        Assignment assignment = new Assignment(from, to);
        dataAssociation.addAssignment(assignment);
      }
    }
    return dataAssociation;
  }
}
 
Example #18
Source File: ExecutionEntityManager.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public void updateProcessInstanceLockTime(String processInstanceId) {
    CommandContext commandContext = Context.getCommandContext();
    Date expirationTime = commandContext.getProcessEngineConfiguration().getClock().getCurrentTime();
    int lockMillis = commandContext.getProcessEngineConfiguration().getAsyncExecutorAsyncJobLockTimeInMillis();
    GregorianCalendar lockCal = new GregorianCalendar();
    lockCal.setTime(expirationTime);
    lockCal.add(Calendar.MILLISECOND, lockMillis);

    HashMap<String, Object> params = new HashMap<>();
    params.put("id", processInstanceId);
    params.put("lockTime", lockCal.getTime());
    params.put("expirationTime", expirationTime);

    int result = getDbSqlSession().update("updateProcessInstanceLockTime", params);
    if (result == 0) {
        throw new ActivitiOptimisticLockingException("Could not lock process instance");
    }
}
 
Example #19
Source File: DefaultHistoryManager.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void recordVariableRemoved(VariableInstanceEntity variable) {
    if (isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
        HistoricVariableInstanceEntity historicProcessVariable = getDbSqlSession()
                .findInCache(HistoricVariableInstanceEntity.class, variable.getId());
        if (historicProcessVariable == null) {
            historicProcessVariable = Context.getCommandContext()
                    .getHistoricVariableInstanceEntityManager()
                    .findHistoricVariableInstanceByVariableInstanceId(variable.getId());
        }

        if (historicProcessVariable != null) {
            Context.getCommandContext()
                    .getHistoricVariableInstanceEntityManager()
                    .delete(historicProcessVariable);
        }
    }
}
 
Example #20
Source File: ProcessDefinitionDiagramHelper.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public boolean shouldCreateDiagram(ProcessDefinitionEntity processDefinition, DeploymentEntity deployment) {
  if (deployment.isNew() 
      && processDefinition.isGraphicalNotationDefined()
      && Context.getCommandContext().getProcessEngineConfiguration().isCreateDiagramOnDeploy()) {
    
    // If the 'getProcessDiagramResourceNameFromDeployment' call returns null, it means 
    // no diagram image for the process definition was provided in the deployment resources.
    return ResourceNameUtil.getProcessDiagramResourceNameFromDeployment(processDefinition, deployment.getResources()) == null;
  }
  
  return false;
}
 
Example #21
Source File: EventSubProcessMessageStartEventActivityBehavior.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) {
  CommandContext commandContext = Context.getCommandContext();
  ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
  ExecutionEntity executionEntity = (ExecutionEntity) execution;
  
  StartEvent startEvent = (StartEvent) execution.getCurrentFlowElement();
  if (startEvent.isInterrupting()) {  
    List<ExecutionEntity> childExecutions = executionEntityManager.findChildExecutionsByParentExecutionId(executionEntity.getParentId());
    for (ExecutionEntity childExecution : childExecutions) {
      if (childExecution.getId().equals(executionEntity.getId()) == false) {
        executionEntityManager.deleteExecutionAndRelatedData(childExecution, 
            DeleteReason.EVENT_SUBPROCESS_INTERRUPTING + "(" + startEvent.getId() + ")", false);
      }
    }
  }
  
  EventSubscriptionEntityManager eventSubscriptionEntityManager = Context.getCommandContext().getEventSubscriptionEntityManager();
  List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions();
  for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
    if (eventSubscription instanceof MessageEventSubscriptionEntity && eventSubscription.getEventName().equals(messageEventDefinition.getMessageRef())) {

      eventSubscriptionEntityManager.delete(eventSubscription);
    }
  }
  
  executionEntity.setCurrentFlowElement((SubProcess) executionEntity.getCurrentFlowElement().getParentContainer());
  executionEntity.setScope(true);
  
  ExecutionEntity outgoingFlowExecution = executionEntityManager.createChildExecution(executionEntity);
  outgoingFlowExecution.setCurrentFlowElement(startEvent);
  
  leave(outgoingFlowExecution);
}
 
Example #22
Source File: EventSubscriptionEntity.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void processEventSync(Object payload) {
    EventHandler eventHandler = Context.getProcessEngineConfiguration().getEventHandler(eventType);
    if (eventHandler == null) {
        throw new ActivitiException("Could not find eventhandler for event of type '" + eventType + "'.");
    }
    eventHandler.handleEvent(this, payload, Context.getCommandContext());
}
 
Example #23
Source File: TaskEntity.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public ExecutionEntity getProcessInstance() {
    if (processInstance == null && processInstanceId != null) {
        processInstance = Context
                .getCommandContext()
                .getExecutionEntityManager()
                .findExecutionById(processInstanceId);
    }
    return processInstance;
}
 
Example #24
Source File: TaskEntity.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void setCategory(String category) {
    this.category = category;

    CommandContext commandContext = Context.getCommandContext();
    if (commandContext != null) {
        commandContext
                .getHistoryManager()
                .recordTaskCategoryChange(id, category);
    }
}
 
Example #25
Source File: SignalEventHandler.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, CommandContext commandContext) {
    if (eventSubscription.getExecutionId() != null) {
        super.handleEvent(eventSubscription, payload, commandContext);
    } else if (eventSubscription.getProcessDefinitionId() != null) {
        // Start event
        String processDefinitionId = eventSubscription.getProcessDefinitionId();
        DeploymentManager deploymentCache = Context
                .getProcessEngineConfiguration()
                .getDeploymentManager();

        ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) deploymentCache.findDeployedProcessDefinitionById(processDefinitionId);
        if (processDefinition == null) {
            throw new ActivitiObjectNotFoundException("No process definition found for id '" + processDefinitionId + "'", ProcessDefinition.class);
        }

        ActivityImpl startActivity = processDefinition.findActivity(eventSubscription.getActivityId());
        if (startActivity == null) {
            throw new ActivitiException("Could no handle signal: no start activity found with id " + eventSubscription.getActivityId());
        }
        ExecutionEntity processInstance = processDefinition.createProcessInstance(null, startActivity);
        if (processInstance == null) {
            throw new ActivitiException("Could not handle signal: no process instance started");
        }

        if (payload != null) {
            if (payload instanceof Map) {
                Map<String, Object> variables = (Map<String, Object>) payload;
                processInstance.setVariables(variables);
            }
        }

        processInstance.start();
    } else {
        throw new ActivitiException("Invalid signal handling: no execution nor process definition set");
    }
}
 
Example #26
Source File: UpdateProcessCmd.java    From lemon with Apache License 2.0 5 votes vote down vote up
public Void execute(CommandContext commandContext) {
    ProcessDefinitionEntity processDefinitionEntity = commandContext
            .getProcessDefinitionEntityManager().findProcessDefinitionById(
                    processDefinitionId);
    String resourceName = processDefinitionEntity.getResourceName();
    String deploymentId = processDefinitionEntity.getDeploymentId();
    JdbcTemplate jdbcTemplate = new JdbcTemplate(Context
            .getProcessEngineConfiguration().getDataSource());
    jdbcTemplate
            .update("update ACT_GE_BYTEARRAY set BYTES_=? where NAME_=? and DEPLOYMENT_ID_=?",
                    bytes, resourceName, deploymentId);

    Context.getProcessEngineConfiguration().getProcessDefinitionCache()
            .remove(processDefinitionId);

    try {
        // update png
        GetBpmnModelCmd getBpmnModelCmd = new GetBpmnModelCmd(
                processDefinitionId);
        BpmnModel bpmnModel = getBpmnModelCmd.execute(commandContext);
        ProcessEngineConfiguration processEngineConfiguration = Context
                .getProcessEngineConfiguration();
        ProcessDefinitionDiagramCmd processDefinitionDiagramCmd = new ProcessDefinitionDiagramCmd(
                processDefinitionEntity.getId());
        InputStream is = processDefinitionDiagramCmd
                .execute(commandContext);
        byte[] pngBytes = IOUtils.toByteArray(is);
        String diagramResourceName = processDefinitionEntity
                .getDiagramResourceName();
        jdbcTemplate
                .update("update ACT_GE_BYTEARRAY set BYTES_=? where NAME_=? and DEPLOYMENT_ID_=?",
                        pngBytes, diagramResourceName, deploymentId);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }

    return null;
}
 
Example #27
Source File: ExecutionEntity.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void fireActivityCompletedEvent() {
    if (Context.getProcessEngineConfiguration() != null && Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
        Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
                ActivitiEventBuilder.createActivityEvent(FlowableEngineEventType.ACTIVITY_COMPLETED,
                        getActivity() != null ? getActivity().getId() : getActivityId(),
                        getActivity() != null ? (String) getActivity().getProperties().get("name") : null,
                        getId(),
                        getProcessInstanceId(),
                        getProcessDefinitionId(),
                        getActivity() != null ? (String) getActivity().getProperties().get("type") : null,
                        getActivity() != null ? getActivity().getActivityBehavior().getClass().getCanonicalName() : null));
    }
}
 
Example #28
Source File: ListenerNotificationHelper.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected CustomPropertiesResolver createCustomPropertiesResolver(ActivitiListener activitiListener) {
  CustomPropertiesResolver customPropertiesResolver = null;
  ListenerFactory listenerFactory = Context.getProcessEngineConfiguration().getListenerFactory();
  if (ImplementationType.IMPLEMENTATION_TYPE_CLASS.equalsIgnoreCase(activitiListener.getCustomPropertiesResolverImplementationType())) {
    customPropertiesResolver = listenerFactory.createClassDelegateCustomPropertiesResolver(activitiListener);
  } else if (ImplementationType.IMPLEMENTATION_TYPE_EXPRESSION.equalsIgnoreCase(activitiListener.getCustomPropertiesResolverImplementationType())) {
    customPropertiesResolver = listenerFactory.createExpressionCustomPropertiesResolver(activitiListener);
  } else if (ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equalsIgnoreCase(activitiListener.getCustomPropertiesResolverImplementationType())) {
    customPropertiesResolver = listenerFactory.createDelegateExpressionCustomPropertiesResolver(activitiListener);
  }
  return customPropertiesResolver;
}
 
Example #29
Source File: CheckWithdrawTaskCmd.java    From lemon with Apache License 2.0 5 votes vote down vote up
/**
 * 删除未完成任务.
 */
public void deleteActiveTasks(String processInstanceId) {
    // humantask
    HumanTaskConnector humanTaskConnector = ApplicationContextHelper
            .getBean(HumanTaskConnector.class);
    humanTaskConnector
            .removeHumanTaskByProcessInstanceId(processInstanceId);

    Context.getCommandContext().getTaskEntityManager()
            .deleteTasksByProcessInstanceId(processInstanceId, null, true);
}
 
Example #30
Source File: TaskEntity.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public List<IdentityLinkEntity> getIdentityLinks() {
    if (!isIdentityLinksInitialized) {
        taskIdentityLinkEntities = Context
                .getCommandContext()
                .getIdentityLinkEntityManager()
                .findIdentityLinksByTaskId(id);
        isIdentityLinksInitialized = true;
    }

    return taskIdentityLinkEntities;
}