package com.flow.flowable.cmd; import org.flowable.bpmn.model.MultiInstanceLoopCharacteristics; import org.flowable.common.engine.api.FlowableException; import org.flowable.common.engine.impl.interceptor.Command; import org.flowable.common.engine.impl.interceptor.CommandContext; import org.flowable.engine.ManagementService; import org.flowable.engine.RuntimeService; import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.flowable.engine.impl.util.CommandContextUtil; import org.flowable.engine.runtime.Execution; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public class AddTaskExecutionCmd implements Command { protected String processInstanceId; protected String activityId; protected String assignee; public AddTaskExecutionCmd(String processInstanceId, String activityId, String assignee) { this.processInstanceId = processInstanceId; this.activityId = activityId; this.assignee = assignee; } @Override public Void execute(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); ManagementService managementService = processEngineConfiguration.getManagementService(); MultiInstanceLoopCharacteristics loopCharacteristics = managementService.executeCommand(new GetLoopCharacteristicsCmd(this.processInstanceId, this.activityId)); if (Objects.nonNull(loopCharacteristics)) { RuntimeService runtimeService = processEngineConfiguration.getRuntimeService(); String collectionName = loopCharacteristics.getInputDataItem(); collectionName = collectionName.substring(2, collectionName.length() - 1); List assigneeList = runtimeService.getVariable( this.processInstanceId, collectionName, List.class ); if (Objects.nonNull(assigneeList) && assigneeList.contains(this.assignee)) { throw new FlowableException("加签用户已存在"); } assigneeList.add(this.assignee); runtimeService.setVariable(this.processInstanceId, collectionName, assigneeList); Execution miExecution = managementService.executeCommand(new GetMultiInstanceRootExecutionCmd(this.processInstanceId, this.activityId)); Integer nrOfInstances = runtimeService.getVariableLocal(miExecution.getId(), "nrOfInstances", Integer.class); runtimeService.setVariableLocal(miExecution.getId(), "nrOfInstances", nrOfInstances + 1); if (!loopCharacteristics.isSequential()) { Integer nrOfActiveInstances = runtimeService.getVariableLocal(miExecution.getId(), "nrOfActiveInstances", Integer.class); runtimeService.setVariableLocal(miExecution.getId(), "nrOfActiveInstances", nrOfActiveInstances + 1); Map executionVariables = new HashMap<>(); executionVariables.put(loopCharacteristics.getElementVariable(), this.assignee); runtimeService.addMultiInstanceExecution( this.activityId, this.processInstanceId, executionVariables ); } } else { throw new FlowableException("当前节点不支持加签"); } return null; } }