boot-admin整合flowable官方editor-app原始碼進行BPMN2-0建模(續)

2023-04-22 06:00:54

boot-admin整合flowable官方editor-app原始碼進行BPMN2-0建模(續)
書接上回

專案原始碼倉庫github
專案原始碼倉庫gitee

boot-admin 是一款採用前後端分離模式、基於SpringCloud微服務架構的SaaS後臺管理框架。系統內建基礎管理、許可權管理、執行管理、定義管理、程式碼生成器和辦公管理6個功能模組,整合分散式事務Seata、工作流引擎Flowable、業務規則引擎Drools、後臺作業排程框架Quartz等,技術棧包括Mybatis-plus、Redis、Nacos、Seata、Flowable、Drools、Quartz、SpringCloud、Springboot Admin Gateway、Liquibase、jwt、Openfeign、I18n等。

在上一篇博文中,已經介紹了 boot-admin 對 editor-app 前端程式碼的整合改造,接下來我們看看後端程式碼。

提供漢化資源json資料

   /**
     * 獲取漢化資源
     * @return
     */
    @RequestMapping(value = "/editor/stencilset", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public String getStencilset() {
        InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json");
        try {
            return IOUtils.toString(stencilsetStream, "utf-8");
        } catch (Exception e) {
            throw new FlowableException("Error while loading stencil set", e);
        }
    }

資源包stencilset.json需放在resources文夾下,這裡提供下載:點選下載漢化包

分頁獲取模型列表

controller:

@RequestMapping("/api/workflow/auth/activiti")
@RestController
@Slf4j
public class ModelController extends BaseController {
    @Resource
    private FormValidator formValidator;
    @Autowired
    private MyModelService modelService;

    @PostMapping("/model/page")
    @ApiOperation("分頁獲取專案資料表列表")
    public ResultDTO getTablePage(@Valid @RequestBody ModelQueryVO queryVO, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            return formValidator.generateMessage(bindingResult);
        }
        return modelService.getPage(queryVO);
    }
}    

service:

    @Override
    public ResultDTO getPage(ModelQueryVO queryVO) throws Exception {
        int offset = (queryVO.getCurrentPage() - 1) * queryVO.getPageSize() + 0;
        List<Model> list = repositoryService.createModelQuery().listPage(offset
                , queryVO.getPageSize());
        int total = (int) repositoryService.createModelQuery().count();
        Page<Model> page = new Page<>();
        page.setRecords(list);
        page.setTotal(total);
        return ResultDTO.success(page);
    }

讀取模型資料

controller:

@RequestMapping("/api/workflow/auth/activiti")
@RestController
@Slf4j
public class ModelController extends BaseController {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 獲取用於編輯的模型JSON資料
     * @param modelId 模型ID
     * @return
     */
    @GetMapping(value = "/model/json")
    public ObjectNode getEditorJson(@RequestParam("modelId") String modelId) {
        ObjectNode modelNode = null;
        Model model = repositoryService.getModel(modelId);
        if (model != null) {
            try {
                if (StringUtils.isNotEmpty(model.getMetaInfo())) {
                    modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
                } else {
                    modelNode = objectMapper.createObjectNode();
                    modelNode.put(MODEL_NAME, model.getName());
                }
                modelNode.put(MODEL_ID, model.getId());
                ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(
                        new String(repositoryService.getModelEditorSource(model.getId()), "utf-8"));
                modelNode.put("model", editorJsonNode);

            } catch (Exception e) {
                log.error("Error creating model JSON", e);
                throw new FlowableException("Error creating model JSON", e);
            }
        }
        return modelNode;
    }
}    

增加新模型

controller:

@RequestMapping("/api/workflow/auth/activiti")
@RestController
@Slf4j
public class ModelController extends BaseController {
    @Resource
    private FormValidator formValidator;
    @Autowired
    private MyModelService modelService;
    
    @PostMapping("/model/add")
    @ApiOperation("儲存資料")
    public ResultDTO save(@Valid @RequestBody ModelDataVO dataVO, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            return formValidator.generateMessage(bindingResult);
        }
        BaseUser baseUser = UserTool.getBaseUser();
        return modelService.addNewModel(dataVO, baseUser);
    }
} 

service:

    @Override
    public ResultDTO addNewModel(ModelDataVO dataVO, BaseUser baseUser) throws Exception {
        //初始化一個空模型
        Model model = repositoryService.newModel();
        //設定一些預設資訊
        String name = dataVO.getName();
        String description = dataVO.getDescription();
        int revision = 1;
        String key = dataVO.getKey();

        ObjectNode modelNode = objectMapper.createObjectNode();
        modelNode.put(MODEL_NAME, name);
        modelNode.put(MODEL_DESCRIPTION, description);
        modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);

        model.setName(name);
        model.setKey(key);
        model.setMetaInfo(modelNode.toString());

        repositoryService.saveModel(model);
        String id = model.getId();

        //完善ModelEditorSource
        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);
        repositoryService.addModelEditorSource(id, editorNode.toString().getBytes("utf-8"));
        return ResultDTO.success(id);
    }

儲存模型資料

    /**
     * 儲存模型資料
     * @param modelId
     * @param name
     * @param description
     * @param json_xml
     * @param svg_xml
     */
    @RequestMapping(value = "/model/save", method = RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.OK)
    public void saveModel(@RequestParam("modelId") String modelId
            , String name, String description
            , String json_xml, String svg_xml) {
        try {
            Model model = repositoryService.getModel(modelId);
            ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            modelJson.put(MODEL_NAME, name);
            modelJson.put(MODEL_DESCRIPTION, description);
            model.setMetaInfo(modelJson.toString());
            model.setName(name);
            repositoryService.saveModel(model);
            repositoryService.addModelEditorSource(model.getId(), json_xml.getBytes("utf-8"));
            InputStream svgStream = new ByteArrayInputStream(svg_xml.getBytes("utf-8"));
            TranscoderInput input = new TranscoderInput(svgStream);
            PNGTranscoder transcoder = new PNGTranscoder();
            // Setup output
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            TranscoderOutput output = new TranscoderOutput(outStream);
            // Do the transformation
            transcoder.transcode(input, output);
            final byte[] result = outStream.toByteArray();
            repositoryService.addModelEditorSourceExtra(model.getId(), result);
            outStream.close();
        } catch (Exception e) {
            log.error("Error saving model", e);
            throw new FlowableException("Error saving model", e);
        }
    }

刪除模型

controller:

@RequestMapping("/api/workflow/auth/activiti")
@RestController
@Slf4j
public class ModelController extends BaseController {
    @Resource
    private FormValidator formValidator;
    @Autowired
    private MyModelService modelService;
    
    @PostMapping("/model/del")
    @ApiOperation("刪除資料")
    public ResultDTO del(@Valid @RequestBody GuidContainerVO guidContainerVO, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            return formValidator.generateMessage(bindingResult);
        }
        return modelService.delete(guidContainerVO.getGuid());
    }    
} 

service:

    @Override
    public ResultDTO delete(String guid) throws Exception {
        repositoryService.deleteModel(guid);
        return ResultDTO.success();
    }

釋出(部署)模型

@RequestMapping("/api/workflow/auth/activiti")
@RestController
@Slf4j
public class ModelController extends BaseController {
    @Resource
    private FormValidator formValidator;
    @Autowired
    private MyModelService modelService;
   
    @PostMapping("/model/deploy")
    public ResultDTO deploy(@Valid @RequestBody GuidContainerVO guidContainerVO, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            return formValidator.generateMessage(bindingResult);
        }
        return modelService.deploy(guidContainerVO.getGuid());
    }
}    

service:

    @Override
    public ResultDTO deploy(String guid) throws Exception {
        /**獲取模型 **/
        Model modelData = repositoryService.getModel(guid);
        byte[] bytes = repositoryService.getModelEditorSource(modelData.getId());
        if (bytes == null) {
            return ResultDTO.failureCustom("模型資料為空,請先設計流程併成功儲存,再進行釋出。");
        }
        JsonNode modelNode = new ObjectMapper().readTree(bytes);
        BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
        if (model.getProcesses().size() == 0) {
            return ResultDTO.failureCustom("資料模型不符要求,請至少設計一條主線流程。");
        }
        /** 設定名稱 **/
        if(StringUtils.isNotBlank(modelData.getCategory())) {
            model.setTargetNamespace(modelData.getCategory());
        }
        byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);

        /** 釋出流程 .bpmn20.xml必需加 **/
        String processName = modelData.getName() + ".bpmn20.xml";
        Deployment deployment = repositoryService.createDeployment()
                .name(modelData.getName())
                .category(modelData.getCategory())
                .key(modelData.getKey())
                .addString(processName, new String(bpmnBytes, "UTF-8"))
                .deploy();
        modelData.setDeploymentId(deployment.getId());
        repositoryService.saveModel(modelData);
        return ResultDTO.success();
    }

總結:經過整合改造,boot-admin與flowable editor-app模型設計器實現緊密整合,不但實現了BPMN流程編輯、修改、釋出等功能,還實現前端 攜帶jwt按許可權存取後端資源。
boot-admin 整合 flowable editor-app 執行效果如下圖所示:

專案原始碼倉庫github
專案原始碼倉庫gitee