org.flowable.common.engine.impl.interceptor.CommandContext Java Examples

The following examples show how to use org.flowable.common.engine.impl.interceptor.CommandContext. 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: HumanTaskActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void handleDueDate(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity,
        ExpressionManager expressionManager, TaskEntity taskEntity, CreateHumanTaskBeforeContext beforeContext) {
    
    if (StringUtils.isNotEmpty(beforeContext.getDueDate())) {
        Object dueDate = expressionManager.createExpression(beforeContext.getDueDate()).getValue(planItemInstanceEntity);
        if (dueDate != null) {
            if (dueDate instanceof Date) {
                taskEntity.setDueDate((Date) dueDate);
            } else if (dueDate instanceof String) {

                String dueDateString = (String) dueDate;
                if (dueDateString.startsWith("P")) {
                    taskEntity.setDueDate(new DateTime(CommandContextUtil.getCmmnEngineConfiguration(commandContext).getClock().getCurrentTime())
                            .plus(Period.parse(dueDateString)).toDate());
                } else {
                    taskEntity.setDueDate(DateTime.parse(dueDateString).toDate());
                }

            } else {
                throw new FlowableIllegalArgumentException("Due date expression does not resolve to a Date or Date string: " + beforeContext.getDueDate());
            }
        }
    }
}
 
Example #2
Source File: HistoryServiceTaskLogTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void deleteTaskWithLogEntries(TaskService taskService, ManagementService managementService, ProcessEngineConfiguration processEngineConfiguration,
        String taskId) {
    taskService.deleteTask(taskId, true);
    managementService.executeCommand(new Command<Void>() {

        @Override
        public Void execute(CommandContext commandContext) {
            HistoricTaskLogEntryEntityManager historicTaskLogEntryEntityManager = CommandContextUtil.getTaskServiceConfiguration(commandContext)
                    .getHistoricTaskLogEntryEntityManager();
            List<HistoricTaskLogEntry> taskLogEntries = historicTaskLogEntryEntityManager
                    .findHistoricTaskLogEntriesByQueryCriteria(new HistoricTaskLogEntryQueryImpl(processEngineConfiguration.getCommandExecutor()));
            for (HistoricTaskLogEntry historicTaskLogEntry : taskLogEntries) {
                historicTaskLogEntryEntityManager.deleteHistoricTaskLogEntry(historicTaskLogEntry.getLogNumber());
            }

            HistoryJobService historyJobService = CommandContextUtil.getHistoryJobService(commandContext);
            List<HistoryJob> jobs = historyJobService.findHistoryJobsByQueryCriteria(new HistoryJobQueryImpl(commandContext));
            for (HistoryJob historyJob : jobs) {
                historyJobService.deleteHistoryJob((HistoryJobEntity) historyJob);
            }

            return null;
        }
    });
}
 
Example #3
Source File: SetFormDefinitionCategoryCmd.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Void execute(CommandContext commandContext) {

    if (formDefinitionId == null) {
        throw new FlowableIllegalArgumentException("Form definition id is null");
    }

    FormDefinitionEntity formDefinition = CommandContextUtil.getFormDefinitionEntityManager(commandContext).findById(formDefinitionId);

    if (formDefinition == null) {
        throw new FlowableObjectNotFoundException("No form definition found for id = '" + formDefinitionId + "'");
    }

    // Update category
    formDefinition.setCategory(category);

    // Remove form from cache, it will be refetched later
    DeploymentCache<FormDefinitionCacheEntry> formDefinitionCache = CommandContextUtil.getFormEngineConfiguration().getFormDefinitionCache();
    if (formDefinitionCache != null) {
        formDefinitionCache.remove(formDefinitionId);
    }

    CommandContextUtil.getFormDefinitionEntityManager(commandContext).update(formDefinition);

    return null;
}
 
Example #4
Source File: EventDefinitionExpressionUtil.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Determines the signal name of the {@link SignalEventDefinition} that is passed:
 * - if a signal name is set, it has precedence
 * - otherwise, the signal ref is used
 * - unless a signalExpression is set
 */
public static String determineSignalName(CommandContext commandContext, SignalEventDefinition signalEventDefinition, BpmnModel bpmnModel, DelegateExecution execution) {
    String signalName = null;
    if (StringUtils.isNotEmpty(signalEventDefinition.getSignalRef())) {
        Signal signal = bpmnModel.getSignal(signalEventDefinition.getSignalRef());
        if (signal != null) {
            signalName = signal.getName();
        } else {
            signalName = signalEventDefinition.getSignalRef();
        }

    } else {
        signalName = signalEventDefinition.getSignalExpression();

    }

    if (StringUtils.isNotEmpty(signalName)) {
        Expression expression = CommandContextUtil.getProcessEngineConfiguration(commandContext).getExpressionManager().createExpression(signalName);
        return expression.getValue(execution != null ? execution : NoExecutionVariableScope.getSharedInstance()).toString();
    }

    return signalName;
}
 
Example #5
Source File: IntermediateCatchMessageEventActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {
    CommandContext commandContext = Context.getCommandContext();
    ExecutionEntity executionEntity = (ExecutionEntity) execution;

    String messageName = EventDefinitionExpressionUtil.determineMessageName(commandContext, messageEventDefinition, execution);
    EventSubscriptionEntity eventSubscription = (EventSubscriptionEntity) CommandContextUtil.getEventSubscriptionService(commandContext).createEventSubscriptionBuilder()
                    .eventType(MessageEventSubscriptionEntity.EVENT_TYPE)
                    .eventName(messageName)
                    .executionId(executionEntity.getId())
                    .processInstanceId(executionEntity.getProcessInstanceId())
                    .activityId(executionEntity.getCurrentActivityId())
                    .processDefinitionId(executionEntity.getProcessDefinitionId())
                    .tenantId(executionEntity.getTenantId())
                    .create();
    
    CountingEntityUtil.handleInsertEventSubscriptionEntityCount(eventSubscription);
    executionEntity.getEventSubscriptions().add(eventSubscription);

    FlowableEventDispatcher eventDispatcher = CommandContextUtil.getProcessEngineConfiguration(commandContext).getEventDispatcher();
    if (eventDispatcher != null && eventDispatcher.isEnabled()) {
        eventDispatcher
                .dispatchEvent(FlowableEventBuilder.createMessageEvent(FlowableEngineEventType.ACTIVITY_MESSAGE_WAITING, executionEntity.getActivityId(), messageName,
                        null, executionEntity.getId(), executionEntity.getProcessInstanceId(), executionEntity.getProcessDefinitionId()));
    }
}
 
Example #6
Source File: DeploymentEntityManagerImpl.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void restoreMessageStartEvent(ProcessDefinition previousProcessDefinition, BpmnModel bpmnModel, StartEvent startEvent, EventDefinition eventDefinition) {
    MessageEventDefinition messageEventDefinition = (MessageEventDefinition) eventDefinition;
    if (bpmnModel.containsMessageId(messageEventDefinition.getMessageRef())) {
        Message message = bpmnModel.getMessage(messageEventDefinition.getMessageRef());
        messageEventDefinition.setMessageRef(message.getName());
    }

    CommandContext commandContext = Context.getCommandContext();
    MessageEventSubscriptionEntity newSubscription = CommandContextUtil.getEventSubscriptionService(commandContext).createMessageEventSubscription();
    String messageName = EventDefinitionExpressionUtil.determineMessageName(commandContext, messageEventDefinition, null);
    newSubscription.setEventName(messageName);
    newSubscription.setActivityId(startEvent.getId());
    newSubscription.setConfiguration(previousProcessDefinition.getId());
    newSubscription.setProcessDefinitionId(previousProcessDefinition.getId());

    if (previousProcessDefinition.getTenantId() != null) {
        newSubscription.setTenantId(previousProcessDefinition.getTenantId());
    }

    CommandContextUtil.getEventSubscriptionService().insertEventSubscription(newSubscription);
    CountingEntityUtil.handleInsertEventSubscriptionEntityCount(newSubscription);
}
 
Example #7
Source File: DmnCommandInvoker.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T execute(final CommandConfig config, final Command<T> command) {
    final CommandContext commandContext = Context.getCommandContext();
    final DmnEngineAgenda agenda = CommandContextUtil.getAgenda(commandContext);
    if (commandContext.isReused() && !agenda.isEmpty()) {
        commandContext.setResult(command.execute(commandContext));
    } else {
        agenda.planOperation(new Runnable() {
            @Override
            public void run() {
                commandContext.setResult(command.execute(commandContext));
            }
        });

        executeOperations(commandContext, true); // true -> always store the case instance id for the regular operation loop, even if it's a no-op operation.
    }
    
    return (T) commandContext.getResult();
}
 
Example #8
Source File: GetTaskVariableCmd.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Object execute(CommandContext commandContext) {
    if (taskId == null) {
        throw new FlowableIllegalArgumentException("taskId is null");
    }
    if (variableName == null) {
        throw new FlowableIllegalArgumentException("variableName is null");
    }

    TaskEntity task = CommandContextUtil.getTaskService().getTask(taskId);

    if (task == null) {
        throw new FlowableObjectNotFoundException("task " + taskId + " doesn't exist", Task.class);
    }

    Object value;

    if (isLocal) {
        value = task.getVariableLocal(variableName, false);
    } else {
        value = task.getVariable(variableName, false);
    }

    return value;
}
 
Example #9
Source File: PlanItemDelegateExpressionActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
    try {
        Expression expressionObject = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getExpressionManager().createExpression(expression);
        Object delegate = DelegateExpressionUtil.resolveDelegateExpression(expressionObject, planItemInstanceEntity, fieldExtensions);
        if (delegate instanceof PlanItemActivityBehavior) {
            ((PlanItemActivityBehavior) delegate).execute(planItemInstanceEntity);

        } else if (delegate instanceof CmmnActivityBehavior) {
            ((CmmnActivityBehavior) delegate).execute(planItemInstanceEntity);

        } else if (delegate instanceof PlanItemJavaDelegate) {
            PlanItemJavaDelegateActivityBehavior behavior = new PlanItemJavaDelegateActivityBehavior((PlanItemJavaDelegate) delegate);
            behavior.execute(planItemInstanceEntity);

        } else {
            throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did neither resolve to an implementation of " + 
                            PlanItemActivityBehavior.class + ", " + CmmnActivityBehavior.class + " nor " + PlanItemJavaDelegate.class);
        }    
       
    } catch (Exception exc) {
        throw new FlowableException(exc.getMessage(), exc);
    }
}
 
Example #10
Source File: NeedsActiveExecutionCmd.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public T execute(CommandContext commandContext) {
    if (executionId == null) {
        throw new FlowableIllegalArgumentException("executionId is null");
    }

    ExecutionEntity execution = CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId);

    if (execution == null) {
        throw new FlowableObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class);
    }

    if (execution.isSuspended()) {
        throw new FlowableException(getSuspendedExceptionMessage());
    }

    return execute(commandContext, execution);
}
 
Example #11
Source File: ProcessDefinitionInfoCache.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public ProcessDefinitionInfoCacheObject get(final String processDefinitionId) {
    ProcessDefinitionInfoCacheObject infoCacheObject = null;
    Command<ProcessDefinitionInfoCacheObject> cacheCommand = new Command<ProcessDefinitionInfoCacheObject>() {

        @Override
        public ProcessDefinitionInfoCacheObject execute(CommandContext commandContext) {
            return retrieveProcessDefinitionInfoCacheObject(processDefinitionId, commandContext);
        }
    };

    if (Context.getCommandContext() != null) {
        infoCacheObject = retrieveProcessDefinitionInfoCacheObject(processDefinitionId, Context.getCommandContext());
    } else {
        infoCacheObject = commandExecutor.execute(cacheCommand);
    }

    return infoCacheObject;
}
 
Example #12
Source File: GetFormDefinitionsForProcessDefinitionCmd.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public List<FormDefinition> execute(CommandContext commandContext) {
    ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition(processDefinitionId);

    if (processDefinition == null) {
        throw new FlowableObjectNotFoundException("Cannot find process definition for id: " + processDefinitionId, ProcessDefinition.class);
    }

    BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(processDefinitionId);

    if (bpmnModel == null) {
        throw new FlowableObjectNotFoundException("Cannot find bpmn model for process definition id: " + processDefinitionId, BpmnModel.class);
    }

    if (CommandContextUtil.getFormRepositoryService() == null) {
        throw new FlowableException("Form repository service is not available");
    }

    formRepositoryService = CommandContextUtil.getFormRepositoryService();
    List<FormDefinition> formDefinitions = getFormDefinitionsFromModel(bpmnModel, processDefinition);

    return formDefinitions;
}
 
Example #13
Source File: CmmnCommandInvoker.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void evaluateUntilStable(CommandContext commandContext) {
    Set<String> involvedCaseInstanceIds = CommandContextUtil.getInvolvedCaseInstanceIds(commandContext);
    if (involvedCaseInstanceIds != null) {

        for (String caseInstanceId : involvedCaseInstanceIds) {
            CommandContextUtil.getAgenda(commandContext).planEvaluateCriteriaOperation(caseInstanceId, true);
        }

        involvedCaseInstanceIds.clear(); // Clearing after scheduling the evaluation. If anything changes, new operations will add ids again.
        executeOperations(commandContext, false); // false -> here, we're past the regular operation loop. Any operation now that is a no-op should not reschedule a new evaluation

        // If new involvedCaseInstanceIds have new entries, this means the evaluation has triggered new operations and data has changed.
        // Need to retrigger the evaluations to make sure no new things can fire now.
        if (!involvedCaseInstanceIds.isEmpty()) {
            evaluateUntilStable(commandContext);
        }
    }
}
 
Example #14
Source File: SerializableType.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void traceValue(Object value, byte[] valueBytes, ValueFields valueFields) {
    if (trackDeserializedObjects && valueFields instanceof VariableInstanceEntity) {
        CommandContext commandContext = Context.getCommandContext();
        if (commandContext != null) {
            if (commandContext.getCurrentEngineConfiguration() instanceof HasVariableServiceConfiguration) {
                HasVariableServiceConfiguration engineConfiguration = (HasVariableServiceConfiguration)
                                commandContext.getCurrentEngineConfiguration();
                VariableServiceConfiguration variableServiceConfiguration = (VariableServiceConfiguration) engineConfiguration.getVariableServiceConfiguration();
                commandContext.addCloseListener(new TraceableVariablesCommandContextCloseListener(
                    new TraceableObject<>(this, value, valueBytes, (VariableInstanceEntity) valueFields, variableServiceConfiguration)
                ));
                variableServiceConfiguration.getInternalHistoryVariableManager().initAsyncHistoryCommandContextCloseListener();
            }
        }
    }
}
 
Example #15
Source File: GetDecisionsForCaseDefinitionCmd.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public List<DmnDecision> execute(CommandContext commandContext) {
    CaseDefinition caseDefinition = CaseDefinitionUtil.getCaseDefinition(caseDefinitionId);
    
    if (caseDefinition == null) {
        throw new FlowableObjectNotFoundException("Cannot find case definition for id: " + caseDefinitionId, CaseDefinition.class);
    }
    
    Case caseModel = CaseDefinitionUtil.getCase(caseDefinitionId);

    if (caseModel == null) {
        throw new FlowableObjectNotFoundException("Cannot find case definition for id: " + caseDefinitionId, Case.class);
    }

    dmnRepositoryService = CommandContextUtil.getDmnEngineConfiguration(commandContext).getDmnRepositoryService();
    if (dmnRepositoryService == null) {
        throw new FlowableException("DMN repository service is not available");
    }

    List<DmnDecision> decision = getDecisionsFromModel(caseModel, caseDefinition);

    return decision;
}
 
Example #16
Source File: SetDeploymentTenantIdCmd.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public Void execute(CommandContext commandContext) {
    if (deploymentId == null) {
        throw new FlowableIllegalArgumentException("deploymentId is null");
    }

    // Update all entities

    DmnDeploymentEntity deployment = CommandContextUtil.getDeploymentEntityManager(commandContext).findById(deploymentId);
    if (deployment == null) {
        throw new FlowableObjectNotFoundException("Could not find deployment with id " + deploymentId);
    }

    deployment.setTenantId(newTenantId);

    // Doing process instances, executions and tasks with direct SQL updates
    // (otherwise would not be performant)
    CommandContextUtil.getDecisionEntityManager(commandContext).updateDecisionTenantIdForDeployment(deploymentId, newTenantId);

    // Doing decision tables in memory, cause we need to clear the decision table cache
    List<DmnDecision> decisionTables = new DecisionQueryImpl().deploymentId(deploymentId).list();
    for (DmnDecision decisionTable : decisionTables) {
        CommandContextUtil.getDmnEngineConfiguration().getDefinitionCache().remove(decisionTable.getId());
    }

    CommandContextUtil.getDeploymentEntityManager(commandContext).update(deployment);

    return null;

}
 
Example #17
Source File: CaseInstanceHelperImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void createAsyncInitJob(CaseInstanceEntity caseInstance, CaseDefinition caseDefinition, 
        Case caseModel, JobService jobService, CommandContext commandContext) {
    
    JobEntity job = jobService.createJob();
    job.setJobHandlerType(AsyncInitializePlanModelJobHandler.TYPE);
    job.setScopeId(caseInstance.getId());
    job.setScopeDefinitionId(caseInstance.getCaseDefinitionId());
    job.setScopeType(ScopeTypes.CMMN);
    job.setElementId(caseDefinition.getId());
    job.setElementName(caseDefinition.getName());
    job.setJobHandlerConfiguration(caseInstance.getId());
    
    List<ExtensionElement> jobCategoryElements = caseModel.getExtensionElements().get("jobCategory");
    if (jobCategoryElements != null && jobCategoryElements.size() > 0) {
        ExtensionElement jobCategoryElement = jobCategoryElements.get(0);
        if (StringUtils.isNotEmpty(jobCategoryElement.getElementText())) {
            CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
            Expression categoryExpression = cmmnEngineConfiguration.getExpressionManager().createExpression(jobCategoryElement.getElementText());
            Object categoryValue = categoryExpression.getValue(caseInstance);
            if (categoryValue != null) {
                job.setCategory(categoryValue.toString());
            }
        }
    }
    
    job.setTenantId(caseInstance.getTenantId());
    jobService.createAsyncJob(job, true);
    jobService.scheduleAsyncJob(job);
}
 
Example #18
Source File: AbstractDynamicStateManager.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void safeDeleteSubProcessInstance(String processInstanceId, List<ExecutionEntity> executionsPool, String deleteReason, CommandContext commandContext) {
    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);

    //Confirm that all the subProcessExecutions are in the executionsPool
    List<ExecutionEntity> subProcessExecutions = executionEntityManager.findChildExecutionsByProcessInstanceId(processInstanceId);
    HashSet<String> executionIdsToMove = executionsPool.stream().map(ExecutionEntity::getId).collect(Collectors.toCollection(HashSet::new));
    Optional<ExecutionEntity> notIncludedExecution = subProcessExecutions.stream().filter(e -> !executionIdsToMove.contains(e.getId())).findAny();
    if (notIncludedExecution.isPresent()) {
        throw new FlowableException("Execution of sub process instance is not moved " + notIncludedExecution.get().getId());
    }

    // delete the sub process instance
    executionEntityManager.deleteProcessInstance(processInstanceId, deleteReason, true);
}
 
Example #19
Source File: DbSchemaUpdate.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ProcessEngineImpl processEngine = (ProcessEngineImpl) ProcessEngines.getDefaultProcessEngine();
    CommandExecutor commandExecutor = processEngine.getProcessEngineConfiguration().getCommandExecutor();
    CommandConfig config = new CommandConfig().transactionNotSupported();
    commandExecutor.execute(config, new Command<Object>() {
        @Override
        public Object execute(CommandContext commandContext) {
            CommandContextUtil.getProcessEngineConfiguration(commandContext).getSchemaManager().schemaUpdate();
            return null;
        }
    });
}
 
Example #20
Source File: ExternalWorkerJobBpmnErrorCmd.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
protected void runJobLogic(ExternalWorkerJobEntity externalWorkerJob, CommandContext commandContext) {
    JobServiceConfiguration jobServiceConfiguration = CommandContextUtil.getJobServiceConfiguration(commandContext);
    // We need to remove the job handler configuration
    String errorHandlerConfiguration;
    if (errorCode != null) {
        errorHandlerConfiguration = "error:" + errorCode;
    } else {
        errorHandlerConfiguration = "error:";
    }
    externalWorkerJob.setJobHandlerConfiguration(errorHandlerConfiguration);

    if (variables != null && !variables.isEmpty()) {
        VariableService variableService = CommandContextUtil.getVariableService(commandContext);
        VariableTypes variableTypes = CommandContextUtil.getVariableServiceConfiguration(commandContext).getVariableTypes();
        for (Map.Entry<String, Object> variableEntry : variables.entrySet()) {
            String varName = variableEntry.getKey();
            Object varValue = variableEntry.getValue();

            VariableType variableType = variableTypes.findVariableType(varValue);
            VariableInstanceEntity variableInstance = variableService.createVariableInstance(varName, variableType, varValue);
            variableInstance.setScopeId(externalWorkerJob.getProcessInstanceId());
            variableInstance.setSubScopeId(externalWorkerJob.getExecutionId());
            variableInstance.setScopeType(ScopeTypes.BPMN_EXTERNAL_WORKER);

            variableService.insertVariableInstance(variableInstance);

            CountingEntityUtil.handleInsertVariableInstanceEntityCount(variableInstance);
        }
    }

    moveExternalWorkerJobToExecutableJob(jobServiceConfiguration, externalWorkerJob, commandContext);
}
 
Example #21
Source File: VariableScopeImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void ensureVariableInstancesInitialized() {
    if (variableInstances == null) {
        variableInstances = new HashMap<>();

        CommandContext commandContext = Context.getCommandContext();
        if (commandContext == null) {
            throw new FlowableException("lazy loading outside command context");
        }
        Collection<VariableInstanceEntity> variableInstancesList = loadVariableInstances();
        for (VariableInstanceEntity variableInstance : variableInstancesList) {
            variableInstances.put(variableInstance.getName(), variableInstance);
        }
    }
}
 
Example #22
Source File: IdentityLinkCreatedHistoryJsonTransformer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void transformJson(HistoryJobEntity job, ObjectNode historicalData, CommandContext commandContext) {
    HistoricIdentityLinkService historicIdentityLinkService = CommandContextUtil.getHistoricIdentityLinkService();
    HistoricIdentityLinkEntity historicIdentityLinkEntity = historicIdentityLinkService.createHistoricIdentityLink();
    historicIdentityLinkEntity.setId(getStringFromJson(historicalData, HistoryJsonConstants.ID));
    historicIdentityLinkEntity.setGroupId(getStringFromJson(historicalData, HistoryJsonConstants.GROUP_ID));
    historicIdentityLinkEntity.setProcessInstanceId(getStringFromJson(historicalData, HistoryJsonConstants.PROCESS_INSTANCE_ID));
    historicIdentityLinkEntity.setTaskId(getStringFromJson(historicalData, HistoryJsonConstants.TASK_ID));
    historicIdentityLinkEntity.setScopeDefinitionId(getStringFromJson(historicalData, HistoryJsonConstants.SCOPE_DEFINITION_ID));
    historicIdentityLinkEntity.setScopeId(getStringFromJson(historicalData, HistoryJsonConstants.SCOPE_ID));
    historicIdentityLinkEntity.setScopeType(getStringFromJson(historicalData, HistoryJsonConstants.SCOPE_TYPE));
    historicIdentityLinkEntity.setType(getStringFromJson(historicalData, HistoryJsonConstants.IDENTITY_LINK_TYPE));
    historicIdentityLinkEntity.setUserId(getStringFromJson(historicalData, HistoryJsonConstants.USER_ID));
    historicIdentityLinkService.insertHistoricIdentityLink(historicIdentityLinkEntity, false);
}
 
Example #23
Source File: BoundaryEventActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void executeInterruptingBehavior(ExecutionEntity executionEntity, CommandContext commandContext) {
    // The destroy scope operation will look for the parent execution and
    // destroy the whole scope, and leave the boundary event using this parent execution.
    //
    // The take outgoing seq flows operation below (the non-interrupting else clause) on the other hand uses the
    // child execution to leave, which keeps the scope alive.
    // Which is what we need here.

    ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
    ExecutionEntity attachedRefScopeExecution = executionEntityManager.findById(executionEntity.getParentId());

    ExecutionEntity parentScopeExecution = null;
    ExecutionEntity currentlyExaminedExecution = executionEntityManager.findById(attachedRefScopeExecution.getParentId());
    while (currentlyExaminedExecution != null && parentScopeExecution == null) {
        if (currentlyExaminedExecution.isScope()) {
            parentScopeExecution = currentlyExaminedExecution;
        } else {
            currentlyExaminedExecution = executionEntityManager.findById(currentlyExaminedExecution.getParentId());
        }
    }

    if (parentScopeExecution == null) {
        throw new FlowableException("Programmatic error: no parent scope execution found for boundary event");
    }

    deleteChildExecutions(attachedRefScopeExecution, executionEntity, commandContext);

    // set new parent for boundary event execution
    executionEntity.setParent(parentScopeExecution);

    // TakeOutgoingSequenceFlow will not set history correct when no outgoing sequence flow for boundary event
    // (This is a theoretical case ... shouldn't use a boundary event without outgoing sequence flow ...)
    if (executionEntity.getCurrentFlowElement() instanceof FlowNode
            && ((FlowNode) executionEntity.getCurrentFlowElement()).getOutgoingFlows().isEmpty()) {
        CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityEnd(executionEntity, null);
    }

    CommandContextUtil.getAgenda(commandContext).planTakeOutgoingSequenceFlowsOperation(executionEntity, true);
}
 
Example #24
Source File: VariableCreatedHistoryJsonTransformer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void transformJson(HistoryJobEntity job, ObjectNode historicalData, CommandContext commandContext) {
    HistoricVariableService historicVariableService = CommandContextUtil.getHistoricVariableService();
    HistoricVariableInstanceEntity historicVariableInstanceEntity = historicVariableService.createHistoricVariableInstance();
    historicVariableInstanceEntity.setId(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_ID));
    historicVariableInstanceEntity.setScopeId(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_SCOPE_ID));
    historicVariableInstanceEntity.setSubScopeId(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_SUB_SCOPE_ID));
    historicVariableInstanceEntity.setScopeType(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_SCOPE_TYPE));
    historicVariableInstanceEntity.setTaskId(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_TASK_ID));
    historicVariableInstanceEntity.setExecutionId(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_EXECUTION_ID));
    historicVariableInstanceEntity.setProcessInstanceId(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_PROCESS_INSTANCE_ID));
    historicVariableInstanceEntity.setRevision(getIntegerFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_REVISION));
    historicVariableInstanceEntity.setName(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_NAME));
    
    VariableTypes variableTypes = CommandContextUtil.getCmmnEngineConfiguration().getVariableTypes();
    VariableType variableType = variableTypes.getVariableType(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_TYPE));
    
    historicVariableInstanceEntity.setVariableType(variableType);

    historicVariableInstanceEntity.setTextValue(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_TEXT_VALUE));
    historicVariableInstanceEntity.setTextValue2(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_TEXT_VALUE2));
    historicVariableInstanceEntity.setDoubleValue(getDoubleFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_DOUBLE_VALUE));
    historicVariableInstanceEntity.setLongValue(getLongFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_LONG_VALUE));
    
    String variableBytes = getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_BYTES_VALUE);
    if (StringUtils.isNotEmpty(variableBytes)) {
        historicVariableInstanceEntity.setBytes(Base64.getDecoder().decode(variableBytes));
    }
    
    Date time = getDateFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_CREATE_TIME);
    historicVariableInstanceEntity.setCreateTime(time);
    historicVariableInstanceEntity.setLastUpdatedTime(time);

    historicVariableService.insertHistoricVariableInstance(historicVariableInstanceEntity);
}
 
Example #25
Source File: ExpressionUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the collection variable name or expression given by the plan items repetition rule and returns its evaluated collection as a list.
 *
 * @param commandContext the command context to be used for evaluating the expression
 * @param planItemInstanceEntity the plan item instance to evaluate the collection variable given by its repetition rule
 * @return the collection variable value as a list of objects, might be null, if there is no repetition rule or no collection or the variable or expression
 *      evaluates to null
 */
@SuppressWarnings("unchecked")
public static Iterable<Object> evaluateRepetitionCollectionVariableValue(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
    RepetitionRule repetitionRule = getRepetitionRule(planItemInstanceEntity);
    if (repetitionRule == null || !repetitionRule.hasCollectionVariable()) {
        return null;
    }

    String collectionExpression = repetitionRule.getCollectionVariableName();

    if (!(collectionExpression.startsWith("${") || collectionExpression.startsWith("#{"))) {
        collectionExpression = "${vars:getOrDefault('" + collectionExpression + "', null)}";
    }

    Object collection = evaluateExpression(commandContext, planItemInstanceEntity, collectionExpression);
    if (collection == null) {
        return null;
    }

    if (collection instanceof Iterable) {
        return (Iterable<Object>) collection;
    }

    throw new FlowableIllegalArgumentException("Could not evaluate collection for repetition rule on plan item with id '" + planItemInstanceEntity.getId() +
        "', collection variable name '" + repetitionRule.getCollectionVariableName() + "' evaluated to '" + collection +
        "', but needs to be a collection, an iterable or an ArrayNode (JSON).");
}
 
Example #26
Source File: ProcessDefinitionQueryImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public List<ProcessDefinition> executeList(CommandContext commandContext) {
    ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);

    List<ProcessDefinition> processDefinitions = CommandContextUtil.getProcessDefinitionEntityManager(commandContext).findProcessDefinitionsByQueryCriteria(this);

    if (processDefinitions != null && processEngineConfiguration.getPerformanceSettings().isEnableLocalization() && processEngineConfiguration.getInternalProcessDefinitionLocalizationManager() != null) {
        for (ProcessDefinition processDefinition : processDefinitions) {
            processEngineConfiguration.getInternalProcessDefinitionLocalizationManager().localize(processDefinition, locale, withLocalizationFallback);
        }
    }

    return processDefinitions;
}
 
Example #27
Source File: AbstractEventHandler.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) {
    String executionId = eventSubscription.getExecutionId();
    ExecutionEntity execution = CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId);
    FlowNode currentFlowElement = (FlowNode) execution.getCurrentFlowElement();

    if (currentFlowElement == null) {
        throw new FlowableException("Error while sending signal for event subscription '" + eventSubscription.getId() + "': " + "no activity associated with event subscription");
    }

    EventSubscriptionUtil.processPayloadMap(payload, execution, currentFlowElement, commandContext);

    CommandContextUtil.getAgenda().planTriggerExecutionOperation(execution);
}
 
Example #28
Source File: GetBatchPartDocumentCmd.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public String execute(CommandContext commandContext) {
    BatchPart batchPart = CommandContextUtil.getBatchService(commandContext).getBatchPart(batchPartId);
    if (batchPart == null) {
        throw new FlowableObjectNotFoundException("No batch part found for id " + batchPartId);
    }
    
    return batchPart.getResultDocumentJson();
}
 
Example #29
Source File: PlanItemInstanceSuspendedHistoryJsonTransformer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void transformJson(HistoryJobEntity job, ObjectNode historicalData, CommandContext commandContext) {
    HistoricPlanItemInstanceEntity historicPlanItemInstanceEntity = updateCommonProperties(historicalData, commandContext);
    
    Date lastSuspendedTime = getDateFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_LAST_SUSPENDED_TIME);
    if (historicPlanItemInstanceEntity.getLastSuspendedTime() == null 
            || historicPlanItemInstanceEntity.getLastSuspendedTime().before(lastSuspendedTime)) {
        historicPlanItemInstanceEntity.setLastSuspendedTime(lastSuspendedTime);
    }
}
 
Example #30
Source File: ExecutionEntityManagerImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void deleteUserTasks(ExecutionEntity executionEntity, String deleteReason, CommandContext commandContext, 
        boolean enableExecutionRelationshipCounts, boolean eventDispatcherEnabled) {
    if (!enableExecutionRelationshipCounts ||
            (enableExecutionRelationshipCounts && ((CountingExecutionEntity) executionEntity).getTaskCount() > 0)) {
        TaskHelper.deleteTasksForExecution(executionEntity, 
                CommandContextUtil.getTaskService(commandContext).findTasksByExecutionId(executionEntity.getId()), deleteReason);
    }
}