org.flowable.engine.delegate.DelegateExecution Java Examples

The following examples show how to use org.flowable.engine.delegate.DelegateExecution. 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: BoundaryCompensateEventActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
    ExecutionEntity executionEntity = (ExecutionEntity) execution;
    BoundaryEvent boundaryEvent = (BoundaryEvent) execution.getCurrentFlowElement();

    if (boundaryEvent.isCancelActivity()) {
        EventSubscriptionService eventSubscriptionService = CommandContextUtil.getEventSubscriptionService();
        List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions();
        for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
            if (eventSubscription instanceof CompensateEventSubscriptionEntity && eventSubscription.getActivityId().equals(compensateEventDefinition.getActivityRef())) {
                eventSubscriptionService.deleteEventSubscription(eventSubscription);
                CountingEntityUtil.handleDeleteEventSubscriptionEntityCount(eventSubscription);
            }
        }
    }

    super.trigger(executionEntity, triggerName, triggerData);
}
 
Example #2
Source File: AbstractBpmnActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void executeCompensateBoundaryEvents(Collection<BoundaryEvent> boundaryEvents, DelegateExecution execution) {

        // The parent execution becomes a scope, and a child execution is created for each of the boundary events
        for (BoundaryEvent boundaryEvent : boundaryEvents) {

            if (CollectionUtil.isEmpty(boundaryEvent.getEventDefinitions())) {
                continue;
            }

            if (!(boundaryEvent.getEventDefinitions().get(0) instanceof CompensateEventDefinition)) {
                continue;
            }

            ExecutionEntity childExecutionEntity = CommandContextUtil.getExecutionEntityManager().createChildExecution((ExecutionEntity) execution);
            childExecutionEntity.setParentId(execution.getId());
            childExecutionEntity.setCurrentFlowElement(boundaryEvent);
            childExecutionEntity.setScope(false);

            ActivityBehavior boundaryEventBehavior = ((ActivityBehavior) boundaryEvent.getBehavior());
            boundaryEventBehavior.execute(childExecutionEntity);
        }

    }
 
Example #3
Source File: ExecutionTreeUtil.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public static ExecutionTree buildExecutionTree(DelegateExecution executionEntity) {

        // Find highest parent
        ExecutionEntity parentExecution = (ExecutionEntity) executionEntity;
        while (parentExecution.getParentId() != null || parentExecution.getSuperExecutionId() != null) {
            if (parentExecution.getParentId() != null) {
                parentExecution = parentExecution.getParent();
            } else {
                parentExecution = parentExecution.getSuperExecution();
            }
        }

        // Collect all child executions now we have the parent
        List<ExecutionEntity> allExecutions = new ArrayList<>();
        allExecutions.add(parentExecution);
        collectChildExecutions(parentExecution, allExecutions);
        return buildExecutionTree(allExecutions);
    }
 
Example #4
Source File: CallActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void completing(DelegateExecution execution, DelegateExecution subProcessInstance) throws Exception {
    // only data. no control flow available on this execution.

    // copy process variables
    for (AbstractDataAssociation dataOutputAssociation : dataOutputAssociations) {
        Object value = null;
        if (dataOutputAssociation.getSourceExpression() != null) {
            value = dataOutputAssociation.getSourceExpression().getValue(subProcessInstance);

        } else {
            value = subProcessInstance.getVariable(dataOutputAssociation.getSource());
        }

        execution.setVariable(dataOutputAssociation.getTarget(), value);
    }
}
 
Example #5
Source File: CreateOrUpdateServiceEndListener.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
@Override
public void notify(DelegateExecution execution) {
    boolean isServiceUpdated = VariableHandling.get(execution, Variables.IS_SERVICE_UPDATED);
    String serviceName = VariableHandling.get(execution, Variables.SERVICE_TO_PROCESS_NAME);
    if (serviceName == null) {
        throw new IllegalStateException("Unable to determine service update status.");
    }
    String exportedVariableName = Constants.VAR_IS_SERVICE_UPDATED_VAR_PREFIX + serviceName;

    RuntimeService runtimeService = Context.getProcessEngineConfiguration()
                                           .getRuntimeService();

    String superExecutionId = execution.getParentId();
    Execution superExecutionResult = runtimeService.createExecutionQuery()
                                                   .executionId(superExecutionId)
                                                   .singleResult();
    superExecutionId = superExecutionResult.getSuperExecutionId();

    runtimeService.setVariable(superExecutionId, exportedVariableName, isServiceUpdated);

}
 
Example #6
Source File: ThrowCustomExceptionBean.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public void throwException(DelegateExecution execution) {
    Object exceptionClassVar = execution.getVariable("exceptionClass");
    if (exceptionClassVar == null) {
        return;
    }

    String exceptionClassName = exceptionClassVar.toString();

    if (StringUtils.isNotEmpty(exceptionClassName)) {
        RuntimeException exception = null;
        try {
            Class<?> clazz = Class.forName(exceptionClassName);
            exception = (RuntimeException) clazz.newInstance();

        } catch (Exception e) {
            throw new FlowableException("Class not found", e);
        }
        throw exception;
    }
}
 
Example #7
Source File: MultiInstanceActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
protected void executeOriginalBehavior(DelegateExecution execution, ExecutionEntity multiInstanceRootExecution, int loopCounter) {
    if (usesCollection() && collectionElementVariable != null) {
        Collection collection = (Collection) resolveAndValidateCollection(execution);

        Object value = null;
        int index = 0;
        Iterator it = collection.iterator();
        while (index <= loopCounter) {
            value = it.next();
            index++;
        }
        setLoopVariable(execution, collectionElementVariable, value);
    }

    execution.setCurrentFlowElement(activity);
    CommandContextUtil.getAgenda().planContinueMultiInstanceOperation((ExecutionEntity) execution, multiInstanceRootExecution, loopCounter);
}
 
Example #8
Source File: IntermediateCatchEventActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected EventGateway getPrecedingEventBasedGateway(DelegateExecution execution) {
    FlowElement currentFlowElement = execution.getCurrentFlowElement();
    if (currentFlowElement instanceof IntermediateCatchEvent) {
        IntermediateCatchEvent intermediateCatchEvent = (IntermediateCatchEvent) currentFlowElement;
        List<SequenceFlow> incomingSequenceFlow = intermediateCatchEvent.getIncomingFlows();

        // If behind an event based gateway, there is only one incoming sequence flow that originates from said gateway
        if (incomingSequenceFlow != null && incomingSequenceFlow.size() == 1) {
            SequenceFlow sequenceFlow = incomingSequenceFlow.get(0);
            FlowElement sourceFlowElement = sequenceFlow.getSourceFlowElement();
            if (sourceFlowElement instanceof EventGateway) {
                return (EventGateway) sourceFlowElement;
            }
        }

    }
    return null;
}
 
Example #9
Source File: SyncFlowableStep.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
private void executeInternal(DelegateExecution execution) {
    initializeStepLogger(execution);
    ProcessContext context = createProcessContext(execution);
    StepPhase stepPhase = getInitialStepPhase(context);
    try {
        getStepHelper().preExecuteStep(context, stepPhase);
        stepPhase = executeStep(context);
        if (stepPhase == StepPhase.RETRY) {
            throw new SLException("A step of the process has failed. Retrying it may solve the issue.");
        }
        getStepHelper().failStepIfProcessIsAborted(context);
    } catch (Exception e) {
        stepPhase = StepPhase.RETRY;
        handleException(context, e);
    } finally {
        context.setVariable(Variables.STEP_PHASE, stepPhase);
        postExecuteStep(context, stepPhase);
    }
}
 
Example #10
Source File: SingletonDelegateExpressionBean.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {

    // just a quick check to avoid creating a specific test for it
    int nrOfFieldExtensions = DelegateHelper.getFields(execution).size();
    if (nrOfFieldExtensions != 3) {
        throw new RuntimeException("Error: 3 field extensions expected, but was " + nrOfFieldExtensions);
    }

    Expression fieldAExpression = DelegateHelper.getFieldExpression(execution, "fieldA");
    Number fieldA = (Number) fieldAExpression.getValue(execution);

    Expression fieldBExpression = DelegateHelper.getFieldExpression(execution, "fieldB");
    Number fieldB = (Number) fieldBExpression.getValue(execution);

    int result = fieldA.intValue() + fieldB.intValue();

    String resultVariableName = DelegateHelper.getFieldExpression(execution, "resultVariableName").getValue(execution).toString();
    execution.setVariable(resultVariableName, result);
}
 
Example #11
Source File: ErrorProcessListener.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
private void handleWithCorrelationId(FlowableEngineEvent event, Runnable handlerFunction) {
    DelegateExecution execution = getExecution(event);
    if (execution != null) {
        LoggingUtil.logWithCorrelationId(VariableHandling.get(execution, Variables.CORRELATION_ID), handlerFunction);
        return;
    }
    handlerFunction.run();
}
 
Example #12
Source File: DelegateExpressionCustomPropertiesResolver.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> getCustomPropertiesMap(DelegateExecution execution) {
    // Note: we can't cache the result of the expression, because the
    // execution can change: eg.
    // delegateExpression='${mySpringBeanFactory.randomSpringBean()}'
    Object delegate = expression.getValue(execution);

    if (delegate instanceof CustomPropertiesResolver) {
        return ((CustomPropertiesResolver) delegate).getCustomPropertiesMap(execution);
    } else {
        throw new FlowableIllegalArgumentException("Custom properties resolver delegate expression " + expression + " did not resolve to an implementation of " + CustomPropertiesResolver.class);
    }
}
 
Example #13
Source File: IntermediateCatchEventActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Specific leave method for intermediate events: does a normal leave(), except when behind an event based gateway. In that case, the other events are cancelled (we're only supporting the
 * exclusive event based gateway type currently). and the process instance is continued through the triggered event.
 */
public void leaveIntermediateCatchEvent(DelegateExecution execution) {
    EventGateway eventGateway = getPrecedingEventBasedGateway(execution);
    if (eventGateway != null) {
        deleteOtherEventsRelatedToEventBasedGateway(execution, eventGateway);
    }

    leave(execution); // Normal leave
}
 
Example #14
Source File: SkipExpressionUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public static boolean shouldSkipFlowElement(String skipExpressionString, String activityId, DelegateExecution execution, CommandContext commandContext) {
    ExpressionManager expressionManager = CommandContextUtil.getProcessEngineConfiguration(commandContext).getExpressionManager();
    Expression skipExpression = expressionManager.createExpression(resolveActiveSkipExpression(skipExpressionString, activityId, 
                    execution.getProcessDefinitionId(), commandContext));
    
    Object value = skipExpression.getValue(execution);

    if (value instanceof Boolean) {
        return ((Boolean) value).booleanValue();

    } else {
        throw new FlowableIllegalArgumentException("Skip expression does not resolve to a boolean: " + skipExpression.getExpressionText());
    }
}
 
Example #15
Source File: CamelBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected Exchange createExchange(DelegateExecution activityExecution, FlowableEndpoint endpoint) {
    Exchange ex = endpoint.createExchange();
    ex.setProperty(FlowableProducer.PROCESS_ID_PROPERTY, activityExecution.getProcessInstanceId());
    ex.setProperty(FlowableProducer.EXECUTION_ID_PROPERTY, activityExecution.getId());
    Map<String, Object> variables = activityExecution.getVariables();
    updateTargetVariables(endpoint);
    copyVariables(variables, ex, endpoint);
    return ex;
}
 
Example #16
Source File: VariablesTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {
    Map<String, Object> vars = execution.getVariables(Arrays.asList("testVar1", "testVar2", "testVar3"), false);

    String testVar1 = (String) vars.get("testVar1");
    String testVar2 = (String) vars.get("testVar2");
    String testVar3 = (String) vars.get("testVar3");

    execution.setVariable("testVar1", testVar1 + "-CHANGED", false);
    execution.setVariable("testVar2", testVar2 + "-CHANGED", false);
    execution.setVariable("testVar3", testVar3 + "-CHANGED", false);

    execution.setVariableLocal("localVar", "localValue", false);
}
 
Example #17
Source File: TransformationDataOutputAssociation.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void evaluate(DelegateExecution execution) {
    Object value = this.transformation.getValue(execution);

    VariableTypes variableTypes = CommandContextUtil.getVariableServiceConfiguration().getVariableTypes();
    try {
        variableTypes.findVariableType(value);
    } catch (final FlowableException e) {
        // Couldn't find a variable type that is able to serialize the output value
        // Perhaps the output value is a Java bean, we try to convert it as JSon
        try {
            final ObjectMapper mapper = new ObjectMapper();

            // By default, Jackson serializes only public fields, we force to use all fields of the Java Bean
            mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

            // By default, Jackson serializes java.util.Date as timestamp, we force ISO-8601
            mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));

            value = mapper.convertValue(value, JsonNode.class);
        } catch (final IllegalArgumentException e1) {
            throw new FlowableException("An error occurs converting output value as JSon", e1);
        }
    }

    execution.setVariable(this.getTarget(), value);
}
 
Example #18
Source File: FlowableEventBuilder.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected static void populateEventWithCurrentContext(FlowableEngineEventImpl event) {
    if (event instanceof FlowableEntityEvent) {
        Object persistedObject = ((FlowableEntityEvent) event).getEntity();
        if (persistedObject instanceof Job) {
            event.setExecutionId(((Job) persistedObject).getExecutionId());
            event.setProcessInstanceId(((Job) persistedObject).getProcessInstanceId());
            event.setProcessDefinitionId(((Job) persistedObject).getProcessDefinitionId());
            
        } else if (persistedObject instanceof DelegateExecution) {
            event.setExecutionId(((DelegateExecution) persistedObject).getId());
            event.setProcessInstanceId(((DelegateExecution) persistedObject).getProcessInstanceId());
            event.setProcessDefinitionId(((DelegateExecution) persistedObject).getProcessDefinitionId());
            
        } else if (persistedObject instanceof IdentityLinkEntity) {
            IdentityLinkEntity idLink = (IdentityLinkEntity) persistedObject;
            if (idLink.getProcessDefinitionId() != null) {
                event.setProcessDefinitionId(idLink.getProcessDefId());
                
            } else if (idLink.getProcessInstanceId() != null) {
                event.setProcessDefinitionId(idLink.getProcessDefId());
                event.setProcessInstanceId(idLink.getProcessInstanceId());
                
            } else if (idLink.getTaskId() != null) {
                event.setProcessDefinitionId(idLink.getProcessDefId());
            }
            
        } else if (persistedObject instanceof Task) {
            event.setProcessInstanceId(((Task) persistedObject).getProcessInstanceId());
            event.setExecutionId(((Task) persistedObject).getExecutionId());
            event.setProcessDefinitionId(((Task) persistedObject).getProcessDefinitionId());
            
        } else if (persistedObject instanceof ProcessDefinition) {
            event.setProcessDefinitionId(((ProcessDefinition) persistedObject).getId());
        }
    }
}
 
Example #19
Source File: BoundaryTimerEventTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void notify(DelegateExecution execution) {
    if ("end".equals(execution.getEventName())) {
        listenerExecutedEndEvent = true;
    } else if ("start".equals(execution.getEventName())) {
        listenerExecutedStartEvent = true;
    }
}
 
Example #20
Source File: ReverseStringsFieldInjected.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution execution) {
    String value1 = (String) text1.getValue(execution);
    execution.setVariable("var1", new StringBuffer(value1).reverse().toString());

    String value2 = (String) text2.getValue(execution);
    execution.setVariable("var2", new StringBuffer(value2).reverse().toString());
}
 
Example #21
Source File: ClassDelegate.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void completing(DelegateExecution execution, DelegateExecution subProcessInstance) throws Exception {
    if (activityBehaviorInstance == null) {
        activityBehaviorInstance = getActivityBehaviorInstance((ActivityExecution) execution);
    }

    if (activityBehaviorInstance instanceof SubProcessActivityBehavior) {
        ((SubProcessActivityBehavior) activityBehaviorInstance).completing(execution, subProcessInstance);
    } else {
        throw new ActivitiException("completing() can only be called on a " + SubProcessActivityBehavior.class.getName() + " instance");
    }
}
 
Example #22
Source File: DoNotDeleteServicesListener.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
protected void notifyInternal(DelegateExecution execution) {
    if (!isRootProcess(execution)) {
        return;
    }
    getStepLogger().warn(Messages.SKIP_SERVICES_DELETION);
}
 
Example #23
Source File: RecorderExecutionListener.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void notify(DelegateExecution execution) {
    ExecutionEntity executionCasted = ((ExecutionEntity) execution);

    org.flowable.bpmn.model.Process process = ProcessDefinitionUtil.getProcess(execution.getProcessDefinitionId());
    String activityId = execution.getCurrentActivityId();
    FlowElement currentFlowElement = process.getFlowElement(activityId, true);

    recordedEvents.add(new RecordedEvent(
            executionCasted.getActivityId(),
            (currentFlowElement != null) ? currentFlowElement.getName() : null,
            execution.getEventName(),
            (String) parameter.getValue(execution)));
}
 
Example #24
Source File: RetryFailingDelegate.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {

    times.add(System.currentTimeMillis());

    if (shallThrow) {
        throw new FlowableException(EXCEPTION_MESSAGE);
    }
}
 
Example #25
Source File: MultiInstanceTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void notify(DelegateExecution execution) {
    Integer loopCounter = (Integer) execution.getVariable("loopCounter");
    if (loopCounter != null) {
        countWithLoopCounter.incrementAndGet();
    } else {
        countWithoutLoopCounter.incrementAndGet();
    }
}
 
Example #26
Source File: BpmnLoggingSessionUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public static ObjectNode fillBasicTaskLoggingData(String message, TaskEntity task, DelegateExecution execution) {
    ObjectNode loggingNode = LoggingSessionUtil.fillLoggingData(message, task.getProcessInstanceId(), task.getExecutionId(), ScopeTypes.BPMN);
    loggingNode.put("scopeDefinitionId", execution.getProcessDefinitionId());
    loggingNode.put("taskId", task.getId());
    putIfNotNull("taskName", task.getName(), loggingNode);
    
    fillScopeDefinitionInfo(execution.getProcessDefinitionId(), loggingNode);
    fillFlowElementInfo(loggingNode, execution);
    
    return loggingNode;
}
 
Example #27
Source File: CaseTaskActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void triggerCaseTask(DelegateExecution execution, Map<String, Object> variables) {
    execution.setVariables(variables);
    ExecutionEntity executionEntity = (ExecutionEntity) execution;
    // Set the reference id and type to null since the execution could be reused
    executionEntity.setReferenceId(null);
    executionEntity.setReferenceType(null);
    leave(execution);
}
 
Example #28
Source File: SecureJavascriptExecutionListener.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void notify(DelegateExecution execution) {
    validateParameters();
    if (SecureJavascriptTaskParseHandler.LANGUAGE_JAVASCRIPT.equalsIgnoreCase(language.getValue(execution).toString())) {
        Object result = SecureJavascriptUtil.evaluateScript(execution, script.getExpressionText());

        if (resultVariable != null) {
            execution.setVariable(resultVariable.getExpressionText(), result);
        }
    } else {
        super.notify(execution);
    }
}
 
Example #29
Source File: TransientVariablesTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void notify(DelegateExecution execution) {
    String persistentVar1 = (String) execution.getVariable("persistentVar1");

    Object unusedTransientVar = execution.getVariable("unusedTransientVar");
    if (unusedTransientVar != null) {
        throw new RuntimeException("Unused transient var should have been deleted");
    }

    String secondTransientVar = (String) execution.getVariable("secondTransientVar");
    Number thirdTransientVar = (Number) execution.getTransientVariable("thirdTransientVar");

    String combinedVar = persistentVar1 + secondTransientVar + thirdTransientVar.intValue();
    execution.setVariable("combinedVar", combinedVar);
}
 
Example #30
Source File: RandomDelegate.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution delegateExecution) {
    Number number1 = (Number) delegateExecution.getVariable("input1");
    Number number2 = (Number) delegateExecution.getVariable("input2");
    int result = number1.intValue() + number2.intValue();
    delegateExecution.setVariable("result_" + random.nextInt(), "result is " + result);
}