/**
   * 查看流程定义
   *
   * @param request
   * @param processDefId 流程定义id
   * @return
   */
  @RequestMapping(value = "/viewprocessDef.do")
  public String viewprocessDef(
      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.getResourceName());

    //        // 输出资源内容到相应对象
    //        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;
  }
  /**
   * 读取资源,通过部署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;
  }
  /**
   * 读取工作流定义的图片或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);
    }
  }
  /**
   * 将部署的流程转换为模型
   *
   * @param procDefId
   * @throws UnsupportedEncodingException
   * @throws XMLStreamException
   */
  @Transactional(readOnly = false)
  public org.activiti.engine.repository.Model convertToModel(String procDefId)
      throws UnsupportedEncodingException, XMLStreamException {

    ProcessDefinition processDefinition =
        repositoryService
            .createProcessDefinitionQuery()
            .processDefinitionId(procDefId)
            .singleResult();
    InputStream bpmnStream =
        repositoryService.getResourceAsStream(
            processDefinition.getDeploymentId(), processDefinition.getResourceName());
    XMLInputFactory xif = XMLInputFactory.newInstance();
    InputStreamReader in = new InputStreamReader(bpmnStream, "UTF-8");
    XMLStreamReader xtr = xif.createXMLStreamReader(in);
    BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);

    BpmnJsonConverter converter = new BpmnJsonConverter();
    ObjectNode modelNode = converter.convertToJson(bpmnModel);
    org.activiti.engine.repository.Model modelData = repositoryService.newModel();
    modelData.setKey(processDefinition.getKey());
    modelData.setName(processDefinition.getResourceName());
    modelData.setCategory(processDefinition.getCategory()); // .getDeploymentId());
    modelData.setDeploymentId(processDefinition.getDeploymentId());
    modelData.setVersion(
        Integer.parseInt(
            String.valueOf(
                repositoryService.createModelQuery().modelKey(modelData.getKey()).count() + 1)));

    ObjectNode modelObjectNode = new ObjectMapper().createObjectNode();
    modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, processDefinition.getName());
    modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, modelData.getVersion());
    modelObjectNode.put(
        ModelDataJsonConstants.MODEL_DESCRIPTION, processDefinition.getDescription());
    modelData.setMetaInfo(modelObjectNode.toString());

    repositoryService.saveModel(modelData);

    repositoryService.addModelEditorSource(
        modelData.getId(), modelNode.toString().getBytes("utf-8"));

    return modelData;
  }
 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());
 }
  /**
   * easyui AJAX请求数据
   *
   * @param request
   * @param response
   * @param dataGrid
   */
  @RequestMapping(params = "datagrid")
  public void datagrid(
      HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {

    ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
    List<ProcessDefinition> list = query.list();

    StringBuffer rows = new StringBuffer();
    int i = 0;
    for (ProcessDefinition pi : list) {
      Deployment deployment =
          repositoryService
              .createDeploymentQuery()
              .deploymentId(pi.getDeploymentId())
              .singleResult();
      i++;
      rows.append(
          "{'id':"
              + i
              + ",'processDefinitionId':'"
              + pi.getId()
              + "','deploymentDate':'"
              + new SimpleDateFormat("yyyy-MM-dd").format(deployment.getDeploymentTime())
              + "','resourceName':'"
              + pi.getResourceName()
              + "','deploymentId':'"
              + pi.getDeploymentId()
              + "','key':'"
              + pi.getKey()
              + "','name':'"
              + pi.getName()
              + "','version':'"
              + pi.getVersion()
              + "','isSuspended':'"
              + pi.isSuspended()
              + "'},");
    }
    String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");

    JSONObject jObject =
        JSONObject.fromObject("{'total':" + query.count() + ",'rows':[" + rowStr + "]}");
    responseDatagrid(response, jObject);
  }
  @Test
  public void testClasspathDeployment() throws IOException {

    // 定义classpath
    String bpmnClasspath = "diagrams/userAndGroupInUserTask.bpmn";
    // 添加资源
    repositoryService.createDeployment().addClasspathResource(bpmnClasspath).deploy();
    // 获取流程定义对象
    ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().singleResult();
    String resourceName = pd.getResourceName();
    System.out.println("资源名称:" + resourceName);

    // 读取资源字节流
    InputStream resourceAsStream =
        repositoryService.getResourceAsStream(pd.getDeploymentId(), resourceName);
    // 输出流的内容
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = resourceAsStream.read(b)) != -1; ) {
      out.append(new String(b, 0, n));
    }
    System.out.println(out);
  }
  protected void addProcessImage() {
    ProcessDefinitionEntity processDefinitionEntity =
        (ProcessDefinitionEntity)
            ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(processDefinition.getId());

    // Only show when graphical notation is defined
    if (processDefinitionEntity != null) {

      boolean didDrawImage = false;

      if (ExplorerApp.get().isUseJavascriptDiagram()) {
        try {

          final InputStream definitionStream =
              repositoryService.getResourceAsStream(
                  processDefinition.getDeploymentId(), processDefinition.getResourceName());
          XMLInputFactory xif = XMLInputFactory.newInstance();
          XMLStreamReader xtr = xif.createXMLStreamReader(definitionStream);
          BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);

          if (bpmnModel.getFlowLocationMap().size() > 0) {

            int maxX = 0;
            int maxY = 0;
            for (String key : bpmnModel.getLocationMap().keySet()) {
              GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(key);
              double elementX = graphicInfo.getX() + graphicInfo.getWidth();
              if (maxX < elementX) {
                maxX = (int) elementX;
              }
              double elementY = graphicInfo.getY() + graphicInfo.getHeight();
              if (maxY < elementY) {
                maxY = (int) elementY;
              }
            }

            Panel imagePanel = new Panel(); // using panel for scrollbars
            imagePanel.addStyleName(Reindeer.PANEL_LIGHT);
            imagePanel.setWidth(100, UNITS_PERCENTAGE);
            imagePanel.setHeight(100, UNITS_PERCENTAGE);
            URL explorerURL = ExplorerApp.get().getURL();
            URL url =
                new URL(
                    explorerURL.getProtocol(),
                    explorerURL.getHost(),
                    explorerURL.getPort(),
                    explorerURL.getPath().replace("/ui", "")
                        + "diagram-viewer/index.html?processDefinitionId="
                        + processDefinition.getId()
                        + "&processInstanceId="
                        + processInstance.getId());
            Embedded browserPanel = new Embedded("", new ExternalResource(url));
            browserPanel.setType(Embedded.TYPE_BROWSER);
            browserPanel.setWidth(maxX + 350 + "px");
            browserPanel.setHeight(maxY + 220 + "px");

            HorizontalLayout panelLayoutT = new HorizontalLayout();
            panelLayoutT.setSizeUndefined();
            imagePanel.setContent(panelLayoutT);
            imagePanel.addComponent(browserPanel);

            panelLayout.addComponent(imagePanel);

            didDrawImage = true;
          }

        } catch (Exception e) {
          LOGGER.error("Error loading process diagram component", e);
        }
      }

      if (didDrawImage == false && processDefinitionEntity.isGraphicalNotationDefined()) {

        StreamResource diagram =
            new ProcessDefinitionImageStreamResourceBuilder()
                .buildStreamResource(processInstance, repositoryService, runtimeService);

        if (diagram != null) {
          Label header = new Label(i18nManager.getMessage(Messages.PROCESS_HEADER_DIAGRAM));
          header.addStyleName(ExplorerLayout.STYLE_H3);
          header.addStyleName(ExplorerLayout.STYLE_DETAIL_BLOCK);
          header.addStyleName(ExplorerLayout.STYLE_NO_LINE);
          panelLayout.addComponent(header);

          Embedded embedded = new Embedded(null, diagram);
          embedded.setType(Embedded.TYPE_IMAGE);
          embedded.setSizeUndefined();

          Panel imagePanel = new Panel(); // using panel for scrollbars
          imagePanel.setScrollable(true);
          imagePanel.addStyleName(Reindeer.PANEL_LIGHT);
          imagePanel.setWidth(100, UNITS_PERCENTAGE);
          imagePanel.setHeight(100, UNITS_PERCENTAGE);

          HorizontalLayout panelLayoutT = new HorizontalLayout();
          panelLayoutT.setSizeUndefined();
          imagePanel.setContent(panelLayoutT);
          imagePanel.addComponent(embedded);

          panelLayout.addComponent(imagePanel);
        }
      }
    }
  }