/*
   * (non-Javadoc)
   *
   * @see com.template.service.common.workflow.IProcessDefinitionService#
   * exportProcessPic(org.activiti.engine.repository.ProcessDefinition,
   * java.lang.String)
   */
  @Override
  public boolean exportProcessPic(String deploymentId) {

    boolean flag = true;
    ProcessDefinition processDefinition =
        repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();

    String diagramResourceName = processDefinition.getDiagramResourceName();
    try {
      diagramResourceName = processDefinition.getDiagramResourceName();
      InputStream imageStream =
          repositoryService.getResourceAsStream(
              processDefinition.getDeploymentId(), diagramResourceName);

      byte[] b = new byte[imageStream.available()];
      imageStream.read(b, 0, b.length);

      File file =
          new File(
              workFlowPicPath
                  + File.separator
                  + processDefinition.getKey()
                  + "."
                  + FilenameUtils.getExtension(diagramResourceName));
      FileUtils.writeByteArrayToFile(file, b);
    } catch (IOException e) {
      flag = false;
    }
    return flag;
  }
 protected String getProcessDisplayName(ProcessDefinition processDefinition) {
   if (processDefinition.getName() != null) {
     return processDefinition.getName();
   } else {
     return processDefinition.getKey();
   }
 }
Пример #3
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";
  }
  @Test
  @Rollback(value = false)
  public void testDeploy() throws Exception {
    String path = ProcessDefManagerTest.class.getClassLoader().getResource("bpmnsub.xml").getPath();
    String value = FileUtils.readFileToString(new File(path));

    Deployment deployment =
        repositoryService
            .createDeployment()
            .addString("sub-model.bpmn", value)
            .name("子流程")
            .category("行政")
            .enableDuplicateFiltering()
            .deploy();
    //
    //        // 4. Start a process instance
    Map<String, Object> map = new HashMap<String, Object>();
    //        map.put("signAssignee", Arrays.asList("hr", "dep", "user"));
    identityService.setAuthenticatedUserId("dynamic");
    ProcessDefinition definition =
        repositoryService
            .createProcessDefinitionQuery()
            .deploymentId(deployment.getId())
            .singleResult();

    ProcessInstance processInstance =
        runtimeService.startProcessInstanceById(definition.getId(), map);
    int i = 0;
    System.out.println(processInstance.getId());
  }
Пример #5
0
  /** 查询已经部署的流程,并且能够启动他 它(demo) add by hongbin */
  public String menu_process_list() {
    // List<Deployment> list = repositoryService.createDeploymentQuery().list();
    List<Object[]> list = new ArrayList<Object[]>();
    ProcessDefinitionQuery processDefinitionQuery =
        repositoryService
            .createProcessDefinitionQuery()
            .orderByDeploymentId()
            .latestVersion()
            .desc(); // 只需要最新的version就行了
    List<ProcessDefinition> processDefinitionList = processDefinitionQuery.list();

    for (ProcessDefinition processDefinition : processDefinitionList) {
      String deploymentId = processDefinition.getDeploymentId();
      Deployment deployment =
          repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
      // ProcessDefinitionEntity pde = (ProcessDefinitionEntity)processDefinition;
      //            Object model =
      // infActiviti.getVariableByProcessInstanceId(pde.getProcessDefinition().getId(),"model");

      list.add(new Object[] {processDefinition, deployment});
    }

    getAllUserAndGroupInfo();
    rhs.put("list", list);
    return "success";
  }
  /**
   * 查看流程定义图
   *
   * @param request
   * @param processDefId 流程定义id
   * @return
   */
  @RequestMapping(value = "/viewprocessDefImage.do")
  public String viewprocessDefImage(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam("processDefId") String processDefId)
      throws Exception {
    // 根据流程定义id查询流程定义
    ProcessDefinition processDefinition =
        repositoryService
            .createProcessDefinitionQuery()
            .processDefinitionId(processDefId)
            .singleResult();

    InputStream inputStream =
        repositoryService.getResourceAsStream(
            processDefinition.getDeploymentId(), processDefinition.getDiagramResourceName());

    //        // 输出资源内容到相应对象
    //        byte[] b = new byte[1024];
    //        int len;
    //        while ((len = inputStream.read(b, 0, 1024)) != -1) {
    //        	response.getOutputStream().write(b, 0, len);
    //        }

    response.getOutputStream().write(IoUtil.readInputStream(inputStream, "processDefInputStream"));

    return null;
  }
Пример #7
0
  /**
   * 读取资源,通过部署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;
  }
Пример #8
0
  /** 流程定义列表 */
  public Page<Object[]> processList(Page<Object[]> page, String category) {

    ProcessDefinitionQuery processDefinitionQuery =
        repositoryService
            .createProcessDefinitionQuery()
            .latestVersion()
            .orderByProcessDefinitionKey()
            .asc();

    if (StringUtils.isNotEmpty(category)) {
      processDefinitionQuery.processDefinitionCategory(category);
    }

    page.setCount(processDefinitionQuery.count());

    List<ProcessDefinition> processDefinitionList =
        processDefinitionQuery.listPage(page.getFirstResult(), page.getMaxResults());
    for (ProcessDefinition processDefinition : processDefinitionList) {
      String deploymentId = processDefinition.getDeploymentId();
      Deployment deployment =
          repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
      page.getList().add(new Object[] {processDefinition, deployment});
    }

    return page;
  }
  @SuppressWarnings("serial")
  private PopupView createProcessDefinitionPopup(final ProcessDefinition processDefinition) {
    final VerticalLayout layout = new VerticalLayout();
    final PopupView popup = new PopupView(processDefinition.getName(), layout);

    layout.setSizeUndefined();
    layout.setMargin(true);
    layout.setSpacing(true);
    Label header =
        new Label(
            String.format(
                "What would you like to do with <b>%s</b>?", processDefinition.getName()));
    header.setContentMode(Label.CONTENT_XHTML);
    layout.addComponent(header);

    Button startNewInstanceButton = new Button("Start a new instance");
    startNewInstanceButton.addStyleName(Reindeer.BUTTON_SMALL);
    startNewInstanceButton.addListener(
        new Button.ClickListener() {

          @Override
          public void buttonClick(ClickEvent event) {
            getPresenter().startNewInstance(processDefinition);
            popup.setPopupVisible(false);
          }
        });
    layout.addComponent(startNewInstanceButton);

    return popup;
  }
Пример #10
0
  /**
   * 读取工作流定义的图片或xml
   *
   * @throws Exception
   */
  @RequestMapping(params = "resourceRead")
  public void resourceRead(
      @RequestParam("processDefinitionId") String processDefinitionId,
      @RequestParam("resourceType") String resourceType,
      HttpServletResponse response)
      throws Exception {
    ProcessDefinition processDefinition =
        repositoryService
            .createProcessDefinitionQuery()
            .processDefinitionId(processDefinitionId)
            .singleResult();
    String resourceName = "";
    if (resourceType.equals("image")) {
      resourceName = processDefinition.getDiagramResourceName();
    } else if (resourceType.equals("xml")) {
      resourceName = processDefinition.getResourceName();
    }
    InputStream resourceAsStream =
        repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName);
    byte[] b = new byte[1024];
    int len = -1;

    while ((len = resourceAsStream.read(b, 0, 1024)) != -1) {
      response.getOutputStream().write(b, 0, len);
    }
  }
 protected String getProcessDisplayName(
     ProcessDefinition processDefinition, ProcessInstance processInstance) {
   if (processDefinition.getName() != null) {
     return processDefinition.getName() + " (" + processInstance.getId() + ")";
   } else {
     return processDefinition.getKey() + " (" + processInstance.getId() + ")";
   }
 }
  public synchronized ProcessEngine installProcessArchive(ProcessArchive processArchive) {
    final String paName = processArchive.getName();

    if (!isActive) {
      throw new FoxPlatformException(
          "Cannot install process archive with name "
              + paName
              + ": ProcessEngineService is not active.");
    }

    if (installedProcessArchivesByName.containsKey(paName)) {
      throw new FoxPlatformException(
          "Cannot install process archive with name '"
              + paName
              + "': process archive with same name already installed.");
    }

    log.info("Installing process archive '" + paName + "'");
    Deployment deployment = performEngineDeployment(processArchive);

    ProcessArchiveContext processArchiveContext =
        new ProcessArchiveContext(deployment, processArchive);
    processArchiveContext.setActive(true);
    installedProcessArchivesByName.put(processArchive.getName(), processArchiveContext);

    ArrayList<ProcessArchive> processArchives =
        new ArrayList<ProcessArchive>(cachedProcessArchives);
    processArchives.add(processArchive);
    cachedProcessArchives = Collections.unmodifiableList(processArchives);

    if (deployment != null) {
      List<ProcessDefinition> processDefinitionsForThisDeployment =
          activitiProcessEngine
              .getRepositoryService()
              .createProcessDefinitionQuery()
              .deploymentId(deployment.getId())
              .list();
      for (ProcessDefinition processDefinition : processDefinitionsForThisDeployment) {
        installedProcessArchivesByProcessDefinitionKey.put(
            processDefinition.getKey(), processArchiveContext);
      }
      log.info(
          "Installed process archive '"
              + paName
              + "' to process engine '"
              + processEngineName
              + "'.");
      return activitiProcessEngine;
    } else {
      log.info(
          "Installed empty process archive '"
              + paName
              + "'. Process archive will have access to process engine with name '"
              + processEngineName
              + "'.");
      return activitiProcessEngine;
    }
  }
Пример #13
0
  /**
   * 级联删除流程定义
   *
   * @return
   */
  public String removeProcessDefinition() {
    RepositoryService repositoryService = processEngine.getRepositoryService();
    ProcessDefinition processDefinition =
        repositoryService.getProcessDefinition(processDefinitionId);

    repositoryService.deleteDeployment(processDefinition.getDeploymentId(), true);

    return RELOAD_PROCESS_DEFINITION;
  }
Пример #14
0
 public static void deleteProcessCascade(String processDefinitionKey) {
   List<ProcessDefinition> processDefinitions =
       repositoryService
           .createProcessDefinitionQuery()
           .processDefinitionKey(processDefinitionKey)
           .list();
   for (ProcessDefinition processDefinition : processDefinitions) {
     repositoryService.deleteDeployment(processDefinition.getDeploymentId(), true);
   }
 }
  @Deployment(resources = {"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testStartProcessInstanceById() {
    List<ProcessDefinition> processDefinitions =
        repositoryService.createProcessDefinitionQuery().list();
    assertEquals(1, processDefinitions.size());

    ProcessDefinition processDefinition = processDefinitions.get(0);
    assertEquals("oneTaskProcess", processDefinition.getKey());
    assertNotNull(processDefinition.getId());
  }
 private void updateComponent() {
   removeAllComponents();
   if (processDefinitions != null) {
     for (ProcessDefinition pd : processDefinitions) {
       final Component processComponent =
           createProcessDefinitionComponent(pd.getName(), pd.getKey());
       addComponent(processComponent);
     }
   }
 }
  @Cacheable("processDefinitionIds")
  public Set<String> getProcessDefinitionIds(String... keys) {
    Set<String> keySet = Sets.newHashSet(keys);
    Set<String> set = new HashSet<String>();
    for (ProcessDefinition processDefinition :
        processEngine.getRepositoryService().createProcessDefinitionQuery().list()) {
      if (keySet.contains(processDefinition.getKey())) set.add(processDefinition.getId());
    }

    return Collections.unmodifiableSet(set);
  }
  protected void initWindow() {
    windowLayout.setSpacing(true);
    addStyleName(Reindeer.WINDOW_LIGHT);
    setModal(true);
    center();

    String name = processDefinition.getName();
    if (StringUtils.isEmpty(name)) {
      name = processDefinition.getKey();
    }
    setCaption(i18nManager.getMessage(Messages.PROCESS_CONVERT_POPUP_CAPTION, name));
  }
  @Deployment(resources = {"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testDeleteDeploymentCascadeWithRunningInstances() {
    List<ProcessDefinition> processDefinitions =
        repositoryService.createProcessDefinitionQuery().list();
    assertEquals(1, processDefinitions.size());
    ProcessDefinition processDefinition = processDefinitions.get(0);

    runtimeService.startProcessInstanceById(processDefinition.getId());

    // Try to delete the deployment, no exception should be thrown
    repositoryService.deleteDeployment(processDefinition.getDeploymentId(), true);
  }
Пример #20
0
 @Test
 public void exportedServices() throws Exception {
   assertNotNull(processEngine);
   assertNotNull(repositoryService);
   // wait for deployment to be done
   Thread.sleep(5000);
   Deployment deployment = repositoryService.createDeploymentQuery().singleResult();
   assertEquals("org.activiti.osgi.example", deployment.getName());
   ProcessDefinition processDefinition =
       repositoryService.createProcessDefinitionQuery().singleResult();
   assertEquals("osgiProcess", processDefinition.getKey());
 }
Пример #21
0
  /**
   * @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;
  }
Пример #22
0
 public void viewXml() throws Exception {
   RepositoryService repositoryService = processEngine.getRepositoryService();
   ProcessDefinition processDefinition =
       repositoryService
           .createProcessDefinitionQuery()
           .processDefinitionId(processDefinitionId)
           .singleResult();
   String resourceName = processDefinition.getResourceName();
   InputStream resourceAsStream =
       repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName);
   ServletActionContext.getResponse().setContentType("text/xml;charset=UTF-8");
   IoUtils.copyStream(resourceAsStream, ServletActionContext.getResponse().getOutputStream());
 }
Пример #23
0
  /**
   * 部署流程 - 保存
   *
   * @param file
   * @return
   */
  @Transactional(readOnly = false)
  public String deploy(String exportDir, String category, MultipartFile file) {

    String message = "";

    String fileName = file.getOriginalFilename();

    try {
      InputStream fileInputStream = file.getInputStream();
      Deployment deployment = null;
      String extension = FilenameUtils.getExtension(fileName);
      if (extension.equals("zip") || extension.equals("bar")) {
        ZipInputStream zip = new ZipInputStream(fileInputStream);
        deployment = repositoryService.createDeployment().addZipInputStream(zip).deploy();
      } else if (extension.equals("png")) {
        deployment =
            repositoryService.createDeployment().addInputStream(fileName, fileInputStream).deploy();
      } else if (fileName.indexOf("bpmn20.xml") != -1) {
        deployment =
            repositoryService.createDeployment().addInputStream(fileName, fileInputStream).deploy();
      } else if (extension.equals("bpmn")) { // bpmn扩展名特殊处理,转换为bpmn20.xml
        String baseName = FilenameUtils.getBaseName(fileName);
        deployment =
            repositoryService
                .createDeployment()
                .addInputStream(baseName + ".bpmn20.xml", fileInputStream)
                .deploy();
      } else {
        message = "不支持的文件类型:" + extension;
      }

      List<ProcessDefinition> list =
          repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).list();

      // 设置流程分类
      for (ProcessDefinition processDefinition : list) {
        // ActUtils.exportDiagramToFile(repositoryService,
        // processDefinition, exportDir);
        repositoryService.setProcessDefinitionCategory(processDefinition.getId(), category);
        message += "部署成功,流程ID=" + processDefinition.getId() + "<br/>";
      }

      if (list.size() == 0) {
        message = "部署失败,没有流程。";
      }

    } catch (Exception e) {
      throw new ActivitiException("部署失败!", e);
    }
    return message;
  }
Пример #24
0
  public FormDTO findStartEventForm(FirstTaskForm firstTaskForm) {
    ProcessDefinition processDefinition =
        processEngine
            .getRepositoryService()
            .createProcessDefinitionQuery()
            .processDefinitionId(firstTaskForm.getProcessDefinitionId())
            .singleResult();
    List<BpmConfForm> bpmConfForms =
        bpmConfFormManager.find(
            "from BpmConfForm where bpmConfNode.bpmConfBase.processDefinitionId=? and bpmConfNode.code=?",
            firstTaskForm.getProcessDefinitionId(),
            firstTaskForm.getActivityId());
    FormDTO formDto = new FormDTO();
    formDto.setProcessDefinitionId(firstTaskForm.getProcessDefinitionId());
    formDto.setActivityId(firstTaskForm.getActivityId());
    formDto.setCode(firstTaskForm.getFormKey());

    if (!bpmConfForms.isEmpty()) {
      BpmConfForm bpmConfForm = bpmConfForms.get(0);

      if (!Integer.valueOf(2).equals(bpmConfForm.getStatus())) {
        if (Integer.valueOf(1).equals(bpmConfForm.getType())) {
          formDto.setRedirect(true);
          formDto.setUrl(bpmConfForm.getValue());
        } else {
          formDto.setCode(bpmConfForm.getValue());
        }
      }
    } else {
      logger.info(
          "cannot find bpmConfForm : {}, {}",
          firstTaskForm.getProcessDefinitionId(),
          formDto.getActivityId());
    }

    FormDTO contentFormDto =
        formConnector.findForm(formDto.getCode(), processDefinition.getTenantId());

    if (contentFormDto == null) {
      logger.error("cannot find form : {}", formDto.getCode());

      return formDto;
    }

    formDto.setRedirect(contentFormDto.isRedirect());
    formDto.setUrl(contentFormDto.getUrl());
    formDto.setContent(contentFormDto.getContent());

    return formDto;
  }
  /**
   * 调用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);
  }
 /** * 显示流程图 * * @return * @throws Exception */
 public String getProcessPic() throws Exception {
   // String taskId = //
   // "2901";//request.getParameter("taskId");3016,552,3020
   String procDefId = ""; // request.getParameter("procDefId");
   ProcessDefinition procDef =
       repositoryService
           .createProcessDefinitionQuery()
           .processDefinitionId(procDefId)
           .singleResult();
   String diagramResourceName = procDef.getDiagramResourceName();
   InputStream imageStream =
       repositoryService.getResourceAsStream(procDef.getDeploymentId(), diagramResourceName);
   // request.setAttribute("inputStream", imageStream);
   return "SUCCESS";
 }
Пример #27
0
  /**
   * @Title: setvalid @Description: 设置是流程启动/挂起
   *
   * @param deploymentId
   * @param request
   * @return AjaxJson
   * @throws
   * @exception
   * @author fly
   * @date 2015年5月13日 上午9:35:50
   */
  @RequestMapping(params = "setvalid")
  @ResponseBody
  public AjaxJson setvalid(@RequestParam("id") String id, HttpServletRequest request) {
    AjaxJson j = new AjaxJson();
    ProcessDefinition processDefinition = repositoryService.getProcessDefinition(id);
    if (processDefinition.isSuspended()) {
      repositoryService.activateProcessDefinitionById(id, true, null);
    } else {
      repositoryService.suspendProcessDefinitionById(id, true, null);
    }

    String message = "操作成功";
    j.setMsg(message);
    return j;
  }
 @RequestMapping(value = "/read-resource")
 public void readResource(
     @RequestParam("pdid") String processDefinitionId,
     @RequestParam("resourceName") String resourceName,
     HttpServletResponse response)
     throws Exception {
   ProcessDefinitionQuery pdq = repositoryService.createProcessDefinitionQuery();
   ProcessDefinition pd = pdq.processDefinitionId(processDefinitionId).singleResult();
   InputStream resourceAsStream =
       repositoryService.getResourceAsStream(pd.getDeploymentId(), resourceName);
   byte[] b = new byte[1024];
   int len = -1;
   while ((len = resourceAsStream.read(b, 0, 1024)) != -1) {
     response.getOutputStream().write(b, 0, len);
   }
 }
  /**
   * 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;
  }
Пример #30
0
  /** 导出图片文件到硬盘 */
  public List<String> exportDiagrams(String exportDir) throws IOException {
    List<String> files = new ArrayList<String>();
    List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();

    for (ProcessDefinition processDefinition : list) {
      String diagramResourceName = processDefinition.getDiagramResourceName();
      String key = processDefinition.getKey();
      int version = processDefinition.getVersion();
      String diagramPath = "";

      InputStream resourceAsStream =
          repositoryService.getResourceAsStream(
              processDefinition.getDeploymentId(), diagramResourceName);
      byte[] b = new byte[resourceAsStream.available()];

      @SuppressWarnings("unused")
      int len = -1;
      resourceAsStream.read(b, 0, b.length);

      // create file if not exist
      String diagramDir = exportDir + "/" + key + "/" + version;
      File diagramDirFile = new File(diagramDir);
      if (!diagramDirFile.exists()) {
        diagramDirFile.mkdirs();
      }
      diagramPath = diagramDir + "/" + diagramResourceName;
      File file = new File(diagramPath);

      // 文件存在退出
      if (file.exists()) {
        // 文件大小相同时直接返回否则重新创建文件(可能损坏)
        logger.debug("diagram exist, ignore... : {}", diagramPath);

        files.add(diagramPath);
      } else {
        file.createNewFile();
        logger.debug("export diagram to : {}", diagramPath);

        // wirte bytes to file
        FileUtils.writeByteArrayToFile(file, b, true);

        files.add(diagramPath);
      }
    }

    return files;
  }