Procházet zdrojové kódy

流程编排生成java逻辑

zhenglingfeng před 8 roky
rodič
revize
7d6be57acc

+ 1 - 0
hos-broker/src/main/java/com/yihu/hos/broker/controllers/ESBCamelController.java

@ -22,6 +22,7 @@ public class ESBCamelController {
    @RequestMapping(value = "/heartbeat", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation(value = "测试服务器可以正常连接", produces = "application/json", notes = "测试服务器可以正常连接")
    public void heartbeat() {
        System.out.println("test");
    }
    @RequestMapping(value = "/serviceFlow", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)

+ 0 - 3
hos-camel/src/main/java/collect/route/CollectQuartzRoute.java

@ -4,9 +4,6 @@ import collect.processor.CollectProcessor0;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
/**
 * @author HZY * @vsrsion 1.0 * Created at 2016/11/17.
 */
public class CollectQuartzRoute extends RouteBuilder {
    public void configure() throws Exception {
        from("quartz://myGroup/myTimerName?cron=0/3 * * * * ?").routeId("routeId").process(new CollectProcessor0())

+ 52 - 0
hos-camel/src/main/java/com/yihu/hos/camel/RouteJavaBuilder.java

@ -0,0 +1,52 @@
package com.yihu.hos.camel;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.util.List;
/**
 * Created by lingfeng on 2016/8/29.
 */
public class RouteJavaBuilder {
    private String packageTemplate = "package com.yihu.hos.%s;%n";
    private String importTemplate = "import org.apache.camel.builder.RouteBuilder;%n" +
            "import org.apache.camel.model.dataformat.XmlJsonDataFormat;%n";
    private String javaDefineTemplate = "public class %s extends RouteBuilder {%n";
    private String packagePathTemplate = System.getProperty("user.dir")//获取到项目的根路径
            + "/src/main/java/com/yihu/hos/%s";
    private String classPathTemplate = System.getProperty("user.dir")//获取到项目的根路径
            + "/src/main/java/com/yihu/hos/%s/%s.java";
    private String javaUrlTemplate = "com.yihu.hos.%s;";
    private String configureTemplate = "    @Override%n" +
            "    public void configure() throws Exception {%n" +
            "%s%n"+
            "    }%n" +
            "}%n";
    private String javaName;
    private String packageName;
    private String configureXml;
    public void generator (String configureInfo) throws Exception {
        String source = String.format(packageTemplate, packageName) +
                String.format(importTemplate) +
                String.format(javaDefineTemplate, javaName) +
                String.format(configureTemplate, configureInfo.substring(0, configureInfo.length() - 1) + ";");
        File packagePath = new File(String.format(packagePathTemplate, packageName));
        if (!packagePath.exists()) {
            packagePath.mkdir();
        }
        File f = new File(String.format(classPathTemplate, packageName, javaName));
        FileWriter fw = new FileWriter(f);
        fw.write(source);
        fw.flush();
        fw.close();//这里只是产生一个JAVA文件,简单的IO操作
    }
}

+ 2 - 2
hos-rest/src/main/resources/config/dbhelper.properties

@ -1,7 +1,7 @@
defaultName = hos-mysql
defaultUri = jdbc:mysql://172.19.103.71:3306/esb?useUnicode=true&characterEncoding=UTF-8
defaultUri = jdbc:mysql://172.19.103.57:3306/esb?useUnicode=true&characterEncoding=UTF-8
defaultUser = hos
defaultPassword = hos
mongodbUri=mongodb://esb:esb@172.19.103.86:27017/?authSource=admin
mongodbUri=mongodb://esb:esb@172.19.103.57:27017/?authSource=admin
mongodbName=hos

+ 1 - 1
hos-rest/src/main/resources/config/http.properties

@ -1,5 +1,5 @@
httpUrl = https://172.19.103.73:443/api/v1.0
httpUrl = https://192.168.131.120:443/api/v1.0
#  http://172.19.103.73:1443/api/v1.0
#\uFFFD\uFFFDhttps://192.168.131.15:4432/api/v1.0
  #https://172.19.103.73:443/api/v1.0

+ 47 - 1
src/main/java/com/yihu/hos/system/controller/ProcessController.java

@ -1,9 +1,14 @@
package com.yihu.hos.system.controller;
import com.yihu.hos.system.service.ProcessManager;
import com.yihu.hos.system.service.intf.ISystemParamManager;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 *  流程管理
@ -15,6 +20,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ProcessController  extends BaseController {
    @Autowired
    private ProcessManager processManager;
    /**
     *  流程管理界面
     *
@ -22,8 +29,47 @@ public class ProcessController  extends BaseController {
     * @return
     */
    @RequestMapping("/initial")
    public String roleInitial(Model model) {
    public String processInitial(Model model) {
        model.addAttribute("contentPage", "system/process/process");
        return "partView";
    }
    @RequestMapping(value = "/getAllApp", method = RequestMethod.GET)
    public Result getAllApp() {
        try {
            return processManager.getAllApp();
        } catch (Exception e) {
            return Result.error("查找所有应用失败");
        }
    }
    @RequestMapping(value = "/getAllAppService", method = RequestMethod.GET)
    public Result getAllAppService() {
        try {
            return processManager.getAllAppService();
        } catch (Exception e) {
            return Result.error("查找所有服务失败");
        }
    }
    @RequestMapping(value = "/getAppService", method = RequestMethod.GET)
    public Result getAppService(String appId) {
        try {
            return processManager.getAppServiceByAppId(appId);
        } catch (Exception e) {
            return Result.error("查找服务失败");
        }
    }
    @RequestMapping(value = "/json", method = RequestMethod.POST)
    public Result formatJson(String code, String name, String positionJson, String flowJson) {
        try {
            String fileName = processManager.formatJson(flowJson);
            processManager.saveProcess(code, name, fileName, positionJson);
            return Result.error("生成模板成功");
        } catch (Exception e) {
            return Result.error("生成模板失败");
        }
    }
}

+ 26 - 0
src/main/java/com/yihu/hos/system/dao/FlowProcessDao.java

@ -0,0 +1,26 @@
package com.yihu.hos.system.dao;
import com.yihu.hos.core.datatype.CollectionUtil;
import com.yihu.hos.system.model.SystemServiceFlow;
import com.yihu.hos.system.model.SystemServiceFlowProcess;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("flowProcessDao")
public class FlowProcessDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "flowProcessDao";
    public List<SystemServiceFlowProcess> getFlowProcessList(String type) throws Exception {
        List<SystemServiceFlowProcess> list = (List<SystemServiceFlowProcess>) super.hibernateTemplate.find("from SystemServiceFlowProcess");
        return list;
    }
    public SystemServiceFlowProcess getFlowProcessByCode(String code) throws Exception {
        List<SystemServiceFlowProcess> list = (List<SystemServiceFlowProcess>) super.hibernateTemplate.find("from SystemServiceFlowProcess s where code=? ", code);
        if (!CollectionUtil.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }
}

+ 49 - 0
src/main/java/com/yihu/hos/system/model/SystemServiceFlowProcess.java

@ -0,0 +1,49 @@
package com.yihu.hos.system.model;
public class SystemServiceFlowProcess implements java.io.Serializable {
    private Integer id;
    private String code;
    private String name;
    private String fileName;
    private String result;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}

+ 195 - 15
src/main/java/com/yihu/hos/system/service/ProcessManager.java

@ -1,20 +1,25 @@
package com.yihu.hos.system.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.config.MongoConfig;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.encrypt.DES;
import com.yihu.hos.system.dao.AppDao;
import com.yihu.hos.system.dao.AppServiceDao;
import com.yihu.hos.system.dao.FlowProcessDao;
import com.yihu.hos.system.model.SystemServiceEndpoint;
import com.yihu.hos.system.model.SystemServiceFlowProcess;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.GridFSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
 * 系统流程管理业务类
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/8/19.
 */
import java.io.File;
import java.io.FileWriter;
import java.util.*;
@Service("ProcessManager")
public class ProcessManager {
@ -24,22 +29,197 @@ public class ProcessManager {
    private AppDao appDao;
    @Resource(name = AppServiceDao.BEAN_ID)
    private AppServiceDao appServiceDao;
    @Resource(name = FlowProcessDao.BEAN_ID)
    private FlowProcessDao processDao;
    private ObjectMapper objectMapper = new ObjectMapper();
    public String getAllApp() {
    public Result getAllApp() throws Exception {
        String hql = "select * from SystemServiceEndpoint";
        List<SystemServiceEndpoint> serviceEndpointList = appServiceDao.getEntityList(SystemServiceEndpoint.class, hql);
        return null;
        String result = objectMapper.writeValueAsString(serviceEndpointList);
        return Result.success(result);
    }
    public String getAllAppService() {
    public Result getAllAppService() throws Exception {
        String hql = "select * from SystemServiceEndpoint";
        List<SystemServiceEndpoint> serviceEndpointList = appServiceDao.getEntityList(SystemServiceEndpoint.class, hql);
        return null;
        String result = objectMapper.writeValueAsString(serviceEndpointList);
        return Result.success(result);
    }
    public String getAppServiceByAppId(String appId) {
    public Result getAppServiceByAppId(String appId) throws Exception {
        String hql = "select * from SystemServiceEndpoint where appId = "+appId+"";
        List<SystemServiceEndpoint> serviceEndpointList = appServiceDao.getEntityList(SystemServiceEndpoint.class, hql);
        return null;
        String result = objectMapper.writeValueAsString(serviceEndpointList);
        return Result.success(result);
    }
    public void saveProcess(String code, String name, String fileName, String positionJsonStr) throws Exception {
        SystemServiceFlowProcess process = new SystemServiceFlowProcess();
        process.setCode(code);
        process.setName(name);
        process.setResult(positionJsonStr);
        process.setFileName(fileName);
        processDao.saveEntity(process);
    }
    public String formatJson(String flowJsonStr) throws Exception {
//        flowJsonStr = "{\n" +
//                "    \"code\": \"cralwer\",\n" +
//                "    \"nodes\": {\n" +
//                "        \"node_1\": {\n" +
//                "            \"name\": \"quartz\",\n" +
//                "            \"value\": \"quartz://myGroup/myTimerName?cron=0/3 * * * * ?\",\n" +
//                "            \"type\": \"service\"\n" +
//                "        },\n" +
//                "        \"node_2\": {\n" +
//                "            \"name\": \"CollectProcessor0\",\n" +
//                "            \"value\": \"collect.processor.CollectProcessor0\",\n" +
//                "            \"type\": \"processor\"\n" +
//                "        },\n" +
//                "        \"node_3\": {\n" +
//                "            \"name\": \"crawler\",\n" +
//                "            \"value\": \"http4://localhost:8088/crawler/patientList\",\n" +
//                "            \"type\": \"service\"\n" +
//                "        }\n" +
//                "    },\n" +
//                "    \"lines\": {\n" +
//                "        \"line_1\": {\n" +
//                "            \"from\": \"node_1\",\n" +
//                "            \"to\": \"node_2\"\n" +
//                "        },\n" +
//                "        \"line_2\": {\n" +
//                "            \"from\": \"node_2\",\n" +
//                "            \"to\": \"node_3\"\n" +
//                "        }\n" +
//                "    }\n" +
//                "}";
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode flowJson = objectMapper.readValue(flowJsonStr, JsonNode.class);
        String code = flowJson.get("code").asText();
        String javaName = toUpperCaseFirstOne(code)+"Route";
        //sort flow by lines
        JsonNode lines = flowJson.get("lines");
        Iterator<JsonNode> lineIterator = lines.iterator();
        String[] nodeNameArray = new String[lines.size() + 1];
        Boolean isFirstLineFlg = true;
        while (lineIterator.hasNext()) {
            JsonNode line = lineIterator.next();
            String nodeNameFrom = line.get("from").asText();
            String nodeNameTo = line.get("to").asText();
            if (isFirstLineFlg) {
                nodeNameArray[0] = nodeNameFrom;
                nodeNameArray[1] = nodeNameTo;
                isFirstLineFlg = false;
                continue;
            }
            for (int i=0; i<nodeNameArray.length; i++) {
                if (nodeNameArray[i].equals(nodeNameFrom)) {
                    if (StringUtil.isEmpty(nodeNameArray[i + 1])) {
                        nodeNameArray[i + 1] = nodeNameTo;
                    } else {
                        insertArray(nodeNameTo, nodeNameArray, i + 1);
                    }
                    break;
                } else if (nodeNameArray[i].equals(nodeNameTo)) {
                    insertArray(nodeNameFrom, nodeNameArray, i);
                }
            }
        }
        //get nodeMap by nodes
        JsonNode nodes = flowJson.get("nodes");
        Map<String, JsonNode> nodeMap = new HashMap<>();
        Iterator<Map.Entry<String, JsonNode>> nodeIterator = nodes.fields();
        //for the java code import processor class
        List<String> processorImport = new ArrayList<>();
        while (nodeIterator.hasNext()) {
            Map.Entry<String, JsonNode> map = nodeIterator.next();
            JsonNode node = map.getValue();
            String type = node.get("type").asText();
            if (type.equals("processor")) {
                processorImport.add(node.get("value").asText());
            }
            nodeMap.put(map.getKey(), map.getValue());
        }
        //mosaic the java code
        Boolean isFirstNodeFlg = true;
        StringBuilder javaBuilder = new StringBuilder();
        javaBuilder.append("package "+code+".route;\n\n");
        javaBuilder.append("import org.apache.camel.Exchange;\n");
        javaBuilder.append("import org.apache.camel.builder.RouteBuilder;\n");
        for (String packageName : processorImport) {
            javaBuilder.append("import " + packageName + ";\n");
        }
        javaBuilder.append("public class "+javaName+" extends RouteBuilder {\n");
        javaBuilder.append("public void configure() throws Exception {\n");
        for (String nodeName : nodeNameArray) {
            JsonNode node = nodeMap.get(nodeName);
            String type = node.get("type").asText();
            String value = node.get("value").asText();
            String name = node.get("name").asText();
            if (isFirstNodeFlg) {
                javaBuilder.append("from(\"");
                javaBuilder.append(value + "\")");
                javaBuilder.append(".routeId(\""+code+"\")");
                isFirstNodeFlg = false;
            } else {
                if (type.equals("processor")) {
                    javaBuilder.append("\n.process(\"new "+name+"())");
                } else {
                    javaBuilder.append("\n.setHeader(Exchange.HTTP_METHOD, constant(\"POST\"))");
                    javaBuilder.append("\n.to(\"");
                    javaBuilder.append(value + "\")");
                }
            }
        }
        javaBuilder.append("\n}\n}");
        System.out.println(javaBuilder.toString());
        String packageFilePath = System.getProperty("user.dir");
        String filePath = packageFilePath + "/" + javaName + ".java";
        File file = new File(filePath);
        FileWriter fw = new FileWriter(file);
        fw.write(javaBuilder.toString());
        fw.flush();
        fw.close();//这里只是产生一个JAVA文件,简单的IO操作
        //upload to mongo
        String dbName = "upload";
        String newFileName;
        try {
            newFileName = GridFSUtil.uploadFile(dbName, filePath, file.getName());
            if (!StringUtil.isEmpty(newFileName)) {
                return newFileName;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    public void insertArray(String nodeName, String[] array, int index) {
        for (int i=index; i<array.length; i++) {
            String nodeNameTemp = array[i];
            array[i] = nodeName;
            nodeName = nodeNameTemp;
        }
    }
    //首字母转大写
    public String toUpperCaseFirstOne(String s)
    {
        if(Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }
}

+ 33 - 0
src/main/resources/resource/SystemServiceFlowProcess.hbm.xml

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.yihu.hos.system.model.SystemServiceFlowProcess" table="system_service_flow_process">
        <id name="id" column="id">
            <generator class="increment"/>
        </id>
        <property name="code" type="java.lang.String">
            <column name="code" length="50">
                <comment>模板标识编码</comment>
            </column>
        </property>
        <property name="name" type="java.lang.String">
            <column name="name" length="255" not-null="true">
                <comment>模板名称</comment>
            </column>
        </property>
        <property name="result" type="java.lang.String">
            <column name="result">
                <comment>模板编辑结果</comment>
            </column>
        </property>
        <property name="fileName" type="java.lang.String">
            <column name="file_name">
                <comment>生成文件存储名称</comment>
            </column>
        </property>
    </class>
</hibernate-mapping>

+ 1 - 3
src/main/webapp/WEB-INF/ehr/jsp/system/process/processJs.jsp

@ -8,11 +8,10 @@
<script type="text/javascript" src="${contextRoot}/develop/lib/gooflow/json2.js"></script>
<script type="text/javascript" src="${contextRoot}/develop/lib/gooflow/goo/codebase/GooFlow.js"></script>
<script type="text/javascript">
    var property = {
        width: 1600,
        height: 700,
        toolBtns: ["start round", "end round", "task round", "node", "chat", "chat","state", "plug", "join", "fork", "complex mix"],
        toolBtns: ["start round", "end round", "task round", "node", "chat", "state", "plug", "join", "fork", "complex mix"],
        haveHead: true,
        headBtns: ["new", "open", "save", "undo", "redo", "reload"], //如果haveHead=true,则定义HEAD区的按钮
        haveTool: true,
@ -27,7 +26,6 @@
        "task": "任务结点",
        node: "自动结点",
        chat: "决策结点",
        chat: "决策结点",
        state: "状态结点",
        plug: "附加插件",
        fork: "分支结点",