protected void setVariable( Execution execution, String name, Object value, RestVariable.RestVariableScope scope, boolean isNew) { // Create can only be done on new variables. Existing variables should be updated using PUT boolean hasVariable = hasVariableOnScope(execution, name, scope); if (isNew && hasVariable) { throw new ActivitiException( "Variable '" + name + "' is already present on execution '" + execution.getId() + "'."); } if (!isNew && !hasVariable) { throw new ActivitiObjectNotFoundException( "Execution '" + execution.getId() + "' doesn't have a variable with name: '" + name + "'.", null); } RuntimeService runtimeService = BPMNOSGIService.getRumtimeService(); if (scope == RestVariable.RestVariableScope.LOCAL) { runtimeService.setVariableLocal(execution.getId(), name, value); } else { if (execution.getParentId() != null) { runtimeService.setVariable(execution.getParentId(), name, value); } else { runtimeService.setVariable(execution.getId(), name, value); } } }
@Deployment( resources = { "org/activiti/examples/bpmn/event/timer/BoundaryTimerEventTest.testInterruptingTimerDuration.bpmn" }) @Test public void testInterruptingTimerDuration() { // Start process instance RuntimeService runtimeService = activitiRule.getRuntimeService(); ProcessInstance pi = runtimeService.startProcessInstanceByKey("escalationExample"); // There should be one task, with a timer : first line support TaskService taskService = activitiRule.getTaskService(); Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult(); assertEquals("First line support", task.getName()); // Manually execute the job ManagementService managementService = activitiRule.getManagementService(); Job timer = managementService.createJobQuery().singleResult(); managementService.executeJob(timer.getId()); // The timer has fired, and the second task (secondlinesupport) now exists task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult(); assertEquals("Second line support", task.getName()); }
protected void addGlobalVariables( Execution execution, int variableType, Map<String, RestVariable> variableMap, UriInfo uriInfo) { RuntimeService runtimeService = BPMNOSGIService.getRumtimeService(); Map<String, Object> rawVariables = runtimeService.getVariables(execution.getId()); List<RestVariable> globalVariables = new RestResponseFactory() .createRestVariables( rawVariables, execution.getId(), variableType, RestVariable.RestVariableScope.GLOBAL, uriInfo.getBaseUri().toString()); // Overlay global variables over local ones. In case they are present the values are not // overridden, // since local variables get precedence over global ones at all times. for (RestVariable var : globalVariables) { if (!variableMap.containsKey(var.getName())) { variableMap.put(var.getName(), var); } } }
/** @param args */ public static void main(String[] args) { // 创建流程引擎 ProcessEngine engine = ProcessEngines.getDefaultProcessEngine(); // 得到流程存储服务组件 RepositoryService repositoryService = engine.getRepositoryService(); // 得到运行时服务组件 RuntimeService runtimeService = engine.getRuntimeService(); // 获取流程任务组件 TaskService taskService = engine.getTaskService(); // 部署流程文件 repositoryService .createDeployment() .addClasspathResource("bpmn11.5/SignalBoundaryEvent.bpmn") .deploy(); // 启动2个流程实例 ProcessInstance pi1 = runtimeService.startProcessInstanceByKey("sbProcess"); ProcessInstance pi2 = runtimeService.startProcessInstanceByKey("sbProcess"); // 查找第一个流程实例中签订合同的任务 Task pi1Task = taskService.createTaskQuery().processInstanceId(pi1.getId()).singleResult(); taskService.complete(pi1Task.getId()); // 查找第二个流程实例中签订合同的任务 Task pi2Task = taskService.createTaskQuery().processInstanceId(pi2.getId()).singleResult(); taskService.complete(pi2Task.getId()); // 此时执行流到达确认合同任务,发送一次信号 runtimeService.signalEventReceived("contactChangeSignal"); // 查询全部的任务 List<Task> tasks = taskService.createTaskQuery().list(); // 输出结果 for (Task task : tasks) { System.out.println(task.getProcessInstanceId() + "---" + task.getName()); } }
/** 流程实例. */ public String listProcessInstances() { RuntimeService runtimeService = processEngine.getRuntimeService(); processInstances = runtimeService.createProcessInstanceQuery().list(); return "listProcessInstances"; }
@Override protected Object doExecute() throws Exception { ProcessEngine processEngine = this.getProcessEngine(); if (processEngine == null) { out().println("Process Engine NOT Found!"); return null; } RuntimeService runtimeService = processEngine.getRuntimeService(); if (this.instanceIDs != null && this.instanceIDs.length > 0) { for (String instanceID : instanceIDs) { runtimeService.deleteProcessInstance(instanceID, "Forcefully terminating the instance"); out().printf("Process instance %s terminated\n", instanceID); } return null; } if (!killAll) { out().println("Process instance IDs required or use the command with -a or --all option"); return null; } else { out().println("Signalling all executions in all active process instances..."); List<ProcessInstance> piList = runtimeService.createProcessInstanceQuery().orderByProcessInstanceId().asc().list(); for (ProcessInstance pi : piList) { String instanceID = pi.getProcessInstanceId(); runtimeService.deleteProcessInstance(instanceID, "Forcefully terminating the instance"); out().printf("Process instance %s terminated\n", instanceID); } } return null; }
/** * 获取流程详细及工作流参数 * * @param id */ @SuppressWarnings("unchecked") public Leave get(String id) { Leave leave = leaveDao.get(id); Map<String, Object> variables = null; HistoricProcessInstance historicProcessInstance = historyService .createHistoricProcessInstanceQuery() .processInstanceId(leave.getProcessInstanceId()) .singleResult(); if (historicProcessInstance != null) { variables = Collections3.extractToMap( historyService .createHistoricVariableInstanceQuery() .processInstanceId(historicProcessInstance.getId()) .list(), "variableName", "value"); } else { variables = runtimeService.getVariables( runtimeService .createProcessInstanceQuery() .processInstanceId(leave.getProcessInstanceId()) .active() .singleResult() .getId()); } leave.setVariables(variables); return leave; }
@Test public void BGC_transfer() throws Exception { fakeSparService.add(OTHER_PERSONAL_IDENTIFIER, ADDRESS); Map<String, Object> properties = new HashMap<>(); properties.put("personalIdentifier", OTHER_PERSONAL_IDENTIFIER); String ocr = "5450897"; properties.put("ocr", ocr); runtimeService.startProcessInstanceByMessage("create-insurance", ocr, properties); when_all_jobs_within_X_days_are_executed(10); Execution execution = runtimeService .createExecutionQuery() .messageEventSubscriptionName("bgc") .processVariableValueEquals("ocr", ocr) .singleResult(); assertThat(execution, notNullValue()); Map<String, Object> eventProperties = new HashMap<String, Object>(); properties.put("amount", 56000); runtimeService.messageEventReceived("bgc", execution.getId(), eventProperties); }
/*----------------------------------------------------------------------------------------------------*/ private void setRepTime(Execution execution) { Integer repTime = (Integer) runtimeService.getVariable(execution.getId(), "repTime"); if (repTime == null) { runtimeService.setVariable(execution.getId(), "repTime", 1); } else { runtimeService.setVariable(execution.getId(), "repTime", ++repTime); } }
public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); RuntimeService runtimeService = (RuntimeService) applicationContext.getBean("runtimeService"); runtimeService.startProcessInstanceByKey("helloWorldProcess"); }
protected Execution getExecutionFromRequest(String executionId) { RuntimeService runtimeService = BPMNOSGIService.getRumtimeService(); Execution execution = runtimeService.createExecutionQuery().executionId(executionId).singleResult(); if (execution == null) { throw new ActivitiObjectNotFoundException( "Could not find an execution with id '" + executionId + "'.", Execution.class); } return execution; }
private void createNewProcess() { processInstance = runtimeService.startProcessInstanceByKey("myProcess"); assertNotNull(processInstance.getId()); identityService = processEngine.getIdentityService(); taskService = processEngine.getTaskService(); pid = processInstance.getProcessInstanceId(); formService = processEngine.getFormService(); runtimeService.setVariable(pid, "mailvar1", "value1"); runtimeService.setVariable(pid, "mailvar2", "value2"); }
@Override public void deleteProcessInstance(Long dossierId) { ProcessInstance pi = runtimeService .createProcessInstanceQuery() .processInstanceBusinessKey(dossierId.toString()) .singleResult(); if (pi != null) { runtimeService.deleteProcessInstance(pi.getProcessInstanceId(), "delete from back office"); } }
public RestVariable getVariableFromRequest( String taskId, String variableName, String scope, boolean includeBinary) { boolean variableFound = false; Object value = null; RestVariableScope variableScope = RestVariable.getScopeFromString(scope); if (variableScope == null) { // First, check local variables (which have precedence when no scope is supplied) if (taskService.hasVariableLocal(taskId, variableName)) { value = taskService.getVariableLocal(taskId, variableName); variableScope = RestVariableScope.LOCAL; variableFound = true; } else { // Revert to execution-variable when not present local on the task Task task = taskService.createTaskQuery().taskId(taskId).singleResult(); if (task.getExecutionId() != null && runtimeService.hasVariable(task.getExecutionId(), variableName)) { value = runtimeService.getVariable(task.getExecutionId(), variableName); variableScope = RestVariableScope.GLOBAL; variableFound = true; } } } else if (variableScope == RestVariableScope.GLOBAL) { Task task = taskService.createTaskQuery().taskId(taskId).singleResult(); if (task.getExecutionId() != null && runtimeService.hasVariable(task.getExecutionId(), variableName)) { value = runtimeService.getVariable(task.getExecutionId(), variableName); variableFound = true; } } else if (variableScope == RestVariableScope.LOCAL) { if (taskService.hasVariableLocal(taskId, variableName)) { value = taskService.getVariableLocal(taskId, variableName); variableFound = true; } } if (!variableFound) { throw new ActivitiObjectNotFoundException( "Task '" + taskId + "' doesn't have a variable with name: '" + variableName + "'.", VariableInstanceEntity.class); } else { return restResponseFactory.createRestVariable( variableName, value, variableScope, taskId, RestResponseFactory.VARIABLE_TASK, includeBinary); } }
@Test public void testExecutionQuery() { // Given RuntimeService runtimeService = mock(RuntimeService.class); ExecutionQuery executionQuery = mock(ExecutionQuery.class); when(processEngine.getRuntimeService()).thenReturn(runtimeService); when(runtimeService.createExecutionQuery()).thenReturn(executionQuery); // When ExecutionQuery createdQuery = executionQuery(); // Then assertThat(createdQuery).isNotNull().isSameAs(executionQuery); verify(runtimeService, times(1)).createExecutionQuery(); verifyNoMoreInteractions(runtimeService); }
@Test public void testProcessInstanceQuery() { // Given RuntimeService runtimeService = mock(RuntimeService.class); ProcessInstanceQuery processInstanceQuery = mock(ProcessInstanceQuery.class); when(processEngine.getRuntimeService()).thenReturn(runtimeService); when(runtimeService.createProcessInstanceQuery()).thenReturn(processInstanceQuery); // When ProcessInstanceQuery createdQuery = processInstanceQuery(); // Then assertThat(createdQuery).isNotNull().isSameAs(processInstanceQuery); verify(runtimeService, times(1)).createProcessInstanceQuery(); verifyNoMoreInteractions(runtimeService); }
/** 流程实例. */ public Page findProcessInstances(String tenantId, Page page) { RuntimeService runtimeService = processEngine.getRuntimeService(); long count = runtimeService.createProcessInstanceQuery().processInstanceTenantId(tenantId).count(); List<ProcessInstance> processInstances = runtimeService .createProcessInstanceQuery() .processInstanceTenantId(tenantId) .listPage((int) page.getStart(), page.getPageSize()); page.setResult(processInstances); page.setTotalCount(count); return page; }
@Override public void costWorkFlowStart(CostApprovalEntity costApproval, HttpServletRequest request) { // 由session取到登录用户id String applyUserId = ResourceUtil.getSessionUserName().getId(); this.save(costApproval); String processKey = request.getParameter("processKey"); if (!StringUtil.isNotEmpty(processKey)) { WorkFlowSetEntity workFlowSet = this.findUniqueByProperty( WorkFlowSetEntity.class, "entityName", costApproval.getClass().getSimpleName()); processKey = workFlowSet.getProcessKey(); } String businessKey = costApproval.getId().toString(); ProcessInstance processInstance = null; // 用来设置启动流程的人员ID,引擎会自动把用户ID保存到activiti:initiator中 identityService.setAuthenticatedUserId(applyUserId); Map<String, Object> variables = new HashMap<String, Object>(); variables.put(ProcessConstantsUtil.getApplyUserId(), applyUserId); processInstance = runtimeService.startProcessInstanceByKey(processKey, businessKey, variables); String processInstanceId = processInstance.getId(); costApproval.setProcessinstanceId(processInstanceId); // 获取并执行当前流程实例的下一步任务 Task task = null; TaskQuery query = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).active(); task = query.singleResult(); variables.put( ProcessConstantsUtil.getDeptLeaderId(), ResourceUtil.getSessionUserName().getCurrentDepart().getDepartManager().getId()); taskService.complete(task.getId(), variables); }
public StreamResource buildStreamResource( ProcessInstance processInstance, RepositoryService repositoryService, RuntimeService runtimeService) { StreamResource imageResource = null; ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService) .getDeployedProcessDefinition(processInstance.getProcessDefinitionId()); if (processDefinition != null && processDefinition.isGraphicalNotationDefined()) { InputStream definitionImageStream = ProcessDiagramGenerator.generateDiagram( processDefinition, "png", runtimeService.getActiveActivityIds(processInstance.getId())); StreamSource streamSource = new InputStreamStreamSource(definitionImageStream); // Create image name String imageExtension = extractImageExtension(processDefinition.getDiagramResourceName()); String fileName = processInstance.getId() + UUID.randomUUID() + "." + imageExtension; imageResource = new StreamResource(streamSource, fileName, ExplorerApp.get()); } return imageResource; }
private String startAndComplete() { RuntimeService runtimeService = activitiRule.getRuntimeService(); Map<String, Object> variableMap = new HashMap<String, Object>(); variableMap.put("isbn", "123456"); String processInstanceID = runtimeService.startProcessInstanceByKey("bookorder", variableMap).getId(); TaskService taskService = activitiRule.getTaskService(); Task task = taskService.createTaskQuery().taskCandidateGroup("sales").singleResult(); variableMap = new HashMap<String, Object>(); variableMap.put("extraInfo", "Extra information"); variableMap.put("isbn", "654321"); taskService.complete(task.getId(), variableMap); return processInstanceID; }
protected void setVariable( Task task, String name, Object value, RestVariableScope scope, boolean isNew) { // Create can only be done on new variables. Existing variables should be updated using PUT boolean hasVariable = hasVariableOnScope(task, name, scope); if (isNew && hasVariable) { throw new ActivitiException( "Variable '" + name + "' is already present on task '" + task.getId() + "'."); } if (!isNew && !hasVariable) { throw new ActivitiObjectNotFoundException( "Task '" + task.getId() + "' doesn't have a variable with name: '" + name + "'.", null); } if (scope == RestVariableScope.LOCAL) { taskService.setVariableLocal(task.getId(), name, value); } else { if (task.getExecutionId() != null) { // Explicitly set on execution, setting non-local variable on task will override // local-variable if exists runtimeService.setVariable(task.getExecutionId(), name, value); } else { // Standalone task, no global variables possible throw new ActivitiIllegalArgumentException( "Cannot set global variable '" + name + "' on task '" + task.getId() + "', task is not part of process."); } } }
/** * easyui 运行中流程列表数据 * * @param request * @param response * @param dataGrid */ @RequestMapping(params = "runningProcessDataGrid") public void runningProcessDataGrid( HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { /* * List<HistoricProcessInstance> historicProcessInstances = * historyService .createHistoricProcessInstanceQuery() * .unfinished().list(); */ ProcessInstanceQuery processInstanceQuery = runtimeService.createProcessInstanceQuery(); List<ProcessInstance> list = processInstanceQuery.list(); StringBuffer rows = new StringBuffer(); for (ProcessInstance hi : list) { rows.append( "{'id':" + hi.getId() + ",'processDefinitionId':'" + hi.getProcessDefinitionId() + "','processInstanceId':'" + hi.getProcessInstanceId() + "','activityId':'" + hi.getActivityId() + "'},"); } String rowStr = StringUtils.substringBeforeLast(rows.toString(), ","); JSONObject jObject = JSONObject.fromObject("{'total':" + list.size() + ",'rows':[" + rowStr + "]}"); responseDatagrid(response, jObject); }
@Test public void person_missing_in_SPAR() throws Exception { Optional<SparResult> existing = fakeSparService.findBy(MISSING_PERSONAL_IDENTIFIER); assertThat(existing, isAbsent()); Map<String, Object> properties = new HashMap<>(); properties.put("personalIdentifier", MISSING_PERSONAL_IDENTIFIER); properties.put("ocr", OCR); runtimeService.startProcessInstanceByMessage("create-insurance", OCR, properties); when_all_jobs_within_X_days_are_executed(10); List<Message> messages = outbox.receivedAfter(Instant.now().minus(Duration.ofHours(1))); assertThat(messages, hasSize(1)); String payload = messages.get(0).getPayload(); assertThat(payload, isJson(withProperty("messageType", equalTo("\"person-does-not-exist\"")))); assertThat( payload, isJson( withProperty( "personalIdentifier", equalTo("\"" + MISSING_PERSONAL_IDENTIFIER.getValue() + "\"")))); assertThat(payload, isJson(withProperty("ocr", equalTo("\"" + OCR + "\"")))); }
/** * 跳转到任务执行页面 * * @param request * @return */ @RequestMapping(value = "/form.do") public String from( HttpServletRequest request, @RequestParam("taskId") String taskId, Model model) { List<Task> taskList = taskService.createTaskQuery().taskId(taskId).list(); Task task = taskList.get(0); // 获取表单数据 TaskFormData tfd = formService.getTaskFormData(taskId); List<FormProperty> fpList = tfd.getFormProperties(); Map map = runtimeService.getVariables(task.getExecutionId()); List<ActivityImpl> activityList = new ArrayList<ActivityImpl>(); try { // 查找所有可驳回的节点 activityList = processExtensionService.findBackActivity(taskId); // model.addAttribute("activityList",activityList); } catch (Exception e) { e.printStackTrace(); } // model.addAttribute("task",task); // model.addAttribute("fpList",fpList); // model.addAttribute("map",map); // model.addAttribute("taskId",taskId); request.setAttribute("task", task); request.setAttribute("fpList", fpList); request.setAttribute("map", map); request.setAttribute("taskId", taskId); request.setAttribute("activityList", activityList); return "/simple/form"; }
@Override @Transactional(readOnly = false) public Defect reviewDefect(Long defectId, String assignedTo) { Defect existingDefect = defectRepository.getById(defectId); String existingAsignee = existingDefect.getAssignedTo(); existingDefect.setStatus(DefectStatus.ASSIGNED); existingDefect.setAssignedTo(assignedTo); defectRepository.update(existingDefect); for (Task task : taskService.createTaskQuery().taskAssignee(existingAsignee).list()) { if (task.getName().equalsIgnoreCase("reviewDefect")) { Long taskDefectId = (Long) runtimeService.getVariable(task.getExecutionId(), "defectId"); if (taskDefectId.equals(defectId)) { taskService.complete(task.getId()); logger.info("Reviewed Defect: " + task.getName() + " Defect Id: " + taskDefectId); } } } logger.info( "Task assigned to: " + existingAsignee + " : " + taskService.createTaskQuery().taskAssignee(existingAsignee)); logger.info( "Task assigned to: " + assignedTo + " : " + taskService.createTaskQuery().taskAssignee(assignedTo)); return existingDefect; }
@Test @Rollback(value = false) public void testDeploy() throws Exception { String path = ProcessDefManagerTest.class.getClassLoader().getResource("bpmnsub.xml").getPath(); String value = FileUtils.readFileToString(new File(path)); Deployment deployment = repositoryService .createDeployment() .addString("sub-model.bpmn", value) .name("子流程") .category("行政") .enableDuplicateFiltering() .deploy(); // // // 4. Start a process instance Map<String, Object> map = new HashMap<String, Object>(); // map.put("signAssignee", Arrays.asList("hr", "dep", "user")); identityService.setAuthenticatedUserId("dynamic"); ProcessDefinition definition = repositoryService .createProcessDefinitionQuery() .deploymentId(deployment.getId()) .singleResult(); ProcessInstance processInstance = runtimeService.startProcessInstanceById(definition.getId(), map); int i = 0; System.out.println(processInstance.getId()); }
/** * 读取资源,通过部署ID * * @param processDefinitionId 流程定义ID * @param processInstanceId 流程实例ID * @param resourceType 资源类型(xml|image) */ public InputStream resourceRead(String procDefId, String proInsId, String resType) throws Exception { if (StringUtils.isBlank(procDefId)) { ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(proInsId).singleResult(); procDefId = processInstance.getProcessDefinitionId(); } ProcessDefinition processDefinition = repositoryService .createProcessDefinitionQuery() .processDefinitionId(procDefId) .singleResult(); String resourceName = ""; if (resType.equals("image")) { resourceName = processDefinition.getDiagramResourceName(); } else if (resType.equals("xml")) { resourceName = processDefinition.getResourceName(); } InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName); return resourceAsStream; }
/** * 启动流程 * * @param entity */ @Transactional(readOnly = false) public void save(Leave leave, Map<String, Object> variables) { // 保存业务数据 if (StringUtils.isBlank(leave.getId())) { leave.preInsert(); leaveDao.insert(leave); } else { leave.preUpdate(); leaveDao.update(leave); } logger.debug("save entity: {}", leave); // 用来设置启动流程的人员ID,引擎会自动把用户ID保存到activiti:initiator中 identityService.setAuthenticatedUserId(leave.getCurrentUser().getLoginName()); // 启动流程 String businessKey = leave.getId().toString(); variables.put("type", "leave"); variables.put("busId", businessKey); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(ActUtils.PD_LEAVE[0], businessKey, variables); leave.setProcessInstance(processInstance); // 更新流程实例ID leave.setProcessInstanceId(processInstance.getId()); leaveDao.updateProcessInstanceId(leave); logger.debug( "start process of {key={}, bkey={}, pid={}, variables={}}", new Object[] {ActUtils.PD_LEAVE[0], businessKey, processInstance.getId(), variables}); }
@Test public void test() { ProcessEngine engine = ProcessEngines.getDefaultProcessEngine(); RepositoryService repositoryService = engine.getRepositoryService(); RuntimeService runtimeService = engine.getRuntimeService(); TaskService taskService = engine.getTaskService(); repositoryService.createDeployment().addClasspathResource("bpmn/first.bpmn").deploy(); runtimeService.startProcessInstanceByKey("process1"); Task task = taskService.createTaskQuery().singleResult(); System.out.println("第一个任务完成前,当前任务名称:" + task.getName()); taskService.complete(task.getId()); task = taskService.createTaskQuery().singleResult(); System.out.println("第二个任务完成前,当前任务名称:" + task.getName()); taskService.complete(task.getId()); task = taskService.createTaskQuery().singleResult(); System.out.println("流程结束后,查找任务:" + task); }
protected boolean hasVariableOnScope( Execution execution, String variableName, RestVariable.RestVariableScope scope) { boolean variableFound = false; RuntimeService runtimeService = BPMNOSGIService.getRumtimeService(); if (scope == RestVariable.RestVariableScope.GLOBAL) { if (execution.getParentId() != null && runtimeService.hasVariable(execution.getParentId(), variableName)) { variableFound = true; } } else if (scope == RestVariable.RestVariableScope.LOCAL) { if (runtimeService.hasVariableLocal(execution.getId(), variableName)) { variableFound = true; } } return variableFound; }