@Deployment
  public void testAsyncInclusiveGateway() {
    // start PI
    String pid =
        runtimeService.startProcessInstanceByKey("asyncInclusiveGateway").getProcessInstanceId();

    // now there is 1 job in the database:
    assertEquals(1, managementService.createJobQuery().count());
    // the listener was not invoked now:
    assertNull(runtimeService.getVariable(pid, "listener"));
    // there is no gateway:
    assertNull(taskService.createTaskQuery().singleResult());

    executeAvailableJobs();

    // the listener was now invoked:
    assertNotNull(runtimeService.getVariable(pid, "listener"));
    // there isn't a job anymore
    assertEquals(0, managementService.createJobQuery().count());
    // now there are 2 user tasks
    List<Task> list = taskService.createTaskQuery().list();
    assertEquals(2, list.size());

    // complete these tasks and finish the process instance
    for (Task task : list) {
      taskService.complete(task.getId());
    }
  }
  @Deployment
  public void testHistoricTaskInstanceQueryProcessFinished() {
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("TwoTaskHistoricTaskQueryTest");
    Task task =
        taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();

    // Running task on running process should be available
    assertEquals(1, historyService.createHistoricTaskInstanceQuery().processUnfinished().count());
    assertEquals(0, historyService.createHistoricTaskInstanceQuery().processFinished().count());

    // Finished and running task on running process should be available
    taskService.complete(task.getId());
    assertEquals(2, historyService.createHistoricTaskInstanceQuery().processUnfinished().count());
    assertEquals(0, historyService.createHistoricTaskInstanceQuery().processFinished().count());

    // 2 finished tasks are found for finished process after completing last task of process
    task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    taskService.complete(task.getId());
    assertEquals(0, historyService.createHistoricTaskInstanceQuery().processUnfinished().count());
    assertEquals(2, historyService.createHistoricTaskInstanceQuery().processFinished().count());

    assertEquals(
        0,
        historyService
            .createHistoricTaskInstanceQuery()
            .processUnfinished()
            .processFinished()
            .count());
  }
 /**
  * Helper method to easily unclaim a task.
  *
  * @param task Task to be claimed for an assignee
  * @return the assigned task - properly refreshed to its unassigned state.
  */
 public static Task unclaim(Task task) {
   if (task == null)
     throw new IllegalArgumentException(
         format("Illegal call " + "of unclaim(task = '%s') - task must " + "not be null!", task));
   taskService().claim(task.getId(), null);
   return taskQuery().taskId(task.getId()).singleResult();
 }
  // Difference with previous test: now the join will be reached first
  @Deployment(
      resources = {
        "org/camunda/bpm/engine/test/bpmn/event/timer/BoundaryTimerNonInterruptingEventTest.testTimerOnConcurrentTasks.bpmn20.xml"
      })
  public void testTimerOnConcurrentTasks2() {
    String procId =
        runtimeService.startProcessInstanceByKey("nonInterruptingOnConcurrentTasks").getId();
    assertEquals(2, taskService.createTaskQuery().count());

    Job timer = managementService.createJobQuery().singleResult();
    managementService.executeJob(timer.getId());
    assertEquals(3, taskService.createTaskQuery().count());

    // Complete 2 tasks that will trigger the join
    Task task = taskService.createTaskQuery().taskDefinitionKey("firstTask").singleResult();
    taskService.complete(task.getId());
    task = taskService.createTaskQuery().taskDefinitionKey("secondTask").singleResult();
    taskService.complete(task.getId());
    assertEquals(1, taskService.createTaskQuery().count());

    // Finally, complete the task that was created due to the timer
    task = taskService.createTaskQuery().taskDefinitionKey("timerFiredTask").singleResult();
    taskService.complete(task.getId());

    assertProcessEnded(procId);
  }
  @Override
  public void execute(DelegateExecution execution) throws Exception {

    Map<String, Object> vars = new HashMap<String, Object>();

    String busKey = (String) execution.getVariable("busKey");

    RandomGeneratorUtil randomUtil = new RandomGeneratorUtil();

    vars.put("paymentRejected", randomUtil.getRandomPaymentRejected());
    vars.put("numberOfPayouts", randomUtil.getRandomNumberOfPayments());
    vars.put("historyOfFraud", randomUtil.getRandomHistoryOfFraud());
    vars.put("userDeterminedFraud", randomUtil.getRandomUserDeterminedFraud());

    Task currentTask =
        execution
            .getProcessEngineServices()
            .getTaskService()
            .createTaskQuery()
            .processInstanceBusinessKey(busKey)
            .singleResult();

    if (currentTask.getTaskDefinitionKey().equals("Task_Select_Manual_User")) {
      execution.getProcessEngineServices().getTaskService().complete(currentTask.getId(), vars);
      throw new BpmnError("TASK_NOT_FOUND");
    }

    execution.getProcessEngineServices().getTaskService().complete(currentTask.getId(), vars);
  }
  /** @see http://jira.codehaus.org/browse/ACT-380 */
  @Deployment
  public void testGetCandidates() {
    runtimeService.startProcessInstanceByKey("DelegateTaskTest.testGetCandidates");

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

    @SuppressWarnings("unchecked")
    Set<String> candidateUsers =
        (Set<String>)
            taskService.getVariable(
                task.getId(), DelegateTaskTestTaskListener.VARNAME_CANDIDATE_USERS);
    assertEquals(2, candidateUsers.size());
    assertTrue(candidateUsers.contains("kermit"));
    assertTrue(candidateUsers.contains("gonzo"));

    @SuppressWarnings("unchecked")
    Set<String> candidateGroups =
        (Set<String>)
            taskService.getVariable(
                task.getId(), DelegateTaskTestTaskListener.VARNAME_CANDIDATE_GROUPS);
    assertEquals(2, candidateGroups.size());
    assertTrue(candidateGroups.contains("management"));
    assertTrue(candidateGroups.contains("accountancy"));
  }
  @Deployment(resources = {"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testSetVariableLocalOnUserTask() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("oneTaskProcess");

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

    taskService.setVariableLocal(task.getId(), "testVar", "testValue");
    ExecutionEntity taskExecution =
        (ExecutionEntity)
            runtimeService.createExecutionQuery().executionId(task.getExecutionId()).singleResult();
    assertNotNull(taskExecution);

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(1, query.count());

    HistoricVariableInstance variable = query.singleResult();
    assertNotNull(variable);

    // the variable is in the task scope
    assertEquals(taskExecution.getActivityInstanceId(), variable.getActivityInstanceId());

    taskService.complete(task.getId());
    assertProcessEnded(pi.getId());
  }
  @Deployment(resources = {"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testSetVariableOnProcessIntanceStartAndSetVariableLocalOnUserTask() {
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("testVar", "testValue");
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);

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

    taskService.setVariableLocal(task.getId(), "testVar", "anotherTestValue");
    ExecutionEntity taskExecution =
        (ExecutionEntity) runtimeService.createExecutionQuery().singleResult();
    assertNotNull(taskExecution);

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(2, query.count());

    List<HistoricVariableInstance> result = query.list();

    HistoricVariableInstance firstVar = result.get(0);
    assertEquals("testVar", firstVar.getVariableName());
    assertEquals("testValue", firstVar.getValue());
    // the variable is in the process instance scope
    assertEquals(pi.getId(), firstVar.getActivityInstanceId());

    HistoricVariableInstance secondVar = result.get(1);
    assertEquals("testVar", secondVar.getVariableName());
    assertEquals("anotherTestValue", secondVar.getValue());
    // the variable is in the task scope
    assertEquals(taskExecution.getActivityInstanceId(), secondVar.getActivityInstanceId());

    taskService.complete(task.getId());
    assertProcessEnded(pi.getId());
  }
  @Deployment(resources = {"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
  public void testCmmnActivityInstanceIdOnTask() {

    // given
    CaseInstance caseInstance = caseService.createCaseInstanceByKey("oneTaskCase");

    String taskExecutionId =
        caseService.createCaseExecutionQuery().activityId("PI_HumanTask_1").singleResult().getId();

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

    // when
    taskService.setVariable(task.getId(), "foo", "bar");

    // then
    HistoricVariableInstance variable =
        historyService.createHistoricVariableInstanceQuery().variableName("foo").singleResult();

    assertNotNull(variable);
    assertEquals(caseInstance.getId(), variable.getActivityInstanceId());

    if (processEngineConfiguration.getHistoryLevel().getId()
        > ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) {
      HistoricDetail variableDetail =
          historyService
              .createHistoricDetailQuery()
              .variableUpdates()
              .variableInstanceId(variable.getId())
              .singleResult();
      assertEquals(taskExecutionId, variableDetail.getActivityInstanceId());
    }
  }
  @Deployment
  public void testConcurrentScopeCompensation() {
    // given a process instance with two concurrent tasks, one of which is waiting
    // before throwing compensation
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("concurrentScopeCompensation");
    Task beforeCompensationTask =
        taskService.createTaskQuery().taskDefinitionKey("beforeCompensationTask").singleResult();
    Task concurrentTask =
        taskService.createTaskQuery().taskDefinitionKey("concurrentTask").singleResult();

    // when throwing compensation such that two subprocesses are compensated
    taskService.complete(beforeCompensationTask.getId());

    // then both compensation handlers have been executed
    if (processEngineConfiguration.getHistoryLevel().getId()
        >= ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) {
      HistoricVariableInstanceQuery historicVariableInstanceQuery =
          historyService.createHistoricVariableInstanceQuery().variableName("compensateScope1Task");

      assertEquals(1, historicVariableInstanceQuery.count());
      assertEquals(1, historicVariableInstanceQuery.list().get(0).getValue());

      historicVariableInstanceQuery =
          historyService.createHistoricVariableInstanceQuery().variableName("compensateScope2Task");

      assertEquals(1, historicVariableInstanceQuery.count());
      assertEquals(1, historicVariableInstanceQuery.list().get(0).getValue());
    }

    // and after completing the concurrent task, the process instance ends successfully
    taskService.complete(concurrentTask.getId());
    assertProcessEnded(processInstance.getId());
  }
  @Test
  @ScenarioUnderTest("init.5")
  public void testInitThrowUnhandledException() {
    // given
    ProcessInstance instance = rule.processInstance();
    Task innerMiSubProcessTask =
        rule.taskQuery().taskDefinitionKey("innerSubProcessTask").singleResult();

    // when
    rule.getRuntimeService()
        .setVariable(instance.getId(), ThrowBpmnErrorDelegate.EXCEPTION_INDICATOR_VARIABLE, true);
    rule.getRuntimeService()
        .setVariable(
            instance.getId(),
            ThrowBpmnErrorDelegate.EXCEPTION_MESSAGE_VARIABLE,
            "unhandledException");

    // then
    try {
      rule.getTaskService().complete(innerMiSubProcessTask.getId());
      Assert.fail("should throw a ThrowBpmnErrorDelegateException");

    } catch (ThrowBpmnErrorDelegateException e) {
      Assert.assertEquals("unhandledException", e.getMessage());
    }
  }
  @Deployment
  public void testHistoricTaskInstanceQueryByProcessVariableValue() throws Exception {
    int historyLevel = processEngineConfiguration.getHistoryLevel().getId();
    if (historyLevel >= ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) {
      Map<String, Object> variables = new HashMap<String, Object>();
      variables.put("hallo", "steffen");

      String processInstanceId =
          runtimeService.startProcessInstanceByKey("HistoricTaskInstanceTest", variables).getId();

      Task runtimeTask =
          taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
      String taskId = runtimeTask.getId();

      HistoricTaskInstance historicTaskInstance =
          historyService
              .createHistoricTaskInstanceQuery()
              .processVariableValueEquals("hallo", "steffen")
              .singleResult();

      assertNotNull(historicTaskInstance);
      assertEquals(taskId, historicTaskInstance.getId());

      taskService.complete(taskId);
      assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskId(taskId).count());

      historyService.deleteHistoricTaskInstance(taskId);
      assertEquals(0, historyService.createHistoricTaskInstanceQuery().count());
    }
  }
  @Deployment
  public void testCompensateParallelSubprocessCompHandlerWaitstate() {

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("compensateProcess");

    List<Task> compensationHandlerTasks =
        taskService.createTaskQuery().taskDefinitionKey("undoBookHotel").list();
    assertEquals(5, compensationHandlerTasks.size());

    ActivityInstance rootActivityInstance =
        runtimeService.getActivityInstance(processInstance.getId());
    List<ActivityInstance> compensationHandlerInstances =
        getInstancesForActivityId(rootActivityInstance, "undoBookHotel");
    assertEquals(5, compensationHandlerInstances.size());

    for (Task task : compensationHandlerTasks) {
      taskService.complete(task.getId());
    }

    Task singleResult = taskService.createTaskQuery().singleResult();
    taskService.complete(singleResult.getId());

    runtimeService.signal(processInstance.getId());
    assertProcessEnded(processInstance.getId());
  }
  private void completeTaskWithVariable(String taskName, String variable, Object value) {
    Task task = taskService.createTaskQuery().taskName(taskName).singleResult();
    assertNotNull("No open task with name '" + taskName + "'", task);

    Map<String, Object> variables = new HashMap<String, Object>();
    if (variable != null) {
      variables.put(variable, value);
    }

    taskService.complete(task.getId(), variables);
  }
 /**
  * Helper method to easily claim a task for a specific assignee.
  *
  * @param task Task to be claimed for an assignee
  * @param assigneeUserId userId of assignee for which the task should be claimed
  * @return the assigned task - properly refreshed to its assigned state.
  */
 public static Task claim(Task task, String assigneeUserId) {
   if (task == null || assigneeUserId == null)
     throw new IllegalArgumentException(
         format(
             "Illegal call "
                 + "of claim(task = '%s', assigneeUserId = '%s') - both must "
                 + "not be null!",
             task, assigneeUserId));
   taskService().claim(task.getId(), assigneeUserId);
   return taskQuery().taskId(task.getId()).singleResult();
 }
  @GET
  @Path("task/{id}")
  @Produces(MediaType.APPLICATION_JSON)
  public FormDto getTaskForm(@PathParam("id") String taskId) {

    TaskFormData formData = processEngine.getFormService().getTaskFormData(taskId);
    Task task = processEngine.getTaskService().createTaskQuery().taskId(taskId).singleResult();

    String formKey = formData != null ? formData.getFormKey() : null;

    return new FormDto(formKey, getApplicationPath(task.getProcessDefinitionId()));
  }
  /** CAM-3628 */
  @Deployment
  public void testCompensateSubprocessWithBoundaryEvent() {
    ProcessInstance instance = runtimeService.startProcessInstanceByKey("compensateProcess");

    Task compensationTask = taskService.createTaskQuery().singleResult();
    assertNotNull(compensationTask);
    assertEquals("undoSubprocess", compensationTask.getTaskDefinitionKey());

    taskService.complete(compensationTask.getId());
    runtimeService.signal(instance.getId());
    assertProcessEnded(instance.getId());
  }
  @Deployment
  public void testCompensateParallelSubprocess() {

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("compensateProcess");

    assertEquals(5, runtimeService.getVariable(processInstance.getId(), "undoBookHotel"));

    Task singleResult = taskService.createTaskQuery().singleResult();
    taskService.complete(singleResult.getId());

    runtimeService.signal(processInstance.getId());
    assertProcessEnded(processInstance.getId());
  }
  @Deployment
  public void FAILING_testSubprocessCompensationHandler() {

    // given a process instance
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("subProcessCompensationHandler");

    // when throwing compensation
    Task beforeCompensationTask = taskService.createTaskQuery().singleResult();
    taskService.complete(beforeCompensationTask.getId());

    // then the compensation handler has been activated
    // and the user task in the sub process can be successfully completed
    Task subProcessTask = taskService.createTaskQuery().singleResult();
    assertNotNull(subProcessTask);
    assertEquals("subProcessTask", subProcessTask.getTaskDefinitionKey());

    taskService.complete(subProcessTask.getId());

    // and the task following compensation should can be successfully completed
    Task afterCompensationTask = taskService.createTaskQuery().singleResult();
    assertNotNull(afterCompensationTask);
    assertEquals("beforeEnd", afterCompensationTask.getTaskDefinitionKey());

    taskService.complete(afterCompensationTask.getId());

    // and the process has successfully ended
    assertProcessEnded(processInstance.getId());
  }
  /** Unnamed @Deployment annotations don't work with parameterized Unit tests */
  @Ignore
  @Test
  @Deployment
  public void ruleUsageExample() {
    RuntimeService runtimeService = engineRule.getRuntimeService();
    runtimeService.startProcessInstanceByKey("ruleUsage");

    TaskService taskService = engineRule.getTaskService();
    Task task = taskService.createTaskQuery().singleResult();
    assertEquals("My Task", task.getName());

    taskService.complete(task.getId());
    assertEquals(0, runtimeService.createProcessInstanceQuery().count());
  }
  @Deployment
  public void testMultipleOutgoingSequenceFlowsOnSubprocess() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("nonInterruptingTimer");

    Job job = managementService.createJobQuery().singleResult();
    assertNotNull(job);

    managementService.executeJob(job.getId());

    Task task = taskService.createTaskQuery().taskDefinitionKey("innerTask1").singleResult();
    assertNotNull(task);
    taskService.complete(task.getId());

    task = taskService.createTaskQuery().taskDefinitionKey("innerTask2").singleResult();
    assertNotNull(task);
    taskService.complete(task.getId());

    task = taskService.createTaskQuery().taskDefinitionKey("timerFiredTask1").singleResult();
    assertNotNull(task);
    taskService.complete(task.getId());

    task = taskService.createTaskQuery().taskDefinitionKey("timerFiredTask2").singleResult();
    assertNotNull(task);
    taskService.complete(task.getId());

    assertProcessEnded(pi.getId());

    // Case 2: fire outer tasks first

    pi = runtimeService.startProcessInstanceByKey("nonInterruptingTimer");

    job = managementService.createJobQuery().singleResult();
    assertNotNull(job);

    managementService.executeJob(job.getId());

    task = taskService.createTaskQuery().taskDefinitionKey("timerFiredTask1").singleResult();
    assertNotNull(task);
    taskService.complete(task.getId());

    task = taskService.createTaskQuery().taskDefinitionKey("timerFiredTask2").singleResult();
    assertNotNull(task);
    taskService.complete(task.getId());

    task = taskService.createTaskQuery().taskDefinitionKey("innerTask1").singleResult();
    assertNotNull(task);
    taskService.complete(task.getId());

    task = taskService.createTaskQuery().taskDefinitionKey("innerTask2").singleResult();
    assertNotNull(task);
    taskService.complete(task.getId());

    assertProcessEnded(pi.getId());
  }
  @Deployment(resources = {"org/camunda/bpm/engine/test/api/runtime/oneTaskProcess.bpmn20.xml"})
  public void testSuspendProcessInstancesDuringProcessDefinitionSuspend() {

    int nrOfProcessInstances = 9;

    // Fire up a few processes for the deployed process definition
    ProcessDefinition processDefinition =
        repositoryService.createProcessDefinitionQuery().singleResult();
    for (int i = 0; i < nrOfProcessInstances; i++) {
      runtimeService.startProcessInstanceByKey(processDefinition.getKey());
    }
    assertEquals(nrOfProcessInstances, runtimeService.createProcessInstanceQuery().count());
    assertEquals(0, runtimeService.createProcessInstanceQuery().suspended().count());
    assertEquals(
        nrOfProcessInstances, runtimeService.createProcessInstanceQuery().active().count());

    // Suspend process definitions and include process instances
    repositoryService.suspendProcessDefinitionById(processDefinition.getId(), true, null);

    // Verify all process instances are also suspended
    for (ProcessInstance processInstance : runtimeService.createProcessInstanceQuery().list()) {
      assertTrue(processInstance.isSuspended());
    }

    // Verify all process instances can't be continued
    for (Task task : taskService.createTaskQuery().list()) {
      try {
        taskService.complete(task.getId());
        fail("A suspended task shouldn't be able to be continued");
      } catch (SuspendedEntityInteractionException e) {
        // This is good
      }
    }
    assertEquals(nrOfProcessInstances, runtimeService.createProcessInstanceQuery().count());
    assertEquals(
        nrOfProcessInstances, runtimeService.createProcessInstanceQuery().suspended().count());
    assertEquals(0, runtimeService.createProcessInstanceQuery().active().count());

    // Activate the process definition again
    repositoryService.activateProcessDefinitionById(processDefinition.getId(), true, null);

    // Verify that all process instances can be completed
    for (Task task : taskService.createTaskQuery().list()) {
      taskService.complete(task.getId());
    }
    assertEquals(0, runtimeService.createProcessInstanceQuery().count());
    assertEquals(0, runtimeService.createProcessInstanceQuery().suspended().count());
    assertEquals(0, runtimeService.createProcessInstanceQuery().active().count());
  }
  @Test
  @Deployment(
      resources =
          "org/camunda/bpm/engine/test/standalone/testing/ProcessEngineRuleParameterizedJunit4Test.ruleUsageExample.bpmn20.xml")
  public void ruleUsageExampleWithNamedAnnotation() {
    RuntimeService runtimeService = engineRule.getRuntimeService();
    runtimeService.startProcessInstanceByKey("ruleUsage");

    TaskService taskService = engineRule.getTaskService();
    Task task = taskService.createTaskQuery().singleResult();
    assertEquals("My Task", task.getName());

    taskService.complete(task.getId());
    assertEquals(0, runtimeService.createProcessInstanceQuery().count());
  }
  // See http://jira.codehaus.org/browse/ACT-1290
  public void testRevisionUpdatedOnSave() {
    Task task = taskService.newTask();
    taskService.saveTask(task);
    assertEquals(1, ((TaskEntity) task).getRevision());

    task.setDescription("first modification");
    taskService.saveTask(task);
    assertEquals(2, ((TaskEntity) task).getRevision());

    task.setDescription("second modification");
    taskService.saveTask(task);
    assertEquals(3, ((TaskEntity) task).getRevision());

    taskService.deleteTask(task.getId(), true);
  }
  @Deployment
  public void testTimerWithCycle() throws Exception {
    runtimeService.startProcessInstanceByKey("nonInterruptingCycle").getId();
    TaskQuery tq = taskService.createTaskQuery().taskDefinitionKey("timerFiredTask");
    assertEquals(0, tq.count());
    moveByHours(1);
    assertEquals(1, tq.count());
    moveByHours(1);
    assertEquals(2, tq.count());

    Task task = taskService.createTaskQuery().taskDefinitionKey("task").singleResult();
    taskService.complete(task.getId());

    moveByHours(1);
    assertEquals(2, tq.count());
  }
  @Deployment(
      resources =
          "org/camunda/bpm/engine/test/bpmn/event/compensate/CompensateEventTest.testSubprocessCompensationHandler.bpmn20.xml")
  public void FAILING_testSubprocessCompensationHandlerDeleteProcessInstance() {

    // given a process instance in compensation
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("subProcessCompensationHandler");
    Task beforeCompensationTask = taskService.createTaskQuery().singleResult();
    taskService.complete(beforeCompensationTask.getId());

    // when deleting the process instance
    runtimeService.deleteProcessInstance(processInstance.getId(), null);

    // then the process instance is ended
    assertProcessEnded(processInstance.getId());
  }
 /**
  * Helper method to easily complete a task and pass some process variables.
  *
  * @param task Task to be completed
  * @param variables Process variables to be passed to the process instance when completing the
  *     task. For setting those variables, you can use withVariables(String key, Object value, ...)
  */
 public static void complete(Task task, Map<String, Object> variables) {
   if (task == null || variables == null)
     throw new IllegalArgumentException(
         format(
             "Illegal call of claim(task = '%s', variables = '%s') - both must not be null!",
             task, variables));
   taskService().complete(task.getId(), variables);
 }
  public void testHistoricTaskInstancePriority() {
    Task task = taskService.newTask();
    taskService.saveTask(task);

    // task exists & has normal priority:
    HistoricTaskInstance hti = historyService.createHistoricTaskInstanceQuery().singleResult();
    assertEquals(Task.PRIORITY_NORMAL, hti.getPriority());

    // set priority to maximum value:
    taskService.setPriority(task.getId(), Task.PRIORITY_MAXIMUM);

    // should be reflected in history
    hti = historyService.createHistoricTaskInstanceQuery().singleResult();
    assertEquals(Task.PRIORITY_MAXIMUM, hti.getPriority());

    taskService.deleteTask(task.getId());
    historyService.deleteHistoricTaskInstance(hti.getId());
  }
  public void testHistoricTaskInstanceOwner() {
    Task task = taskService.newTask();
    taskService.saveTask(task);

    // task exists & has no owner:
    HistoricTaskInstance hti = historyService.createHistoricTaskInstanceQuery().singleResult();
    assertNull(hti.getOwner());

    // set owner to jonny:
    taskService.setOwner(task.getId(), "jonny");

    // should be reflected in history
    hti = historyService.createHistoricTaskInstanceQuery().singleResult();
    assertEquals("jonny", hti.getOwner());

    taskService.deleteTask(task.getId());
    historyService.deleteHistoricTaskInstance(hti.getId());
  }
  private void completeTasks(String taskName, int times) {
    List<Task> tasks = taskService.createTaskQuery().taskName(taskName).list();

    assertTrue(
        "Actual there are "
            + tasks.size()
            + " open tasks with name '"
            + taskName
            + "'. Expected at least "
            + times,
        times <= tasks.size());

    Iterator<Task> taskIterator = tasks.iterator();
    for (int i = 0; i < times; i++) {
      Task task = taskIterator.next();
      taskService.complete(task.getId());
    }
  }