@Test
 public void testMail() {
   createNewProcess();
   Task nextTask = taskService.createTaskQuery().singleResult();
   HashMap<String, String> map = new HashMap<String, String>();
   formService.submitTaskFormData(nextTask.getId(), map);
 }
Пример #2
0
 public void tesBasicTaskPropertiesNotNull() {
   Task task = taskService.createTaskQuery().taskId(taskIds.get(0)).singleResult();
   assertNotNull(task.getDescription());
   assertNotNull(task.getId());
   assertNotNull(task.getName());
   assertNotNull(task.getCreateTime());
 }
Пример #3
0
  @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);
  }
Пример #4
0
  /** Test getting a task variable. GET runtime/tasks/{taskId}/variables/{variableName}/data */
  public void testGetTaskVariableData() throws Exception {
    try {
      // Test variable behaviour on standalone tasks
      Task task = taskService.newTask();
      taskService.saveTask(task);
      taskService.setVariableLocal(
          task.getId(), "localTaskVariable", "This is a binary piece of text".getBytes());

      // Force content-type to TEXT_PLAIN to make sure this is ignored and application-octect-stream
      // is always returned
      ClientResource client =
          getAuthenticatedClient(
              RestUrls.createRelativeResourceUrl(
                  RestUrls.URL_TASK_VARIABLE_DATA, task.getId(), "localTaskVariable"));
      client.get(MediaType.TEXT_PLAIN);

      assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());
      String actualResponseBytesAsText = client.getResponse().getEntityAsText();
      assertEquals("This is a binary piece of text", actualResponseBytesAsText);
      assertEquals(MediaType.APPLICATION_OCTET_STREAM.getName(), getMediaType(client));
    } finally {
      // Clean adhoc-tasks even if test fails
      List<Task> tasks = taskService.createTaskQuery().list();
      for (Task task : tasks) {
        taskService.deleteTask(task.getId(), true);
      }
    }
  }
Пример #5
0
  /**
   * @Title: backProcess @Description: 驳回流程
   *
   * @param @param taskId 当前任务ID
   * @param @param activityId 驳回节点ID
   * @param @param variables 流程存储参数
   * @param @throws Exception 设定文件
   * @return void 返回类型
   * @throws
   */
  @Override
  public void backProcess(String taskId, String activityId, Map<String, Object> variables)
      throws Exception {

    if (StringUtil.isStrEmpty(activityId)) {
      throw new Exception("驳回目标节点ID为空!");
    }

    if (this.isJointTask(taskId)) {
      throw new Exception("驳回节点为会签节点,不可以驳回!");
    }

    // TODO 目前还不知道该段代码是做什么的
    // 查询本节点发起的会签任务,并结束
    //		List<Task> tasks = taskService.createTaskQuery().parentTaskId(taskId)
    //				.taskDescription("jointProcess").list();
    //		for (Task task : tasks) {
    //			commitProcess(task.getId(), null, null);
    //		}

    // 查找所有并行任务节点,同时驳回
    List<Task> taskList =
        findTaskListByKey(
            findProcInsByTaskId(taskId).getId(), findTaskById(taskId).getTaskDefinitionKey());
    for (Task task : taskList) {
      commitProcess(task.getId(), variables, activityId);
    }
  }
Пример #6
0
  /** Test getting a task variable. GET runtime/tasks/{taskId}/variables/{variableName}/data */
  public void testGetTaskVariableDataSerializable() throws Exception {
    try {
      TestSerializableVariable originalSerializable = new TestSerializableVariable();
      originalSerializable.setSomeField("This is some field");

      // Test variable behaviour on standalone tasks
      Task task = taskService.newTask();
      taskService.saveTask(task);
      taskService.setVariableLocal(task.getId(), "localTaskVariable", originalSerializable);

      ClientResource client =
          getAuthenticatedClient(
              RestUrls.createRelativeResourceUrl(
                  RestUrls.URL_TASK_VARIABLE_DATA, task.getId(), "localTaskVariable"));
      client.get();
      assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());

      // Read the serializable from the stream
      ObjectInputStream stream =
          new ObjectInputStream(client.getResponse().getEntity().getStream());
      Object readSerializable = stream.readObject();
      assertNotNull(readSerializable);
      assertTrue(readSerializable instanceof TestSerializableVariable);
      assertEquals(
          "This is some field", ((TestSerializableVariable) readSerializable).getSomeField());
      assertEquals(MediaType.APPLICATION_JAVA_OBJECT.getName(), getMediaType(client));
    } finally {
      // Clean adhoc-tasks even if test fails
      List<Task> tasks = taskService.createTaskQuery().list();
      for (Task task : tasks) {
        taskService.deleteTask(task.getId(), true);
      }
    }
  }
Пример #7
0
  @Put
  public TaskResponse updateTask(TaskRequest taskRequest) {
    if (!authenticate()) {
      return null;
    }

    if (taskRequest == null) {
      throw new ResourceException(
          new Status(
              Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode(),
              "A request body was expected when updating the task.",
              null,
              null));
    }

    Task task = getTaskFromRequest();

    // Populate the task properties based on the request
    populateTaskFromRequest(task, taskRequest);

    // Save the task and fetch agian, it's possible that an assignment-listener has updated
    // fields after it was saved so we can't use the in-memory task
    ActivitiUtil.getTaskService().saveTask(task);
    task = ActivitiUtil.getTaskService().createTaskQuery().taskId(task.getId()).singleResult();

    return getApplication(ActivitiRestServicesApplication.class)
        .getRestResponseFactory()
        .createTaskReponse(this, task);
  }
Пример #8
0
  @Delete
  public void deleteTask() {
    if (!authenticate()) {
      return;
    }

    Form query = getQuery();
    Boolean cascadeHistory = getQueryParameterAsBoolean("cascadeHistory", query);
    String deleteReason = getQueryParameter("deleteReason", query);

    Task taskToDelete = getTaskFromRequest();
    if (taskToDelete.getExecutionId() != null) {
      // Can't delete a task that is part of a process instance
      throw new ResourceException(
          new Status(
              Status.CLIENT_ERROR_FORBIDDEN.getCode(),
              "Cannot delete a task that is part of a process-instance.",
              null,
              null));
    }

    if (cascadeHistory != null) {
      // Ignore delete-reason since the task-history (where the reason is recorded) will be deleted
      // anyway
      ActivitiUtil.getTaskService().deleteTask(taskToDelete.getId(), cascadeHistory);
    } else {
      // Delete with delete-reason
      ActivitiUtil.getTaskService().deleteTask(taskToDelete.getId(), deleteReason);
    }
    getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
  }
Пример #9
0
  @Deployment(
      resources = {
        "org/activiti/engine/test/bpmn/event/signal/SignalEventTests.catchMultipleSignals.bpmn20.xml",
        "org/activiti/engine/test/bpmn/event/signal/SignalEventTests.throwAlertSignal.bpmn20.xml",
        "org/activiti/engine/test/bpmn/event/signal/SignalEventTests.throwAbortSignal.bpmn20.xml"
      })
  public void testSignalCatchDifferentSignals() {

    runtimeService.startProcessInstanceByKey("catchSignal");

    assertEquals(2, createEventSubscriptionQuery().count());
    assertEquals(1, runtimeService.createProcessInstanceQuery().count());

    runtimeService.startProcessInstanceByKey("throwAbort");

    assertEquals(1, createEventSubscriptionQuery().count());
    assertEquals(1, runtimeService.createProcessInstanceQuery().count());

    Task taskAfterAbort = taskService.createTaskQuery().taskAssignee("gonzo").singleResult();
    assertNotNull(taskAfterAbort);
    taskService.complete(taskAfterAbort.getId());

    runtimeService.startProcessInstanceByKey("throwSignal");

    assertEquals(0, createEventSubscriptionQuery().count());
    assertEquals(0, runtimeService.createProcessInstanceQuery().count());
  }
Пример #10
0
  @Deployment
  public void testUseSignalForExceptionsBetweenParallelPaths() {
    runtimeService.startProcessInstanceByKey("processWithSignal");

    // First task should be to select the developers
    Task task = taskService.createTaskQuery().singleResult();
    assertEquals("Enter developers", task.getName());
    taskService.complete(
        task.getId(),
        CollectionUtil.singletonMap(
            "developers", Arrays.asList("developerOne", "developerTwo", "developerThree")));

    // Should be three distinct tasks for each developer
    assertEquals(
        "Develop specifications",
        taskService.createTaskQuery().taskAssignee("developerOne").singleResult().getName());
    assertEquals(
        "Develop specifications",
        taskService.createTaskQuery().taskAssignee("developerTwo").singleResult().getName());
    assertEquals(
        "Develop specifications",
        taskService.createTaskQuery().taskAssignee("developerThree").singleResult().getName());

    // Negotiate with client is a task for kermit
    task = taskService.createTaskQuery().taskAssignee("kermit").singleResult();
    assertEquals("Negotiate with client", task.getName());

    // When the kermit task is completed, it throws a signal which should cancel the multi instance
    taskService.complete(task.getId(), CollectionUtil.singletonMap("negotationFailed", true));

    // No tasks should be open then and process should have ended
    assertEquals(0, taskService.createTaskQuery().count());
    assertEquals(0, runtimeService.createExecutionQuery().count());
  }
  /**
   * 跳转到任务执行页面
   *
   * @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";
  }
  @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());
  }
  @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;
  }
Пример #14
0
  /**
   * easyui AJAX请求数据 待领任务
   *
   * @param request
   * @param response
   * @param dataGrid
   */
  @RequestMapping(params = "waitingClaimTaskDataGrid")
  public void waitingClaimTaskDataGrid(
      HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {

    // String userId = "hruser";
    String userId = ResourceUtil.getSessionUserName().getId();
    TaskService taskService = processEngine.getTaskService();
    List<Task> tasks =
        taskService
            .createTaskQuery()
            .taskCandidateUser(userId)
            .active()
            .list(); // .taskCandidateGroup("hr").active().list();

    StringBuffer rows = new StringBuffer();
    for (Task t : tasks) {
      rows.append(
          "{'name':'"
              + t.getName()
              + "','taskId':'"
              + t.getId()
              + "','processDefinitionId':'"
              + t.getProcessDefinitionId()
              + "'},");
    }
    String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");

    JSONObject jObject =
        JSONObject.fromObject("{'total':" + tasks.size() + ",'rows':[" + rowStr + "]}");
    responseDatagrid(response, jObject);
  }
  @Test
  public void testAcknowledgement() {
    TaskService taskService = processEngine.getTaskService();
    FormService formService = processEngine.getFormService();

    List<Task> tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());
    assertEquals("get acknowledgement", tasks.get(0).getName());

    for (Task task : tasks) {
      Map<String, String> formData = new HashMap<String, String>();
      formService.submitTaskFormData(task.getId(), formData); // Stack trace starts here
    }

    tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(0, tasks.size());
  }
  /**
   * Task variation over time i.e. tasks started and completed over the months
   *
   * @return array with the no. of tasks started and completed over the months
   */
  @GET
  @Path("/taskVariation/")
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public ResponseHolder taskVariationOverTime() {
    ResponseHolder response = new ResponseHolder();
    List list = new ArrayList();
    String[] MONTHS = {
      "Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"
    };
    SimpleDateFormat ft = new SimpleDateFormat("M");

    InstanceStatPerMonth[] taskStatPerMonths = new InstanceStatPerMonth[12];
    for (int i = 0; i < taskStatPerMonths.length; i++) {
      taskStatPerMonths[i] = new InstanceStatPerMonth();
      taskStatPerMonths[i].setMonth(MONTHS[i]);
      taskStatPerMonths[i].setCompletedInstances(0);
      taskStatPerMonths[i].setStartedInstances(0);
    }
    // Get completed tasks
    List<HistoricTaskInstance> taskList =
        BPMNOSGIService.getHistoryService()
            .createHistoricTaskInstanceQuery()
            .taskTenantId(str)
            .finished()
            .list();

    for (HistoricTaskInstance instance : taskList) {
      int startTime = Integer.parseInt(ft.format(instance.getCreateTime()));
      int endTime = Integer.parseInt(ft.format(instance.getEndTime()));
      taskStatPerMonths[startTime - 1].setStartedInstances(
          taskStatPerMonths[startTime - 1].getStartedInstances() + 1);
      taskStatPerMonths[endTime - 1].setCompletedInstances(
          taskStatPerMonths[endTime - 1].getCompletedInstances() + 1);
    }
    // Get active/started tasks
    List<Task> taskActive =
        BPMNOSGIService.getTaskService().createTaskQuery().taskTenantId(str).active().list();
    for (Task instance : taskActive) {

      int startTime = Integer.parseInt(ft.format(instance.getCreateTime()));
      taskStatPerMonths[startTime - 1].setStartedInstances(
          taskStatPerMonths[startTime - 1].getStartedInstances() + 1);
    }

    // Get suspended tasks
    List<Task> taskSuspended =
        BPMNOSGIService.getTaskService().createTaskQuery().taskTenantId(str).suspended().list();
    for (Task instance : taskSuspended) {

      int startTime = Integer.parseInt(ft.format(instance.getCreateTime()));
      taskStatPerMonths[startTime - 1].setStartedInstances(
          taskStatPerMonths[startTime - 1].getStartedInstances() + 1);
    }
    for (int i = 0; i < taskStatPerMonths.length; i++) {
      list.add(taskStatPerMonths[i]);
    }
    response.setData(list);
    return response;
  }
Пример #17
0
 /**
  * @Title: isJointTask @Description: 根据taskId判断是否是会签任务节点
  *
  * @param @param taskId
  * @param @return 设定文件
  * @return boolean 返回类型
  * @throws
  */
 public boolean isJointTask(String taskId) {
   Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
   if (task.getTaskLocalVariables().containsKey("nrOfInstances")) {
     return true;
   } else {
     return true;
   }
 }
  @Test
  @Deployment(resources = "diagrams/chapter7/expression.bpmn")
  public void testExpression() {
    MyBean myBean = new MyBean();
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("myBean", myBean);
    String name = "Henry Yan";
    variables.put("name", name);

    // 运行期表达式
    identityService.setAuthenticatedUserId("henryyan");
    String businessKey = "9999"; // 业务ID
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("expression", businessKey, variables);
    assertEquals(
        "henryyan",
        runtimeService.getVariable(processInstance.getId(), "authenticatedUserIdForTest"));
    assertEquals(
        "Henry Yan, added by print(String name)",
        runtimeService.getVariable(processInstance.getId(), "returnValue"));
    assertEquals(businessKey, runtimeService.getVariable(processInstance.getId(), "businessKey"));

    // 显示数据库状态
    List<Map<String, Object>> rows =
        managementService
            .createTablePageQuery()
            .tableName("ACT_HI_DETAIL")
            .listPage(0, 100)
            .getRows();
    for (Map<String, Object> map : rows) {
      Set<Entry<String, Object>> entrySet = map.entrySet();
      for (Entry<String, Object> entry : entrySet) {
        System.out.println(entry.getKey() + " = " + entry.getValue());
      }
      System.out.println("-------------------------");
    }

    System.out.println("==============字节流数据==============");
    rows =
        managementService
            .createTablePageQuery()
            .tableName("ACT_GE_BYTEARRAY")
            .listPage(0, 100)
            .getRows();
    for (Map<String, Object> map : rows) {
      Set<Entry<String, Object>> entrySet = map.entrySet();
      for (Entry<String, Object> entry : entrySet) {
        System.out.println(entry.getKey() + " = " + entry.getValue());
      }
      System.out.println("-------------------------");
    }

    // DelegateTask 设置的变量
    Task task =
        taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    String setByTask = (String) taskService.getVariable(task.getId(), "setByTask");
    assertEquals("I'm setted by DelegateTask, " + name, setByTask);
  }
Пример #19
0
  @Deployment(
      resources = {
        "org/activiti/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"
      })
  public void testTaskDueAfter() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
    Task task =
        taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();

    // Set due-date on task
    Calendar dueDateCal = Calendar.getInstance();
    task.setDueDate(dueDateCal.getTime());
    taskService.saveTask(task);

    Calendar oneHourAgo = Calendar.getInstance();
    oneHourAgo.setTime(dueDateCal.getTime());
    oneHourAgo.add(Calendar.HOUR, -1);

    Calendar oneHourLater = Calendar.getInstance();
    oneHourLater.setTime(dueDateCal.getTime());
    oneHourLater.add(Calendar.HOUR, 1);

    assertEquals(
        1,
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .dueAfter(oneHourAgo.getTime())
            .count());
    assertEquals(
        0,
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .dueAfter(oneHourLater.getTime())
            .count());

    // Update due-date to null, shouldn't show up anymore in query that matched before
    task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    task.setDueDate(null);
    taskService.saveTask(task);

    assertEquals(
        0,
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .dueAfter(oneHourLater.getTime())
            .count());
    assertEquals(
        0,
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .dueAfter(oneHourAgo.getTime())
            .count());
  }
 @Override
 public List<PiecejustifDTO> getPieceJustifFromProcess(Long dossierId, ValidationTask step) {
   Task task =
       taskService
           .createTaskQuery()
           .processInstanceBusinessKey(dossierId.toString())
           .taskDefinitionKey(step.getValue())
           .singleResult();
   return (List<PiecejustifDTO>) runtimeService.getVariable(task.getExecutionId(), "piecejustifs");
 }
Пример #21
0
  @Test
  @Ignore
  public void testHappyPath() {

    // Create test applicant
    Applicant applicant = new Applicant("John Doe", "*****@*****.**", "12344");
    applicantRepository.save(applicant);

    // Start process instance
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("applicant", applicant);
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("hireProcessWithJpa", variables);

    // First, the 'phone interview' should be active
    Task task =
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .taskCandidateGroup("dev-managers")
            .singleResult();
    Assert.assertEquals("Telephone interview", task.getName());

    // Completing the phone interview with success should trigger two new tasks
    Map<String, Object> taskVariables = new HashMap<String, Object>();
    taskVariables.put("telephoneInterviewOutcome", true);
    taskService.complete(task.getId(), taskVariables);

    List<Task> tasks =
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .orderByTaskName()
            .asc()
            .list();
    Assert.assertEquals(2, tasks.size());
    Assert.assertEquals("Financial negotiation", tasks.get(0).getName());
    Assert.assertEquals("Tech interview", tasks.get(1).getName());

    // Completing both should wrap up the subprocess, send out the 'welcome mail' and end the
    // process instance
    taskVariables = new HashMap<String, Object>();
    taskVariables.put("techOk", true);
    taskService.complete(tasks.get(0).getId(), taskVariables);

    taskVariables = new HashMap<String, Object>();
    taskVariables.put("financialOk", true);
    taskService.complete(tasks.get(1).getId(), taskVariables);

    // Verify email
    Assert.assertEquals(1, wiser.getMessages().size());

    // Verify process completed
    Assert.assertEquals(1, historyService.createHistoricProcessInstanceQuery().finished().count());
  }
 private List<Defect> findDefects(String username, String taskName) {
   List<Task> tasks = taskService.createTaskQuery().taskAssignee(username).list();
   List<Long> defectIds = new ArrayList<Long>();
   for (Task task : tasks) {
     if (task.getName().equalsIgnoreCase(taskName)) {
       Long defectId = (Long) runtimeService.getVariable(task.getExecutionId(), "defectId");
       defectIds.add(defectId);
     }
   }
   return defectRepository.findByIds(defectIds);
 }
  private void assertThatErrorHasBeenCaught(String procId) {
    // The service task will throw an error event,
    // which is caught on the service task boundary
    assertEquals("No tasks found in task list.", 1, taskService.createTaskQuery().count());
    Task task = taskService.createTaskQuery().singleResult();
    assertEquals("Escalated Task", task.getName());

    // Completing the task will end the process instance
    taskService.complete(task.getId());
    assertProcessEnded(procId);
  }
Пример #24
0
  /**
   * 查询待办任务
   *
   * @param userId 用户ID
   * @return
   */
  public List<Leave> findTodoTasks(String userId) {

    List<Leave> results = new ArrayList<Leave>();
    List<Task> tasks = new ArrayList<Task>();
    // 根据当前人的ID查询
    List<Task> todoList =
        taskService
            .createTaskQuery()
            .processDefinitionKey(ActUtils.PD_LEAVE[0])
            .taskAssignee(userId)
            .active()
            .orderByTaskPriority()
            .desc()
            .orderByTaskCreateTime()
            .desc()
            .list();
    // 根据当前人未签收的任务
    List<Task> unsignedTasks =
        taskService
            .createTaskQuery()
            .processDefinitionKey(ActUtils.PD_LEAVE[0])
            .taskCandidateUser(userId)
            .active()
            .orderByTaskPriority()
            .desc()
            .orderByTaskCreateTime()
            .desc()
            .list();
    // 合并
    tasks.addAll(todoList);
    tasks.addAll(unsignedTasks);
    // 根据流程的业务ID查询实体并关联
    for (Task task : tasks) {
      String processInstanceId = task.getProcessInstanceId();
      ProcessInstance processInstance =
          runtimeService
              .createProcessInstanceQuery()
              .processInstanceId(processInstanceId)
              .active()
              .singleResult();
      String businessKey = processInstance.getBusinessKey();
      Leave leave = leaveDao.get(businessKey);
      leave.setTask(task);
      leave.setProcessInstance(processInstance);
      leave.setProcessDefinition(
          repositoryService
              .createProcessDefinitionQuery()
              .processDefinitionId((processInstance.getProcessDefinitionId()))
              .singleResult());
      results.add(leave);
    }
    return results;
  }
Пример #25
0
  @Deployment(
      resources = {
        "org/activiti/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"
      })
  public void testTaskDueDate() 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())
            .dueDate(dueDate)
            .count());

    Calendar otherDate = Calendar.getInstance();
    otherDate.add(Calendar.YEAR, 1);
    assertEquals(
        0,
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .dueDate(otherDate.getTime())
            .count());

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

    assertEquals(
        1,
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .dueAfter(priorDate.getTime())
            .count());

    assertEquals(
        1,
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .dueBefore(otherDate.getTime())
            .count());
  }
Пример #26
0
 @Test
 public void testSetAssignee() {
   ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
   IdentityService identityService = engine.getIdentityService();
   User user = creatUser(identityService, "user1", "张三", "last", "*****@*****.**", "123");
   TaskService taskService = engine.getTaskService();
   Task task1 = taskService.newTask("task1");
   task1.setName("申请任务");
   taskService.saveTask(task1);
   taskService.setAssignee(task1.getId(), user.getId());
   System.out.println(
       "用户张三受理的任务数量:" + taskService.createTaskQuery().taskAssignee(user.getId()).count());
 }
Пример #27
0
  @Deployment
  public void testNoneEndEventAfterSignalInConcurrentProcess() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("my-process");
    assertNotNull(processInstance);

    Task task = taskService.createTaskQuery().taskDefinitionKey("usertask1").singleResult();
    taskService.claim(task.getId(), "user");
    taskService.complete(task.getId());

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

    assertEquals("usertask2", task.getTaskDefinitionKey());
  }
  public TTaskAbstract adapt(Task vendorTask) {
    TTaskAbstract taskAbstract = new TTaskAbstract();
    taskAbstract.setId(vendorTask.getId());
    taskAbstract.setName(new QName(vendorTask.getName()));
    // taskAbstract.set ->  vendorTask.getAssignee()
    taskAbstract.setPresentationName(vendorTask.getDescription()); // /not sure about this
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(vendorTask.getCreateTime());
    taskAbstract.setCreatedOn(new XMLGregorianCalendarImpl(calendar));
    taskAbstract.setPriority(BigInteger.valueOf(vendorTask.getPriority()));

    return taskAbstract;
  }
  @Deployment
  public void testCatchErrorOnEmbeddedSubprocess() {
    runtimeService.startProcessInstanceByKey("boundaryErrorOnEmbeddedSubprocess");

    // After process start, usertask in subprocess should exist
    Task task = taskService.createTaskQuery().singleResult();
    assertEquals("subprocessTask", task.getName());

    // After task completion, error end event is reached and caught
    taskService.complete(task.getId());
    task = taskService.createTaskQuery().singleResult();
    assertEquals("task after catching the error", task.getName());
  }
Пример #30
0
  @Test
  @Deployment(resources = {PROCESS_RESOURCE})
  public void processRejected() throws InterruptedException {
    Map<String, Object> procVars = createStartFormVariables();

    ProcessInstance pi =
        activitiRule
            .getProcessEngine()
            .getRuntimeService()
            .startProcessInstanceByKey(PROCESS_KEY, procVars);

    //		assertNotNull(pi);

    Task task = activitiRule.getTaskService().createTaskQuery().singleResult();
    //		assertNotNull(task);

    Map<String, Object> taskVars = new HashMap<String, Object>();
    taskVars.put("decide", "reject");
    activitiRule.getProcessEngine().getTaskService().complete(task.getId(), taskVars);

    HistoryService historyService = activitiRule.getHistoryService();

    HistoricProcessInstance historicProcessInstance =
        historyService
            .createHistoricProcessInstanceQuery()
            .processInstanceId(pi.getProcessInstanceId())
            .singleResult();

    //		assertNotNull(historicProcessInstance);
    // check that only one process running
    //		assertEquals(pi.getProcessInstanceId(), historicProcessInstance.getId());

    List<HistoricActivityInstance> activityList =
        historyService
            .createHistoricActivityInstanceQuery()
            .processInstanceId(pi.getProcessInstanceId())
            .list();

    JobQuery jquery = activitiRule.getManagementService().createJobQuery();

    // check how many tasks must be done
    //		assertEquals("done task count", 6, activityList.size());

    // and the job is done
    //		assertEquals("job is done", 0, jquery.count());

    //		assertEquals(0, activitiRule.getProcessEngine().getRuntimeService()
    //				.createProcessInstanceQuery().count());

  }