/** 历史任务. */
  public Page findHistoricTaskInstances(String tenantId, Page page) {
    HistoryService historyService = processEngine.getHistoryService();

    long count = historyService.createHistoricTaskInstanceQuery().taskTenantId(tenantId).count();
    List<HistoricTaskInstance> historicTaskInstances =
        historyService
            .createHistoricTaskInstanceQuery()
            .taskTenantId(tenantId)
            .listPage((int) page.getStart(), page.getPageSize());
    page.setResult(historicTaskInstances);
    page.setTotalCount(count);

    return page;
  }
 public static List<HistoricTaskInstance> getHistoricTaskInstanceByProcessInstanceId(
     String processInstanceId) {
   return historyService
       .createHistoricTaskInstanceQuery()
       .processInstanceId(processInstanceId)
       .list();
 }
 /**
  * @param processInstanceId
  * @return
  */
 @Override
 public List<HistoricTaskInstance> createHistoricTaskInstanceQuery(String processInstanceId) {
   return historyService
       .createHistoricTaskInstanceQuery()
       .processInstanceId(processInstanceId)
       .list();
 }
  public String listHistoricTasks() {
    HistoryService historyService = processEngine.getHistoryService();

    historicTaskInstances = historyService.createHistoricTaskInstanceQuery().list();

    return "listHistoricTasks";
  }
  /**
   * easyui AJAX请求数据 已办任务
   *
   * @param request
   * @param response
   * @param dataGrid
   */
  @RequestMapping(params = "finishedTaskDataGrid")
  public void finishedTask(
      HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {

    // String userId = "leaderuser";
    String userId = ResourceUtil.getSessionUserName().getId();
    List<HistoricTaskInstance> historicTasks =
        historyService.createHistoricTaskInstanceQuery().taskAssignee(userId).finished().list();

    StringBuffer rows = new StringBuffer();
    for (HistoricTaskInstance t : historicTasks) {
      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':" + historicTasks.size() + ",'rows':[" + rowStr + "]}");
    responseDatagrid(response, jObject);
  }
  /**
   * 已办任务(历史任务)
   *
   * @return
   */
  public String listHistoryTasks() {
    HistoryService historyService = processEngine.getHistoryService();
    String username = SpringSecurityUtils.getCurrentUsername();
    historicTasks =
        historyService.createHistoricTaskInstanceQuery().taskAssignee(username).finished().list();

    return "listHistoryTasks";
  }
 protected HistoricTaskInstance getHistoricTaskInstanceFromRequest(String taskId) {
   HistoricTaskInstance taskInstance =
       historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
   if (taskInstance == null) {
     throw new ActivitiObjectNotFoundException(
         "Could not find a task instance with id '" + taskId + "'.", HistoricTaskInstance.class);
   }
   return taskInstance;
 }
  /**
   * 查看历史【包含流程跟踪、任务列表(完成和未完成)、流程变量】
   *
   * @return
   */
  public String viewHistory() {
    HistoryService historyService = processEngine.getHistoryService();
    historicTasks =
        historyService
            .createHistoricTaskInstanceQuery()
            .processInstanceId(processInstanceId)
            .list();
    historicVariableInstances =
        historyService
            .createHistoricVariableInstanceQuery()
            .processInstanceId(processInstanceId)
            .list();

    return "viewHistory";
  }
  /**
   * Generic method which will figure out to which task page must be jumped, based on the task data.
   *
   * <p>Note that, if possible, it is always more performant to use the more specific showXXXPage()
   * methods.
   */
  public void showTaskPage(String taskId) {
    Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
    String loggedInUserId = ExplorerApp.get().getLoggedInUser().getId();

    if (task == null) {
      // If no runtime task exists, our only hope is the archive page
      boolean isOwner =
          historyService
                  .createHistoricTaskInstanceQuery()
                  .taskId(taskId)
                  .taskOwner(loggedInUserId)
                  .count()
              == 1;
      if (isOwner) {
        showArchivedPage(taskId);
      } else {
        showNavigationError(taskId);
      }
    } else if (loggedInUserId.equals(task.getOwner())) {
      showTasksPage(taskId);
    } else if (loggedInUserId.equals(task.getAssignee())) {
      showInboxPage(taskId);
    } else if (taskService.createTaskQuery().taskInvolvedUser(loggedInUserId).count() == 1) {
      showInvolvedPage(taskId);
    } else {
      // queued
      List<String> groupIds = getGroupIds(loggedInUserId);
      List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(task.getId());
      Iterator<IdentityLink> identityLinkIterator = identityLinks.iterator();

      boolean pageFound = false;
      while (!pageFound && identityLinkIterator.hasNext()) {
        IdentityLink identityLink = identityLinkIterator.next();
        if (identityLink.getGroupId() != null && groupIds.contains(identityLink.getGroupId())) {
          showQueuedPage(identityLink.getGroupId(), task.getId());
          pageFound = true;
        }
      }

      // We've tried hard enough, the user now gets a notification. He deserves it.
      if (!pageFound) {
        showNavigationError(taskId);
      }
    }
  }
 /**
  * Get completed task instances which were finished after the given date and time
  *
  * @return BPMNTaskInstance array if the historic task instance list is not null
  */
 public BPMNTaskInstance[] getCompletedTaskInstances() {
   HistoryService historyService = BPMNServerHolder.getInstance().getEngine().getHistoryService();
   HistoricTaskInstanceQuery instanceQuery = historyService.createHistoricTaskInstanceQuery();
   List<HistoricTaskInstance> historicTaskInstanceList = null;
   String time =
       readPublishTimeFromRegistry(
           AnalyticsPublisherConstants.TASK_RESOURCE_PATH,
           AnalyticsPublisherConstants.LAST_TASK_INSTANCE_END_TIME);
   if (time == null) {
     if (instanceQuery.finished().list().size() != 0) {
       historicTaskInstanceList =
           instanceQuery.finished().orderByHistoricTaskInstanceEndTime().asc().list();
     }
   } else {
     Date dateFormat = DateConverter.convertStringToDate(time);
     int listSize = instanceQuery.finished().taskCompletedAfter(dateFormat).list().size();
     if (listSize != 0) {
       /*When using the startedAfter() method it returns the finished objects according to the time stored of
       last completed instance. But if the list length is one then it always return the same object in the
       list twice from the last updated time which stored in the carbon registry.
       (avoid to return same object repeatedly if the list has only one object)*/
       if (listSize == 1) {
         return null;
       }
       historicTaskInstanceList =
           instanceQuery
               .finished()
               .taskCompletedAfter(dateFormat)
               .orderByHistoricTaskInstanceEndTime()
               .asc()
               .listPage(1, listSize);
     }
   }
   if (historicTaskInstanceList != null) {
     if (log.isDebugEnabled()) {
       log.debug(
           "Write BPMN task instance to the carbon registry..."
               + historicTaskInstanceList.toString());
     }
     writeTaskEndTimeToRegistry(historicTaskInstanceList);
     return getBPMNTaskInstances(historicTaskInstanceList);
   }
   return null;
 }
 @RequestMapping(value = "/list")
 @ResponseBody
 public Map<String, Object> list(
     @RequestParam("page") int curPage,
     @RequestParam("rows") int pageSize,
     HttpServletRequest req) {
   HistoricTaskInstanceQuery historicTaskInstanceQuery =
       historyService.createHistoricTaskInstanceQuery(); // .taskAssignee("5")
   long total = historicTaskInstanceQuery.count();
   List<HistoricTaskInstance> list =
       historicTaskInstanceQuery
           .orderByTaskCreateTime()
           .desc()
           .listPage((curPage - 1) * pageSize, pageSize);
   Map<String, Object> obj = new HashMap<String, Object>();
   obj.put("total", total);
   obj.put("list", list);
   return obj;
 }
  /**
   * easyui 流程历史数据获取
   *
   * @param request
   * @param response
   * @param dataGrid
   */
  @RequestMapping(params = "taskHistoryList")
  public void taskHistoryList(
      @RequestParam("processInstanceId") String processInstanceId,
      HttpServletRequest request,
      HttpServletResponse response,
      DataGrid dataGrid) {

    List<HistoricTaskInstance> historicTasks =
        historyService
            .createHistoricTaskInstanceQuery()
            .processInstanceId(processInstanceId)
            .list();

    StringBuffer rows = new StringBuffer();
    for (HistoricTaskInstance hi : historicTasks) {
      rows.append(
          "{'name':'"
              + hi.getName()
              + "','processInstanceId':'"
              + hi.getProcessInstanceId()
              + "','startTime':'"
              + hi.getStartTime()
              + "','endTime':'"
              + hi.getEndTime()
              + "','assignee':'"
              + hi.getAssignee()
              + "','deleteReason':'"
              + hi.getDeleteReason()
              + "'},");
      // System.out.println(hi.getName()+"@"+hi.getAssignee()+"@"+hi.getStartTime()+"@"+hi.getEndTime());
    }

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

    JSONObject jObject =
        JSONObject.fromObject("{'total':" + historicTasks.size() + ",'rows':[" + rowStr + "]}");
    responseDatagrid(response, jObject);
  }
  protected void addTasks() {
    Label header = new Label(i18nManager.getMessage(Messages.PROCESS_INSTANCE_HEADER_TASKS));
    header.addStyleName(ExplorerLayout.STYLE_H3);
    header.addStyleName(ExplorerLayout.STYLE_DETAIL_BLOCK);
    header.addStyleName(ExplorerLayout.STYLE_NO_LINE);
    panelLayout.addComponent(header);

    panelLayout.addComponent(new Label("&nbsp;", Label.CONTENT_XHTML));

    Table taskTable = new Table();
    taskTable.addStyleName(ExplorerLayout.STYLE_PROCESS_INSTANCE_TASK_LIST);
    taskTable.setWidth(100, UNITS_PERCENTAGE);

    // Fetch all tasks
    List<HistoricTaskInstance> tasks =
        historyService
            .createHistoricTaskInstanceQuery()
            .processInstanceId(processInstance.getId())
            .orderByHistoricTaskInstanceEndTime()
            .desc()
            .orderByHistoricTaskInstanceStartTime()
            .desc()
            .list();

    if (tasks.size() > 0) {

      // Finished icon
      taskTable.addContainerProperty(
          "finished", Component.class, null, "", null, Table.ALIGN_CENTER);
      taskTable.setColumnWidth("finished", 22);

      taskTable.addContainerProperty(
          "name",
          String.class,
          null,
          i18nManager.getMessage(Messages.TASK_NAME),
          null,
          Table.ALIGN_LEFT);
      taskTable.addContainerProperty(
          "priority",
          Integer.class,
          null,
          i18nManager.getMessage(Messages.TASK_PRIORITY),
          null,
          Table.ALIGN_LEFT);
      taskTable.addContainerProperty(
          "assignee",
          Component.class,
          null,
          i18nManager.getMessage(Messages.TASK_ASSIGNEE),
          null,
          Table.ALIGN_LEFT);
      taskTable.addContainerProperty(
          "dueDate",
          Component.class,
          null,
          i18nManager.getMessage(Messages.TASK_DUEDATE),
          null,
          Table.ALIGN_LEFT);
      taskTable.addContainerProperty(
          "startDate",
          Component.class,
          null,
          i18nManager.getMessage(Messages.TASK_CREATE_TIME),
          null,
          Table.ALIGN_LEFT);
      taskTable.addContainerProperty(
          "endDate",
          Component.class,
          null,
          i18nManager.getMessage(Messages.TASK_COMPLETE_TIME),
          null,
          Table.ALIGN_LEFT);

      panelLayout.addComponent(taskTable);
      panelLayout.setExpandRatio(taskTable, 1.0f);

      for (HistoricTaskInstance task : tasks) {
        addTaskItem(task, taskTable);
      }

      taskTable.setPageLength(taskTable.size());
    } else {
      // No tasks
      Label noTaskLabel = new Label(i18nManager.getMessage(Messages.PROCESS_INSTANCE_NO_TASKS));
      panelLayout.addComponent(noTaskLabel);
    }
  }