1. 程式人生 > >Activiti工作流實現檢視流程圖圖片並在當前流程上新增紅圈

Activiti工作流實現檢視流程圖圖片並在當前流程上新增紅圈

為什麼要用Activiti工作流以及Acitiviti工作流的基礎用法就不多說了,廢話不多說,直接上程式碼(呼叫該方法,頁面使用img標籤即可)

package com.supermap.zzsubcorp.iPark.assetsMetaDataEngine.activiti.controller;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricDetail;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.SubProcessActivityBehavior;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.ReadOnlyProcessDefinition;
import org.activiti.engine.impl.pvm.delegate.ActivityBehavior;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.supermap.zzsubcorp.iPark.assetsMetaDataEngine.activiti.ActivityUtil;
@Controller
@RequestMapping(value = "/traceProcess")
public class TraceProcessController {
	
	@Autowired
    TaskService taskService;

    @Autowired
    HistoryService historyService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    protected IdentityService identityService;

    @Autowired
    ProcessEngineConfiguration processEngineConfiguration;
	/**
     * 讀取流程資源
     */
    @RequestMapping(value = "trace/data/auto/{executionId}")
    public void readResource(@PathVariable("executionId") String executionId, HttpServletResponse response)
            throws Exception {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(executionId).singleResult();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult();
        List<String> activeActivityIds = runtimeService.getActiveActivityIds(executionId);
        List<String> highLightedFlows = getHighLightedFlows(processDefinition, processInstance.getId());
        ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
       //InputStream imageStream =diagramGenerator.generateDiagram(bpmnModel, "png", activeActivityIds, highLightedFlows);
        String activityFontName=processEngineConfiguration.getActivityFontName();
        String labelFontName=processEngineConfiguration.getLabelFontName();
        InputStream imageStream =diagramGenerator.generateDiagram(bpmnModel, "png", activeActivityIds, highLightedFlows,activityFontName,labelFontName,null, null, 1.0);

        // 輸出資源內容到相應物件
        byte[] b = new byte[1024];
        int len;
        while ((len = imageStream.read(b, 0, 1024)) != -1) {
            response.getOutputStream().write(b, 0, len);
        }
    }
    
    private List<String> getHighLightedFlows(ProcessDefinitionEntity processDefinition, String processInstanceId) {
        List<String> highLightedFlows = new ArrayList<String>();
        List<HistoricActivityInstance> historicActivityInstances = historyService
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricActivityInstanceStartTime().asc().list();

        List<String> historicActivityInstanceList = new ArrayList<String>();
        for (HistoricActivityInstance hai : historicActivityInstances) {
            historicActivityInstanceList.add(hai.getActivityId());
        }

        // add current activities to list
        List<String> highLightedActivities = runtimeService.getActiveActivityIds(processInstanceId);
        historicActivityInstanceList.addAll(highLightedActivities);

        // activities and their sequence-flows
        for (ActivityImpl activity : processDefinition.getActivities()) {
            int index = historicActivityInstanceList.indexOf(activity.getId());

            if (index >= 0 && index + 1 < historicActivityInstanceList.size()) {
                List<PvmTransition> pvmTransitionList = activity
                        .getOutgoingTransitions();
                for (PvmTransition pvmTransition : pvmTransitionList) {
                    String destinationFlowId = pvmTransition.getDestination().getId();
                    if (destinationFlowId.equals(historicActivityInstanceList.get(index + 1))) {
                        highLightedFlows.add(pvmTransition.getId());
                    }
                }
            }
        }
        return highLightedFlows;
    }
    /**
     * 讀取歷史資料
     *
     * @return
     */
    @RequestMapping(value = "trace/view/{executionId}")
    public ModelAndView historyDatas(@PathVariable("executionId") String executionId) {
        ModelAndView mav = new ModelAndView("chapter13/trace-process");

        // 查詢Execution物件
        Execution execution = runtimeService.createExecutionQuery().executionId(executionId).singleResult();

        // 查詢所有的歷史活動記錄
        String processInstanceId = execution.getProcessInstanceId();
        List<HistoricActivityInstance> activityInstances = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();

        // 查詢歷史流程例項
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId).singleResult();

        // 查詢流程有關的變數
        List<HistoricVariableInstance> variableInstances = historyService.createHistoricVariableInstanceQuery()
                .processInstanceId(processInstanceId).list();

        List<HistoricDetail> formProperties = historyService.createHistoricDetailQuery().processInstanceId(processInstanceId).formProperties().list();

        // 查詢流程定義物件
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult();

        // 查詢執行時流程例項
        ProcessInstance parentProcessInstance = runtimeService.createProcessInstanceQuery()
                .subProcessInstanceId(execution.getProcessInstanceId()).singleResult();

        mav.addObject("parentProcessInstance", parentProcessInstance);
        mav.addObject("historicProcessInstance", historicProcessInstance);
        mav.addObject("variableInstances", variableInstances);
        mav.addObject("activities", activityInstances);
        mav.addObject("formProperties", formProperties);
        mav.addObject("processDefinition", processDefinition);
        mav.addObject("executionId", executionId);

        return mav;
    }

    /**
     * 讀取跟蹤資料
     *
     * @param executionId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "trace/data/{executionId}")
    @ResponseBody
    public List<Map<String, Object>> readActivityDatas(@PathVariable("executionId") String executionId) throws Exception {
        ExecutionEntity executionEntity = (ExecutionEntity) runtimeService.createExecutionQuery().executionId(executionId).singleResult();
        List<String> activeActivityIds = runtimeService.getActiveActivityIds(executionId);

        RepositoryServiceImpl repositoryServiceImpl = (RepositoryServiceImpl) repositoryService;
        ReadOnlyProcessDefinition deployedProcessDefinition = repositoryServiceImpl
                .getDeployedProcessDefinition(executionEntity.getProcessDefinitionId());

        ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) deployedProcessDefinition;
        List<ActivityImpl> activitiList = processDefinition.getActivities();//獲得當前任務的所有節點

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

            ActivityBehavior activityBehavior = activity.getActivityBehavior();

            boolean currentActiviti = false;
            // 當前節點
            String activityId = activity.getId();
            if (activeActivityIds.contains(activityId)) {
                currentActiviti = true;
            }
            Map<String, Object> activityImageInfo = packageSingleActivitiInfo(activity, executionEntity.getId(), currentActiviti);
            activityInfos.add(activityImageInfo);

            // 處理子流程
            if (activityBehavior instanceof SubProcessActivityBehavior) {
                List<ActivityImpl> innerActivityList = activity.getActivities();
                for (ActivityImpl innerActivity : innerActivityList) {
                    String innerActivityId = innerActivity.getId();
                    if (activeActivityIds.contains(innerActivityId)) {
                        currentActiviti = true;
                    } else {
                        currentActiviti = false;
                    }
                    activityImageInfo = packageSingleActivitiInfo(innerActivity, executionEntity.getId(), currentActiviti);
                    activityInfos.add(activityImageInfo);
                }
            }

        }

        return activityInfos;
    }

    /**
     * 封裝輸出資訊,包括:當前節點的X、Y座標、變數資訊、任務型別、任務描述
     *
     * @param activity
     * @param currentActiviti
     * @return
     */
    private Map<String, Object> packageSingleActivitiInfo(ActivityImpl activity, String executionId,
                                                          boolean currentActiviti) throws Exception {
        Map<String, Object> activityInfo = new HashMap<String, Object>();
        activityInfo.put("currentActiviti", currentActiviti);

        // 設定圖形的XY座標以及寬度、高度
        setSizeAndPositonInfo(activity, activityInfo);

        Map<String, Object> vars = new HashMap<String, Object>();
        Map<String, Object> properties = activity.getProperties();
        vars.put("任務型別", ActivityUtil.getZhActivityType(properties.get("type").toString()));
        vars.put("任務名稱", properties.get("name"));

        // 當前節點的task
        if (currentActiviti) {
            setCurrentTaskInfo(executionId, activity.getId(), vars);
        }

       // logger.debug("trace variables: {}", vars);
        activityInfo.put("vars", vars);
        return activityInfo;
    }

    /**
     * 獲取當前節點資訊
     *
     * @return
     */
    private void setCurrentTaskInfo(String executionId, String activityId, Map<String, Object> vars) {
        Task currentTask = taskService.createTaskQuery().executionId(executionId)
                .taskDefinitionKey(activityId).singleResult();
       // logger.debug("current task for processInstance: {}", ToStringBuilder.reflectionToString(currentTask));

        if (currentTask == null) return;

        String assignee = currentTask.getAssignee();
        if (assignee != null) {
            User assigneeUser = identityService.createUserQuery().userId(assignee).singleResult();
            String userInfo = assigneeUser.getFirstName() + " " + assigneeUser.getLastName() + "/" + assigneeUser.getId();
            vars.put("當前處理人", userInfo);
            vars.put("建立時間", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(currentTask.getCreateTime()));
        } else {
            vars.put("任務狀態", "未簽收");
        }

    }

    /**
     * 設定寬度、高度、座標屬性
     *
     * @param activity
     * @param activityInfo
     */
    private void setSizeAndPositonInfo(ActivityImpl activity, Map<String, Object> activityInfo) {
        activityInfo.put("width", activity.getWidth());
        activityInfo.put("height", activity.getHeight());
        activityInfo.put("x", activity.getX());
        activityInfo.put("y", activity.getY());
    }
}