Java Code Examples for org.flowable.engine.impl.util.CommandContextUtil#getCommandContext()

The following examples show how to use org.flowable.engine.impl.util.CommandContextUtil#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: JobEntityManager.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void hintAsyncExecutor(Job job) {

        AsyncExecutor asyncExecutor = Context.getProcessEngineConfiguration().getAsyncExecutor();
        CommandContext commandContext = CommandContextUtil.getCommandContext();

        TransactionContext transactionContext = org.flowable.common.engine.impl.context.Context.getTransactionContext();
        if (transactionContext != null) {
            JobAddedTransactionListener jobAddedTransactionListener = new JobAddedTransactionListener(job, asyncExecutor,
                CommandContextUtil.getJobServiceConfiguration(commandContext).getCommandExecutor());
            transactionContext.addTransactionListener(TransactionState.COMMITTED, jobAddedTransactionListener);

        } else {
            CommandContextCloseListener commandContextCloseListener = new AsyncJobAddedNotification(job, asyncExecutor);
            Context.getCommandContext().addCloseListener(commandContextCloseListener);

        }
    }
 
Example 2
Source File: ExecutionEntityManagerImpl.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteRelatedDataForExecution(ExecutionEntity executionEntity, String deleteReason) {

    // To start, deactivate the current incoming execution
    executionEntity.setEnded(true);
    executionEntity.setActive(false);
    
    CommandContext commandContext = CommandContextUtil.getCommandContext();
    boolean enableExecutionRelationshipCounts = CountingEntityUtil.isExecutionRelatedEntityCountEnabled(executionEntity);
    
    // If event dispatching is disabled, related entities can be deleted in bulk. Otherwise, they need to be fetched
    // and events need to be sent for each of them separately (the bulk delete still happens).
    FlowableEventDispatcher eventDispatcher = CommandContextUtil.getProcessEngineConfiguration(commandContext).getEventDispatcher();
    boolean eventDispatcherEnabled = eventDispatcher != null && eventDispatcher.isEnabled();
    
    deleteIdentityLinks(executionEntity, commandContext, eventDispatcherEnabled);
    deleteEntityLinks(executionEntity, commandContext, eventDispatcherEnabled);
    deleteVariables(executionEntity, commandContext, enableExecutionRelationshipCounts, eventDispatcherEnabled);
    deleteUserTasks(executionEntity, deleteReason, commandContext, enableExecutionRelationshipCounts, eventDispatcherEnabled);
    deleteJobs(executionEntity, commandContext, enableExecutionRelationshipCounts, eventDispatcherEnabled);
    deleteEventSubScriptions(executionEntity, enableExecutionRelationshipCounts, eventDispatcherEnabled);
    deleteActivityInstances(executionEntity, commandContext);
    deleteSubCases(executionEntity, commandContext);
}
 
Example 3
Source File: AbstractFlowableEngineEventListener.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected DelegateExecution getExecution(FlowableEngineEvent event) {
    String executionId = event.getExecutionId();

    if (executionId != null) {
        CommandContext commandContext = CommandContextUtil.getCommandContext();
        if (commandContext != null) {
            return CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId);
            }
        }
    return null;
}
 
Example 4
Source File: DefaultHistoryVariableManager.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void initAsyncHistoryCommandContextCloseListener() {
	if (processEngineConfiguration.isAsyncHistoryEnabled()) {
		CommandContext commandContext = CommandContextUtil.getCommandContext();
    	commandContext.addCloseListener(new AsyncHistorySessionCommandContextCloseListener(
    			commandContext.getSession(AsyncHistorySession.class), processEngineConfiguration.getAsyncHistoryListener()));
    }
}
 
Example 5
Source File: SendEventTaskActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void trigger(DelegateExecution execution, String signalName, Object signalData) {
    if (sendEventServiceTask.isTriggerable()) {
        Object eventInstance = execution.getTransientVariables().get(EventConstants.EVENT_INSTANCE);
        if (eventInstance instanceof EventInstance) {
            EventInstanceBpmnUtil.handleEventInstanceOutParameters(execution, sendEventServiceTask, (EventInstance) eventInstance);
        }

        CommandContext commandContext = CommandContextUtil.getCommandContext();
        EventSubscriptionService eventSubscriptionService = CommandContextUtil.getEventSubscriptionService(commandContext);
        ExecutionEntity executionEntity = (ExecutionEntity) execution;
        List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions();

        String eventType = null;
        if (StringUtils.isNotEmpty(sendEventServiceTask.getTriggerEventType())) {
            eventType = sendEventServiceTask.getTriggerEventType();
        } else {
            eventType = sendEventServiceTask.getEventType();
        }
        
        EventModel eventModel = null;
        if (Objects.equals(ProcessEngineConfiguration.NO_TENANT_ID, execution.getTenantId())) {
            eventModel = CommandContextUtil.getEventRepositoryService(commandContext).getEventModelByKey(eventType);
        } else {
            eventModel = CommandContextUtil.getEventRepositoryService(commandContext).getEventModelByKey(eventType, execution.getTenantId());
        }

        for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
            if (Objects.equals(eventModel.getKey(), eventSubscription.getEventType())) {
                eventSubscriptionService.deleteEventSubscription(eventSubscription);
            }
        }
        
        leave(execution);
    }
}
 
Example 6
Source File: ServiceTaskJavaDelegateActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void trigger(DelegateExecution execution, String signalName, Object signalData) {
    CommandContext commandContext = CommandContextUtil.getCommandContext();
    ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
    
    if (triggerable && javaDelegate instanceof TriggerableActivityBehavior) {
        if (processEngineConfiguration.isLoggingSessionEnabled()) {
            BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_BEFORE_TRIGGER, 
                            "Triggering service task with java class " + javaDelegate.getClass().getName(), execution);
        }
        
        ((TriggerableActivityBehavior) javaDelegate).trigger(execution, signalName, signalData);
        
        if (processEngineConfiguration.isLoggingSessionEnabled()) {
            BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_AFTER_TRIGGER,
                            "Triggered service task with java class " + javaDelegate.getClass().getName(), execution);
        }
        
        leave(execution);
    
    } else {
        if (processEngineConfiguration.isLoggingSessionEnabled()) {
            if (!triggerable) {
                BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_WRONG_TRIGGER, 
                                "Service task with java class triggered but not triggerable " + javaDelegate.getClass().getName(), execution);
            } else {
                BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_WRONG_TRIGGER, 
                                "Service task with java class triggered but not implementing TriggerableActivityBehavior " + javaDelegate.getClass().getName(), execution);
            }
        }
    }
}
 
Example 7
Source File: AbstractProcessInstanceMigrationJobHandler.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected static ObjectMapper getObjectMapper() {
    if (CommandContextUtil.getCommandContext() != null) {
        return CommandContextUtil.getProcessEngineConfiguration().getObjectMapper();
    } else {
        return new ObjectMapper();
    }
}
 
Example 8
Source File: TimerEventHandler.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected static JsonNode readJsonValue(String config) throws IOException {
    if (CommandContextUtil.getCommandContext() != null) {
        return CommandContextUtil.getProcessEngineConfiguration().getObjectMapper().readTree(config);
    } else {
        return new ObjectMapper().readTree(config);
    }
}
 
Example 9
Source File: ExecutionEntityManagerImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteExecutionAndRelatedData(ExecutionEntity executionEntity, String deleteReason, boolean deleteHistory, boolean cancel, FlowElement cancelActivity) {
    if (!deleteHistory && executionEntity.isActive()
            && executionEntity.getCurrentFlowElement() != null
            && !executionEntity.isMultiInstanceRoot()) {
        
        CommandContextUtil.getActivityInstanceEntityManager().recordActivityEnd(executionEntity, deleteReason);
    }
    
    deleteRelatedDataForExecution(executionEntity, deleteReason);
    delete(executionEntity);

    if (cancel && !executionEntity.isProcessInstanceType()) {
        dispatchActivityCancelled(executionEntity, cancelActivity != null ? cancelActivity : executionEntity.getCurrentFlowElement());
    }
    
    if (executionEntity.isProcessInstanceType() && executionEntity.getCallbackId() != null) {
        CommandContext commandContext = CommandContextUtil.getCommandContext();
        ProcessInstanceHelper processInstanceHelper = CommandContextUtil.getProcessInstanceHelper(commandContext);
        if (cancel) {
            processInstanceHelper.callCaseInstanceStateChangeCallbacks(commandContext, executionEntity,
                    ProcessInstanceState.RUNNING, ProcessInstanceState.CANCELLED);
        } else {
            processInstanceHelper.callCaseInstanceStateChangeCallbacks(commandContext, executionEntity,
                    ProcessInstanceState.RUNNING, ProcessInstanceState.COMPLETED);
        }
    }
}
 
Example 10
Source File: FlowableProcessEventImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public DelegateExecution getExecution() {
    String executionId = getExecutionId();
    if (executionId != null) {
        CommandContext commandContext = CommandContextUtil.getCommandContext();
        if (commandContext != null) {
            return CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId);
        }
    }
    return null;
}
 
Example 11
Source File: Context.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public static CommandContext getCommandContext() {
    return CommandContextUtil.getCommandContext();
}
 
Example 12
Source File: ServiceTaskExpressionActivityBehavior.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {
    Object value = null;
    try {
        CommandContext commandContext = CommandContextUtil.getCommandContext();
        String skipExpressionText = null;
        if (skipExpression != null) {
            skipExpressionText = skipExpression.getExpressionText();
        }
        boolean isSkipExpressionEnabled = SkipExpressionUtil.isSkipExpressionEnabled(skipExpressionText, serviceTaskId, execution, commandContext);
        if (!isSkipExpressionEnabled || !SkipExpressionUtil.shouldSkipFlowElement(skipExpressionText, serviceTaskId, execution, commandContext)) {

            if (CommandContextUtil.getProcessEngineConfiguration(commandContext).isEnableProcessDefinitionInfoCache()) {
                ObjectNode taskElementProperties = BpmnOverrideContext.getBpmnOverrideElementProperties(serviceTaskId, execution.getProcessDefinitionId());
                if (taskElementProperties != null && taskElementProperties.has(DynamicBpmnConstants.SERVICE_TASK_EXPRESSION)) {
                    String overrideExpression = taskElementProperties.get(DynamicBpmnConstants.SERVICE_TASK_EXPRESSION).asText();
                    if (StringUtils.isNotEmpty(overrideExpression) && !overrideExpression.equals(expression.getExpressionText())) {
                        expression = CommandContextUtil.getProcessEngineConfiguration(commandContext).getExpressionManager().createExpression(overrideExpression);
                    }
                }
            }

            value = expression.getValue(execution);
            if (resultVariable != null) {
                if (storeResultVariableAsTransient) {
                    if (useLocalScopeForResultVariable) {
                        execution.setTransientVariableLocal(resultVariable, value);
                    } else {
                        execution.setTransientVariable(resultVariable, value);
                    }
                } else {
                    if (useLocalScopeForResultVariable) {
                        execution.setVariableLocal(resultVariable, value);
                    } else {
                        execution.setVariable(resultVariable, value);
                    }
                }
            }
        }
        if (!this.triggerable) {
            leave(execution);
        }

    } catch (Exception exc) {

        Throwable cause = exc;
        BpmnError error = null;
        while (cause != null) {
            if (cause instanceof BpmnError) {
                error = (BpmnError) cause;
                break;
            } else if (cause instanceof RuntimeException) {
                if (ErrorPropagation.mapException((RuntimeException) cause, (ExecutionEntity) execution, mapExceptions)) {
                    return;
                }
            }
            cause = cause.getCause();
        }

        if (error != null) {
            ErrorPropagation.propagateError(error, execution);
        } else {
            throw exc;
        }
    }
}
 
Example 13
Source File: ServiceTaskJavaDelegateActivityBehavior.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {
    CommandContext commandContext = CommandContextUtil.getCommandContext();
    String skipExpressionText = null;
    if (skipExpression != null) {
        skipExpressionText = skipExpression.getExpressionText();
    }
    boolean isSkipExpressionEnabled = SkipExpressionUtil.isSkipExpressionEnabled(skipExpressionText, 
                    execution.getCurrentActivityId(), execution, commandContext);
    
    ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
    if (!isSkipExpressionEnabled || !SkipExpressionUtil.shouldSkipFlowElement(skipExpressionText, 
                    execution.getCurrentActivityId(), execution, commandContext)) {
        
        try {
            if (processEngineConfiguration.isLoggingSessionEnabled()) {
                BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_ENTER, 
                                "Executing service task with java class " + javaDelegate.getClass().getName(), execution);
            }
            
            processEngineConfiguration.getDelegateInterceptor().handleInvocation(new JavaDelegateInvocation(javaDelegate, execution));
            
            if (processEngineConfiguration.isLoggingSessionEnabled()) {
                BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_EXIT, 
                                "Executed service task with java class " + javaDelegate.getClass().getName(), execution);
            }
            
        } catch (RuntimeException e) {
            if (processEngineConfiguration.isLoggingSessionEnabled()) {
                BpmnLoggingSessionUtil.addErrorLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_EXCEPTION, 
                                "Service task with java class " + javaDelegate.getClass().getName() + " threw exception " + e.getMessage(), e, execution);
            }
            
            throw e;
        }
        
    } else {
        if (processEngineConfiguration.isLoggingSessionEnabled()) {
            BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SKIP_TASK, "Skipped service task " + execution.getCurrentActivityId() + 
                            " with skip expression " + skipExpressionText, execution);
        }
    }

    if (!triggerable) {
        leave(execution);
    }
}
 
Example 14
Source File: ServiceTaskDelegateExpressionActivityBehavior.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {

    CommandContext commandContext = CommandContextUtil.getCommandContext();
    ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
    boolean loggingSessionEnabled = processEngineConfiguration.isLoggingSessionEnabled();
    try {

        String skipExpressionText = null;
        if (skipExpression != null) {
            skipExpressionText = skipExpression.getExpressionText();
        }
        boolean isSkipExpressionEnabled = SkipExpressionUtil.isSkipExpressionEnabled(skipExpressionText, serviceTaskId, execution, commandContext);
        if (!isSkipExpressionEnabled || !SkipExpressionUtil.shouldSkipFlowElement(skipExpressionText, serviceTaskId, execution, commandContext)) {


            if (processEngineConfiguration.isEnableProcessDefinitionInfoCache()) {
                ObjectNode taskElementProperties = BpmnOverrideContext.getBpmnOverrideElementProperties(serviceTaskId, execution.getProcessDefinitionId());
                if (taskElementProperties != null && taskElementProperties.has(DynamicBpmnConstants.SERVICE_TASK_DELEGATE_EXPRESSION)) {
                    String overrideExpression = taskElementProperties.get(DynamicBpmnConstants.SERVICE_TASK_DELEGATE_EXPRESSION).asText();
                    if (StringUtils.isNotEmpty(overrideExpression) && !overrideExpression.equals(expression.getExpressionText())) {
                        expression = processEngineConfiguration.getExpressionManager().createExpression(overrideExpression);
                    }
                }
            }

            Object delegate = DelegateExpressionUtil.resolveDelegateExpression(expression, execution, fieldDeclarations);

            if (loggingSessionEnabled) {
                BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_ENTER,
                        "Executing service task with delegate " + delegate, execution);
            }

            if (delegate instanceof ActivityBehavior) {

                if (delegate instanceof AbstractBpmnActivityBehavior) {
                    ((AbstractBpmnActivityBehavior) delegate).setMultiInstanceActivityBehavior(getMultiInstanceActivityBehavior());
                }

                processEngineConfiguration
                        .getDelegateInterceptor().handleInvocation(new ActivityBehaviorInvocation((ActivityBehavior) delegate, execution));

            } else if (delegate instanceof JavaDelegate) {
                processEngineConfiguration
                        .getDelegateInterceptor().handleInvocation(new JavaDelegateInvocation((JavaDelegate) delegate, execution));

                if (!triggerable) {
                    leave(execution);
                }
            } else {
                throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did neither resolve to an implementation of " + ActivityBehavior.class + " nor " + JavaDelegate.class);
            }

            if (loggingSessionEnabled) {
                BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_EXIT,
                        "Executed service task with delegate " + delegate, execution);
            }

        } else {
            if (loggingSessionEnabled) {
                BpmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SKIP_TASK, "Skipped service task " + execution.getCurrentActivityId() +
                        " with skip expression " + skipExpressionText, execution);
            }
            leave(execution);
        }
    } catch (Exception exc) {

        if (loggingSessionEnabled) {
            BpmnLoggingSessionUtil.addErrorLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_EXCEPTION,
                    "Service task with delegate expression " + expression + " threw exception " + exc.getMessage(), exc, execution);
        }

        Throwable cause = exc;
        BpmnError error = null;
        while (cause != null) {
            if (cause instanceof BpmnError) {
                error = (BpmnError) cause;
                break;

            } else if (cause instanceof RuntimeException) {
                if (ErrorPropagation.mapException((RuntimeException) cause, (ExecutionEntity) execution, mapExceptions)) {
                    return;
                }
            }
            cause = cause.getCause();
        }

        if (error != null) {
            ErrorPropagation.propagateError(error, execution);
        } else if (exc instanceof FlowableException) {
            throw exc;
        } else {
            throw new FlowableException(exc.getMessage(), exc);
        }

    }
}
 
Example 15
Source File: ExternalWorkerTaskActivityBehavior.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {
    CommandContext commandContext = CommandContextUtil.getCommandContext();
    String skipExpressionText = null;
    if (skipExpression != null) {
        skipExpressionText = skipExpression.getExpressionText();
    }

    FlowElement currentFlowElement = execution.getCurrentFlowElement();
    String elementId = currentFlowElement.getId();
    boolean isSkipExpressionEnabled = SkipExpressionUtil.isSkipExpressionEnabled(skipExpressionText, elementId, execution, commandContext);
    if (!isSkipExpressionEnabled || !SkipExpressionUtil.shouldSkipFlowElement(skipExpressionText, elementId, execution, commandContext)) {
        CreateExternalWorkerJobInterceptor interceptor = CommandContextUtil.getProcessEngineConfiguration(commandContext)
                .getCreateExternalWorkerJobInterceptor();

        CreateExternalWorkerJobBeforeContext beforeContext = new CreateExternalWorkerJobBeforeContext(
                externalWorkerServiceTask,
                execution,
                getJobCategory(currentFlowElement)
        );

        if (interceptor != null) {
            interceptor.beforeCreateExternalWorkerJob(beforeContext);
        }

        JobServiceConfiguration jobServiceConfiguration = CommandContextUtil.getJobServiceConfiguration(commandContext);
        JobService jobService = jobServiceConfiguration.getJobService();

        ExternalWorkerJobEntity job = jobService.createExternalWorkerJob();
        job.setExecutionId(execution.getId());
        job.setProcessInstanceId(execution.getProcessInstanceId());
        job.setProcessDefinitionId(execution.getProcessDefinitionId());
        job.setElementId(elementId);
        job.setElementName(currentFlowElement.getName());
        job.setJobHandlerType(ExternalWorkerTaskCompleteJobHandler.TYPE);
        job.setExclusive(exclusive);

        if (StringUtils.isNotEmpty(beforeContext.getJobCategory())) {
            Expression categoryExpression = CommandContextUtil.getProcessEngineConfiguration(commandContext)
                    .getExpressionManager()
                    .createExpression(beforeContext.getJobCategory());
            Object categoryValue = categoryExpression.getValue(execution);
            if (categoryValue != null) {
                job.setCategory(categoryValue.toString());
            }
        }

        job.setJobType(JobEntity.JOB_TYPE_EXTERNAL_WORKER);
        job.setRetries(jobServiceConfiguration.getAsyncExecutorNumberOfRetries());

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

        Expression jobTopicExpression;
        if (StringUtils.isEmpty(beforeContext.getJobTopicExpression())) {
            jobTopicExpression = this.jobTopicExpression;
        } else {
            jobTopicExpression = CommandContextUtil.getProcessEngineConfiguration(commandContext)
                    .getExpressionManager()
                    .createExpression(beforeContext.getJobTopicExpression());
        }
        Object topicValue = jobTopicExpression.getValue(execution);
        if (topicValue != null && !topicValue.toString().isEmpty()) {
            job.setJobHandlerConfiguration(topicValue.toString());
        } else {
            throw new FlowableException("Expression " + jobTopicExpression + " did not evaluate to a valid value (non empty String). Was: " + topicValue);
        }

        jobService.insertExternalWorkerJob(job);

        if (interceptor != null) {
            interceptor.afterCreateExternalWorkerJob(new CreateExternalWorkerJobAfterContext(
                    (ExternalWorkerServiceTask) currentFlowElement,
                    job,
                    execution
            ));
        }
    } else {
        leave(execution);
    }
}
 
Example 16
Source File: SendEventTaskActivityBehavior.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {
    CommandContext commandContext = CommandContextUtil.getCommandContext();
    EventRegistry eventRegistry = CommandContextUtil.getEventRegistry(commandContext);

    EventModel eventModel = getEventModel(commandContext, execution);
    ExecutionEntity executionEntity = (ExecutionEntity) execution;

    boolean sendSynchronously = sendEventServiceTask.isSendSynchronously() || executedAsAsyncJob;
    if (!sendSynchronously) {
        JobService jobService = CommandContextUtil.getJobService(commandContext);

        JobEntity job = jobService.createJob();
        job.setExecutionId(execution.getId());
        job.setProcessInstanceId(execution.getProcessInstanceId());
        job.setProcessDefinitionId(execution.getProcessDefinitionId());
        job.setElementId(sendEventServiceTask.getId());
        job.setElementName(sendEventServiceTask.getName());
        job.setJobHandlerType(AsyncSendEventJobHandler.TYPE);

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

        executionEntity.getJobs().add(job);

        jobService.createAsyncJob(job, true);
        jobService.scheduleAsyncJob(job);

    } else {
        Collection<EventPayloadInstance> eventPayloadInstances = EventInstanceBpmnUtil.createEventPayloadInstances(executionEntity,
            CommandContextUtil.getProcessEngineConfiguration(commandContext).getExpressionManager(),
            execution.getCurrentFlowElement(),
            eventModel);

        boolean sendOnSystemChannel = isSendOnSystemChannel(execution);
        List<ChannelModel> channelModels = getChannelModels(commandContext, execution, sendOnSystemChannel);
        EventInstanceImpl eventInstance = new EventInstanceImpl(eventModel.getKey(), eventPayloadInstances, execution.getTenantId());
        if (!channelModels.isEmpty()) {
            eventRegistry.sendEventOutbound(eventInstance, channelModels);
        }

        if (sendOnSystemChannel) {
            eventRegistry.sendSystemEventOutbound(eventInstance);
        }

    }

    if (sendEventServiceTask.isTriggerable() && !executedAsAsyncJob) {
        String triggerEventDefinitionKey;
        if (StringUtils.isNotEmpty(sendEventServiceTask.getTriggerEventType())) {
            triggerEventDefinitionKey = sendEventServiceTask.getTriggerEventType();

        } else {
            triggerEventDefinitionKey = eventModel.getKey();
        }
        
        EventSubscriptionEntity eventSubscription = (EventSubscriptionEntity) CommandContextUtil
            .getEventSubscriptionService(commandContext).createEventSubscriptionBuilder()
                .eventType(triggerEventDefinitionKey)
                .executionId(execution.getId())
                .processInstanceId(execution.getProcessInstanceId())
                .activityId(execution.getCurrentActivityId())
                .processDefinitionId(execution.getProcessDefinitionId())
                .scopeType(ScopeTypes.BPMN)
                .tenantId(execution.getTenantId())
                .configuration(CorrelationUtil.getCorrelationKey(BpmnXMLConstants.ELEMENT_TRIGGER_EVENT_CORRELATION_PARAMETER, commandContext, executionEntity))
                .create();
        
        CountingEntityUtil.handleInsertEventSubscriptionEntityCount(eventSubscription);
        executionEntity.getEventSubscriptions().add(eventSubscription);

    } else if ( (sendSynchronously && !executedAsAsyncJob)
            || (!sendEventServiceTask.isTriggerable() && executedAsAsyncJob)) {
        // If this send task is specifically marked to send synchronously and is not triggerable then leave
        leave(execution);
    }
}
 
Example 17
Source File: EvaluateConditionalEventsOperation.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected void evaluateEventSubProcesses(List<EventSubProcess> eventSubProcesses, ExecutionEntity parentExecution) {
    if (eventSubProcesses != null) {
        for (EventSubProcess eventSubProcess : eventSubProcesses) {
            List<StartEvent> startEvents = eventSubProcess.findAllSubFlowElementInFlowMapOfType(StartEvent.class);
            if (startEvents != null) {
                for (StartEvent startEvent : startEvents) {
                    
                    if (startEvent.getEventDefinitions() != null && !startEvent.getEventDefinitions().isEmpty() && 
                                    startEvent.getEventDefinitions().get(0) instanceof ConditionalEventDefinition) {
                        
                        CommandContext commandContext = CommandContextUtil.getCommandContext();
                        ConditionalEventDefinition conditionalEventDefinition = (ConditionalEventDefinition) startEvent.getEventDefinitions().get(0);
                        
                        boolean conditionIsTrue = false;
                        String conditionExpression = conditionalEventDefinition.getConditionExpression();
                        if (StringUtils.isNotEmpty(conditionExpression)) {
                            Expression expression = CommandContextUtil.getProcessEngineConfiguration(commandContext).getExpressionManager().createExpression(conditionExpression);
                            Object result = expression.getValue(parentExecution);
                            if (result != null && result instanceof Boolean && (Boolean) result) {
                                conditionIsTrue = true;
                            }
                        
                        } else {
                            conditionIsTrue = true;
                        }
                        
                        if (conditionIsTrue) {
                            ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
                            if (startEvent.isInterrupting()) {
                                executionEntityManager.deleteChildExecutions(parentExecution, null, true);
                            }

                            ExecutionEntity eventSubProcessExecution = executionEntityManager.createChildExecution(parentExecution);
                            eventSubProcessExecution.setScope(true);
                            eventSubProcessExecution.setCurrentFlowElement(eventSubProcess);

                            CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(eventSubProcessExecution);
                            
                            ExecutionEntity startEventSubProcessExecution = executionEntityManager.createChildExecution(eventSubProcessExecution);
                            startEventSubProcessExecution.setCurrentFlowElement(startEvent);
                            
                            CommandContextUtil.getAgenda(commandContext).planContinueProcessOperation(startEventSubProcessExecution);
                        }
                    }
                }
            }
        }
    }
}
 
Example 18
Source File: ExclusiveGatewayActivityBehavior.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
/**
 * The default behaviour of BPMN, taking every outgoing sequence flow (where the condition evaluates to true), is not valid for an exclusive gateway.
 * 
 * Hence, this behaviour is overridden and replaced by the correct behavior: selecting the first sequence flow which condition evaluates to true (or which hasn't got a condition) and leaving the
 * activity through that sequence flow.
 * 
 * If no sequence flow is selected (ie all conditions evaluate to false), then the default sequence flow is taken (if defined).
 */
@Override
public void leave(DelegateExecution execution) {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Leaving exclusive gateway '{}'", execution.getCurrentActivityId());
    }

    ExclusiveGateway exclusiveGateway = (ExclusiveGateway) execution.getCurrentFlowElement();

    CommandContext commandContext = CommandContextUtil.getCommandContext();
    ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
    FlowableEventDispatcher eventDispatcher = null;
    if (processEngineConfiguration != null) {
        eventDispatcher = processEngineConfiguration.getEventDispatcher();
    }
    if (eventDispatcher != null && eventDispatcher.isEnabled()) {
        processEngineConfiguration.getEventDispatcher().dispatchEvent(
                FlowableEventBuilder.createActivityEvent(FlowableEngineEventType.ACTIVITY_COMPLETED, exclusiveGateway.getId(), exclusiveGateway.getName(), execution.getId(),
                        execution.getProcessInstanceId(), execution.getProcessDefinitionId(), exclusiveGateway));
    }

    SequenceFlow outgoingSequenceFlow = null;
    SequenceFlow defaultSequenceFlow = null;
    String defaultSequenceFlowId = exclusiveGateway.getDefaultFlow();

    // Determine sequence flow to take
    Iterator<SequenceFlow> sequenceFlowIterator = exclusiveGateway.getOutgoingFlows().iterator();
    while (outgoingSequenceFlow == null && sequenceFlowIterator.hasNext()) {
        SequenceFlow sequenceFlow = sequenceFlowIterator.next();

        String skipExpressionString = sequenceFlow.getSkipExpression();
        if (!SkipExpressionUtil.isSkipExpressionEnabled(skipExpressionString, sequenceFlow.getId(), execution, commandContext)) {
            boolean conditionEvaluatesToTrue = ConditionUtil.hasTrueCondition(sequenceFlow, execution);
            if (conditionEvaluatesToTrue && (defaultSequenceFlowId == null || !defaultSequenceFlowId.equals(sequenceFlow.getId()))) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Sequence flow '{}' selected as outgoing sequence flow.", sequenceFlow.getId());
                }
                outgoingSequenceFlow = sequenceFlow;
            }
            
        } else if (SkipExpressionUtil.shouldSkipFlowElement(skipExpressionString, sequenceFlow.getId(), execution, Context.getCommandContext())) {
            outgoingSequenceFlow = sequenceFlow;
        }

        // Already store it, if we would need it later. Saves one for loop.
        if (defaultSequenceFlowId != null && defaultSequenceFlowId.equals(sequenceFlow.getId())) {
            defaultSequenceFlow = sequenceFlow;
        }

    }

    // Leave the gateway
    if (outgoingSequenceFlow != null) {
        execution.setCurrentFlowElement(outgoingSequenceFlow);
    } else {
        if (defaultSequenceFlow != null) {
            execution.setCurrentFlowElement(defaultSequenceFlow);
        } else {

            // No sequence flow could be found, not even a default one
            throw new FlowableException("No outgoing sequence flow of the exclusive gateway '" + exclusiveGateway.getId() + "' could be selected for continuing the process");
        }
    }

    super.leave(execution);
}
 
Example 19
Source File: HttpActivityBehaviorImpl.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {

    String skipExpressionText = httpServiceTask.getSkipExpression();

    CommandContext commandContext = CommandContextUtil.getCommandContext();

    boolean isSkipExpressionEnabled = SkipExpressionUtil.isSkipExpressionEnabled(skipExpressionText,
            execution.getCurrentActivityId(), execution, commandContext);

    if (!isSkipExpressionEnabled || !SkipExpressionUtil.shouldSkipFlowElement(skipExpressionText,
            execution.getCurrentActivityId(), execution, commandContext)) {

        HttpRequest request = new HttpRequest();

        try {
            request.setMethod(getStringFromField(requestMethod, execution));
            request.setUrl(getStringFromField(requestUrl, execution));
            request.setHeaders(getStringFromField(requestHeaders, execution));
            request.setBody(getStringFromField(requestBody, execution));
            request.setBodyEncoding(getStringFromField(requestBodyEncoding, execution));
            request.setTimeout(getIntFromField(requestTimeout, execution));
            request.setNoRedirects(getBooleanFromField(disallowRedirects, execution));
            request.setIgnoreErrors(getBooleanFromField(ignoreException, execution));
            request.setSaveRequest(getBooleanFromField(saveRequestVariables, execution));
            request.setSaveResponse(getBooleanFromField(saveResponseParameters, execution));
            request.setSaveResponseTransient(getBooleanFromField(saveResponseParametersTransient, execution));
            request.setSaveResponseAsJson(getBooleanFromField(saveResponseVariableAsJson, execution));
            request.setPrefix(getStringFromField(resultVariablePrefix, execution));

            String failCodes = getStringFromField(failStatusCodes, execution);
            String handleCodes = getStringFromField(handleStatusCodes, execution);

            if (failCodes != null) {
                request.setFailCodes(getStringSetFromField(failCodes));
            }
            if (handleCodes != null) {
                request.setHandleCodes(getStringSetFromField(handleCodes));
            }

            if (request.getPrefix() == null) {
                request.setPrefix(execution.getCurrentFlowElement().getId());
            }

            // Save request fields
            if (request.isSaveRequest()) {
                execution.setVariable(request.getPrefix() + "RequestMethod", request.getMethod());
                execution.setVariable(request.getPrefix() + "RequestUrl", request.getUrl());
                execution.setVariable(request.getPrefix() + "RequestHeaders", request.getHeaders());
                execution.setVariable(request.getPrefix() + "RequestBody", request.getBody());
                execution.setVariable(request.getPrefix() + "RequestBodyEncoding", request.getBodyEncoding());
                execution.setVariable(request.getPrefix() + "RequestTimeout", request.getTimeout());
                execution.setVariable(request.getPrefix() + "DisallowRedirects", request.isNoRedirects());
                execution.setVariable(request.getPrefix() + "FailStatusCodes", failCodes);
                execution.setVariable(request.getPrefix() + "HandleStatusCodes", handleCodes);
                execution.setVariable(request.getPrefix() + "IgnoreException", request.isIgnoreErrors());
                execution.setVariable(request.getPrefix() + "SaveRequestVariables", request.isSaveRequest());
                execution.setVariable(request.getPrefix() + "SaveResponseParameters", request.isSaveResponse());
            }

        } catch (Exception e) {
            if (e instanceof FlowableException) {
                throw (FlowableException) e;
            } else {
                throw new FlowableException(HTTP_TASK_REQUEST_FIELD_INVALID + " in execution " + execution.getId(), e);
            }
        }

        httpActivityExecutor.validate(request);

        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
        HttpClientConfig httpClientConfig = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig();

        httpActivityExecutor.execute(
                request,
                execution,
                execution.getId(),
                createHttpRequestHandler(httpServiceTask.getHttpRequestHandler(), processEngineConfiguration),
                createHttpResponseHandler(httpServiceTask.getHttpResponseHandler(), processEngineConfiguration),
                getStringFromField(responseVariableName, execution),
                mapExceptions,
                httpClientConfig.getSocketTimeout(),
                httpClientConfig.getConnectTimeout(),
                httpClientConfig.getConnectionRequestTimeout());
    }

    leave(execution);
}