Example #1
0
  /**
   * Generates some test tasks. - 6 tasks where kermit is a candidate - 1 tasks where gonzo is
   * assignee - 2 tasks assigned to management group - 2 tasks assigned to accountancy group - 1
   * task assigned to both the management and accountancy group
   */
  private List<String> generateTestTasks() throws Exception {
    List<String> ids = new ArrayList<String>();

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
    // 6 tasks for kermit
    ClockUtil.setCurrentTime(sdf.parse("01/01/2001 01:01:01.000"));
    for (int i = 0; i < 6; i++) {
      Task task = taskService.newTask();
      task.setName("testTask");
      task.setDescription("testTask description");
      task.setPriority(3);
      taskService.saveTask(task);
      ids.add(task.getId());
      taskService.addCandidateUser(task.getId(), "kermit");
    }

    ClockUtil.setCurrentTime(sdf.parse("02/02/2002 02:02:02.000"));
    // 1 task for gonzo
    Task task = taskService.newTask();
    task.setName("gonzoTask");
    task.setDescription("gonzo description");
    task.setPriority(4);
    taskService.saveTask(task);
    taskService.setAssignee(task.getId(), "gonzo");
    taskService.setVariable(task.getId(), "testVar", "someVariable");
    ids.add(task.getId());

    ClockUtil.setCurrentTime(sdf.parse("03/03/2003 03:03:03.000"));
    // 2 tasks for management group
    for (int i = 0; i < 2; i++) {
      task = taskService.newTask();
      task.setName("managementTask");
      task.setPriority(10);
      taskService.saveTask(task);
      taskService.addCandidateGroup(task.getId(), "management");
      ids.add(task.getId());
    }

    ClockUtil.setCurrentTime(sdf.parse("04/04/2004 04:04:04.000"));
    // 2 tasks for accountancy group
    for (int i = 0; i < 2; i++) {
      task = taskService.newTask();
      task.setName("accountancyTask");
      task.setName("accountancy description");
      taskService.saveTask(task);
      taskService.addCandidateGroup(task.getId(), "accountancy");
      ids.add(task.getId());
    }

    ClockUtil.setCurrentTime(sdf.parse("05/05/2005 05:05:05.000"));
    // 1 task assigned to management and accountancy group
    task = taskService.newTask();
    task.setName("managementAndAccountancyTask");
    taskService.saveTask(task);
    taskService.addCandidateGroup(task.getId(), "management");
    taskService.addCandidateGroup(task.getId(), "accountancy");
    ids.add(task.getId());

    return ids;
  }
  protected void setVariable(
      Task task, String name, Object value, RestVariableScope scope, boolean isNew) {
    // Create can only be done on new variables. Existing variables should be updated using PUT
    boolean hasVariable = hasVariableOnScope(task, name, scope);
    if (isNew && hasVariable) {
      throw new ActivitiException(
          "Variable '" + name + "' is already present on task '" + task.getId() + "'.");
    }

    if (!isNew && !hasVariable) {
      throw new ActivitiObjectNotFoundException(
          "Task '" + task.getId() + "' doesn't have a variable with name: '" + name + "'.", null);
    }

    if (scope == RestVariableScope.LOCAL) {
      taskService.setVariableLocal(task.getId(), name, value);
    } else {
      if (task.getExecutionId() != null) {
        // Explicitly set on execution, setting non-local variable on task will override
        // local-variable if exists
        runtimeService.setVariable(task.getExecutionId(), name, value);
      } else {
        // Standalone task, no global variables possible
        throw new ActivitiIllegalArgumentException(
            "Cannot set global variable '"
                + name
                + "' on task '"
                + task.getId()
                + "', task is not part of process.");
      }
    }
  }
Example #3
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);
  }
Example #4
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 args */
 public static void main(String[] args) {
   // 创建流程引擎
   ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
   // 得到流程存储服务组件
   RepositoryService repositoryService = engine.getRepositoryService();
   // 得到运行时服务组件
   RuntimeService runtimeService = engine.getRuntimeService();
   // 获取流程任务组件
   TaskService taskService = engine.getTaskService();
   // 部署流程文件
   repositoryService
       .createDeployment()
       .addClasspathResource("bpmn11.5/SignalBoundaryEvent.bpmn")
       .deploy();
   // 启动2个流程实例
   ProcessInstance pi1 = runtimeService.startProcessInstanceByKey("sbProcess");
   ProcessInstance pi2 = runtimeService.startProcessInstanceByKey("sbProcess");
   // 查找第一个流程实例中签订合同的任务
   Task pi1Task = taskService.createTaskQuery().processInstanceId(pi1.getId()).singleResult();
   taskService.complete(pi1Task.getId());
   // 查找第二个流程实例中签订合同的任务
   Task pi2Task = taskService.createTaskQuery().processInstanceId(pi2.getId()).singleResult();
   taskService.complete(pi2Task.getId());
   // 此时执行流到达确认合同任务,发送一次信号
   runtimeService.signalEventReceived("contactChangeSignal");
   // 查询全部的任务
   List<Task> tasks = taskService.createTaskQuery().list();
   // 输出结果
   for (Task task : tasks) {
     System.out.println(task.getProcessInstanceId() + "---" + task.getName());
   }
 }
  /**
   * Generates some test tasks. - 2 tasks where kermit is a candidate and 1 task where gonzo is
   * assignee
   */
  private List<String> generateTestTasks() throws Exception {
    List<String> ids = new ArrayList<String>();

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
    // 2 tasks for kermit
    ClockUtil.setCurrentTime(sdf.parse("01/01/2001 01:01:01.000"));
    for (int i = 0; i < 2; i++) {
      Task task = taskService.newTask();
      task.setName("testTask");
      task.setDescription("testTask description");
      task.setPriority(3);
      taskService.saveTask(task);
      ids.add(task.getId());
      taskService.setVariableLocal(task.getId(), "test", "test");
      taskService.addCandidateUser(task.getId(), "kermit");
    }

    ClockUtil.setCurrentTime(sdf.parse("02/02/2002 02:02:02.000"));
    // 1 task for gonzo
    Task task = taskService.newTask();
    task.setName("gonzoTask");
    task.setDescription("gonzo description");
    task.setPriority(4);
    taskService.saveTask(task);
    taskService.setAssignee(task.getId(), "gonzo");
    taskService.setVariableLocal(task.getId(), "testVar", "someVariable");
    taskService.setVariableLocal(task.getId(), "testVar2", 123);
    ids.add(task.getId());

    return ids;
  }
  /** 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);
      }
    }
  }
  private void assertErrorCaughtInConcurrentEmbeddedSubprocesses(String processDefinitionKey) {
    // Completing task A will lead to task D
    String procId = runtimeService.startProcessInstanceByKey(processDefinitionKey).getId();
    List<Task> tasks = taskService.createTaskQuery().orderByTaskName().asc().list();
    assertEquals(2, tasks.size());
    assertEquals("task A", tasks.get(0).getName());
    assertEquals("task B", tasks.get(1).getName());
    taskService.complete(tasks.get(0).getId());
    Task task = taskService.createTaskQuery().singleResult();
    assertEquals("task D", task.getName());
    taskService.complete(task.getId());
    assertProcessEnded(procId);

    // Completing task B will lead to task C
    procId = runtimeService.startProcessInstanceByKey(processDefinitionKey).getId();
    tasks = taskService.createTaskQuery().orderByTaskName().asc().list();
    assertEquals(2, tasks.size());
    assertEquals("task A", tasks.get(0).getName());
    assertEquals("task B", tasks.get(1).getName());
    taskService.complete(tasks.get(1).getId());

    tasks = taskService.createTaskQuery().orderByTaskName().asc().list();
    assertEquals(2, tasks.size());
    assertEquals("task A", tasks.get(0).getName());
    assertEquals("task C", tasks.get(1).getName());
    taskService.complete(tasks.get(1).getId());
    task = taskService.createTaskQuery().singleResult();
    assertEquals("task A", task.getName());

    taskService.complete(task.getId());
    task = taskService.createTaskQuery().singleResult();
    assertEquals("task D", task.getName());
  }
  /** 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);
      }
    }
  }
  @Test
  public void testCouponValidation() {
    TaskService taskService = processEngine.getTaskService();
    FormService formService = processEngine.getFormService();

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

    /** Invalid coupon hash */
    for (Task task : tasks) {
      assertNotNull(task);
      assertEquals("get coupon", task.getName());
      Map<String, String> formData = new HashMap<String, String>();
      formData.put("hash", "abc");
      formService.submitTaskFormData(task.getId(), formData);

      break;
    }

    tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());

    /** Valid coupon hash */
    for (Task task : tasks) {
      assertNotNull(task);
      assertEquals("get coupon", task.getName());
      Map<String, String> formData = new HashMap<String, String>();
      formData.put("hash", "abcd");
      formService.submitTaskFormData(task.getId(), formData);

      break;
    }

    // check if the price was reduced correctly
    Object price = runtimeService.getVariable(processInstance.getId(), "price");
    assertNotNull(price);
    assertEquals(new Double(130), price);

    // 'get bank transfer data' should be next on the list
    tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());
    assertEquals("get bank transfer data", tasks.get(0).getName());
  }
  @Test
  public void testBankTransferValidation() {
    TaskService taskService = processEngine.getTaskService();
    FormService formService = processEngine.getFormService();

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

    // Invalid bank data
    for (Task task : tasks) {
      assertNotNull(task);
      assertEquals("get bank transfer data", task.getName());
      Map<String, String> formData = new HashMap<String, String>();
      formData.put("bankName", "Bank austria"); // invalid bank-name
      formData.put("bankCode", "12000");
      formData.put("accountNumber", "12345678901");
      formData.put("holdersName", "Max Muster");
      formService.submitTaskFormData(task.getId(), formData);
    }

    tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());
    // As of an error the form should be empty
    assertEquals(0, formService.getTaskFormData(tasks.get(0).getId()).getFormProperties().size());

    // Valid bank data
    for (Task task : tasks) {
      assertNotNull(task);
      assertEquals("get bank transfer data", task.getName());
      Map<String, String> formData = new HashMap<String, String>();
      formData.put("bankName", "Bank Austria");
      formData.put("bankCode", "12000");
      formData.put("accountNumber", "12345678901");
      formData.put("holdersName", "Max Muster");
      formService.submitTaskFormData(task.getId(), formData); // Stack trace starts here
    }

    tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());
    assertEquals("get acknowledgement", tasks.get(0).getName());
  }
  /**
   * Test updating a single task variable using a binary stream. PUT
   * runtime/tasks/{taskId}/variables/{variableName}
   */
  public void testUpdateBinaryTaskVariable() throws Exception {
    try {
      Task task = taskService.newTask();
      taskService.saveTask(task);
      taskService.setVariable(task.getId(), "binaryVariable", "Original value".getBytes());

      InputStream binaryContent = new ByteArrayInputStream("This is binary content".getBytes());

      // Add name, type and scope
      Map<String, String> additionalFields = new HashMap<String, String>();
      additionalFields.put("name", "binaryVariable");
      additionalFields.put("type", "binary");
      additionalFields.put("scope", "local");

      // Upload a valid BPMN-file using multipart-data
      Representation uploadRepresentation =
          new HttpMultipartRepresentation("value", binaryContent, additionalFields);

      ClientResource client =
          getAuthenticatedClient(
              RestUrls.createRelativeResourceUrl(
                  RestUrls.URL_TASK_VARIABLE, task.getId(), "binaryVariable"));
      Representation response = client.put(uploadRepresentation);
      assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());

      JsonNode responseNode = objectMapper.readTree(response.getStream());
      assertNotNull(responseNode);
      assertEquals("binaryVariable", responseNode.get("name").asText());
      assertTrue(responseNode.get("value").isNull());
      assertEquals("local", responseNode.get("scope").asText());
      assertEquals("binary", responseNode.get("type").asText());
      assertNotNull(responseNode.get("valueUrl").isNull());
      assertTrue(
          responseNode
              .get("valueUrl")
              .asText()
              .endsWith(
                  RestUrls.createRelativeResourceUrl(
                      RestUrls.URL_TASK_VARIABLE_DATA, task.getId(), "binaryVariable")));

      // Check actual value of variable in engine
      Object variableValue = taskService.getVariableLocal(task.getId(), "binaryVariable");
      assertNotNull(variableValue);
      assertTrue(variableValue instanceof byte[]);
      assertEquals("This is binary content", new String((byte[]) variableValue));
    } finally {
      // Clean adhoc-tasks even if test fails
      List<Task> tasks = taskService.createTaskQuery().list();
      for (Task task : tasks) {
        taskService.deleteTask(task.getId(), true);
      }
    }
  }
Example #13
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());
  }
  /**
   * 调用Webservice后决定是否需要总经理审批
   *
   * <p>请先执行LeaveWebserviceUtil#main方法发布WebService
   */
  @Test
  @Deployment(resources = "diagrams/leave-webservice.bpmn")
  public void testWithWebserviceFalse() throws Exception {

    // 验证是否部署成功
    long count = repositoryService.createProcessDefinitionQuery().count();
    assertEquals(1, count);

    ProcessDefinition processDefinition =
        repositoryService
            .createProcessDefinitionQuery()
            .processDefinitionKey("leave-webservice")
            .singleResult();

    // 设置当前用户
    String currentUserId = "henryyan";
    identityService.setAuthenticatedUserId(currentUserId);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Map<String, String> variables = new HashMap<String, String>();
    Calendar ca = Calendar.getInstance();
    String startDate = sdf.format(ca.getTime());
    ca.add(Calendar.DAY_OF_MONTH, 2); // 当前日期加2天
    String endDate = sdf.format(ca.getTime());

    // 启动流程
    variables.put("startDate", startDate);
    variables.put("endDate", endDate);
    variables.put("reason", "公休");
    ProcessInstance processInstance =
        formService.submitStartFormData(processDefinition.getId(), variables);
    assertNotNull(processInstance);

    // 部门领导审批通过
    Task deptLeaderTask =
        taskService.createTaskQuery().taskCandidateGroup("deptLeader").singleResult();
    variables = new HashMap<String, String>();
    variables.put("deptLeaderApproved", "true");
    formService.submitTaskFormData(deptLeaderTask.getId(), variables);

    // 人事审批通过
    Task hrTask = taskService.createTaskQuery().taskCandidateGroup("hr").singleResult();
    variables = new HashMap<String, String>();
    variables.put("hrApproved", "true");
    formService.submitTaskFormData(hrTask.getId(), variables);

    // 判断是否执行了webservice
    Boolean needed = (Boolean) runtimeService.getVariable(processInstance.getId(), "needed");
    assertFalse(needed);
  }
  @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);
  }
  @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());
  }
Example #17
0
  /**
   * easyui AJAX请求数据 待办任务
   *
   * @param request
   * @param response
   * @param dataGrid
   */
  @RequestMapping(params = "claimedTaskDataGrid")
  public void claimedTaskDataGrid(
      HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {

    // String userId = "leaderuser";
    String userId = ResourceUtil.getSessionUserName().getId();
    TaskService taskService = processEngine.getTaskService();
    List<Task> tasks = taskService.createTaskQuery().taskAssignee(userId).list();

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

    JSONObject jObject =
        JSONObject.fromObject("{'total':" + tasks.size() + ",'rows':[" + rowStr + "]}");
    responseDatagrid(response, jObject);
  }
  @Test
  public void testRemindCustomer() {
    createNewProcess();
    runtimeService.setVariable(pid, "RemainderAmount", "0");
    Task nextTask = taskService.createTaskQuery().singleResult();
    HashMap<String, String> map = new HashMap<String, String>();
    formService.submitTaskFormData(nextTask.getId(), map);

    Task nextTask2 = taskService.createTaskQuery().singleResult();
    formService.submitTaskFormData(nextTask2.getId(), map);

    Task nextTask3 = taskService.createTaskQuery().singleResult();
    formService.submitTaskFormData(nextTask3.getId(), map);

    Task lastTasks = taskService.createTaskQuery().singleResult();
  }
 @Test
 public void testMail() {
   createNewProcess();
   Task nextTask = taskService.createTaskQuery().singleResult();
   HashMap<String, String> map = new HashMap<String, String>();
   formService.submitTaskFormData(nextTask.getId(), map);
 }
  protected RestVariable setSimpleVariable(RestVariable restVariable, Task task, boolean isNew) {
    if (restVariable.getName() == null) {
      throw new ActivitiIllegalArgumentException("Variable name is required");
    }

    // Figure out scope, revert to local is omitted
    RestVariableScope scope = restVariable.getVariableScope();
    if (scope == null) {
      scope = RestVariableScope.LOCAL;
    }

    Object actualVariableValue =
        getApplication(ActivitiRestServicesApplication.class)
            .getRestResponseFactory()
            .getVariableValue(restVariable);
    setVariable(task, restVariable.getName(), actualVariableValue, scope, isNew);

    return getApplication(ActivitiRestServicesApplication.class)
        .getRestResponseFactory()
        .createRestVariable(
            this,
            restVariable.getName(),
            actualVariableValue,
            scope,
            task.getId(),
            null,
            null,
            false);
  }
Example #21
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());
  }
  /**
   * @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);
    }
  }
  @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;
  }
Example #24
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);
  }
Example #25
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());
 }
  @Override
  public void receiveDossier(Task task, Dossier dossier) {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("gender", dossier.getOwner().getGender().toString());
    params.put("lastname", dossier.getOwner().getLastName());
    params.put("nomEnfant", dossier.getCandidat().getLastname());
    params.put("prenomEnfant", dossier.getCandidat().getFirstname());
    params.put("firstname", dossier.getOwner().getFirstName());
    params.put("refdossier", dossier.getGeneratedNumDossier());

    try {
      EmailDTO email =
          emailService.populateEmail(
              EmailType.PIECES_RECEIVED, dossier.getOwner().getEmail(), sender, params, "", "");
      emailService.prepare(email);

      InboxMessage message = new InboxMessage();
      message.setParentUser(dossier.getOwner());
      message.setSubject(email.getSubject());
      message.setContent(email.getMessage());
      message.setMsgDate(new Date());
      message.setMsgStatus(InboxMessageStatus.UNREAD);
      inboxMessageRepos.save(message);
    } catch (Exception e) {
      e.printStackTrace();
    }

    taskService.complete(task.getId());
  }
 @Override
 public void acceptAnalysedDossier(Task task, Dossier dossier) {
   // Initialise process variables
   Map<String, Object> processParams = new HashMap<String, Object>();
   processParams.put("accepte", true);
   taskService.complete(task.getId(), processParams);
 }
  @Deployment
  public void testCatchErrorOnSequentialMultiInstance() {
    String procId = runtimeService.startProcessInstanceByKey("catchErrorOnSequentialMi").getId();

    // complete one task
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("throwError", false);
    Task task = taskService.createTaskQuery().singleResult();
    taskService.complete(task.getId(), vars);

    // complete second task and throw error
    vars.put("throwError", true);
    task = taskService.createTaskQuery().singleResult();
    taskService.complete(task.getId(), vars);

    assertProcessEnded(procId);
  }
Example #29
0
 @Test
 public void test() {
   ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
   RepositoryService repositoryService = engine.getRepositoryService();
   RuntimeService runtimeService = engine.getRuntimeService();
   TaskService taskService = engine.getTaskService();
   repositoryService.createDeployment().addClasspathResource("bpmn/first.bpmn").deploy();
   runtimeService.startProcessInstanceByKey("process1");
   Task task = taskService.createTaskQuery().singleResult();
   System.out.println("第一个任务完成前,当前任务名称:" + task.getName());
   taskService.complete(task.getId());
   task = taskService.createTaskQuery().singleResult();
   System.out.println("第二个任务完成前,当前任务名称:" + task.getName());
   taskService.complete(task.getId());
   task = taskService.createTaskQuery().singleResult();
   System.out.println("流程结束后,查找任务:" + task);
 }
  /** Test getting a task variable. GET runtime/tasks/{taskId}/variables/{variableName}/data */
  public void testGetTaskVariableDataForIllegalVariables() throws Exception {
    try {
      // Test variable behaviour on standalone tasks
      Task task = taskService.newTask();
      taskService.saveTask(task);
      taskService.setVariableLocal(
          task.getId(), "localTaskVariable", "this is a plain string variable");

      // Try getting data for non-binary variable
      ClientResource client =
          getAuthenticatedClient(
              RestUrls.createRelativeResourceUrl(
                  RestUrls.URL_TASK_VARIABLE_DATA, task.getId(), "localTaskVariable"));
      try {
        client.get();
        fail("Exception expected");
      } catch (ResourceException expected) {
        assertEquals(Status.CLIENT_ERROR_NOT_FOUND, expected.getStatus());
        assertEquals(
            "The variable does not have a binary data stream.",
            expected.getStatus().getDescription());
      }

      // Try getting data for unexisting property
      client =
          getAuthenticatedClient(
              RestUrls.createRelativeResourceUrl(
                  RestUrls.URL_TASK_VARIABLE_DATA, task.getId(), "unexistingVariable"));
      try {
        client.get();
        fail("Exception expected");
      } catch (ResourceException expected) {
        assertEquals(Status.CLIENT_ERROR_NOT_FOUND, expected.getStatus());
        assertEquals(
            "Task '" + task.getId() + "' doesn't have a variable with name: 'unexistingVariable'.",
            expected.getStatus().getDescription());
      }

    } finally {
      // Clean adhoc-tasks even if test fails
      List<Task> tasks = taskService.createTaskQuery().list();
      for (Task task : tasks) {
        taskService.deleteTask(task.getId(), true);
      }
    }
  }