/**
  * Get completed process instances which were finished after the given date and time
  *
  * @return BPMNProcessInstance array if the historic process instance list is not null
  */
 public BPMNProcessInstance[] getCompletedProcessInstances() {
   HistoryService historyService = BPMNServerHolder.getInstance().getEngine().getHistoryService();
   HistoricProcessInstanceQuery instanceQuery =
       historyService.createHistoricProcessInstanceQuery();
   List<HistoricProcessInstance> historicProcessInstanceList = null;
   String time =
       readPublishTimeFromRegistry(
           AnalyticsPublisherConstants.PROCESS_RESOURCE_PATH,
           AnalyticsPublisherConstants.LAST_PROCESS_INSTANCE_PUBLISH_TIME);
   if (time == null) {
     if (instanceQuery.finished().list().size() != 0) {
       // if the stored time is null in the registry file then send all completed process
       // instances.
       historicProcessInstanceList =
           instanceQuery.finished().orderByProcessInstanceStartTime().asc().list();
     }
   } else {
     Date timeInDateFormat = DateConverter.convertStringToDate(time);
     int listSize = instanceQuery.finished().startedAfter(timeInDateFormat).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;
       }
       // send the process instances which were finished after the given date/time in registry
       historicProcessInstanceList =
           instanceQuery
               .finished()
               .startedAfter(timeInDateFormat)
               .orderByProcessInstanceStartTime()
               .asc()
               .listPage(1, listSize);
     }
   }
   if (historicProcessInstanceList != null) {
     if (log.isDebugEnabled()) {
       log.debug(
           "Write the published time of the last BPMN process instance to the carbon registry..."
               + historicProcessInstanceList.toString());
     }
     /*write the last published time to the registry because lets say as an example when a new process is completed,
     then the attributes belong to that process instance should be published to the DAS and if we are not stored
     the last published time, then all the completed processes which were previously published are also re-published
     to the DAS.*/
     writePublishTimeToRegistry(historicProcessInstanceList);
     // return ProcessInstances set as BPMNProcessInstance array
     return getBPMNProcessInstances(historicProcessInstanceList);
   }
   return null;
 }
  /**
   * Get the average time duration of completed processes
   *
   * @return list with the completed processes and the average time duration taken for each process
   */
  @GET
  @Path("/avgDurationToCompleteProcess/")
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public ResponseHolder getAvgTimeDurationForCompletedProcesses() {
    List<ProcessDefinition> deployements =
        BPMNOSGIService.getRepositoryService()
            .createProcessDefinitionQuery()
            .processDefinitionTenantId(str)
            .list();

    ResponseHolder response = new ResponseHolder();
    List list = new ArrayList<>();

    for (ProcessDefinition instance : deployements) {
      CompletedProcesses bpmnProcessInstance = new CompletedProcesses();
      bpmnProcessInstance.setProcessDefinitionId(instance.getId());

      double totalTime = 0;
      double averageTime = 0;
      String processDefinitionID = instance.getId();

      HistoricProcessInstanceQuery historicProcessInstanceQuery =
          BPMNOSGIService.getHistoryService()
              .createHistoricProcessInstanceQuery()
              .processInstanceTenantId(str)
              .processDefinitionId(processDefinitionID)
              .finished();

      long noOfHistoricInstances = historicProcessInstanceQuery.count();

      if (noOfHistoricInstances == 0) {
      } else {
        List<HistoricProcessInstance> instanceList = historicProcessInstanceQuery.list();

        for (HistoricProcessInstance completedProcess : instanceList) {
          double timeDurationOfTask = completedProcess.getDurationInMillis();
          double timeInMins = timeDurationOfTask / (1000 * 60);
          totalTime += timeInMins;
        }
        averageTime = totalTime / noOfHistoricInstances;
        bpmnProcessInstance.setAverageTimeForCompletion(averageTime);
        list.add(bpmnProcessInstance);
      }
    }
    response.setData(list);
    return response;
  }
  /**
   * Average task duration for completed processes
   *
   * @param pId processDefintionId of the process selected to view the average time duration for
   *     each task
   * @return list of completed tasks with the average time duration for the selected process
   */
  @GET
  @Path("/avgTaskDurationForCompletedProcess/{pId}")
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public ResponseHolder avgTaskTimeDurationForCompletedProcesses(@PathParam("pId") String pId) {
    long countOfProcesses =
        BPMNOSGIService.getRepositoryService()
            .createProcessDefinitionQuery()
            .processDefinitionTenantId(str)
            .processDefinitionId(pId)
            .count();
    if (countOfProcesses == 0) {
      throw new ActivitiObjectNotFoundException(
          "Could not find process with process definition id '" + pId + "'.");
    }

    ResponseHolder response = new ResponseHolder();
    List taskListForProcess = new ArrayList<>();
    HashMap<String, Long> map = new HashMap<String, Long>();
    // Get the number of completed/finished process instance for each process definition
    HistoricProcessInstanceQuery historicProcessInstanceQuery =
        BPMNOSGIService.getHistoryService()
            .createHistoricProcessInstanceQuery()
            .processInstanceTenantId(str)
            .processDefinitionId(pId)
            .finished();
    // Get the count of the complete process instances
    long noOfHistoricInstances = historicProcessInstanceQuery.count();

    // If the deployed process doesnot have any completed process instances --> Ignore
    if (noOfHistoricInstances == 0) {
      response.setData(taskListForProcess);
    }
    // If the deployed process has completed process instances --> then
    else {

      BPMNTaskInstance tInstance = new BPMNTaskInstance();
      // Get the list of completed tasks/activities in the completed process instance by passing the
      // process definition id of the process
      List<HistoricTaskInstance> taskList =
          BPMNOSGIService.getHistoryService()
              .createHistoricTaskInstanceQuery()
              .taskTenantId(str)
              .processDefinitionId(pId)
              .processFinished()
              .list();
      // Iterate through each completed task/activity and get the task name and duration
      for (HistoricTaskInstance taskInstance : taskList) {
        // Get the task name
        String taskKey = taskInstance.getTaskDefinitionKey();
        // Get the time duration taken for the task to be completed
        long taskDuration = taskInstance.getDurationInMillis();

        if (map.containsKey(taskKey)) {
          long tt = map.get(taskKey);
          map.put(taskKey, taskDuration + tt);
        } else {
          map.put(taskKey, taskDuration);
        }
        // Iterating Task List finished
      }
      Iterator iterator = map.keySet().iterator();
      while (iterator.hasNext()) {
        String key = iterator.next().toString();
        double value = map.get(key) / noOfHistoricInstances;
        tInstance = new BPMNTaskInstance();
        tInstance.setTaskDefinitionKey(key);
        tInstance.setAverageTimeForCompletion(value);
        taskListForProcess.add(tInstance);
      }

      response.setData(taskListForProcess);
    }
    return response;
  }
  protected DataResponse getQueryResponse(
      HistoricProcessInstanceQueryRequest queryRequest, Form urlQuery) {
    HistoricProcessInstanceQuery query =
        ActivitiUtil.getHistoryService().createHistoricProcessInstanceQuery();

    // Populate query based on request
    if (queryRequest.getProcessInstanceId() != null) {
      query.processInstanceId(queryRequest.getProcessInstanceId());
    }
    if (queryRequest.getProcessInstanceIds() != null
        && !queryRequest.getProcessInstanceIds().isEmpty()) {
      query.processInstanceIds(new HashSet<String>(queryRequest.getProcessInstanceIds()));
    }
    if (queryRequest.getProcessDefinitionKey() != null) {
      query.processDefinitionKey(queryRequest.getProcessDefinitionKey());
    }
    if (queryRequest.getProcessDefinitionId() != null) {
      query.processDefinitionId(queryRequest.getProcessDefinitionId());
    }
    if (queryRequest.getProcessBusinessKey() != null) {
      query.processInstanceBusinessKey(queryRequest.getProcessBusinessKey());
    }
    if (queryRequest.getInvolvedUser() != null) {
      query.involvedUser(queryRequest.getInvolvedUser());
    }
    if (queryRequest.getSuperProcessInstanceId() != null) {
      query.superProcessInstanceId(queryRequest.getSuperProcessInstanceId());
    }
    if (queryRequest.getExcludeSubprocesses() != null) {
      query.excludeSubprocesses(queryRequest.getExcludeSubprocesses());
    }
    if (queryRequest.getFinishedAfter() != null) {
      query.finishedAfter(queryRequest.getFinishedAfter());
    }
    if (queryRequest.getFinishedBefore() != null) {
      query.finishedBefore(queryRequest.getFinishedBefore());
    }
    if (queryRequest.getStartedAfter() != null) {
      query.startedAfter(queryRequest.getStartedAfter());
    }
    if (queryRequest.getStartedBefore() != null) {
      query.startedBefore(queryRequest.getStartedBefore());
    }
    if (queryRequest.getStartedBy() != null) {
      query.startedBy(queryRequest.getStartedBy());
    }
    if (queryRequest.getFinished() != null) {
      if (queryRequest.getFinished()) {
        query.finished();
      } else {
        query.unfinished();
      }
    }
    if (queryRequest.getIncludeProcessVariables() != null) {
      if (queryRequest.getIncludeProcessVariables()) {
        query.includeProcessVariables();
      }
    }
    if (queryRequest.getVariables() != null) {
      addVariables(query, queryRequest.getVariables());
    }

    if (queryRequest.getTenantId() != null) {
      query.processInstanceTenantId(queryRequest.getTenantId());
    }

    if (queryRequest.getTenantIdLike() != null) {
      query.processInstanceTenantIdLike(queryRequest.getTenantIdLike());
    }

    if (Boolean.TRUE.equals(queryRequest.getWithoutTenantId())) {
      query.processInstanceWithoutTenantId();
    }

    return new HistoricProcessInstancePaginateList(this)
        .paginateList(urlQuery, queryRequest, query, "processInstanceId", allowedSortProperties);
  }
  protected void addVariables(
      HistoricProcessInstanceQuery processInstanceQuery, List<QueryVariable> variables) {
    RestResponseFactory responseFactory =
        getApplication(ActivitiRestServicesApplication.class).getRestResponseFactory();

    for (QueryVariable variable : variables) {
      if (variable.getVariableOperation() == null) {
        throw new ActivitiIllegalArgumentException(
            "Variable operation is missing for variable: " + variable.getName());
      }
      if (variable.getValue() == null) {
        throw new ActivitiIllegalArgumentException(
            "Variable value is missing for variable: " + variable.getName());
      }

      boolean nameLess = variable.getName() == null;

      Object actualValue = responseFactory.getVariableValue(variable);

      // A value-only query is only possible using equals-operator
      if (nameLess && variable.getVariableOperation() != QueryVariableOperation.EQUALS) {
        throw new ActivitiIllegalArgumentException(
            "Value-only query (without a variable-name) is only supported when using 'equals' operation.");
      }

      switch (variable.getVariableOperation()) {
        case EQUALS:
          if (nameLess) {
            processInstanceQuery.variableValueEquals(actualValue);
          } else {
            processInstanceQuery.variableValueEquals(variable.getName(), actualValue);
          }
          break;

        case EQUALS_IGNORE_CASE:
          if (actualValue instanceof String) {
            processInstanceQuery.variableValueEqualsIgnoreCase(
                variable.getName(), (String) actualValue);
          } else {
            throw new ActivitiIllegalArgumentException(
                "Only string variable values are supported when ignoring casing, but was: "
                    + actualValue.getClass().getName());
          }
          break;

        case NOT_EQUALS:
          processInstanceQuery.variableValueNotEquals(variable.getName(), actualValue);
          break;

        case LIKE:
          if (actualValue instanceof String) {
            processInstanceQuery.variableValueLike(variable.getName(), (String) actualValue);
          } else {
            throw new ActivitiIllegalArgumentException(
                "Only string variable values are supported for like, but was: "
                    + actualValue.getClass().getName());
          }
          break;

        case GREATER_THAN:
          processInstanceQuery.variableValueGreaterThan(variable.getName(), actualValue);
          break;

        case GREATER_THAN_OR_EQUALS:
          processInstanceQuery.variableValueGreaterThanOrEqual(variable.getName(), actualValue);
          break;

        case LESS_THAN:
          processInstanceQuery.variableValueLessThan(variable.getName(), actualValue);
          break;

        case LESS_THAN_OR_EQUALS:
          processInstanceQuery.variableValueLessThanOrEqual(variable.getName(), actualValue);
          break;

        default:
          throw new ActivitiIllegalArgumentException(
              "Unsupported variable query operation: " + variable.getVariableOperation());
      }
    }
  }
Example #6
0
  /**
   * @Title: myWorkTaskData @Description: TODO
   *
   * @param request
   * @param response
   * @param dataGrid void
   * @throws
   * @exception
   * @author fly
   * @date 2015年6月23日 上午10:20:42
   */
  @RequestMapping(params = "myWorkTaskData")
  public void myWorkTaskData(
      HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {

    String userId = ResourceUtil.getSessionUserName().getId();
    // involvedUser 当前用户相关的
    HistoricProcessInstanceQuery query =
        historyService.createHistoricProcessInstanceQuery().involvedUser(userId);

    List<HistoricProcessInstance> historicTasks =
        query
            .orderByProcessInstanceStartTime()
            .desc()
            .listPage(dataGrid.getStart(), dataGrid.getEnd());
    long total = query.count();
    System.out.println(dataGrid.getStart() + " end: " + dataGrid.getEnd());
    StringBuffer rows = new StringBuffer();
    for (HistoricProcessInstance t : historicTasks) {
      ProcessDefinition processDefinition =
          repositoryService.getProcessDefinition(t.getProcessDefinitionId());

      rows.append(
          "{'id':'"
              + t.getId()
              + "','key':'"
              + processDefinition.getName()
              + "-"
              + DateUtils.date_sdf.format(t.getStartTime())
              + "','taskId':'"
              + t.getId()
              + "'");
      // 流程详细查看
      WorkFlowSetEntity workFlowSet =
          systemService.findUniqueByProperty(
              WorkFlowSetEntity.class, "deploymentId", processDefinition.getDeploymentId());
      if (workFlowSet != null) {
        rows.append(",'action':'" + workFlowSet.getDetailUrl() + "'");
      }
      // 流程用户处理
      if (t.getStartUserId() != null) {
        TSUser user = systemService.get(TSUser.class, t.getStartUserId());
        rows.append(",'username':'******'");
      }

      // 流程开始结束时间处理
      if (t.getStartTime() == null) {
        rows.append(",'beginDate':'无'");
      } else {
        rows.append(",'beginDate':'" + DateUtils.datetimeFormat.format(t.getStartTime()) + "'");
      }
      if (t.getEndTime() == null) {
        rows.append(",'endDate':'无','stateType':'办理中'");

      } else {
        rows.append(
            ",'endDate':'"
                + DateUtils.datetimeFormat.format(t.getEndTime())
                + "','stateType':'已完成'");
      }
      rows.append("},");
    }
    String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");

    JSONObject jObject = JSONObject.fromObject("{'total':" + total + ",'rows':[" + rowStr + "]}");
    responseDatagrid(response, jObject);
  }