(三)工作流实现多API编排(工作流部分)

首先引入ACTIVITI工作流引擎,相关教程很多,这里便不再赘述。配置完成后,打开localhost:8002,默认进入首页,点击流程创建便可以在Web端进行流程绘制。
(三)工作流实现多API编排(工作流部分)_第1张图片
流程创建代码

 @GetMapping("/create")
    public void create(HttpServletResponse response, String name, String key) throws IOException {
        logger.info("创建模型入参name:{},key:{}", name, key);
        Model model = repositoryService.newModel();
        ObjectNode modelNode = objectMapper.createObjectNode();
        modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
        modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, "");
        modelNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
        model.setName(name);
        model.setKey(key);
        model.setMetaInfo(modelNode.toString());
        repositoryService.saveModel(model);
        createObjectNode(model.getId());
        response.sendRedirect("/editor?modelId=" + model.getId());

        logger.info("创建模型结束,返回模型ID:{}", model.getId());
    }

    /**
     * 创建模型时完善ModelEditorSource
     *
     * @param modelId
     */
    @SuppressWarnings("deprecation")
    private void createObjectNode(String modelId) {
        logger.info("创建模型完善ModelEditorSource入参模型ID:{}", modelId);
        ObjectNode editorNode = objectMapper.createObjectNode();
        editorNode.put("id", "canvas");
        editorNode.put("resourceId", "canvas");
        ObjectNode stencilSetNode = objectMapper.createObjectNode();
        stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
        editorNode.put("stencilset", stencilSetNode);
        try {
            repositoryService.addModelEditorSource(modelId, editorNode.toString().getBytes("utf-8"));
        } catch (Exception e) {
            logger.info("创建模型时完善ModelEditorSource服务异常:{}", e);
        }
        logger.info("创建模型完善ModelEditorSource结束");
    }

创建后需要发布将流程压入数据库才能启动和运行,运行时首先遍历流程节点,然后通过feign的方式调用API相关函数,通过路径查询到完整的API信息,然后调用API运行函数运行该API。

	 @ResponseBody
    @GetMapping("/publish")
    public Object publish(String modelId, HttpServletResponse response) {
        logger.info("流程部署入参modelId:{}", modelId);
        Map<String, String> map = new HashMap<String, String>();
        try {
            Model modelData = repositoryService.getModel(modelId);
            byte[] bytes = repositoryService.getModelEditorSource(modelData.getId());
            if (bytes == null) {
                logger.info("部署ID:{}的模型数据为空,请先设计流程并成功保存,再进行发布", modelId);
                map.put("code", "FAILURE");
                return map;
            }
            JsonNode modelNode = new ObjectMapper().readTree(bytes);
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            Deployment deployment = repositoryService.createDeployment()
                    .name(modelData.getName())
                    .addBpmnModel(modelData.getKey() + ".bpmn20.xml", model)
                    .deploy();
            modelData.setDeploymentId(deployment.getId());
            repositoryService.saveModel(modelData);
            map.put("code", "SUCCESS");
            response.sendRedirect("/index");
        } catch (Exception e) {
            logger.info("部署modelId:{}模型服务异常:{}", modelId, e);
            map.put("code", "FAILURE");
        }
        logger.info("流程部署出参map:{}", map);
        return map;
    }
   
   
    @ResponseBody
    @GetMapping("/run")
    public void runProcessInstance(String modelName, HttpServletResponse response) throws IOException {

        if (modelName != null) {
            System.out.println("流程名字:" + modelName);
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(modelName);
            System.out.println("流程id:" + processInstance.getProcessDefinitionId());
//			System.out.println("当前活动id:"+processInstance.getActivityId());
//			System.out.println("流程实例id:"+processInstance.getDeploymentId());
            System.out.println("流程key:" + processInstance.getProcessDefinitionKey());
            System.out.println("启动成功");

        } else {
            System.out.println("启动失败");
        }
        response.sendRedirect("/index");
    }


    @ResponseBody
    @GetMapping("/complete/{modelName}")
    public CommonResult completeTaskAPI(@PathVariable String  modelName) {

        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey(modelName) //流程Key
                .list();
        Result r = new Result();
        r.setNum(1);
  
        if (taskList.size() != 0) {
            for (Task task : taskList) {
                System.out.println(task.getId()+"id is");
                TaskFormData userTaskFormData = formService.getTaskFormData(task.getId());
                List<FormProperty> formProperties = userTaskFormData.getFormProperties();

                int formSize = formProperties.size();
                if (formSize == 0) {//说明没有参数
                    commonResult =   CompeleteApiAPI(task.getName(), "");
                    stack.push(commonResult);
                    taskService.complete(task.getId(),var);
                    System.out.println("完成的任务id:" + task.getId()+"任务名字是"+task.getName());
                } else {
                    for (FormProperty formProperty : formProperties) {
                        if (formProperty.getId() != null) {
                            commonResult = CompeleteApiAPI(task.getName(), formProperty.getId());
                            stack.push(commonResult);
                            taskService.complete(task.getId());
                            System.out.println("完成的任务id:" + task.getId()+"任务名字是"+task.getName());
                        } else {
                            System.out.println("参数:" + formProperty.getId());
                            commonResult = CompeleteApiAPI(task.getName(), "");
                            stack.push(commonResult);
                            taskService.complete(task.getId());
                        }
                    }
                }
            }
            if (flag == true)
            {
                completeTaskAPI(modelName);

                return commonResult1;
            } else
            {
                System.out.println("出现异常!停止运行!");

                return  new CommonResult(404,"error","");
            }
        }
        else
        {
            System.out.println("任务结束!");
            System.out.println("任务:"+commonResult);
            return commonResult;
        }

 //API运行函数,远程调用API管理模块的相关函数
    public boolean CompeleteApi(String apiName, String data) {
        CommonResult apiData = restTemplate.getForObject(ApiManagerUrl + "/findApiByName/" + apiName, CommonResult.class);
        System.out.println(apiData);
        if (apiData.getCode() == 200) {
            JSONObject jsonObject = new JSONObject(apiData.getData());

            String servers = (String) jsonObject.get("servers");
            String paths = (String) jsonObject.get("paths");
            String url = "http://" + servers + paths;
            String method = (String) jsonObject.get("methods");

            if (!data.equals("")) {
                // data != null
                if (method.equals("POST")) {
                    result = ApiPost.interfaceUtil(url, data);
                } else {

                    System.out.println("参数是:" + data);
                    int url_flag = url.indexOf("{");
                    System.out.println(url.substring(0, url_flag));
                    result = ApiComplete.interfaceUtil(url.substring(0, url_flag) + data, "");
                }
            } else {
                result = ApiComplete.interfaceUtil(url, "");
            }
            modelAndView.addObject("resultSet",result);
            return true;
        } else {
            System.out.println("没有该api");
            return false;
        }
    }
    @ResponseBody
    @GetMapping("/delete")
    public void deleteProcessInstance(String modelId) {
        System.out.println(modelId);

        if (modelId != null) {
            System.out.println("删除的id为" + modelId);
            repositoryService.deleteModel(modelId);
        } else {
            System.out.println("id为空,无法删除");
        }

    }

你可能感兴趣的:(ACTIVITI工作流,java)