Parcourir la source

Merge branch 'master' of http://192.168.1.220:10080/esb/esb

demon il y a 8 ans
Parent
commit
ba50174a8e
22 fichiers modifiés avec 615 ajouts et 98 suppressions
  1. 7 0
      hos-arbiter/pom.xml
  2. 25 0
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/HosArbiterApplication.java
  3. 37 0
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/configuration/ArbiterServerConfiguration.java
  4. 0 34
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/controllers/ProxyController.java
  5. 2 20
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ArbiterServerService.java
  6. 66 0
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ProxyService.java
  7. 30 9
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ServiceFlowService.java
  8. 15 8
      hos-arbiter/src/main/resources/application.yml
  9. 22 0
      hos-arbiter/src/test/java/com/yihu/hos/arbiter/services/ProxyServiceTest.java
  10. 1 0
      hos-broker/src/main/java/com/yihu/hos/broker/controllers/ESBCamelController.java
  11. 0 3
      hos-camel/src/main/java/collect/route/CollectQuartzRoute.java
  12. 52 0
      hos-camel/src/main/java/com/yihu/hos/camel/RouteJavaBuilder.java
  13. 2 2
      hos-rest/src/main/resources/config/dbhelper.properties
  14. 1 1
      hos-rest/src/main/resources/config/http.properties
  15. 3 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ServiceFlowConstant.java
  16. 46 1
      src/main/java/com/yihu/hos/system/controller/ProcessController.java
  17. 26 0
      src/main/java/com/yihu/hos/system/dao/FlowProcessDao.java
  18. 49 0
      src/main/java/com/yihu/hos/system/model/SystemServiceFlowProcess.java
  19. 195 15
      src/main/java/com/yihu/hos/system/service/ProcessManager.java
  20. 2 2
      src/main/resources/application.yml
  21. 33 0
      src/main/resources/resource/SystemServiceFlowProcess.hbm.xml
  22. 1 3
      src/main/webapp/WEB-INF/ehr/jsp/system/process/processJs.jsp

+ 7 - 0
hos-arbiter/pom.xml

@ -40,6 +40,13 @@
            <artifactId>hos-web-framework</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.zbus/zbus -->
        <dependency>
            <groupId>org.zbus</groupId>
            <artifactId>zbus</artifactId>
            <version>7.2.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>

+ 25 - 0
hos-arbiter/src/main/java/com/yihu/hos/arbiter/HosArbiterApplication.java

@ -1,21 +1,46 @@
package com.yihu.hos.arbiter;
import com.yihu.hos.arbiter.configuration.ArbiterServerConfiguration;
import com.yihu.hos.arbiter.services.ProxyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.zbus.mq.server.MqServer;
import org.zbus.mq.server.MqServerConfig;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class HosArbiterApplication implements CommandLineRunner {
    private ArbiterServerConfiguration configuration;
    private ProxyService proxyService;
    public static void main(String[] args) {
        SpringApplication.run(HosArbiterApplication.class, args);
    }
    @Override
    public void run(String... strings) throws Exception {
        if (configuration.isCentral()) {
            MqServerConfig config = new MqServerConfig();
            config.serverPort = configuration.getCentralPort();
            config.storePath = configuration.getCentralStore();
            final MqServer server = new MqServer(config);
            server.start();
        } else {
            proxyService.start();
        }
    }
    @Autowired
    public void setConfiguration(ArbiterServerConfiguration configuration) {
        this.configuration = configuration;
    }
    @Autowired
    public void setProxyService(ProxyService proxyService) {
        this.proxyService = proxyService;
    }
}

+ 37 - 0
hos-arbiter/src/main/java/com/yihu/hos/arbiter/configuration/ArbiterServerConfiguration.java

@ -2,7 +2,11 @@ package com.yihu.hos.arbiter.configuration;
import com.yihu.hos.core.datatype.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zbus.broker.ZbusBroker;
import java.io.IOException;
/**
 * @author Airhead
@ -12,11 +16,16 @@ import org.springframework.context.annotation.Configuration;
public class ArbiterServerConfiguration {
    @Value("${arbiter.central.url}")
    private String centralUrl;
    @Value("${arbiter.central.port}")
    private Integer centralPort;
    @Value("${arbiter.central.store}")
    private String centralStore;
    @Value("${arbiter.terminal.url}")
    private String terminalUrl;
    @Value("${arbiter.tenant.name}")
    private String tenant;
    private ZbusBroker zbusBroker;
    public String getCentralUrl() {
        return centralUrl;
@ -34,6 +43,34 @@ public class ArbiterServerConfiguration {
        return StringUtil.isEmpty(centralUrl);
    }
    public Integer getCentralPort() {
        return centralPort;
    }
    public String getCentralStore() {
        return centralStore;
    }
    @Bean
    public ZbusBroker getZbusBroker() {
        try {
            zbusBroker = new ZbusBroker(this.centralUrl);
            return zbusBroker;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void finalize() throws Throwable {
        if (zbusBroker != null) {
            zbusBroker.close();
        }
        super.finalize();
    }
//    public boolean isTerminal() {
//        return !isCentral();
//    }

+ 0 - 34
hos-arbiter/src/main/java/com/yihu/hos/arbiter/controllers/ProxyController.java

@ -1,34 +0,0 @@
package com.yihu.hos.arbiter.controllers;
import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
 * @author Airhead
 * @since 2016/12/2.
 */
@RestController
@RequestMapping("/proxy")
public class ProxyController {
    @Autowired
    private CamelContext camelContext;
    @RequestMapping()
    public void proxy(@RequestHeader Map<String, String> headers,
                      @RequestBody String body) {
        Map<String, Object> header = new HashMap<>();
        header.put("event", headers.get("event"));
        ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
        producerTemplate.sendBodyAndHeaders(ServiceFlowConstant.FLOW_EVENT_ENDPOINT, body, header);
    }
}

+ 2 - 20
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ArbiterServerService.java

@ -1,11 +1,8 @@
package com.yihu.hos.arbiter.services;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.arbiter.configuration.ArbiterServerConfiguration;
import com.yihu.hos.arbiter.models.ArbiterServer;
import com.yihu.hos.core.http.HTTPResponse;
import com.yihu.hos.core.http.HttpClientKit;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
@ -36,29 +33,14 @@ public class ArbiterServerService {
    public void start() {
        //中心Arbiter服务器直接注册
        if (configuration.isCentral()) {
            ArbiterServer arbiterServer = new ArbiterServer();
            arbiterServer.setTenant(configuration.getTenant());
            arbiterServer.setUrl(configuration.getTerminalUrl());
            this.save(arbiterServer);
            return;
        }
        //终端Arbiter服务器调用中心Arbiter服务进行注册
        ArbiterServer arbiterServer = new ArbiterServer();
        arbiterServer.setTenant(configuration.getTenant());
        arbiterServer.setUrl(configuration.getTerminalUrl());
        try {
            String jsonBody = objectMapper.writeValueAsString(arbiterServer);
            HTTPResponse response = HttpClientKit.post(configuration.getCentralUrl() + "/arbiter", jsonBody);
            if (response.getStatusCode() != 200) {
                logger.error("register terminal arbiter server failed");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        this.save(arbiterServer);
    }
    public void save(ArbiterServer arbiterServer) {

+ 66 - 0
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ProxyService.java

@ -0,0 +1,66 @@
package com.yihu.hos.arbiter.services;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Consumer;
import org.zbus.net.http.Message;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
 * @author Airhead
 * @since 2016/12/22.
 */
@Service
public class ProxyService {
    private static final Logger logger = LoggerFactory.getLogger(ProxyService.class);
    @Autowired
    private CamelContext camelContext;
    private ZbusBroker zbusBroker;
    private Consumer consumer;
    public void proxy(Message message, Consumer consumer) {
        Map<String, Object> header = new HashMap<>();
        header.put("event", message.getHead("event"));
        ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
        producerTemplate.sendBodyAndHeaders(ServiceFlowConstant.FLOW_EVENT_ENDPOINT, message.getBodyString(), header);
    }
    public void start() {
        if (zbusBroker == null) {
            logger.error("zbusBroker is null");
            return;
        }
        consumer = new Consumer(zbusBroker, ServiceFlowConstant.SSH);
        try {
            consumer.start(this::proxy);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }
    @Autowired
    public void setZbusBroker(ZbusBroker zbusBroker) {
        this.zbusBroker = zbusBroker;
    }
    @Override
    protected void finalize() throws Throwable {
        consumer.close();
        super.finalize();
    }
}

+ 30 - 9
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ServiceFlowService.java

@ -1,7 +1,6 @@
package com.yihu.hos.arbiter.services;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.arbiter.models.ArbiterServer;
import com.yihu.hos.arbiter.models.BrokerServer;
import com.yihu.hos.core.http.HTTPResponse;
import com.yihu.hos.core.http.HttpClientKit;
@ -17,9 +16,11 @@ import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Producer;
import org.zbus.net.http.Message;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -45,6 +46,8 @@ public class ServiceFlowService {
    @Autowired
    private ArbiterServerService arbiterServerService;
    private ZbusBroker zbusBroker;
    public ServiceFlow save(ServiceFlow serviceFlow) {
        if (serviceFlow == null) {
@ -345,13 +348,31 @@ public class ServiceFlowService {
     * @param msg    消息
     */
    public void proxy(@Headers Map<String, String> header, @Body String msg) {
        String tenant = header.get("tenant");
        String event = header.get("event");
        ArbiterServer arbiterServer = arbiterServerService.get(tenant);
        header.remove("tenant");
        header = new HashMap<>();
        header.put("event",event);
        HttpClientKit.post(arbiterServer.getUrl() + "/proxy", msg, header);
        if (zbusBroker == null) {
            logger.error("zbusBroker is null.");
            return;
        }
        try {
            Producer producer = new Producer(zbusBroker, ServiceFlowConstant.SSH);
            producer.createMQ();    //确定为创建消息队列需要显示调用
            Message message = new Message();
            message.setHead(header);
            message.setMethod("POST");
            message.setBody(msg);
            message = producer.sendSync(message);
            logger.debug(message);
        } catch (IOException | InterruptedException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }
    @Autowired
    public void setZbusBroker(ZbusBroker zbusBroker) {
        this.zbusBroker = zbusBroker;
    }
    private boolean sendMessage(BrokerServer brokerServer, String method, String path, String msg) {

+ 15 - 8
hos-arbiter/src/main/resources/application.yml

@ -3,9 +3,6 @@ server:
spring:
  application:
    name: ArbiterServer
  central:
    url: http://127.0.0.1:10135
---
spring:
  profiles: dev
@ -49,9 +46,11 @@ arbiter:
  timer:
      period: 10000
  central:
    url: http://127.0.0.1:10135
    url:
    port: 15555
    store: ./store
  terminal:
    url: http://127.0.0.1:10135
    url: 127.0.0.1:15555
  tenant:
    name: jkzl
---
@ -73,7 +72,13 @@ arbiter:
  timer:
      period: 10000
  central:
    url: http://127.0.0.1:10135
    url:
    port: 15555
    store: ./store
  terminal:
    url: 192.168.131.38:15555
  tenant:
    name: yichang
---
spring:
  profiles: lfq
@ -93,8 +98,10 @@ arbiter:
  timer:
      period: 10000
  central:
    url: http://192.168.131.119:10135
    url: 192.168.131.119:15555
    port: 15555
    store: ./store
  terminal:
    url: http://192.168.131.38:10135
    url: 192.168.131.38:15555
  tenant:
    name: yichang

+ 22 - 0
hos-arbiter/src/test/java/com/yihu/hos/arbiter/services/ProxyServiceTest.java

@ -0,0 +1,22 @@
package com.yihu.hos.arbiter.services;
import org.junit.Test;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Producer;
import org.zbus.net.http.Message;
/**
 * @author Airhead
 * @since 2016/12/22.
 */
public class ProxyServiceTest {
    @Test
    public void proxy() throws Exception {
        Producer producer = new Producer(new ZbusBroker("192.168.131.38:15555"), "RemoteControl");
        producer.createMQ();//确定为创建消息队列需要显示调用
        Message msg = new Message();
        msg.setBody("hello world"); //消息体底层是byte[]
        msg = producer.sendSync(msg);
    }
}

+ 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

+ 3 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ServiceFlowConstant.java

@ -36,4 +36,7 @@ public interface ServiceFlowConstant {
    //BrokerServer
    String BROKER_SERVER_ON = "brokerServerOn"; //Broker启动
    String BROKER_SERVER_OFF = "brokerServerOff";//Broker停止
    //ArbiterServer MQ
    String SSH = "ssh";
}

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

@ -1,9 +1,13 @@
package com.yihu.hos.system.controller;
import com.yihu.hos.system.service.ProcessManager;
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 +19,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ProcessController  extends BaseController {
    @Autowired
    private ProcessManager processManager;
    /**
     *  流程管理界面
     *
@ -22,8 +28,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();
    }
}

+ 2 - 2
src/main/resources/application.yml

@ -110,14 +110,14 @@ spring:
    show-sql: false
  data:
    mongodb:
      host: 172.19.103.86
      host: 172.19.103.57
      port: 27017
      username: esb
      password: esb
      authenticationDatabase: admin
      gridFsDatabase: dfs
  activemq:
    broker-url: tcp://172.19.103.86:61616?wireFormat.maxInactivityDuration=0
    broker-url: tcp://172.19.103.57:61616?wireFormat.maxInactivityDuration=0
    user: admin
    password: admin
    pooled: false

+ 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: "分支结点",