Java Code Examples for org.activiti.engine.runtime.ProcessInstance

The following examples show how to use org.activiti.engine.runtime.ProcessInstance. These examples are extracted from open source projects. 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 Project: activiti6-boot2   Source File: ExpressionManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment
public void testAuthenticatedUserIdAvailable() {
  try {
    // Setup authentication
    Authentication.setAuthenticatedUserId("frederik");
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testAuthenticatedUserIdAvailableProcess");
    
    // Check if the variable that has been set in service-task is the authenticated user
    String value = (String) runtimeService.getVariable(processInstance.getId(), "theUser");
    assertNotNull(value);
    assertEquals("frederik", value);
  } finally {
    // Cleanup
    Authentication.setAuthenticatedUserId(null);
  }
}
 
Example 2
Source Project: activiti6-boot2   Source File: MultiInstanceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { "org/activiti5/engine/test/bpmn/multiinstance/MultiInstanceTest.testNestedMultiInstanceTasks.bpmn20.xml"})
public void testNestedMultiInstanceTasks() {
  List<String> processes = Arrays.asList("process A", "process B");
  List<String> assignees = Arrays.asList("kermit", "gonzo");
  Map<String, Object> variableMap = new HashMap<String, Object>();
  variableMap.put("subProcesses", processes);
  variableMap.put("assignees", assignees);

  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("miNestedMultiInstanceTasks", variableMap);

  List<Task> tasks = taskService.createTaskQuery().list();
  assertEquals(processes.size() * assignees.size(), tasks.size());

  for (Task t : tasks) {
    taskService.complete(t.getId());
  }

  List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().processDefinitionKey("miNestedMultiInstanceTasks").list();
  assertEquals(0, processInstances.size());
  assertProcessEnded(processInstance.getId());
}
 
Example 3
Source Project: activiti6-boot2   Source File: Activiti6Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@org.activiti.engine.test.Deployment
public void testLongServiceTaskLoop() {
  int maxCount = 3210; // You can make this as big as you want (as long as
                       // it still fits within transaction timeouts). Go
                       // on, try it!
  Map<String, Object> vars = new HashMap<String, Object>();
  vars.put("counter", new Integer(0));
  vars.put("maxCount", maxCount);
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testLongServiceTaskLoop", vars);
  assertNotNull(processInstance);
  assertTrue(processInstance.isEnded());

  assertEquals(maxCount, CountingServiceTaskTestDelegate.CALL_COUNT.get());
  assertEquals(0, runtimeService.createExecutionQuery().count());

  if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {
    assertEquals(maxCount, historyService.createHistoricActivityInstanceQuery()
        .processInstanceId(processInstance.getId()).activityId("serviceTask").count());
  }
}
 
Example 4
Source Project: activiti6-boot2   Source File: TerminateEndEventTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment(resources={
  "org/activiti5/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateInCallActivity.bpmn", 
  "org/activiti5/engine/test/bpmn/event/end/TerminateEndEventTest.subProcessTerminate.bpmn" 
})
public void testTerminateInCallActivity() throws Exception {
  ProcessInstance pi = runtimeService.startProcessInstanceByKey("terminateEndEventExample");

  // should terminate the called process and continue the parent
  long executionEntities = runtimeService.createExecutionQuery().count();
  assertEquals(1, executionEntities);
  
  Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).taskDefinitionKey("preNormalEnd").singleResult();
  taskService.complete(task.getId());
  
  assertProcessEnded(pi.getId());
}
 
Example 5
Source Project: activiti6-boot2   Source File: TaskQueryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { "org/activiti/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml" })
public void testTaskDueDateOr() throws Exception {
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
  Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();

  // Set due-date on task
  Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
  task.setDueDate(dueDate);
  taskService.saveTask(task);

  assertEquals(1, taskService.createTaskQuery().processInstanceId(processInstance.getId()).or().taskId("invalid").taskDueDate(dueDate).count());

  Calendar otherDate = Calendar.getInstance();
  otherDate.add(Calendar.YEAR, 1);
  assertEquals(0, taskService.createTaskQuery().processInstanceId(processInstance.getId()).or().taskId("invalid").taskDueDate(otherDate.getTime()).count());

  Calendar priorDate = Calendar.getInstance();
  priorDate.setTime(dueDate);
  priorDate.roll(Calendar.YEAR, -1);

  assertEquals(1, taskService.createTaskQuery().processInstanceId(processInstance.getId()).or().taskId("invalid").taskDueAfter(priorDate.getTime()).count());

  assertEquals(1, taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskDueBefore(otherDate.getTime()).count());
}
 
Example 6
Source Project: activiti6-boot2   Source File: TaskServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { "org/activiti5/engine/test/api/oneTaskProcess.bpmn20.xml" })
public void testTaskAttachmentWithProcessInstanceId() {
  if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {
    
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
    
    String processInstanceId = processInstance.getId();
    taskService.createAttachment("web page", null, processInstanceId, "weatherforcast", "temperatures and more", "http://weather.com");
    Attachment attachment = taskService.getProcessInstanceAttachments(processInstanceId).get(0);
    assertEquals("weatherforcast", attachment.getName());
    assertEquals("temperatures and more", attachment.getDescription());
    assertEquals("web page", attachment.getType());
    assertEquals(processInstanceId, attachment.getProcessInstanceId());
    assertNull(attachment.getTaskId());
    assertEquals("http://weather.com", attachment.getUrl());
    assertNull(taskService.getAttachmentContent(attachment.getId()));
    
    // Finally, clean up
    taskService.deleteAttachment(attachment.getId());
    
    // TODO: Bad API design. Need to fix attachment/comment properly
    ((TaskServiceImpl) taskService).deleteComments(null, processInstanceId);
  }
}
 
Example 7
@Deployment
public void testOnCompleteCommitted() {
  CurrentTaskTransactionDependentTaskListener.clear();

  Map<String, Object> variables = new HashMap<>();
  variables.put("serviceTask1", false);
  variables.put("serviceTask2", false);

  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("taskListenersOnCompleteCommitted", variables);

  // task 1 has committed listener
  Task task = taskService.createTaskQuery().singleResult();
  taskService.complete(task.getId());

  // task 2 has rolled-back listener
  task = taskService.createTaskQuery().singleResult();
  taskService.complete(task.getId());

  List<CurrentTaskTransactionDependentTaskListener.CurrentTask> currentTasks = CurrentTaskTransactionDependentTaskListener.getCurrentTasks();
  assertEquals(1, currentTasks.size());

  assertEquals("usertask1", currentTasks.get(0).getTaskId());
  assertEquals("User Task 1", currentTasks.get(0).getTaskName());
  assertEquals(processInstance.getId(), currentTasks.get(0).getProcessInstanceId());
  assertNotNull(currentTasks.get(0).getProcessInstanceId());
}
 
Example 8
Source Project: activiti6-boot2   Source File: CamelVariableBodyMapTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { "process/HelloCamelBodyMap.bpmn20.xml" })
public void testCamelBody() throws Exception {
  Map<String, Object> varMap = new HashMap<String, Object>();
  varMap.put("camelBody", "hello world");
  service1.expectedBodiesReceived(varMap);
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("HelloCamel", varMap);
  // Ensure that the variable is equal to the expected value.
  assertEquals("hello world", runtimeService.getVariable(processInstance.getId(), "camelBody"));
  service1.assertIsSatisfied();

  Task task = taskService.createTaskQuery().singleResult();

  // Ensure that the name of the task is correct.
  assertEquals("Hello Task", task.getName());

  // Complete the task.
  taskService.complete(task.getId());
}
 
Example 9
Source Project: activiti6-boot2   Source File: ActivitiProducer.java    License: Apache License 2.0 6 votes vote down vote up
protected void copyResultToCamel(Exchange exchange, ProcessInstance pi) {
  exchange.setProperty(PROCESS_ID_PROPERTY, pi.getProcessInstanceId());

  Map<String, Object> returnVars = getActivitiEndpoint().getReturnVarMap();

  if (returnVars != null && returnVars.size() > 0) {

    Map<String, Object> processVariables = null;
    if (repositoryService.isActiviti5ProcessDefinition(pi.getProcessDefinitionId())) {
      Activiti5CompatibilityHandler activiti5CompatibilityHandler = Activiti5Util.getActiviti5CompatibilityHandler(); 
      processVariables = activiti5CompatibilityHandler.getVariables(pi);
    } else {
      processVariables = ((ExecutionEntity) pi).getVariables();
    }
    
    if (processVariables != null) {
      for (String variableName : returnVars.keySet()) {
        if (processVariables.containsKey(variableName)) {
          exchange.setProperty(variableName, processVariables.get(variableName));
        }
      }
    }
  }
}
 
Example 10
Source Project: activiti6-boot2   Source File: RuntimeServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment(resources={
"org/activiti5/engine/test/api/oneSubProcess.bpmn20.xml"})
public void testRemoveVariableInParentScope() {
  Map<String, Object> vars = new HashMap<String, Object>();
  vars.put("variable1", "value1");
  vars.put("variable2", "value2");
  
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startSimpleSubProcess", vars);
  Task currentTask = taskService.createTaskQuery().singleResult();
  
  runtimeService.removeVariable(currentTask.getExecutionId(), "variable1");

  assertNull(runtimeService.getVariable(processInstance.getId(), "variable1"));
  assertEquals("value2", runtimeService.getVariable(processInstance.getId(), "variable2"));
  
  checkHistoricVariableUpdateEntity("variable1", processInstance.getId());
}
 
Example 11
Source Project: activiti6-boot2   Source File: ProcessInstanceQueryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { "org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml" })
public void testQueryAllVariableTypes() throws Exception {
  Map<String, Object> vars = new HashMap<String, Object>();
  vars.put("nullVar", null);
  vars.put("stringVar", "string");
  vars.put("longVar", 10L);
  vars.put("doubleVar", 1.2);
  vars.put("integerVar", 1234);
  vars.put("booleanVar", true);
  vars.put("shortVar", (short) 123);

  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars);

  ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery().variableValueEquals("nullVar", null).variableValueEquals("stringVar", "string").variableValueEquals("longVar", 10L)
      .variableValueEquals("doubleVar", 1.2).variableValueEquals("integerVar", 1234).variableValueEquals("booleanVar", true).variableValueEquals("shortVar", (short) 123);

  List<ProcessInstance> processInstances = query.list();
  assertNotNull(processInstances);
  assertEquals(1, processInstances.size());
  assertEquals(processInstance.getId(), processInstances.get(0).getId());

  runtimeService.deleteProcessInstance(processInstance.getId(), "test");
}
 
Example 12
Source Project: activiti6-boot2   Source File: DynamicUserTaskTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment(resources={"org/activiti5/engine/test/bpmn/usertask/DynamicUserTaskTest.assignment.bpmn20.xml"})
public void testChangeAssignee() {
  // first test without changing the form key
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("dynamicUserTask");
  String processDefinitionId = processInstance.getProcessDefinitionId();
  
  Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
  assertEquals("test", task.getAssignee());
  taskService.complete(task.getId());
  
  assertProcessEnded(processInstance.getId());
  
  // now test with changing the form key
  ObjectNode infoNode = dynamicBpmnService.changeUserTaskAssignee("task1", "test2");
  dynamicBpmnService.saveProcessDefinitionInfo(processDefinitionId, infoNode);
  
  processInstance = runtimeService.startProcessInstanceByKey("dynamicUserTask");
  
  task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
  assertEquals("test2", task.getAssignee());
  taskService.complete(task.getId());
  
  assertProcessEnded(processInstance.getId());
}
 
Example 13
Source Project: activiti6-boot2   Source File: MultiInstanceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment
public void testAct901() {

  Date startTime = processEngineConfiguration.getClock().getCurrentTime();

  ProcessInstance pi = runtimeService.startProcessInstanceByKey("multiInstanceSubProcess");
  List<Task> tasks = taskService.createTaskQuery().processInstanceId(pi.getId()).orderByTaskName().asc().list();

  processEngineConfiguration.getClock().setCurrentTime(new Date(startTime.getTime() + 61000L)); // timer is set to one minute
  List<Job> timers = managementService.createTimerJobQuery().list();
  assertEquals(5, timers.size());

  // Execute all timers one by one (single thread vs thread pool of job
  // executor, which leads to optimisticlockingexceptions!)
  for (Job timer : timers) {
    managementService.moveTimerToExecutableJob(timer.getId());
    managementService.executeJob(timer.getId());
  }

  // All tasks should be canceled
  tasks = taskService.createTaskQuery().processInstanceId(pi.getId()).orderByTaskName().asc().list();
  assertEquals(0, tasks.size());
}
 
Example 14
/**
 * Verifying that the event subscriptions do get removed when removing a process instance.
 */
public void testBoundaryEventSubscrptionsDeletedOnProcessInstanceDelete() {
  String deploymentId1 = deployBoundaryMessageTestProcess();
  runtimeService.startProcessInstanceByKeyAndTenantId("messageTest", TENANT_ID);
  assertEquals("My Task", taskService.createTaskQuery().singleResult().getName());
  
  String deploymentId2 = deployBoundaryMessageTestProcess();
  ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKeyAndTenantId("messageTest", TENANT_ID);
  assertEquals(2, taskService.createTaskQuery().count());
  assertEquals(2, getAllEventSubscriptions().size());
  
  // Deleting PI of second deployment
  runtimeService.deleteProcessInstance(processInstance2.getId(), "testing");
  assertEquals("My Task", taskService.createTaskQuery().singleResult().getName());
  assertEquals(1, getAllEventSubscriptions().size());
  
  runtimeService.messageEventReceived("myMessage", getExecutionIdsForMessageEventSubscription("myMessage").get(0));
  assertEquals(0, getAllEventSubscriptions().size());
  assertEquals("Task after message", taskService.createTaskQuery().singleResult().getName());
  
  cleanup(deploymentId1, deploymentId2);
}
 
Example 15
Source Project: activiti6-boot2   Source File: RuntimeServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { "org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml" })
public void testRemoveVariable() {
  Map<String, Object> vars = new HashMap<String, Object>();
  vars.put("variable1", "value1");
  vars.put("variable2", "value2");

  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
  runtimeService.setVariables(processInstance.getId(), vars);

  runtimeService.removeVariable(processInstance.getId(), "variable1");

  assertNull(runtimeService.getVariable(processInstance.getId(), "variable1"));
  assertNull(runtimeService.getVariableLocal(processInstance.getId(), "variable1"));
  assertEquals("value2", runtimeService.getVariable(processInstance.getId(), "variable2"));

  checkHistoricVariableUpdateEntity("variable1", processInstance.getId());
}
 
Example 16
@Deployment
public void testSimple() {
  if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.FULL)) {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("myProc");
    TaskQuery taskQuery = taskService.createTaskQuery();
    Task userTask = taskQuery.singleResult();
    assertEquals("userTask1", userTask.getName());

    taskService.complete(userTask.getId(), CollectionUtil.singletonMap("myVar", "test789"));

    assertProcessEnded(processInstance.getId());

    List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery().list();
    assertEquals(1, variables.size());

    HistoricVariableInstanceEntity historicVariable = (HistoricVariableInstanceEntity) variables.get(0);
    assertEquals("test456", historicVariable.getTextValue());

    assertEquals(5, historyService.createHistoricActivityInstanceQuery().count());
    assertEquals(3, historyService.createHistoricDetailQuery().count());
  }
}
 
Example 17
Source Project: activiti6-boot2   Source File: DynamicServiceTaskTest.java    License: Apache License 2.0 5 votes vote down vote up
@Deployment
public void testChangeClassName() {
  // first test without changing the class name
  Map<String, Object> varMap = new HashMap<String, Object>();
  varMap.put("count", 0);
  varMap.put("count2", 0);
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("dynamicServiceTask", varMap);
  
  Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
  taskService.complete(task.getId());
  
  assertEquals(1, runtimeService.getVariable(processInstance.getId(), "count"));
  assertEquals(0, runtimeService.getVariable(processInstance.getId(), "count2"));
  
  task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
  taskService.complete(task.getId());
  
  assertProcessEnded(processInstance.getId());
  
  // now test with changing the class name
  varMap = new HashMap<String, Object>();
  varMap.put("count", 0);
  varMap.put("count2", 0);
  processInstance = runtimeService.startProcessInstanceByKey("dynamicServiceTask", varMap);
  
  String processDefinitionId = processInstance.getProcessDefinitionId();
  ObjectNode infoNode = dynamicBpmnService.changeServiceTaskClassName("service", "org.activiti.engine.test.bpmn.servicetask.DummyServiceTask2");
  dynamicBpmnService.saveProcessDefinitionInfo(processDefinitionId, infoNode);
  
  task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
  taskService.complete(task.getId());
  
  assertEquals(0, runtimeService.getVariable(processInstance.getId(), "count"));
  assertEquals(1, runtimeService.getVariable(processInstance.getId(), "count2"));
  
  task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
  taskService.complete(task.getId());
  
  assertProcessEnded(processInstance.getId());
}
 
Example 18
Source Project: activiti6-boot2   Source File: TenancyTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testCallActivityWithTenant() {
  if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {
    String tenantId = "apache";

    // deploying both processes. Process 1 will call Process 2
    repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testCallActivityWithTenant-process01.bpmn20.xml").tenantId(tenantId).deploy();
    repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testCallActivityWithTenant-process02.bpmn20.xml").tenantId(tenantId).deploy();

    // Starting Process 1. Process 1 will be executed successfully but
    // when the call to process 2 is made internally it will throw the
    // exception
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKeyAndTenantId("process1", null, CollectionUtil.singletonMap("sendFor", "test"), tenantId);
    Assert.assertNotNull(processInstance);

    Assert.assertEquals(1, historyService.createHistoricProcessInstanceQuery().processDefinitionKey("process2").processInstanceTenantId(tenantId).count());
    Assert.assertEquals(1, historyService.createHistoricProcessInstanceQuery().processDefinitionKey("process2").count());

    // following line if executed will give activiti object not found
    // exception as the process1 is linked to a tenant id.
    try {
      processInstance = runtimeService.startProcessInstanceByKey("process1");
      Assert.fail();
    } catch (Exception e) {

    }

    // Cleanup
    for (Deployment deployment : repositoryService.createDeploymentQuery().list()) {
      repositoryService.deleteDeployment(deployment.getId(), true);
    }
  }
}
 
Example 19
@Deployment
public void testSkipExpression() {
  Map<String, Object> variables = new HashMap<String, Object>();
  variables.put("input", "right");
  variables.put("_ACTIVITI_SKIP_EXPRESSION_ENABLED", true);
  variables.put("skipLeft", true);
  variables.put("skipRight", false);
  ProcessInstance pi = runtimeService.startProcessInstanceByKey("testSkipExpression", variables);

  Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();

  assertEquals("task left", task.getName());
}
 
Example 20
Source Project: activiti6-boot2   Source File: VariableEventsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Deployment(resources = {"org/activiti5/engine/test/api/runtime/oneTaskProcess.bpmn20.xml"})
public void testStartEndProcessInstanceVariableEvents() throws Exception {
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("var1", "value1");
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);

    assertEquals(1, listener.getEventsReceived().size());
    assertEquals(ActivitiEventType.VARIABLE_CREATED, listener.getEventsReceived().get(0).getType());

    Task task = taskService.createTaskQuery().processInstanceId( processInstance.getId()).singleResult();
    taskService.complete(task.getId());

    assertEquals(2, listener.getEventsReceived().size());
    assertEquals(ActivitiEventType.VARIABLE_DELETED, listener.getEventsReceived().get(1).getType());
}
 
Example 21
@Deployment
public void testSequentialSimulationRun() throws Exception {
  ProcessInstance simulationExperiment = runtimeService.startProcessInstanceByKey("multiInstanceResultVariablesSimulationRun");
  // all simulationManager executions are finished
  assertEquals(2, runtimeService.createExecutionQuery().count());

  // simulation run check - process variables has to be set to the value. "Hello worldX!"
  String simulationRunResult = (String) runtimeService.getVariable(simulationExperiment.getProcessInstanceId(), "simulationRunResult-0");
  assertThat(simulationRunResult, is("Hello world0!"));
  simulationRunResult = (String) runtimeService.getVariable(simulationExperiment.getProcessInstanceId(), "simulationRunResult-1");
  assertThat(simulationRunResult, is("Hello world1!"));
  simulationRunResult = (String) runtimeService.getVariable(simulationExperiment.getProcessInstanceId(), "simulationRunResult-2");
  assertThat(simulationRunResult, is("Hello world2!"));
  simulationRunResult = (String) runtimeService.getVariable(simulationExperiment.getProcessInstanceId(), "simulationRunResult-3");
  assertThat(simulationRunResult, is("Hello world3!"));
  simulationRunResult = (String) runtimeService.getVariable(simulationExperiment.getProcessInstanceId(), "simulationRunResult-4");
  assertThat(simulationRunResult, is("Hello world4!"));

  // process end
  runtimeService.trigger(runtimeService.createExecutionQuery()
      .onlyChildExecutions().singleResult().getId());
  // no process instance is running
  assertEquals(0, runtimeService.createExecutionQuery().count());
}
 
Example 22
Source Project: maven-framework-project   Source File: WorkFlowController.java    License: MIT License 5 votes vote down vote up
/**
 * 根据流程实例Id和资源类型加载流程资源
 * @param processInstanceId 流程实例id
 * @param resourceType 流程资源类型
 * @param request
 * @param response
 */
@RequestMapping(value="/loadResourceByProcessInstance",method={RequestMethod.GET,RequestMethod.POST})
public void loadResourceByProcessInstance(@RequestParam("processInstanceId")String processInstanceId,@RequestParam("resourceType")String resourceType,HttpServletRequest request, HttpServletResponse response){
	//根据流程实例id查询流程实例
	ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
	//根据流程定义id查询流程定义
	ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult();
	
	String resourceName="";
	if(resourceType.equals("xml")){
		//获取流程定义资源名称
		resourceName=processDefinition.getResourceName();
	}else if(resourceType.equals("image")){
		//获取流程图资源名称
		resourceName=processDefinition.getDiagramResourceName();
	}
	//打开流程资源流
	InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName);
	//输出到浏览器
	try {
		byte[] byteArray = IOUtils.toByteArray(resourceAsStream);
		ServletOutputStream servletOutputStream = response.getOutputStream();
		servletOutputStream.write(byteArray, 0, byteArray.length);
		servletOutputStream.flush();
		servletOutputStream.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 23
Source Project: activiti6-boot2   Source File: BusinessProcess.java    License: Apache License 2.0 5 votes vote down vote up
public ProcessInstance startProcessById(String processDefinitionId, String businessKey) {
  validateValidUsage();

  ProcessInstance instance = processEngine.getRuntimeService().startProcessInstanceById(processDefinitionId, businessKey, getAndClearCachedVariables());
  if (!instance.isEnded()) {
    setExecution(instance);
  }
  return instance;
}
 
Example 24
Source Project: acitviti6.0   Source File: ActivitiController.java    License: MIT License 5 votes vote down vote up
@RequestMapping("singleAssignee")  
public void setSingleAssignee() {  
	
	//根据bpmn文件部署流程  
	repositoryService.createDeployment().addClasspathResource("singleAssignee.bpmn").deploy();
	// 设置User Task1受理人变量
	Map<String, Object> variables = new HashMap<>();
	variables.put("user1", "007");
	//采用key来启动流程定义并设置流程变量,返回流程实例  
	ProcessInstance pi = runtimeService.startProcessInstanceByKey("singleAssignee", variables);  
	String processId = pi.getId();  
	System.out.println("流程创建成功,当前流程实例ID:"+processId);
	
	// 注意 这里需要拿007来查询,key-value需要拿value来获取任务
	List<Task> list = taskService.createTaskQuery().taskAssignee("007").list();
	if(list!=null && list.size()>0){ 
           for(org.activiti.engine.task.Task task:list){  
               System.out.println("任务ID:"+task.getId());  
               System.out.println("任务的办理人:"+task.getAssignee());  
               System.out.println("任务名称:"+task.getName());  
               System.out.println("任务的创建时间:"+task.getCreateTime());  
               System.out.println("流程实例ID:"+task.getProcessInstanceId());  
               System.out.println("#######################################");
           }
       }
	
	// 设置User Task2的受理人变量
	Map<String, Object> variables1 = new HashMap<>();
	variables1.put("user2", "Kevin");
	// 因为007只有一个代办的任务,直接完成任务,并赋值下一个节点的受理人user2为Kevin办理
	taskService.complete(list.get(0).getId(), variables1);
	System.out.println("User Task1被完成了,此时流程已流转到User Task2");
}
 
Example 25
Source Project: activiti6-boot2   Source File: FullHistoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Deployment
public void testDeleteRunningHistoricProcessInstance() {
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("HistoricTaskInstanceTest");
  assertNotNull(processInstance);

  try {
    // Delete the historic process-instance, which is still running
    historyService.deleteHistoricProcessInstance(processInstance.getId());
    fail("Exception expected when deleting process-instance that is still running");
  } catch (ActivitiException ae) {
    // Expected exception
    assertTextPresent("Process instance is still running, cannot delete historic process instance", ae.getMessage());
  }
}
 
Example 26
Source Project: activiti6-boot2   Source File: RuntimeServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Deployment(resources={
  "org/activiti5/engine/test/api/oneTaskProcess.bpmn20.xml"})
public void testStartProcessInstanceWithBusinessKey() {
  ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
  
  // by key
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", "123");
  assertNotNull(processInstance);
  assertEquals("123", processInstance.getBusinessKey());
  assertEquals(1, runtimeService.createProcessInstanceQuery().processDefinitionKey("oneTaskProcess").count());
  
  // by key with variables
  processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", "456", CollectionUtil.singletonMap("var", "value"));
  assertNotNull(processInstance);
  assertEquals(2, runtimeService.createProcessInstanceQuery().processDefinitionKey("oneTaskProcess").count());
  assertEquals("value", runtimeService.getVariable(processInstance.getId(), "var"));
  
  // by id
  processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(), "789");
  assertNotNull(processInstance);
  assertEquals(3, runtimeService.createProcessInstanceQuery().processDefinitionKey("oneTaskProcess").count());
  
  // by id with variables
  processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(), "101123", CollectionUtil.singletonMap("var", "value2"));
  assertNotNull(processInstance);
  assertEquals(4, runtimeService.createProcessInstanceQuery().processDefinitionKey("oneTaskProcess").count());
  assertEquals("value2", runtimeService.getVariable(processInstance.getId(), "var"));
}
 
Example 27
Source Project: activiti-in-action-codes   Source File: LeaveController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 任务列表
 *
 * @param leave
 */
@RequestMapping(value = "task/view/{taskId}")
public ModelAndView showTaskView(@PathVariable("taskId") String taskId) {
    Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
    String processInstanceId = task.getProcessInstanceId();
    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    Leave leave = leaveManager.get(new Long(processInstance.getBusinessKey()));
    ModelAndView mav = new ModelAndView("/chapter7/leave/task-" + task.getTaskDefinitionKey());
    mav.addObject("leave", leave);
    mav.addObject("task", task);
    return mav;
}
 
Example 28
Source Project: activiti-in-action-codes   Source File: ListenerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Deployment(resources = {"diagrams/chapter7/listener/listener.bpmn"})
public void testListener() {
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("endListener", new ProcessEndExecutionListener());
    variables.put("assignmentDelegate", new TaskAssigneeListener());
    variables.put("name", "Henry Yan");

    identityService.setAuthenticatedUserId("henryyan");
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("listener", variables);

    // 校验是否执行了启动监听
    String processInstanceId = processInstance.getId();
    assertTrue((Boolean) runtimeService.getVariable(processInstanceId, "setInStartListener"));

    Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).taskAssignee("jenny").singleResult();
    String setInTaskCreate = (String) taskService.getVariable(task.getId(), "setInTaskCreate");
    assertEquals("create, Hello, Henry Yan", setInTaskCreate);
    taskService.complete(task.getId());

    // 流程结束后查询变量
    List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).list();
    boolean hasVariableOfEndListener = false;
    for (HistoricVariableInstance variableInstance : list) {
        if (variableInstance.getVariableName().equals("setInEndListener")) {
            hasVariableOfEndListener = true;
        }
    }
    assertTrue(hasVariableOfEndListener);
}
 
Example 29
/**
 * 测试前加签
 */
@Test
public void testInsertTasksBefore() throws Exception
{
	ProcessInstance instance = _processEngine.getRuntimeService().startProcessInstanceByKey("test2");
	TaskService taskService = _processEngine.getTaskService();
	TaskFlowControlService tfcs = _taskFlowControlServiceFactory.create(instance.getId());
	//到了step2
	Assert.assertEquals("step2", taskService.createTaskQuery().singleResult().getTaskDefinitionKey());
	//在前面加两个节点
	ActivityImpl[] as = tfcs.insertTasksBefore("step2", "bluejoe", "alex");
	//应该执行到了第一个节点
	Assert.assertEquals(as[0].getId(), taskService.createTaskQuery().singleResult().getTaskDefinitionKey());
	Assert.assertEquals("bluejoe", taskService.createTaskQuery().singleResult().getAssignee());
	//完成该节点
	taskService.complete(taskService.createTaskQuery().singleResult().getId());
	//应该到了下一个节点
	Assert.assertEquals(as[1].getId(), taskService.createTaskQuery().singleResult().getTaskDefinitionKey());
	Assert.assertEquals("alex", taskService.createTaskQuery().singleResult().getAssignee());
	//完成该节点
	taskService.complete(taskService.createTaskQuery().singleResult().getId());
	//应该到了下一个节点
	Assert.assertEquals("step2", taskService.createTaskQuery().singleResult().getTaskDefinitionKey());
	//完成step2
	taskService.complete(taskService.createTaskQuery().singleResult().getId());
	//应该到了step3
	Assert.assertEquals("step3", taskService.createTaskQuery().singleResult().getTaskDefinitionKey());

	//确认历史轨迹里已保存
	//step1,step2,step2-1,step2-2,step2,step3
	List<HistoricActivityInstance> activities = _processEngine.getHistoryService()
			.createHistoricActivityInstanceQuery().processInstanceId(instance.getId()).list();
	Assert.assertEquals(6, activities.size());

	//删掉流程
	_processEngine.getRuntimeService().deleteProcessInstance(instance.getId(), "test");
}
 
Example 30
Source Project: activiti6-boot2   Source File: AdhocSubProcessTest.java    License: Apache License 2.0 5 votes vote down vote up
@Deployment
public void testFlowsInAdhocSubProcess() {
  Map<String, Object> variableMap = new HashMap<String, Object>();
  variableMap.put("completed", false);
  ProcessInstance pi = runtimeService.startProcessInstanceByKey("simpleSubProcess", variableMap);
  Execution execution = runtimeService.createExecutionQuery().activityId("adhocSubProcess").singleResult();
  assertNotNull(execution);
  
  List<FlowNode> enabledActivities = runtimeService.getEnabledActivitiesFromAdhocSubProcess(execution.getId());
  assertEquals(2, enabledActivities.size());
  
  runtimeService.executeActivityInAdhocSubProcess(execution.getId(), "subProcessTask");
  Task subProcessTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
  assertEquals("Task in subprocess", subProcessTask.getName());
  
  taskService.complete(subProcessTask.getId());
  
  try {
    runtimeService.executeActivityInAdhocSubProcess(execution.getId(), "subProcessTask2");
    fail("exception expected because can only enable one activity in a sequential ad-hoc sub process");
  } catch (ActivitiException e) {
    // expected
  }
  
  subProcessTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
  assertEquals("The next task", subProcessTask.getName());
  
  variableMap = new HashMap<String, Object>();
  variableMap.put("completed", true);
  taskService.complete(subProcessTask.getId(), variableMap);
  
  Task afterTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
  assertEquals("After task", afterTask.getName());
  
  taskService.complete(afterTask.getId());
  
  assertNull(runtimeService.createProcessInstanceQuery().processInstanceId(pi.getId()).singleResult());
}