/**
   * @param tasks
   * @return
   */
  public List<TaskVo> buildTaskVos(List<Task> tasks) {
    List<TaskVo> taskRtn = new ArrayList<>();

    if (null != tasks && !tasks.isEmpty()) {
      // 根据流程的业务ID查询实体并关联
      for (Task task : tasks) {

        String processInstanceId = task.getProcessInstanceId();
        ProcessInstance processInstance =
            runtimeService
                .createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .active()
                .singleResult();
        String businessName = (String) task.getTaskLocalVariables().get(WebConstants.BUSINESS_NAME);
        String taskId = task.getId();
        String businessKey = processInstance.getBusinessKey();

        if (StringUtils.isBlank(businessKey)) {
          continue;
        }
        if (StringUtils.isBlank(businessName)) {
          businessName = getBusinessName(taskId, businessKey);
        }

        ProcessDefinition processDefinition =
            getProcessDefinition(processInstance.getProcessDefinitionId());
        int version = processDefinition.getVersion();
        String taskName = task.getName();
        String createTime =
            DateUtils.SINGLETONE.format(task.getCreateTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
        String assignee = task.getAssignee();
        boolean suspended = task.isSuspended();

        String processDefinitionId = processInstance.getProcessDefinitionId();

        TaskVo taskInfo = new TaskVo();
        taskInfo.setProcessInstanceId(processInstanceId);
        taskInfo.setBusinessKey(businessKey);
        taskInfo.setProcessDefinitionId(processDefinitionId);
        taskInfo.setId(taskId);
        taskInfo.setName(taskName);
        taskInfo.setCreateTime(createTime);
        taskInfo.setAssignee(assignee);
        taskInfo.setSuspended(suspended);
        taskInfo.setVersion(version);
        taskInfo.setBusinessName(businessName);
        taskRtn.add(taskInfo);
      }
    }
    return taskRtn;
  }
  @Override
  public void startFlow(String key, String user) {
    ProcessInstance ins = runtimeService.startProcessInstanceByKey(key);
    String actInstId = ins.getProcessDefinitionId();
    String actDefId = ins.getProcessDefinitionId();

    AppUser appUser = userService.getByUserName(key);

    FlowInstance flowIns = new FlowInstance();
    flowIns.setActDefId(actDefId);
    flowIns.setActInstId(actInstId);
    flowIns.setCreator(key);
    flowIns.setCreatorId(appUser.getUserId());
  }
  public StreamResource buildStreamResource(
      ProcessInstance processInstance,
      RepositoryService repositoryService,
      RuntimeService runtimeService) {

    StreamResource imageResource = null;

    ProcessDefinitionEntity processDefinition =
        (ProcessDefinitionEntity)
            ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(processInstance.getProcessDefinitionId());

    if (processDefinition != null && processDefinition.isGraphicalNotationDefined()) {
      InputStream definitionImageStream =
          ProcessDiagramGenerator.generateDiagram(
              processDefinition,
              "png",
              runtimeService.getActiveActivityIds(processInstance.getId()));

      StreamSource streamSource = new InputStreamStreamSource(definitionImageStream);

      // Create image name
      String imageExtension = extractImageExtension(processDefinition.getDiagramResourceName());
      String fileName = processInstance.getId() + UUID.randomUUID() + "." + imageExtension;

      imageResource = new StreamResource(streamSource, fileName, ExplorerApp.get());
    }
    return imageResource;
  }
Exemple #4
0
  /**
   * 跳转到流程图型显示页面
   *
   * @return
   */
  public String process_diagram() {
    String processDefinitionId = getpara("processDefinitionId");
    String processInstanceId = getpara("processInstanceId");

    if (processDefinitionId.equals("")) {
      ProcessInstance processInstance =
          runtimeService
              .createProcessInstanceQuery()
              .processInstanceId(processInstanceId)
              .singleResult();
      processDefinitionId = processInstance.getProcessDefinitionId();
    }
    ProcessDefinition processDefinition =
        repositoryService
            .createProcessDefinitionQuery()
            .processDefinitionId(processDefinitionId)
            .singleResult();
    InputStream in =
        repositoryService.getResourceAsStream(
            processDefinition.getDeploymentId(), processDefinition.getDiagramResourceName());
    try {
      rhs.put("imgWidth", ImageIO.read(in).getWidth());
      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

    rhs.put("processDefinitionId", processDefinitionId);
    rhs.put("processInstanceId", processInstanceId);
    return "success";
  }
  /**
   * easyui 运行中流程列表数据
   *
   * @param request
   * @param response
   * @param dataGrid
   */
  @RequestMapping(params = "runningProcessDataGrid")
  public void runningProcessDataGrid(
      HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {

    /*
     * List<HistoricProcessInstance> historicProcessInstances =
     * historyService .createHistoricProcessInstanceQuery()
     * .unfinished().list();
     */
    ProcessInstanceQuery processInstanceQuery = runtimeService.createProcessInstanceQuery();
    List<ProcessInstance> list = processInstanceQuery.list();

    StringBuffer rows = new StringBuffer();
    for (ProcessInstance hi : list) {
      rows.append(
          "{'id':"
              + hi.getId()
              + ",'processDefinitionId':'"
              + hi.getProcessDefinitionId()
              + "','processInstanceId':'"
              + hi.getProcessInstanceId()
              + "','activityId':'"
              + hi.getActivityId()
              + "'},");
    }

    String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");

    JSONObject jObject =
        JSONObject.fromObject("{'total':" + list.size() + ",'rows':[" + rowStr + "]}");
    responseDatagrid(response, jObject);
  }
  /**
   * 读取资源,通过部署ID
   *
   * @param processDefinitionId 流程定义ID
   * @param processInstanceId 流程实例ID
   * @param resourceType 资源类型(xml|image)
   */
  public InputStream resourceRead(String procDefId, String proInsId, String resType)
      throws Exception {

    if (StringUtils.isBlank(procDefId)) {
      ProcessInstance processInstance =
          runtimeService.createProcessInstanceQuery().processInstanceId(proInsId).singleResult();
      procDefId = processInstance.getProcessDefinitionId();
    }
    ProcessDefinition processDefinition =
        repositoryService
            .createProcessDefinitionQuery()
            .processDefinitionId(procDefId)
            .singleResult();

    String resourceName = "";
    if (resType.equals("image")) {
      resourceName = processDefinition.getDiagramResourceName();
    } else if (resType.equals("xml")) {
      resourceName = processDefinition.getResourceName();
    }

    InputStream resourceAsStream =
        repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName);
    return resourceAsStream;
  }
Exemple #7
0
 /** 启动流程实例 使用key启动默认是按照最新版本的流程定义启动 */
 @Test
 public void startProcessInstance() {
   ProcessInstance p1 =
       processEngine
           .getRuntimeService() // 与正在执行的流程实例和执行对象相关的service
           .startProcessInstanceByKey("hellowrold"); // 使用流程定义的key
   // key=bpmn文件中ID值
   System.out.println("流程实例ID " + p1.getId()); // 流程实例ID
   System.out.println("流程定义ID" + p1.getProcessDefinitionId()); // 流程定义ID
 }
 @Test
 public void startProcessInstance() {
   Map<String, Object> variableMap = new HashMap<String, Object>();
   variableMap.put("price", 150);
   processInstance = runtimeService.startProcessInstanceByKey("OnlinePaymentProcess", variableMap);
   assertNotNull(processInstance.getId());
   logger.info(
       "Created new Activiti process instance: id "
           + processInstance.getId()
           + " "
           + processInstance.getProcessDefinitionId());
 }
Exemple #9
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;
  }
Exemple #10
0
  /**
   * 流程图型显示,高亮流程所在环节
   *
   * @return
   */
  public String process_diagram_complex() {
    try {
      HttpServletResponse resp = ServletActionContext.getResponse();

      String processInstanceId = getpara("processInstanceId");
      if (!infActiviti
          .processInstanceStatus(processInstanceId)
          .equals(ProcessInstanceStatus.Done)) {
        ProcessInstance processInstance =
            runtimeService
                .createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        String processDefinitionId = processInstance.getProcessDefinitionId();

        ProcessDefinitionEntity processDefinition =
            (ProcessDefinitionEntity)
                ((RepositoryServiceImpl) repositoryService)
                    .getDeployedProcessDefinition(processDefinitionId);
        log.debug(runtimeService.getActiveActivityIds(processInstanceId).toString());

        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
        InputStream in =
            ProcessDiagramGenerator.generateDiagram(
                model, "png", runtimeService.getActiveActivityIds(processInstanceId));

        resp.setContentType("image/png");

        BufferedInputStream bin = new BufferedInputStream(in);
        ServletOutputStream out = resp.getOutputStream();
        byte[] b = new byte[1024];
        int l = bin.read(b);
        while (l != -1) {
          out.write(b);
          l = bin.read(b);
        }
        bin.close();
        in.close();
        out.flush();
        out.close();
        /**/
      } else {
        PrintWriter out = resp.getWriter();
        out.write("The Process have been completed......");
        out.flush();
        out.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Exemple #11
0
  public Page<Leave> find(Page<Leave> page, Leave leave) {

    leave.getSqlMap().put("dsf", dataScopeFilter(leave.getCurrentUser(), "o", "u"));

    leave.setPage(page);
    page.setList(leaveDao.findList(leave));

    for (Leave item : page.getList()) {
      String processInstanceId = item.getProcessInstanceId();
      Task task =
          taskService
              .createTaskQuery()
              .processInstanceId(processInstanceId)
              .active()
              .singleResult();
      item.setTask(task);
      HistoricProcessInstance historicProcessInstance =
          historyService
              .createHistoricProcessInstanceQuery()
              .processInstanceId(processInstanceId)
              .singleResult();
      if (historicProcessInstance != null) {
        item.setHistoricProcessInstance(historicProcessInstance);
        item.setProcessDefinition(
            repositoryService
                .createProcessDefinitionQuery()
                .processDefinitionId(historicProcessInstance.getProcessDefinitionId())
                .singleResult());
      } else {
        ProcessInstance processInstance =
            runtimeService
                .createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .active()
                .singleResult();
        if (processInstance != null) {
          item.setProcessInstance(processInstance);
          item.setProcessDefinition(
              repositoryService
                  .createProcessDefinitionQuery()
                  .processDefinitionId(processInstance.getProcessDefinitionId())
                  .singleResult());
        }
      }
    }
    return page;
  }
Exemple #12
0
  @Deployment(
      resources = {
        "org/activiti/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"
      })
  public void testProcessDefinitionId() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

    List<Task> tasks =
        taskService
            .createTaskQuery()
            .processDefinitionId(processInstance.getProcessDefinitionId())
            .list();
    assertEquals(1, tasks.size());
    assertEquals(processInstance.getId(), tasks.get(0).getProcessInstanceId());

    assertEquals(0, taskService.createTaskQuery().processDefinitionId("unexisting").count());
  }
  @Test
  public void startProcess() throws Exception {
    RepositoryService repositoryService = activitiRule.getRepositoryService();
    TaskService taskService = activitiRule.getTaskService();
    repositoryService
        .createDeployment()
        .addInputStream("process1.bpmn20.xml", new FileInputStream(filename))
        .deploy();
    RuntimeService runtimeService = activitiRule.getRuntimeService();
    Map<String, Object> variableMap = new HashMap<String, Object>();
    variableMap.put("name", "Activiti");
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("MyProcess", variableMap);
    assertNotNull(processInstance.getId());
    System.out.println(
        "id " + processInstance.getId() + " " + processInstance.getProcessDefinitionId());

    assertNotNull(taskService.createTaskQuery().taskAssignee("fg").singleResult());
  }
  public ProcessInstanceDetailPanel(
      String processInstanceId, AbstractTablePage processInstancePage) {

    // Member initialization
    this.processInstancePage = processInstancePage;

    this.runtimeService = ProcessEngines.getDefaultProcessEngine().getRuntimeService();
    this.repositoryService = ProcessEngines.getDefaultProcessEngine().getRepositoryService();
    this.taskService = ProcessEngines.getDefaultProcessEngine().getTaskService();
    this.historyService = ProcessEngines.getDefaultProcessEngine().getHistoryService();
    this.i18nManager = ExplorerApp.get().getI18nManager();
    this.variableRendererManager = ExplorerApp.get().getVariableRendererManager();

    this.processInstance = getProcessInstance(processInstanceId);
    this.processDefinition = getProcessDefinition(processInstance.getProcessDefinitionId());
    this.historicProcessInstance = getHistoricProcessInstance(processInstanceId);
    this.identityService = ProcessEngines.getDefaultProcessEngine().getIdentityService();

    init();
  }
  /**
   * 流程跟踪图
   *
   * @param processInstanceId 流程实例ID
   * @return 封装了各种节点信息
   */
  public List<Map<String, Object>> traceProcess(String processInstanceId) throws Exception {
    Execution execution =
        runtimeService.createExecutionQuery().executionId(processInstanceId).singleResult(); // 执行实例
    Object property = PropertyUtils.getProperty(execution, "activityId");
    String activityId = "";
    if (property != null) {
      activityId = property.toString();
    }
    ProcessInstance processInstance =
        runtimeService
            .createProcessInstanceQuery()
            .processInstanceId(processInstanceId)
            .singleResult();
    ProcessDefinitionEntity processDefinition =
        (ProcessDefinitionEntity)
            ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(processInstance.getProcessDefinitionId());
    List<ActivityImpl> activitiList = processDefinition.getActivities(); // 获得当前任务的所有节点

    List<Map<String, Object>> activityInfos = new ArrayList<Map<String, Object>>();
    for (ActivityImpl activity : activitiList) {

      boolean currentActiviti = false;
      String id = activity.getId();

      // 当前节点
      if (id.equals(activityId)) {
        currentActiviti = true;
      }

      Map<String, Object> activityImageInfo =
          packageSingleActivitiInfo(activity, processInstance, currentActiviti);

      activityInfos.add(activityImageInfo);
    }

    return activityInfos;
  }
  /**
   * 显示图片
   *
   * @return
   */
  @RequestMapping(value = "/viewPic.do")
  public void viewPic(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam("executionId") String executionId)
      throws Exception {
    ProcessInstance processInstance =
        runtimeService.createProcessInstanceQuery().processInstanceId(executionId).singleResult();
    BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
    List<String> activeActivityIds = runtimeService.getActiveActivityIds(executionId);

    // 使用spring注入引擎请使用下面的这行代码
    Context.setProcessEngineConfiguration(processEngine.getProcessEngineConfiguration());

    InputStream imageStream =
        ProcessDiagramGenerator.generateDiagram(bpmnModel, "png", activeActivityIds);

    // 输出资源内容到相应对象
    byte[] b = new byte[1024];
    int len;
    while ((len = imageStream.read(b, 0, 1024)) != -1) {
      response.getOutputStream().write(b, 0, len);
    }
  }
  @Deployment
  public void testSubmitFormData() throws Exception {
    Map<String, Object> variableMap = new HashMap<String, Object>();
    variableMap.put("SpeakerName", "John Doe");
    Address address = new Address();
    variableMap.put("address", address);
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("oneTaskProcess", variableMap);
    String processInstanceId = processInstance.getId();
    String processDefinitionId = processInstance.getProcessDefinitionId();
    Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();

    ClientResource client =
        getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_FORM_DATA));
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("taskId", task.getId());
    ArrayNode propertyArray = objectMapper.createArrayNode();
    requestNode.put("properties", propertyArray);
    ObjectNode propNode = objectMapper.createObjectNode();
    propNode.put("id", "room");
    propNode.put("value", 123l);
    propertyArray.add(propNode);
    try {
      client.post(requestNode);
    } catch (Exception e) {
      // expected
      assertEquals(Status.SERVER_ERROR_INTERNAL, client.getResponse().getStatus());
    }

    propNode = objectMapper.createObjectNode();
    propNode.put("id", "street");
    propNode.put("value", "test");
    propertyArray.add(propNode);
    client.release();
    client.post(requestNode);

    assertEquals(Status.SUCCESS_NO_CONTENT, client.getResponse().getStatus());
    task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
    assertNull(task);
    processInstance =
        runtimeService
            .createProcessInstanceQuery()
            .processInstanceId(processInstanceId)
            .singleResult();
    assertNull(processInstance);
    List<HistoricVariableInstance> variables =
        historyService
            .createHistoricVariableInstanceQuery()
            .processInstanceId(processInstanceId)
            .list();
    Map<String, HistoricVariableInstance> historyMap =
        new HashMap<String, HistoricVariableInstance>();
    for (HistoricVariableInstance historicVariableInstance : variables) {
      historyMap.put(historicVariableInstance.getVariableName(), historicVariableInstance);
    }

    assertEquals("123", historyMap.get("room").getValue());
    assertEquals(processInstanceId, historyMap.get("room").getProcessInstanceId());

    processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", variableMap);
    processInstanceId = processInstance.getId();
    task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();

    requestNode.put("taskId", task.getId());
    propNode = objectMapper.createObjectNode();
    propNode.put("id", "direction");
    propNode.put("value", "nowhere");
    propertyArray.add(propNode);
    try {
      client.release();
      client.post(requestNode);
    } catch (Exception e) {
      // expected
      assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, client.getResponse().getStatus());
    }

    propNode.put("value", "up");
    client.release();
    client.post(requestNode);
    assertEquals(Status.SUCCESS_NO_CONTENT, client.getResponse().getStatus());
    task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
    assertNull(task);
    processInstance =
        runtimeService
            .createProcessInstanceQuery()
            .processInstanceId(processInstanceId)
            .singleResult();
    assertNull(processInstance);
    variables =
        historyService
            .createHistoricVariableInstanceQuery()
            .processInstanceId(processInstanceId)
            .list();
    historyMap.clear();
    for (HistoricVariableInstance historicVariableInstance : variables) {
      historyMap.put(historicVariableInstance.getVariableName(), historicVariableInstance);
    }

    assertEquals("123", historyMap.get("room").getValue());
    assertEquals(processInstanceId, historyMap.get("room").getProcessInstanceId());
    assertEquals("up", historyMap.get("direction").getValue());

    requestNode = objectMapper.createObjectNode();
    requestNode.put("processDefinitionId", processDefinitionId);
    propertyArray = objectMapper.createArrayNode();
    requestNode.put("properties", propertyArray);
    propNode = objectMapper.createObjectNode();
    propNode.put("id", "number");
    propNode.put("value", 123);
    propertyArray.add(propNode);
    client.release();
    Representation response = client.post(requestNode);
    assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());
    JsonNode responseNode = objectMapper.readTree(response.getStream());
    assertNotNull(responseNode.get("id").asText());
    assertEquals(processDefinitionId, responseNode.get("processDefinitionId").asText());
    task =
        taskService
            .createTaskQuery()
            .processInstanceId(responseNode.get("id").asText())
            .singleResult();
    assertNotNull(task);
  }
  /** Test querying historic activity instance. GET history/historic-activity-instances */
  @Deployment(resources = {"org/activiti/rest/service/api/twoTaskProcess.bpmn20.xml"})
  public void testQueryActivityInstances() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
    Task task =
        taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    taskService.complete(task.getId());

    // Set tenant on deployment
    managementService.executeCommand(new ChangeDeploymentTenantIdCmd(deploymentId, "myTenant"));

    ProcessInstance processInstance2 =
        runtimeService.startProcessInstanceByKeyAndTenantId("oneTaskProcess", "myTenant");

    String url = RestUrls.createRelativeResourceUrl(RestUrls.URL_HISTORIC_ACTIVITY_INSTANCES);

    assertResultsPresentInDataResponse(url + "?activityId=processTask", 2, "processTask");

    assertResultsPresentInDataResponse(
        url + "?activityId=processTask&finished=true", 1, "processTask");

    assertResultsPresentInDataResponse(
        url + "?activityId=processTask&finished=false", 1, "processTask");

    assertResultsPresentInDataResponse(url + "?activityId=processTask2", 1, "processTask2");

    assertResultsPresentInDataResponse(url + "?activityId=processTask3", 0);

    assertResultsPresentInDataResponse(url + "?activityName=Process%20task", 2, "processTask");

    assertResultsPresentInDataResponse(url + "?activityName=Process%20task2", 1, "processTask2");

    assertResultsPresentInDataResponse(url + "?activityName=Process%20task3", 0);

    assertResultsPresentInDataResponse(
        url + "?activityType=userTask", 3, "processTask", "processTask2");

    assertResultsPresentInDataResponse(url + "?activityType=startEvent", 2, "theStart");

    assertResultsPresentInDataResponse(url + "?activityType=receiveTask", 0);

    assertResultsPresentInDataResponse(
        url + "?processInstanceId=" + processInstance.getId(),
        3,
        "theStart",
        "processTask",
        "processTask2");

    assertResultsPresentInDataResponse(
        url + "?processInstanceId=" + processInstance2.getId(), 2, "theStart", "processTask");

    assertResultsPresentInDataResponse(
        url + "?processDefinitionId=" + processInstance.getProcessDefinitionId(),
        5,
        "theStart",
        "processTask",
        "processTask2");

    assertResultsPresentInDataResponse(url + "?taskAssignee=kermit", 2, "processTask");

    assertResultsPresentInDataResponse(url + "?taskAssignee=fozzie", 1, "processTask2");

    assertResultsPresentInDataResponse(url + "?taskAssignee=fozzie2", 0);

    // Without tenant ID, only activities for processinstance1
    assertResultsPresentInDataResponse(url + "?withoutTenantId=true", 3);

    // Tenant id
    assertResultsPresentInDataResponse(url + "?tenantId=myTenant", 2, "theStart", "processTask");
    assertResultsPresentInDataResponse(url + "?tenantId=anotherTenant");

    // Tenant id like
    assertResultsPresentInDataResponse(
        url + "?tenantIdLike=" + encode("%enant"), 2, "theStart", "processTask");
    assertResultsPresentInDataResponse(url + "?tenantIdLike=anotherTenant");
  }
  @Deployment
  public void testHistoricTaskInstanceQuery() throws Exception {
    // First instance is finished
    ProcessInstance finishedInstance =
        runtimeService.startProcessInstanceByKey("HistoricTaskQueryTest");

    // Set priority to non-default value
    Task task =
        taskService.createTaskQuery().processInstanceId(finishedInstance.getId()).singleResult();
    task.setPriority(1234);
    Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 04:05:06");
    task.setDueDate(dueDate);

    taskService.saveTask(task);

    // Complete the task
    String taskId = task.getId();
    taskService.complete(taskId);

    // Task id
    assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskId(taskId).count());
    assertEquals(
        0, historyService.createHistoricTaskInstanceQuery().taskId("unexistingtaskid").count());

    // Name
    assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskName("Clean up").count());
    assertEquals(
        0, historyService.createHistoricTaskInstanceQuery().taskName("unexistingname").count());
    assertEquals(
        1, historyService.createHistoricTaskInstanceQuery().taskNameLike("Clean u%").count());
    assertEquals(
        1, historyService.createHistoricTaskInstanceQuery().taskNameLike("%lean up").count());
    assertEquals(
        1, historyService.createHistoricTaskInstanceQuery().taskNameLike("%lean u%").count());
    assertEquals(
        0,
        historyService.createHistoricTaskInstanceQuery().taskNameLike("%unexistingname%").count());

    // Description
    assertEquals(
        1,
        historyService
            .createHistoricTaskInstanceQuery()
            .taskDescription("Historic task description")
            .count());
    assertEquals(
        0,
        historyService
            .createHistoricTaskInstanceQuery()
            .taskDescription("unexistingdescription")
            .count());
    assertEquals(
        1,
        historyService
            .createHistoricTaskInstanceQuery()
            .taskDescriptionLike("%task description")
            .count());
    assertEquals(
        1,
        historyService
            .createHistoricTaskInstanceQuery()
            .taskDescriptionLike("Historic task %")
            .count());
    assertEquals(
        1, historyService.createHistoricTaskInstanceQuery().taskDescriptionLike("%task%").count());
    assertEquals(
        0,
        historyService
            .createHistoricTaskInstanceQuery()
            .taskDescriptionLike("%unexistingdescripton%")
            .count());

    // Execution id
    assertEquals(
        1,
        historyService
            .createHistoricTaskInstanceQuery()
            .executionId(finishedInstance.getId())
            .count());
    assertEquals(
        0,
        historyService
            .createHistoricTaskInstanceQuery()
            .executionId("unexistingexecution")
            .count());

    // Process instance id
    assertEquals(
        1,
        historyService
            .createHistoricTaskInstanceQuery()
            .processInstanceId(finishedInstance.getId())
            .count());
    assertEquals(
        0,
        historyService.createHistoricTaskInstanceQuery().processInstanceId("unexistingid").count());

    // Process definition id
    assertEquals(
        1,
        historyService
            .createHistoricTaskInstanceQuery()
            .processDefinitionId(finishedInstance.getProcessDefinitionId())
            .count());
    assertEquals(
        0,
        historyService
            .createHistoricTaskInstanceQuery()
            .processDefinitionId("unexistingdefinitionid")
            .count());

    // Process definition name
    assertEquals(
        1,
        historyService
            .createHistoricTaskInstanceQuery()
            .processDefinitionName("Historic task query test process")
            .count());
    assertEquals(
        0,
        historyService
            .createHistoricTaskInstanceQuery()
            .processDefinitionName("unexistingdefinitionname")
            .count());

    // Process definition key
    assertEquals(
        1,
        historyService
            .createHistoricTaskInstanceQuery()
            .processDefinitionKey("HistoricTaskQueryTest")
            .count());
    assertEquals(
        0,
        historyService
            .createHistoricTaskInstanceQuery()
            .processDefinitionKey("unexistingdefinitionkey")
            .count());

    // Assignee
    assertEquals(
        1, historyService.createHistoricTaskInstanceQuery().taskAssignee("kermit").count());
    assertEquals(
        0, historyService.createHistoricTaskInstanceQuery().taskAssignee("johndoe").count());
    assertEquals(
        1, historyService.createHistoricTaskInstanceQuery().taskAssigneeLike("%ermit").count());
    assertEquals(
        1, historyService.createHistoricTaskInstanceQuery().taskAssigneeLike("kermi%").count());
    assertEquals(
        1, historyService.createHistoricTaskInstanceQuery().taskAssigneeLike("%ermi%").count());
    assertEquals(
        0, historyService.createHistoricTaskInstanceQuery().taskAssigneeLike("%johndoe%").count());

    // Delete reason
    assertEquals(
        1,
        historyService
            .createHistoricTaskInstanceQuery()
            .taskDeleteReason(TaskEntity.DELETE_REASON_COMPLETED)
            .count());
    assertEquals(
        0, historyService.createHistoricTaskInstanceQuery().taskDeleteReason("deleted").count());

    // Task definition ID
    assertEquals(
        1, historyService.createHistoricTaskInstanceQuery().taskDefinitionKey("task").count());
    assertEquals(
        0,
        historyService
            .createHistoricTaskInstanceQuery()
            .taskDefinitionKey("unexistingkey")
            .count());

    // Task priority
    assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskPriority(1234).count());
    assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskPriority(5678).count());

    // Due date
    Calendar anHourAgo = Calendar.getInstance();
    anHourAgo.setTime(dueDate);
    anHourAgo.add(Calendar.HOUR, -1);

    Calendar anHourLater = Calendar.getInstance();
    anHourLater.setTime(dueDate);
    anHourLater.add(Calendar.HOUR, 1);

    assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskDueDate(dueDate).count());
    assertEquals(
        0,
        historyService.createHistoricTaskInstanceQuery().taskDueDate(anHourAgo.getTime()).count());
    assertEquals(
        0,
        historyService
            .createHistoricTaskInstanceQuery()
            .taskDueDate(anHourLater.getTime())
            .count());

    // Due date before
    assertEquals(
        1,
        historyService
            .createHistoricTaskInstanceQuery()
            .taskDueBefore(anHourLater.getTime())
            .count());
    assertEquals(
        0,
        historyService
            .createHistoricTaskInstanceQuery()
            .taskDueBefore(anHourAgo.getTime())
            .count());

    // Due date after
    assertEquals(
        1,
        historyService.createHistoricTaskInstanceQuery().taskDueAfter(anHourAgo.getTime()).count());
    assertEquals(
        0,
        historyService
            .createHistoricTaskInstanceQuery()
            .taskDueAfter(anHourLater.getTime())
            .count());

    // Finished and Unfinished - Add anther other instance that has a running task (unfinished)
    runtimeService.startProcessInstanceByKey("HistoricTaskQueryTest");

    assertEquals(1, historyService.createHistoricTaskInstanceQuery().finished().count());
    assertEquals(1, historyService.createHistoricTaskInstanceQuery().unfinished().count());
  }
  @Deployment(
      resources = {
        "org/activiti/rest/api/management/JobCollectionResourceTest.testTimerProcess.bpmn20.xml"
      })
  public void testGetJobs() throws Exception {
    Calendar hourAgo = Calendar.getInstance();
    hourAgo.add(Calendar.HOUR, -1);

    Calendar inAnHour = Calendar.getInstance();
    inAnHour.add(Calendar.HOUR, 1);

    // Start process, forcing error on job-execution
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey(
            "timerProcess", Collections.singletonMap("error", (Object) Boolean.TRUE));

    Job timerJob =
        managementService
            .createJobQuery()
            .processInstanceId(processInstance.getId())
            .timers()
            .singleResult();
    assertNotNull(timerJob);

    for (int i = 0; i < timerJob.getRetries(); i++) {
      // Force execution of job until retries are exhausted
      try {
        managementService.executeJob(timerJob.getId());
        fail();
      } catch (ActivitiException expected) {
        // Ignore, we expect the exception
      }
    }
    timerJob =
        managementService
            .createJobQuery()
            .processInstanceId(processInstance.getId())
            .timers()
            .singleResult();
    assertEquals(0, timerJob.getRetries());

    // Fetch the async-job (which has retries left)
    Job asyncJob =
        managementService
            .createJobQuery()
            .processInstanceId(processInstance.getId())
            .withRetriesLeft()
            .singleResult();

    // Test fetching all jobs
    String url = RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION);
    assertResultsPresentInDataResponse(url, asyncJob.getId(), timerJob.getId());

    // Fetch using job-id
    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION) + "?id=" + asyncJob.getId();
    assertResultsPresentInDataResponse(url, asyncJob.getId());

    // Fetch using processInstanceId
    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
            + "?processInstanceId="
            + processInstance.getId();
    assertResultsPresentInDataResponse(url, asyncJob.getId(), timerJob.getId());

    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
            + "?processInstanceId=unexisting";
    assertResultsPresentInDataResponse(url);

    // Fetch using executionId
    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
            + "?executionId="
            + asyncJob.getExecutionId();
    assertResultsPresentInDataResponse(url, asyncJob.getId());

    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
            + "?executionId="
            + timerJob.getExecutionId();
    assertResultsPresentInDataResponse(url, timerJob.getId());

    // Fetch using processDefinitionId
    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
            + "?processDefinitionId="
            + processInstance.getProcessDefinitionId();
    assertResultsPresentInDataResponse(url, asyncJob.getId(), timerJob.getId());

    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
            + "?processDefinitionId=unexisting";
    assertResultsPresentInDataResponse(url);

    // Fetch using withRetriesLeft
    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION) + "?withRetriesLeft=true";
    assertResultsPresentInDataResponse(url, asyncJob.getId());

    // Fetch using executable
    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION) + "?executable=true";
    assertResultsPresentInDataResponse(url, asyncJob.getId());

    // Fetch using timers only
    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION) + "?timersOnly=true";
    assertResultsPresentInDataResponse(url, timerJob.getId());

    // Combining messagesOnly with timersOnly should result in exception
    ClientResource client =
        getAuthenticatedClient(
            RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
                + "?timersOnly=true&messagesOnly=true");
    try {
      client.get();
      fail("Exception expected");
    } catch (ResourceException expected) {
      assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, expected.getStatus());
      assertEquals(
          "Only one of 'timersOnly' or 'messagesOnly' can be provided.",
          expected.getStatus().getDescription());
    }

    // Fetch using dueBefore
    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
            + "?dueBefore="
            + getISODateString(inAnHour.getTime());
    assertResultsPresentInDataResponse(url, timerJob.getId());

    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
            + "?dueBefore="
            + getISODateString(hourAgo.getTime());
    assertResultsPresentInDataResponse(url);

    // Fetch using dueAfter
    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
            + "?dueAfter="
            + getISODateString(hourAgo.getTime());
    assertResultsPresentInDataResponse(url, timerJob.getId());

    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
            + "?dueAfter="
            + getISODateString(inAnHour.getTime());
    assertResultsPresentInDataResponse(url);

    // Fetch using withException
    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION) + "?withException=true";
    assertResultsPresentInDataResponse(url, timerJob.getId());

    // Fetch with exceptionMessage
    url =
        RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION)
            + "?exceptionMessage="
            + timerJob.getExceptionMessage();
    assertResultsPresentInDataResponse(url, timerJob.getId());

    // Fetch with empty exceptionMessage
    url = RestUrls.createRelativeResourceUrl(RestUrls.URL_JOB_COLLECTION) + "?exceptionMessage=";
    assertResultsPresentInDataResponse(url);
  }
  @Deployment
  public void testGetFormData() throws Exception {
    Map<String, Object> variableMap = new HashMap<String, Object>();
    variableMap.put("SpeakerName", "John Doe");
    Address address = new Address();
    variableMap.put("address", address);
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("oneTaskProcess", variableMap);
    Task task =
        taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();

    ClientResource client =
        getAuthenticatedClient(
            RestUrls.createRelativeResourceUrl(RestUrls.URL_FORM_DATA) + "?taskId=" + task.getId());
    Representation response = client.get();
    assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());

    // Check resulting task
    JsonNode responseNode = objectMapper.readTree(response.getStream());
    assertEquals(7, responseNode.get("formProperties").size());
    Map<String, JsonNode> mappedProperties = new HashMap<String, JsonNode>();
    for (JsonNode propNode : responseNode.get("formProperties")) {
      mappedProperties.put(propNode.get("id").asText(), propNode);
    }
    JsonNode propNode = mappedProperties.get("room");
    assertNotNull(propNode);
    assertEquals("room", propNode.get("id").asText());
    assertTrue(propNode.get("name").isNull());
    assertTrue(propNode.get("type").isNull());
    assertTrue(propNode.get("value").isNull());
    assertTrue(propNode.get("readable").asBoolean());
    assertTrue(propNode.get("writable").asBoolean());
    assertTrue(propNode.get("required").asBoolean() == false);

    propNode = mappedProperties.get("duration");
    assertNotNull(propNode);
    assertEquals("duration", propNode.get("id").asText());
    assertTrue(propNode.get("name").isNull());
    assertEquals("long", propNode.get("type").asText());
    assertTrue(propNode.get("value").isNull());
    assertTrue(propNode.get("readable").asBoolean());
    assertTrue(propNode.get("writable").asBoolean());
    assertTrue(propNode.get("required").asBoolean() == false);

    propNode = mappedProperties.get("speaker");
    assertNotNull(propNode);
    assertEquals("speaker", propNode.get("id").asText());
    assertTrue(propNode.get("name").isNull());
    assertTrue(propNode.get("type").isNull());
    assertEquals("John Doe", propNode.get("value").asText());
    assertTrue(propNode.get("readable").asBoolean());
    assertTrue(propNode.get("writable").asBoolean() == false);
    assertTrue(propNode.get("required").asBoolean() == false);

    propNode = mappedProperties.get("street");
    assertNotNull(propNode);
    assertEquals("street", propNode.get("id").asText());
    assertTrue(propNode.get("name").isNull());
    assertTrue(propNode.get("type").isNull());
    assertTrue(propNode.get("value").isNull());
    assertTrue(propNode.get("readable").asBoolean());
    assertTrue(propNode.get("writable").asBoolean());
    assertTrue(propNode.get("required").asBoolean());

    propNode = mappedProperties.get("start");
    assertNotNull(propNode);
    assertEquals("start", propNode.get("id").asText());
    assertTrue(propNode.get("name").isNull());
    assertEquals("date", propNode.get("type").asText());
    assertTrue(propNode.get("value").isNull());
    assertEquals("dd-MMM-yyyy", propNode.get("datePattern").asText());
    assertTrue(propNode.get("readable").asBoolean());
    assertTrue(propNode.get("writable").asBoolean());
    assertTrue(propNode.get("required").asBoolean() == false);

    propNode = mappedProperties.get("end");
    assertNotNull(propNode);
    assertEquals("end", propNode.get("id").asText());
    assertEquals("End", propNode.get("name").asText());
    assertEquals("date", propNode.get("type").asText());
    assertTrue(propNode.get("value").isNull());
    assertEquals("dd/MM/yyyy", propNode.get("datePattern").asText());
    assertTrue(propNode.get("readable").asBoolean());
    assertTrue(propNode.get("writable").asBoolean());
    assertTrue(propNode.get("required").asBoolean() == false);

    propNode = mappedProperties.get("direction");
    assertNotNull(propNode);
    assertEquals("direction", propNode.get("id").asText());
    assertTrue(propNode.get("name").isNull());
    assertEquals("enum", propNode.get("type").asText());
    assertTrue(propNode.get("value").isNull());
    assertTrue(propNode.get("datePattern").isNull());
    assertTrue(propNode.get("readable").asBoolean());
    assertTrue(propNode.get("writable").asBoolean());
    assertTrue(propNode.get("required").asBoolean() == false);
    JsonNode enumValues = propNode.get("enumValues");
    assertEquals(4, enumValues.size());
    Map<String, String> mappedEnums = new HashMap<String, String>();
    for (JsonNode enumNode : enumValues) {
      mappedEnums.put(enumNode.get("id").asText(), enumNode.get("name").asText());
    }
    assertEquals("Go Left", mappedEnums.get("left"));
    assertEquals("Go Right", mappedEnums.get("right"));
    assertEquals("Go Up", mappedEnums.get("up"));
    assertEquals("Go Down", mappedEnums.get("down"));

    client =
        getAuthenticatedClient(
            RestUrls.createRelativeResourceUrl(RestUrls.URL_FORM_DATA)
                + "?processDefinitionId="
                + processInstance.getProcessDefinitionId());
    response = client.get();
    assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());

    // Check resulting task
    responseNode = objectMapper.readTree(response.getStream());
    assertEquals(2, responseNode.get("formProperties").size());
    mappedProperties.clear();
    for (JsonNode propertyNode : responseNode.get("formProperties")) {
      mappedProperties.put(propertyNode.get("id").asText(), propertyNode);
    }

    propNode = mappedProperties.get("number");
    assertNotNull(propNode);
    assertEquals("number", propNode.get("id").asText());
    assertEquals("Number", propNode.get("name").asText());
    assertEquals("long", propNode.get("type").asText());
    assertTrue(propNode.get("value").isNull());
    assertTrue(propNode.get("readable").asBoolean());
    assertTrue(propNode.get("writable").asBoolean());
    assertTrue(propNode.get("required").asBoolean() == false);

    propNode = mappedProperties.get("description");
    assertNotNull(propNode);
    assertEquals("description", propNode.get("id").asText());
    assertEquals("Description", propNode.get("name").asText());
    assertTrue(propNode.get("type").isNull());
    assertTrue(propNode.get("value").isNull());
    assertTrue(propNode.get("readable").asBoolean());
    assertTrue(propNode.get("writable").asBoolean());
    assertTrue(propNode.get("required").asBoolean() == false);

    client =
        getAuthenticatedClient(
            RestUrls.createRelativeResourceUrl(RestUrls.URL_FORM_DATA)
                + "?processDefinitionId=123");
    try {
      response = client.get();
      fail();
    } catch (Exception e) {
      // expected
      assertEquals(Status.CLIENT_ERROR_NOT_FOUND, client.getResponse().getStatus());
    }

    client =
        getAuthenticatedClient(
            RestUrls.createRelativeResourceUrl(RestUrls.URL_FORM_DATA)
                + "?processDefinitionId2=123");
    try {
      response = client.get();
      fail();
    } catch (Exception e) {
      // expected
      assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, client.getResponse().getStatus());
    }
  }