Java Code Examples for org.activiti.bpmn.model.Process#getFlowElement()

The following examples show how to use org.activiti.bpmn.model.Process#getFlowElement() . 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: PoolsConverterTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
private void validateModel(BpmnModel model) {
  assertEquals(1, model.getPools().size());
  Pool pool = model.getPools().get(0);
  assertEquals("pool1", pool.getId());
  assertEquals("Pool", pool.getName());
  Process process = model.getProcess(pool.getId());
  assertNotNull(process);
  assertEquals(2, process.getLanes().size());
  Lane lane = process.getLanes().get(0);
  assertEquals("lane1", lane.getId());
  assertEquals("Lane 1", lane.getName());
  assertEquals(2, lane.getFlowReferences().size());
  lane = process.getLanes().get(1);
  assertEquals("lane2", lane.getId());
  assertEquals("Lane 2", lane.getName());
  assertEquals(2, lane.getFlowReferences().size());
  FlowElement flowElement = process.getFlowElement("flow1");
  assertNotNull(flowElement);
  assertTrue(flowElement instanceof SequenceFlow);
}
 
Example 2
Source File: JobDefinitionServiceImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the first asyncable task in the given model is indeed asynchronous. Only asserts when the configuration is set to true.
 *
 * @param bpmnModel The BPMN model
 */
private void assertFirstTaskIsAsync(BpmnModel bpmnModel)
{
    if (Boolean.TRUE.equals(configurationHelper.getProperty(ConfigurationValue.ACTIVITI_JOB_DEFINITION_ASSERT_ASYNC, Boolean.class)))
    {
        Process process = bpmnModel.getMainProcess();
        for (StartEvent startEvent : process.findFlowElementsOfType(StartEvent.class))
        {
            for (SequenceFlow sequenceFlow : startEvent.getOutgoingFlows())
            {
                String targetRef = sequenceFlow.getTargetRef();
                FlowElement targetFlowElement = process.getFlowElement(targetRef);
                if (targetFlowElement instanceof Activity)
                {
                    Assert.isTrue(((Activity) targetFlowElement).isAsynchronous(), "Element with id \"" + targetRef +
                        "\" must be set to activiti:async=true. All tasks which start the workflow must be asynchronous to prevent certain undesired " +
                        "transactional behavior, such as records of workflow not being saved on errors. Please refer to Activiti and herd documentations " +
                        "for details.");
                }
            }
        }
    }
}
 
Example 3
Source File: WorkflowBuilderTest.java    From maven-framework-project with MIT License 6 votes vote down vote up
@Test
public void testBuildDefault()  {
    BpmnModel model = workflowBldr.defaultDocumentApprove();
    Process process = model.getProcesses().get(0);
    SubProcess sub = (SubProcess)process.getFlowElement(Workflow.SUB_PROC_ID_DOC_APPROVAL);
    log.debug(sub.getName());
    Collection<FlowElement> flowElements  = sub.getFlowElements();
    List<UserTask> userTasks = Lists.newArrayList();
    for(FlowElement el : flowElements){
        log.debug(el.getClass().getName() + " -- " + el.getId());
        if (el.getClass().equals(org.activiti.bpmn.model.UserTask.class)){
            userTasks.add((UserTask)(el));
        }
    }

    int i = 1;
    for(UserTask uTask : userTasks){
        Approval approval = new Approval();
        approval.setPosition(i);
        i++;
        approval.setCandidateGroups(Lists.newArrayList(uTask.getCandidateGroups()));
        approval.setCandidateUsers(Lists.newArrayList(uTask.getCandidateUsers()));
    }
}
 
Example 4
Source File: ExecutionGraphUtil.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies if the element with the given source identifier can reach the element with the target identifier through following sequence flow.
 */
public static boolean isReachable(String processDefinitionId, String sourceElementId, String targetElementId) {

  // Fetch source and target elements
  Process process = ProcessDefinitionUtil.getProcess(processDefinitionId);

  FlowElement sourceFlowElement = process.getFlowElement(sourceElementId, true);
  FlowNode sourceElement = null;
  if (sourceFlowElement instanceof FlowNode) {
    sourceElement = (FlowNode) sourceFlowElement;
  } else if (sourceFlowElement instanceof SequenceFlow) {
    sourceElement = (FlowNode) ((SequenceFlow) sourceFlowElement).getTargetFlowElement();
  }

  FlowElement targetFlowElement = process.getFlowElement(targetElementId, true);
  FlowNode targetElement = null;
  if (targetFlowElement instanceof FlowNode) {
    targetElement = (FlowNode) targetFlowElement;
  } else if (targetFlowElement instanceof SequenceFlow) {
    targetElement = (FlowNode) ((SequenceFlow) targetFlowElement).getTargetFlowElement();
  }

  if (sourceElement == null) {
    throw new ActivitiException("Invalid sourceElementId '" + sourceElementId + "': no element found for this id n process definition '" + processDefinitionId + "'");
  }
  if (targetElement == null) {
    throw new ActivitiException("Invalid targetElementId '" + targetElementId + "': no element found for this id n process definition '" + processDefinitionId + "'");
  }

  Set<String> visitedElements = new HashSet<String>();
  return isReachable(process, sourceElement, targetElement, visitedElements);
}
 
Example 5
Source File: ProcessDefinitionPersistenceTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void testProcessDefinitionIntrospection() {
  String deploymentId = repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/db/processOne.bpmn20.xml").deploy().getId();

  String procDefId = repositoryService.createProcessDefinitionQuery().singleResult().getId();
  ProcessDefinition processDefinition = ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(procDefId);

  assertEquals(procDefId, processDefinition.getId());
  assertEquals("Process One", processDefinition.getName());
  
  Process process = repositoryService.getBpmnModel(processDefinition.getId()).getMainProcess();
  StartEvent startElement = (StartEvent) process.getFlowElement("start");
  assertNotNull(startElement);
  assertEquals("start", startElement.getId());
  assertEquals("S t a r t", startElement.getName());
  assertEquals("the start event", startElement.getDocumentation());
  List<SequenceFlow> outgoingFlows = startElement.getOutgoingFlows();
  assertEquals(1, outgoingFlows.size());
  assertEquals("${a == b}", outgoingFlows.get(0).getConditionExpression());

  EndEvent endElement = (EndEvent) process.getFlowElement("end");
  assertNotNull(endElement);
  assertEquals("end", endElement.getId());

  assertEquals("flow1", outgoingFlows.get(0).getId());
  assertEquals("Flow One", outgoingFlows.get(0).getName());
  assertEquals("The only transitions in the process", outgoingFlows.get(0).getDocumentation());
  assertSame(startElement, outgoingFlows.get(0).getSourceFlowElement());
  assertSame(endElement, outgoingFlows.get(0).getTargetFlowElement());

  repositoryService.deleteDeployment(deploymentId);
}
 
Example 6
Source File: EventGatewayValidator.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> errors) {
  List<EventGateway> eventGateways = process.findFlowElementsOfType(EventGateway.class);
  for (EventGateway eventGateway : eventGateways) {
    for (SequenceFlow sequenceFlow : eventGateway.getOutgoingFlows()) {
      FlowElement flowElement = process.getFlowElement(sequenceFlow.getTargetRef(), true);
      if (flowElement != null && flowElement instanceof IntermediateCatchEvent == false) {
        addError(errors, Problems.EVENT_GATEWAY_ONLY_CONNECTED_TO_INTERMEDIATE_EVENTS, process, eventGateway, "Event based gateway can only be connected to elements of type intermediateCatchEvent");
      }
    }
  }
}
 
Example 7
Source File: EventValidator.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected void handleCompensationEventDefinition(BpmnModel bpmnModel, Process process, Event event, EventDefinition eventDefinition, List<ValidationError> errors) {
  CompensateEventDefinition compensateEventDefinition = (CompensateEventDefinition) eventDefinition;

  // Check activityRef
  if ((StringUtils.isNotEmpty(compensateEventDefinition.getActivityRef()) && process.getFlowElement(compensateEventDefinition.getActivityRef(), true) == null)) {
    addError(errors, Problems.COMPENSATE_EVENT_INVALID_ACTIVITY_REF, process, event, "Invalid attribute value for 'activityRef': no activity with the given id");
  }
}
 
Example 8
Source File: WorkflowBuilder.java    From maven-framework-project with MIT License 5 votes vote down vote up
/**
 * @param group - If null is passed, the default document approval workflow will be used.
 * @return a sorted list of approvals contained in the workflow associated with the given group
 */
public List<Approval> getDocApprovalsByGroup(String group) {
    String base = Workflow.PROCESS_ID_DOC_APPROVAL;
    String procId = StringUtils.isBlank(group) ? base : base + "-" + group;
    log.debug("building approval list for procDef: " + procId);
    ProcessDefinition pd =
            this.repositoryService.createProcessDefinitionQuery().processDefinitionKey(procId).latestVersion().singleResult();
    BpmnModel model = this.repositoryService.getBpmnModel(pd.getId());
    Process process = model.getProcesses().get(0);

    SubProcess sub = (SubProcess) process.getFlowElement(Workflow.SUB_PROC_ID_DOC_APPROVAL);
    log.debug(sub.getName());
    Collection<FlowElement> flowElements = sub.getFlowElements();
    List<UserTask> userTasks = Lists.newArrayList();
    for (FlowElement el : flowElements) {
        if (el.getClass().equals(org.activiti.bpmn.model.UserTask.class)) {
            userTasks.add((UserTask) (el));
        }
    }

    List<Approval> approvals = Lists.newArrayList();
    int i = 1;
    for (UserTask userTask : userTasks) {
        approvals.add(fromUserTask(userTask, i));
        i++;
    }
    return approvals;
}
 
Example 9
Source File: CompensationEventHandler.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, CommandContext commandContext) {

    String configuration = eventSubscription.getConfiguration();
    if (configuration == null) {
      throw new ActivitiException("Compensating execution not set for compensate event subscription with id " + eventSubscription.getId());
    }

    ExecutionEntity compensatingExecution = commandContext.getExecutionEntityManager().findById(configuration);

    String processDefinitionId = compensatingExecution.getProcessDefinitionId();
    Process process = ProcessDefinitionUtil.getProcess(processDefinitionId);
    if (process == null) {
      throw new ActivitiException("Cannot start process instance. Process model (id = " + processDefinitionId + ") could not be found");
    }

    FlowElement flowElement = process.getFlowElement(eventSubscription.getActivityId(), true);

    if (flowElement instanceof SubProcess && ((SubProcess) flowElement).isForCompensation() == false) {

      // descend into scope:
      compensatingExecution.setScope(true);
      List<CompensateEventSubscriptionEntity> eventsForThisScope = commandContext.getEventSubscriptionEntityManager().findCompensateEventSubscriptionsByExecutionId(compensatingExecution.getId());
      ScopeUtil.throwCompensationEvent(eventsForThisScope, compensatingExecution, false);

    } else {

      try {

        if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
          commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
                ActivitiEventBuilder.createActivityEvent(ActivitiEventType.ACTIVITY_COMPENSATE, flowElement.getId(), flowElement.getName(),
                    compensatingExecution.getId(), compensatingExecution.getProcessInstanceId(), compensatingExecution.getProcessDefinitionId(), flowElement));
        }
        compensatingExecution.setCurrentFlowElement(flowElement);
        Context.getAgenda().planContinueProcessInCompensation(compensatingExecution);

      } catch (Exception e) {
        throw new ActivitiException("Error while handling compensation event " + eventSubscription, e);
      }

    }
  }
 
Example 10
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 11
Source File: SequenceflowValidator.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@Override
protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> errors) {
  List<SequenceFlow> sequenceFlows = process.findFlowElementsOfType(SequenceFlow.class);
  for (SequenceFlow sequenceFlow : sequenceFlows) {

    String sourceRef = sequenceFlow.getSourceRef();
    String targetRef = sequenceFlow.getTargetRef();

    if (StringUtils.isEmpty(sourceRef)) {
      addError(errors, Problems.SEQ_FLOW_INVALID_SRC, process, sequenceFlow, "Invalid source for sequenceflow");
    }
    if (StringUtils.isEmpty(targetRef)) {
      addError(errors, Problems.SEQ_FLOW_INVALID_TARGET, process, sequenceFlow, "Invalid target for sequenceflow");
    }

    // Implicit check: sequence flow cannot cross (sub) process
    // boundaries, hence we check the parent and not the process
    // (could be subprocess for example)
    FlowElement source = process.getFlowElement(sourceRef, true);
    FlowElement target = process.getFlowElement(targetRef, true);

    // Src and target validation
    if (source == null) {
      addError(errors, Problems.SEQ_FLOW_INVALID_SRC, process, sequenceFlow, "Invalid source for sequenceflow");
    }
    if (target == null) {
      addError(errors, Problems.SEQ_FLOW_INVALID_TARGET, process, sequenceFlow, "Invalid target for sequenceflow");
    }

    if (source != null && target != null) {
      FlowElementsContainer sourceContainer = process.getFlowElementsContainer(source.getId());
      FlowElementsContainer targetContainer = process.getFlowElementsContainer(target.getId());

      if (sourceContainer == null) {
        addError(errors, Problems.SEQ_FLOW_INVALID_SRC, process, sequenceFlow, "Invalid source for sequenceflow");
      }
      if (targetContainer == null) {
        addError(errors, Problems.SEQ_FLOW_INVALID_TARGET, process, sequenceFlow, "Invalid target for sequenceflow");
      }
      if (sourceContainer != null && targetContainer != null && sourceContainer.equals(targetContainer) == false) {
        addError(errors, Problems.SEQ_FLOW_INVALID_TARGET, process, sequenceFlow, "Invalid target for sequenceflow, the target isn't defined in the same scope as the source");
      }
    }
  }
}