package com.yihu.hos.system.service; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.yihu.hos.common.graph.BFSGraph; import com.yihu.hos.common.graph.DGraph; import com.yihu.hos.common.graph.Edge; import com.yihu.hos.core.datatype.StringUtil; 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.dao.ProcessorDao; import com.yihu.hos.system.model.SystemApp; import com.yihu.hos.system.model.SystemServiceEndpoint; import com.yihu.hos.system.model.SystemServiceFlowProcess; import com.yihu.hos.system.model.SystemServiceFlowProcessor; import com.yihu.hos.web.framework.model.Result; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; @Service("ProcessManager") public class ProcessManager { public static final String BEAN_ID = "ProcessManager"; @Resource(name = AppDao.BEAN_ID) private AppDao appDao; @Resource(name = AppServiceDao.BEAN_ID) private AppServiceDao appServiceDao; @Resource(name = ProcessorDao.BEAN_ID) private ProcessorDao processorDao; @Resource(name = FlowProcessDao.BEAN_ID) private FlowProcessDao processDao; private ObjectMapper objectMapper = new ObjectMapper(); public Result getAllApp() throws Exception { String hql = "from SystemApp"; List appList = appDao.getEntityList(SystemApp.class, hql); String result = objectMapper.writeValueAsString(appList); return Result.success(result); } public Result getAllAppService() throws Exception { String hql = "from SystemServiceEndpoint"; List serviceEndpointList = appServiceDao.getEntityList(SystemServiceEndpoint.class, hql); String result = objectMapper.writeValueAsString(serviceEndpointList); return Result.success(result); } public Result getAppServiceByAppId(String appId) throws Exception { String hql = "from SystemServiceEndpoint where appId = "+appId+""; List serviceEndpointList = appServiceDao.getEntityList(SystemServiceEndpoint.class, hql); String result = objectMapper.writeValueAsString(serviceEndpointList); return Result.success(result); } public Result getAllProcessor() throws Exception { String hql = "from SystemServiceFlowProcessor"; List processorList = processorDao.getEntityList(SystemServiceFlowProcessor.class, hql); String result = objectMapper.writeValueAsString(processorList); 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 static void main(String[] args) throws Exception { String 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\": \"CrawlerProcessor0\",\n" + " \"value\": \"crawler.processor.CrawlerProcessor0\",\n" + " \"type\": \"processor\"\n" + " },\n" + " \"node_3\": {\n" + " \"name\": \"crawler\",\n" + " \"value\": \"body().isEqualTo(false)\",\n" + " \"type\": \"judgement\"\n" + " },\n" + " \"node_4\": {\n" + " \"name\": \"crawler\",\n" + " \"value\": \"http4://localhost:8088/crawler/collect\",\n" + " \"type\": \"service\"\n" + " },\n" + " \"node_5\": {\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" + " \"line_3\": {\n" + " \"from\": \"node_3\",\n" + " \"to\": \"node_4\",\n" + " \"value\": \"correct\"\n" + " },\n" + " \"line_4\": {\n" + " \"from\": \"node_3\",\n" + " \"to\": \"node_5\"\n" + " }\n" + " }\n" + "}"; formatJson(flowJsonStr); } public static String formatJson(String flowJsonStr) throws Exception { String root = ""; ObjectMapper objectMapper = new ObjectMapper(); JsonNode flowJson = objectMapper.readValue(flowJsonStr, JsonNode.class); String code = flowJson.get("code").asText(); //sort flow by lines JsonNode lines = flowJson.get("lines"); Iterator> lineIterator = lines.fields(); //get nodeMap by nodes JsonNode nodes = flowJson.get("nodes"); Iterator> nodeIterator = nodes.fields(); //for the java code import processor class Map nodeMap = new HashMap<>(); Map lineMap = new HashMap<>(); DGraph mDG = new BFSGraph(); while (nodeIterator.hasNext()) { Map.Entry map = nodeIterator.next(); nodeMap.put(map.getKey(), map.getValue()); if (StringUtil.isEmpty(mDG.get(0))) { root = map.getKey(); } mDG.add(map.getKey()); } while (lineIterator.hasNext()) { Map.Entry map = lineIterator.next(); lineMap.put(map.getKey(), map.getValue()); String nodeNameFrom = map.getValue().get("from").asText(); String nodeNameTo = map.getValue().get("to").asText(); mDG.add(new Edge<>(nodeNameFrom, nodeNameTo, map.getKey())); } //generate the java code return generate(code, root, lineMap, nodeMap, mDG); } public static String generate(String code, String root, Map lineMap, Map nodeMap, DGraph mDG) throws IOException { Boolean isFirstNodeFlg = true; StringBuilder javaBuilder = new StringBuilder(); String javaName = toUpperCaseFirstOne(code)+"Route"; javaBuilder.append("package "+code+".route;\n\n"); javaBuilder.append("import org.apache.camel.Exchange;\n"); javaBuilder.append("import org.apache.camel.builder.RouteBuilder;\n"); javaBuilder.append("import crawler.SplitUtil;\n"); for (String key : nodeMap.keySet()) { JsonNode node = nodeMap.get(key); String type = node.get("type").asText(); if (type.equals("processor")) { javaBuilder.append("import " + node.get("value").asText() + ";\n"); } } javaBuilder.append("public class "+javaName+" extends RouteBuilder {\n"); javaBuilder.append("public void configure() throws Exception {\n"); Iterator it = mDG.iterator(root); while(it.hasNext()) { String nodeName = it.next(); 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")) { JsonNode args = node.get("args"); if (args == null) { javaBuilder.append("\n.process(\"new "+name+"())"); } else { String argStr = ""; String[] argArr = args.asText().split(","); for (String arg : argArr) { argStr += "\"" + arg + "\","; } argStr = StringUtil.substring(argStr, 0, argStr.length() - 1); javaBuilder.append("\n.process(\"new "+name+"("+argStr+"))"); } } else if (type.equals("judgement")) { judgement(javaBuilder, value, nodeName, mDG, it, lineMap, nodeMap); } else if (type.equals("circle")) { split(javaBuilder, value); } else if (type.equals("aggregate")) { aggregate(javaBuilder); } else if (type.equals("multicast")) { mulitcast(javaBuilder, value, nodeName, mDG, it, lineMap, nodeMap); } 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 newFileName; // try { // newFileName = GridFSUtil.uploadFile(filePath, file.getName(), null); // if (!StringUtil.isEmpty(newFileName)) { // return newFileName; // } // } catch (Exception e) { // e.printStackTrace(); // } return ""; } //首字母转大写 public static 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(); } public static void judgement(StringBuilder javaBuilder, String value, String nodeName, DGraph mDG, Iterator it, Map lineMap, Map nodeMap) { javaBuilder.append("\n.when("+value+")"); List> edgeList = mDG.getEdgeList(nodeName); String trueNodeName = ""; String falseNodeName = ""; for (Edge edge : edgeList) { it.next(); String nextNodeName = edge.getDest(); String nextLineName = edge.getName(); JsonNode nextLine = lineMap.get(nextLineName); if (nextLine.get("value") != null &&nextLine.get("value").asText().equals("correct")) { trueNodeName = nextNodeName; } else { falseNodeName = nextNodeName; } } JsonNode node1 = nodeMap.get(trueNodeName); JsonNode node2 = nodeMap.get(falseNodeName); String firstValue = node1.get("value").asText(); String secondValue = node2.get("value").asText(); javaBuilder.append("\n.setHeader(Exchange.HTTP_METHOD, constant(\"POST\"))"); javaBuilder.append("\n.to(\""); javaBuilder.append(firstValue + "\")"); javaBuilder.append(".otherwise()"); javaBuilder.append("\n.setHeader(Exchange.HTTP_METHOD, constant(\"POST\"))"); javaBuilder.append("\n.to(\""); javaBuilder.append(secondValue + "\")"); } public static void split(StringBuilder javaBuilder, String value) { javaBuilder.append("\n.split().method(Split.class, \""+value+"\")"); } public static void aggregate(StringBuilder javaBuilder) { javaBuilder.append("\n.aggregate(header(\"test_correlation_key\"), new Aggregate()).completionSize(3)"); } public static void mulitcast(StringBuilder javaBuilder, String value, String nodeName, DGraph mDG, Iterator it, Map lineMap, Map nodeMap) { List> edgeList = mDG.getEdgeList(nodeName); String endpoints = ""; for (Edge edge : edgeList) { String nextNodeName = edge.getDest(); JsonNode node = nodeMap.get(nextNodeName); endpoints += "\"" + node.get("value") + "\","; it.next(); } endpoints = StringUtil.substring(endpoints, 0, endpoints.length() - 1); javaBuilder.append("\n.multicast().stopOnException().to("+endpoints+").end()"); } }