[工作流与Activiti] - No.4 简易工作流系统搭建(3) : 流程管理功能+个人任务管理

版权声明:Copyright©TJU YanMing https://blog.csdn.net/tjuyanming/article/details/75207981

这篇文章,我将完善流程管理和用户任务管理,内容很简单,主要是设计一些后端activiti函数的调用已经前端数据处理的问题。最后我会给大家提供一下activiti学习的文档,由我们小组整理而成,大概100来页

1.在model包中添加以下类,源码见项目。

MyProcess:在视图层显示流程定义信息

MyActivity:在前端显示的 某任务节点 对应流程实例 所有经历的活动节点

MyHIstoricProc:某用户所发起的所有流程实例

MyProperty:流程定义中表单的属性值

MyTask:某个用户的任务

2.在Service 和service.impl中分别添加ProcessService和MyTaskService及其实现

ProcessService

public interface ProcessService {
    List<MyProcess> getAllProcess();
    List<MyProcess> getAllUnsuspendProcess();
    String getProcessXML(String processId);
    BufferedImage getProcessImg(String processId);
    boolean deleteProcess(String deployId);
    String changeProcessStatus(String processId);
    void convertToModel(String processId);
    List<MyActivity> getAllHistoricActiIns(String processId);
    BufferedImage getProgressImg(String processId);
    List<MyProperty> getHisActiDetail(String processId,String activityInsId);
}
ProcessServiceImpl

@Service
public class ProcessServiceImpl implements ProcessService {

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    /**
    * @Date: 16:38 2017/6/2
     * 获取所有激活中的流程
    */
    @Override
    public List<MyProcess> getAllUnsuspendProcess() {
        List<MyProcess> resList = new ArrayList<MyProcess>();
        try {
            List<ProcessDefinition>list = repositoryService.createProcessDefinitionQuery()
                    .orderByProcessDefinitionId().asc().list();
            for (ProcessDefinition process : list) {
                //判断是否挂起
                if(!process.isSuspended()) {
                    MyProcess myProcess = new MyProcess(process);
                    resList.add(myProcess);
                }
            }
            return resList;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }



    /**
    * @Date: 16:39 2017/6/2
     * 获取指定流程id 对应所有流程实例中的 所有的活动实例
     * @param processId 流程id
    */
    @Override
    public List<MyActivity> getAllHistoricActiIns(String processId) {
        List<MyActivity> resList = new ArrayList<>();
        List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processId)
                .orderByHistoricActivityInstanceStartTime()
                .asc()
                .list();

        for (HistoricActivityInstance hai : list) {
            //只显示 任务节点 和 开始结束事件
            if (hai.getActivityType().endsWith("Task") || hai.getActivityType().endsWith("Event")){
                resList.add(new MyActivity(hai));
            }
        }
        return resList;
    }


    /**
    * @Date: 16:40 2017/6/2
     * 获取所有流程定义
    */
    @Override
    public List<MyProcess> getAllProcess() {
        List<MyProcess> resList = new ArrayList<MyProcess>();
        try {
            List<ProcessDefinition>list = repositoryService.createProcessDefinitionQuery()
                    .orderByProcessDefinitionId().asc().list();
            for (ProcessDefinition process : list) {
                MyProcess myProcess = new MyProcess(process);
                resList.add(myProcess);
            }
            return resList;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }

    /**
    * @Date: 16:41 2017/6/2
     * 获取流程定义图片
    */
    @Override
    public BufferedImage getProcessImg(String processId) {
        try {
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(processId).singleResult();
            String deployId = processDefinition.getDeploymentId();
            //获取流程定义的图片资源名
            String ImgResource = processDefinition.getDiagramResourceName();
            //根据部署id、资源名 查询图片二进制流
            InputStream imageStream = repositoryService.getResourceAsStream(deployId, ImgResource);
            BufferedImage bufferedImage = ImageIO.read(imageStream);
            return bufferedImage;
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }

    /**
    * @Date: 16:47 2017/6/2
     * 获取流程XML
    */
    @Override
    public String getProcessXML(String processId) {
        String resXML = "";
        try {
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(processId).singleResult();
            String deployId = processDefinition.getDeploymentId();
            //获取 xml资源文件名
            String XMLResource = processDefinition.getResourceName();
            InputStream resourceAsStream = repositoryService
                    .getResourceAsStream(deployId, XMLResource);
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] bpmnByte = new byte[1024];
            int len = -1;
            while ((len = resourceAsStream.read(bpmnByte, 0, 1024)) != -1) {
                outSteam.write(bpmnByte, 0, len);
            }
            //首先把String转换为ISO-8859-1,然后在前端用UTF-8显示
            resXML =  new String(outSteam.toString().getBytes("UTF-8"),"ISO-8859-1");
            return resXML;
       }catch (Exception e){
            e.printStackTrace();
            return resXML;
        }
    }

    /**
    * @Date: 16:48 2017/6/2
     * 删除流程部署(定义)
    */
    @Override
    public boolean deleteProcess(String deployId) {
        try{
            repositoryService.deleteDeployment(deployId,true);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
    * @Date: 16:48 2017/6/2
     * 更改流程状态
     * -1:错误 1:激活 2:挂起
    */
    @Override
    public String changeProcessStatus(String processId) {
        final String suspend = "2";
        final String unsuspend = "1";
        final String errorStatus = "-1";
        try{
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(processId).singleResult();
            //激活流程 1
            if(processDefinition.isSuspended()){

                repositoryService.activateProcessDefinitionById(processId);
                return unsuspend;
            }
            //挂起流程 2
            else{
                // 此处为按ID挂起,同时挂起所有与流程相关,立刻挂起
                repositoryService.suspendProcessDefinitionById(processId);
                return suspend;
            }
        }catch (Exception e){
            e.printStackTrace();
            return errorStatus;
        }
    }

    /**
    * @Date: 16:49 2017/6/2
     * 流程转换成模型
    */
    @Override
    public void convertToModel(String processId) {
        try {
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(processId).singleResult();
            InputStream bpmnStream = repositoryService
                    .getResourceAsStream(processDefinition.getDeploymentId(),
                            processDefinition.getResourceName());
            XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
            InputStreamReader in = new InputStreamReader(bpmnStream, "UTF-8");
            XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(in);
            BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xmlStreamReader);
            BpmnJsonConverter converter = new BpmnJsonConverter();
            ObjectNode modelNode = converter.convertToJson(bpmnModel);
            Model model = repositoryService.newModel();
            model.setKey(processDefinition.getKey());
            model.setName(processDefinition.getResourceName());
            model.setCategory(processDefinition.getDeploymentId());
            ObjectNode modelObjectNode = new ObjectMapper().createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME,
                    processDefinition.getName());
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION,
                    processDefinition.getDescription());
            model.setMetaInfo(modelObjectNode.toString());
            repositoryService.saveModel(model);
            repositoryService.addModelEditorSource(model.getId(),
                    modelNode.toString().getBytes("UTF-8"));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
    * @Date: 16:51 2017/6/2
     * 获取指定流程进度追踪图
    */
    @Override
    public BufferedImage getProgressImg(String processInstanceId) {
        BufferedImage bufferedImage = null;
        //获取流程实例对象和流程定义实体对象来进行查询工作
        HistoricProcessInstance processInstance =  historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity)repositoryService.getProcessDefinition(processInstance.getProcessDefinitionId());
        //获取历史活动实例列表,用于后续确定高亮的线
        List<HistoricActivityInstance> highLightedActivitList =  historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceStartTime().asc().list();
        //高亮线路id集合
        List<String> highLightedFlows = getHighLightedFlows(definitionEntity,highLightedActivitList);
        //高亮节点id集合
        List<String> highLighted = new ArrayList<String>();
        List<Execution> exeList = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).list();
        CharSequence charSequence = "Task";
        for (Execution exe : exeList) {
            String type = historyService.createNativeHistoricActivityInstanceQuery().sql("select * from act_hi_actinst where ACT_ID_ ='"+exe.getActivityId()+"'").list().get(0).getActivityType();
            if(type.contains(charSequence)){
                highLighted.add(exe.getActivityId());
            }
        }
        //获取模型
        BpmnModel bpmnModel = repositoryService
                .getBpmnModel(processInstance.getProcessDefinitionId());
        //获取流程图片生成器
        DefaultProcessDiagramGenerator dpdg = new DefaultProcessDiagramGenerator();
        //绘制图片
        InputStream input = dpdg.generateDiagram(bpmnModel, "png", highLighted,highLightedFlows,"宋体","宋体",null,1.0);        try{
            bufferedImage= ImageIO.read(input);
        }catch (Exception e){
            e.printStackTrace();
        }
        return bufferedImage;
    }


    /**
    * @Date: 16:51 2017/6/2
     * 获取历史活动 每个节点的 表单属性
    */
    @Override
    public List<MyProperty> getHisActiDetail(String processId,String activityInsId) {
        List<MyProperty> resList = new ArrayList<>();
        List<HistoricDetail> historicDetailList = historyService
                .createHistoricDetailQuery().processInstanceId(
                        processId).activityInstanceId(activityInsId).orderByFormPropertyId().asc().list();
        if (historicDetailList != null && historicDetailList.size() > 0) {
            for (HistoricDetail historicDetail:historicDetailList) {
                HistoricVariableUpdate variable = (HistoricVariableUpdate) historicDetail;

                System.out.println(variable.getVariableName() + variable.getValue());
                resList.add(new MyProperty(variable.getVariableName(),variable.getVariableTypeName(),variable.getValue().toString()));
            }
        }
        return resList;
    }

    /**
    * @Date: 16:55 2017/6/2
     * 获取需要高亮的线id
    */
    private List<String> getHighLightedFlows(
            ProcessDefinitionEntity processDefinitionEntity,
            List<HistoricActivityInstance> historicActivityInstances) {
        List<String> highFlows = new ArrayList<String>();// 用以保存高亮的线flowId
        for (int i = 0; i < historicActivityInstances.size(); i++) {// 对历史流程节点进行遍历
            ActivityImpl activityImpl = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i)
                            .getActivityId());// 得到节点定义的详细信息
            List<ActivityImpl> sameStartTimeNodes = new ArrayList<ActivityImpl>();// 用以保存后需开始时间相同的节点
            if ((i + 1) >= historicActivityInstances.size()) {
                break;
            }
            ActivityImpl sameActivityImpl1 = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i + 1)
                            .getActivityId());
            // 将后面第一个节点放在时间相同节点的集合里
            sameStartTimeNodes.add(sameActivityImpl1);
            for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
                HistoricActivityInstance activityImpl1 = historicActivityInstances
                        .get(j);// 后续第一个节点
                HistoricActivityInstance activityImpl2 = historicActivityInstances
                        .get(j + 1);// 后续第二个节点
                if (activityImpl2.getStartTime().getTime()-
                        activityImpl1.getStartTime().getTime()<100) {
                    // 如果第一个节点和第二个节点开始时间相同保存
                    ActivityImpl sameActivityImpl2 = processDefinitionEntity
                            .findActivity(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);

                } else {
                    String type = historyService.createNativeHistoricActivityInstanceQuery().sql("select * from act_hi_actinst where ACT_ID_ ='"+activityImpl2.getActivityId()+"'").list().get(0).getActivityType();
                    if(historicActivityInstances.get(i).getEndTime() != null && type.contains("parallel")){
                        ActivityImpl sameActivityImpl2 = processDefinitionEntity
                                .findActivity(activityImpl2.getActivityId());
                        sameStartTimeNodes.add(sameActivityImpl2);
                    }
                    // 有不相同跳出循环
                    break;
                }
            }
            if(historicActivityInstances.get(i).getEndTime() != null){
                List<PvmTransition> pvmTransitions = activityImpl
                        .getOutgoingTransitions();// 取出节点的所有出去的线
                for (PvmTransition pvmTransition : pvmTransitions) {
                    // 对所有的线进行遍历
                    ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition
                            .getDestination();
                    // 如果取出的线的目标节点存在时间相同的节点里,保存该线的id,进行高亮显示
                    if (sameStartTimeNodes.contains(pvmActivityImpl)) {
                        highFlows.add(pvmTransition.getId());
                    }
                }
            }
        }
        return highFlows;
    }


}

MyTaskService

public interface MyTaskService {
    List<MyTask> getTaskByUsername(String username);
    List<MyProperty> getTaskFormProperty(String taskId);
    String getTaskProcessInstance(String taskId);
}
MyTaskServiceImpl

@Service
public class MyTaskServiceImpl implements MyTaskService {

    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private FormService formService;

    /**
    * @Date: 16:33 2017/6/2
     * 获取正在运行中的任务 对应的流程实例
    */
    @Override
    public String getTaskProcessInstance(String taskId) {
       return runtimeService.createNativeProcessInstanceQuery().sql("select * from act_ru_task where ID_ = '"+taskId+"'").singleResult().getProcessInstanceId();
    }

    /**
    * @Date: 16:36 2017/6/2
     * 获取任务表单属性
    */
    @Override
    public List<MyProperty> getTaskFormProperty(String taskId) {
        List<MyProperty> resList = new ArrayList<>();
        TaskFormData taskFormData = formService.getTaskFormData(taskId);
        List<FormProperty> list = taskFormData.getFormProperties();
        for(FormProperty f : list){
            System.out.println(f.getName() + " " + f.getType().getName());
            resList.add(new MyProperty(f));
        }
        return resList;
    }

    /**
    * @Date: 16:37 2017/6/2
     * 获取某个用户所有的待办事务
    */
    @Override
    public List<MyTask> getTaskByUsername(String username) {
        List<MyTask> resList = new ArrayList<>();
        List<Task> list = taskService.createTaskQuery()
                            .taskCandidateOrAssigned(username).list();
        for(Task task : list){
                MyTask myTask = new MyTask(task);
                String processInstanceId = task.getProcessInstanceId();
                String startMan = historyService.createHistoricProcessInstanceQuery()
                        .processInstanceId(processInstanceId)
                        .singleResult().getStartUserId();
                myTask.setStartMan(startMan);
                resList.add(myTask);
        }
        return resList;
    }
}

3.添加流程管理相关的html页面以及静态资源

4.添加ProcessController处理流程管理中的路由和TaskController中处理任务的路由

ProcessController

@Controller
@RequestMapping("/process")
public class ProcessController {

    @Autowired
    private ProcessService processService;
    @Autowired
    private FormService formService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private MyTaskService myTaskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RepositoryService repositoryService;

    /**
    * @Date: 14:18 2017/6/16
     * 获取所有流程定义
    */
    @RequestMapping(value = "/getAllProcess",method = RequestMethod.GET)
    @ResponseBody
    public JSONArray getAllProcess(){

        return JSONArray.fromObject(processService.getAllProcess());
    }

    /**
    * @Date: 14:23 2017/6/16
     * 获取指定流程定义XML
     * @param request 前端传回请求
    */
    @RequestMapping(value = "/getProcessXML",method = RequestMethod.GET)
    @ResponseBody
    public String getProcessXML(HttpServletRequest request) throws Exception{
        //在String中添加<xmp>,在html中显示xml标签
        String resXML = "<xmp>";
        String processId = request.getParameter("processId");
        //对流程id进行转码
        processId = new String(processId.getBytes("ISO-8859-1"),"UTF-8");
        resXML = resXML + processService.getProcessXML(processId) + "</xmp>";
        return resXML;
    }

    /**
    * @Date: 14:24 2017/6/16
     * 获取指定流程定义Img
     * @param request 前端传回请求
    */
    @RequestMapping(value = "/getProcessImg",method = RequestMethod.GET)
    @ResponseBody
    public String getProcessImg(HttpSession session,HttpServletRequest request/*, HttpServletResponse response*/) throws UnsupportedEncodingException{
        //获取request中的processId,进行转码为UTF-8
        String processId = request.getParameter("processId");
        processId = new String(processId.getBytes("ISO-8859-1"),"UTF-8");
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processId).singleResult();
        String processName =processDefinition.getName();
        String processDeploy = processDefinition.getDeploymentId();
        try {
            //设置response编码和内容类型
            //response.setCharacterEncoding("UTF-8");
            //response.setContentType("image/png");
            //获取流通图片bufferImage
            String fileName = "";
            String fileName_url = "";
            User tmpUser = SpringSessionUtil.getSession(session);
            if(tmpUser!=null) {
                //fileName = "D://tempory-def//" +tmpUser.getUsername()+"-"+ processDeploy + ".png";
                String rootContext = System.getProperty("web.root");
                fileName = rootContext + "//static//process_images//" + tmpUser.getUsername()+"-"+ processDeploy + ".png";
                System.out.println(fileName);
                File file = new File(fileName);
                BufferedImage bufferedImage = processService.getProcessImg(processId);
                //写入response中
                ImageIO.write(bufferedImage, "PNG", file);
                //fileName_url = "http://localhost:8080/activiti3.0/static/process_images/" + tmpUser.getUsername()+"-"+ processDeploy + ".png";
                fileName_url = request.getContextPath() + "/static/process_images/" + tmpUser.getUsername()+"-"+ processDeploy + ".png";
            }
            return fileName_url;
        }catch (Exception e){
            e.printStackTrace();
            return "wrong";
        }
    }

    /**
    * @Date: 14:31 2017/6/16
     * 删除流程定义
     * @param deployId 流程部署Id
    */
    @RequestMapping(value = "/deleteProcess",method = RequestMethod.GET)
    @ResponseBody
    public String deleteProcess(@RequestParam("deployId")String deployId) throws Exception{
        deployId = new String(deployId.getBytes("ISO-8859-1"),"UTF-8");
        return processService.deleteProcess(deployId)?"right":"wrong";
    }

    /**
    * @Date: 14:41 2017/6/16
     * 更改流程状态
     * 1:激活 2:挂起
    */
    @RequestMapping(value = "/changeStatus",method = RequestMethod.GET)
    @ResponseBody
    public String changeProcessStatus(@RequestParam("processId")String processId) throws Exception{
        processId = new String(processId.getBytes("ISO-8859-1"),"UTF-8");
        return processService.changeProcessStatus(processId);
    }

    /**
    * @Date: 14:42 2017/6/16
     * 将流程转换为模型
    */
    @RequestMapping(value = "/convertToModel",method = RequestMethod.GET)
    @ResponseBody
    public String convertToModel(@RequestParam("processId")String processId)
    throws UnsupportedEncodingException,XMLStreamException{
        try {
            processId = new String(processId.getBytes("ISO-8859-1"), "UTF-8");
            processService.convertToModel(processId);
            return "right";
        }catch (Exception e){
            e.printStackTrace();
            return "wrong";
        }
    }

    /**
    * @Date: 14:43 2017/6/16
     * 获取流程属性
    */
    //未使用
    @RequestMapping(value = "/getProperty",method = RequestMethod.GET)
    @ResponseBody
    public JSONArray getProperty(@RequestParam("processId")String processId) throws UnsupportedEncodingException
    {

        processId = new String(processId.getBytes("ISO-8859-1"),"UTF-8");
        List<MyProperty> resList = new ArrayList<>();
        //获取流程开始节点的属性
        StartFormData startFormData = formService.getStartFormData(processId);
        List<FormProperty> list = startFormData.getFormProperties();
        for(FormProperty f : list){
            System.out.println(f.getName() + " " + f.getType().getName());
            resList.add(new MyProperty(f.getName(),f.getType().getName()));
        }
        return JSONArray.fromObject(resList);

    }

    /**
    * @Date: 14:45 2017/6/16
     * 获取所有激活流程
    */
    @RequestMapping(value = "/getUnsuspendProcess",method = RequestMethod.GET)
    @ResponseBody
    public JSONArray getUnsusProcess(){
        return JSONArray.fromObject(processService.getAllUnsuspendProcess());
    }

    /**
    * @Date: 14:46 2017/6/16
     * 获取指定任务 所属流程实例 中的各个活动任务节点具体信息(不包括表单属性)
    */
    @RequestMapping(value = "/getDetail",method = RequestMethod.GET)
    @ResponseBody
    public JSONArray getDetail(HttpServletRequest request) throws UnsupportedEncodingException{
        String taskId = request.getParameter("taskId");
        taskId = new String(taskId.getBytes("ISO-8859-1"),"UTF-8");
        String processId = myTaskService.getTaskProcessInstance(taskId);
        return JSONArray.fromObject(processService.getAllHistoricActiIns(processId));
    }

    /**
    * @Date: 14:53 2017/6/16
     *  获取某一历史活动节点表单属性
    */
    @RequestMapping(value = "/getHisDetail",method = RequestMethod.GET)
    @ResponseBody
    public JSONArray getHisDetail(HttpServletRequest request) throws UnsupportedEncodingException{
        //获取任务节点id
        String taskId = request.getParameter("taskId");
        //获取活动节点id
        String activityInsId = request.getParameter("activityInsId");
        taskId = new String(taskId.getBytes("ISO-8859-1"),"UTF-8");
        activityInsId = new String(activityInsId.getBytes("ISO-8859-1"),"UTF-8");
        //获取流程实例节点id
        String processId = myTaskService.getTaskProcessInstance(taskId);
        return JSONArray.fromObject(processService.getHisActiDetail(processId,activityInsId));
    }

    /**
    * @Date: 15:35 2017/6/16
     * 获取获取某用户所有历史流程实例集合,包括已完结和正在处理的
     * @param username 用户名
    */
    @RequestMapping(value = "/getHisProc",method = RequestMethod.GET)
    @ResponseBody
    public JSONArray getHisProc(@RequestParam("username")String username) throws UnsupportedEncodingException{
        username = new String(username.getBytes("ISO-8859-1"),"UTF-8");
        //获取某用户所有历史流程实例集合
        List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().startedBy(username).list();
        List<MyHistoricProc> resList = new ArrayList<>();
        for (HistoricProcessInstance hpi : list) {
            resList.add(new MyHistoricProc(hpi));
        }
        return JSONArray.fromObject(resList);
    }

    /**
    * @Date: 15:36 2017/6/16
     * 发起一个流程实例
    */
    @RequestMapping(value = "/startProcess",method = RequestMethod.GET)
    @ResponseBody
    public String startProcess(HttpServletRequest request) throws UnsupportedEncodingException{
        try {
            //获取流程发起人
            String startMan = request.getParameter("startMan");
            //获取流程Id
            String processId = request.getParameter("processId");
            startMan = new String(startMan.getBytes("ISO-8859-1"),"UTF-8");
            processId = new String(processId.getBytes("ISO-8859-1"),"UTF-8");
            //设置流程定义中的applyUserId的值
            identityService.setAuthenticatedUserId(startMan);
            //发起流程实例
            runtimeService.startProcessInstanceById(processId);
            return "right";
        }catch (Exception e){
            return "wrong";
        }
    }

    /**
    * @Date: 15:37 2017/6/16
     * 根据任务节点Id获取流程进度追踪图
    */
    @RequestMapping(value = "/getProgressImg",method = RequestMethod.GET)
    @ResponseBody
    public String getProgress(HttpSession session,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{

        String taskId = request.getParameter("taskId");
        taskId = new String(taskId.getBytes("ISO-8859-1"),"UTF-8");
        String processInstanceId = myTaskService.getTaskProcessInstance(taskId);
        BufferedImage bufferedImage = processService.getProgressImg(processInstanceId);
        try {
            //设置response编码和内容类型
            //response.setCharacterEncoding("UTF-8");
            //response.setContentType("image/png");
            String fileName = "";
            String fileName_url = "";
            User tmpUser = SpringSessionUtil.getSession(session);
            if(tmpUser!=null) {
                //fileName = "D://tempory-prg//" +tmpUser.getUsername()+"-"+ processInstanceId + "-" + taskId + ".png";
                //fileName = "E://activiti30//src//main//webapp//static//process_images//" +tmpUser.getUsername()+"-"+ processInstanceId + "-" + taskId + ".png";
                String rootContext = System.getProperty("web.root");
                fileName = rootContext + "//static//process_images//"+tmpUser.getUsername()+"-"+ processInstanceId + "-" + taskId + ".png";
                System.out.println(fileName);
                File file = new File(fileName);
                ImageIO.write(bufferedImage, "PNG", file);
                fileName_url = request.getContextPath() + "/static/process_images/" + tmpUser.getUsername()+"-"+ processInstanceId + "-" + taskId + ".png";

            }
            return fileName_url;
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
    }

    /**
    * @Date: 15:39 2017/6/16
     * 根据历史流程实例Id获取进度追踪图
     *
    */
    @RequestMapping(value = "/getHisProgressImg",method = RequestMethod.GET)
    @ResponseBody
    public String getHisProgress(HttpSession session,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{

        String processInstanceId = request.getParameter("processId");
        processInstanceId = new String(processInstanceId.getBytes("ISO-8859-1"),"UTF-8");
        BufferedImage bufferedImage = processService.getProgressImg(processInstanceId);
        try {
            //response.setCharacterEncoding("UTF-8");
            //response.setContentType("image/png");
            String fileName = "";
            String fileName_url = "";
            User tmpUser = SpringSessionUtil.getSession(session);
            if(tmpUser!=null) {
                //fileName = "D://tempory-his//"+tmpUser.getUsername()+ "-" + "his-" + processInstanceId + ".png";
                //fileName = "E://activiti30//src//main//webapp//static//process_images//"+tmpUser.getUsername()+ "-" + "his-" + processInstanceId + ".png";
                String rootContext = System.getProperty("web.root");
                fileName = rootContext+ "//static//process_images//"+tmpUser.getUsername()+ "-" + "his-" + processInstanceId + ".png";
                System.out.println(fileName);
                File file = new File(fileName);
                ImageIO.write(bufferedImage, "PNG", file);
                fileName_url = request.getContextPath() + "/static/process_images/" + tmpUser.getUsername()+ "-" + "his-" + processInstanceId + ".png";
            }

            return fileName_url;
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
    }




}
TaskController

@Controller
@RequestMapping("/task")
public class TaskController {

    @Autowired
    private MyTaskService myTaskService;
    @Autowired
    private FormService formService;
    @Autowired
    private TaskService taskService;

    /**
    * @Date: 15:42 2017/6/18
     * 根据用户名获取任务(出现在我的待办中)
    */
    @RequestMapping(value = "/getTaskByUsername",method = RequestMethod.GET)
    @ResponseBody
    public JSONArray getTaskByUsername(@RequestParam("username")String username) throws Exception{
        username = new String(username.getBytes("ISO-8859-1"),"UTF-8");
        return JSONArray.fromObject(myTaskService.getTaskByUsername(username));
    }

    /**
    * @Date: 15:44 2017/6/16
     * 根据任务id获取任务表单的属性
    */
    @RequestMapping(value = "getCmnt",method = RequestMethod.GET)
    @ResponseBody
    public JSONArray getTaskFormProperty(@RequestParam("taskId") String taskId) throws UnsupportedEncodingException{
        taskId = new String(taskId.getBytes("ISO-8859-1"),"UTF-8");
        return JSONArray.fromObject(myTaskService.getTaskFormProperty(taskId));
    }

    /**
    * @Date: 15:53 2017/6/16
     * 根据任务id 完成某个任务
     *
    */
    @RequestMapping(value = "completeTask",method = RequestMethod.GET)
    @ResponseBody
    public String completeTask(HttpServletRequest request) throws UnsupportedEncodingException{
       try {
            //获取任务id
            String taskId = request.getParameter("taskId");
            //查询该任务的表单属性
            FormData formData = formService.getTaskFormData(taskId);
            Map<String, Object> variables = new HashMap<>();
            //获取表单数据的属性集合
            List<FormProperty> cmnt = formData.getFormProperties();
            for (FormProperty property : cmnt) { //遍历属性集合所有属性

                String pName = property.getName();
                pName = new String(pName.getBytes("UTF-8"),"ISO-8859-1");
                String pVar = request.getParameter(pName); //在request获取属性值
                if(pVar == null){ //如果request中没有该值
                    return "wrong"; // 返回错误状态
                }else {
                    pName = new String(pName.getBytes("ISO-8859-1"), "UTF-8");
                    pVar = new String(pVar.getBytes("ISO-8859-1"), "UTF-8");
                    variables.put(pName, pVar);
                }
           }
           taskService.complete(taskId, variables); // 完成任务
            return "right";
       }catch (Exception e){
           e.printStackTrace();
           return "wrong";
       }
    }
}

注:这部分代码都比较的简单,都是很简单的业务逻辑。比较难得是流程追踪部分的代码,我也已经放了注释。
本来想这个系列一点一点的分析给读者看,但是有很多东西,不知道从何讲起,并且我觉得activiti上手也不难。在做的过程中,Activiti modeler 汉化以及如何处理中文编码问题花了很多的时间。

如果你在模型管理的过程中,创建中文名称的模型,在modeler 中显示乱码,可以尝试更改一下org.activiti.rest.editor中的StencilsetRestResource,将反悔的字符串更改为:

return new String(IOUtils.toString(stencilsetStream).getBytes("unicode"),"ISO-8859-1");

同理,其他地方的也可以这么更改。


P.S.文章不妥之处还望指正


本文Github源码下载

Activiti文档下载地址


      

展开阅读全文

没有更多推荐了,返回首页