浏览代码

Merge branch 'master' of luofaqiang/esb into master

罗发强 8 年之前
父节点
当前提交
21da834cfa
共有 33 个文件被更改,包括 643 次插入648 次删除
  1. 11 6
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/HosArbiterApplication.java
  2. 40 0
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/configuration/ArbiterServerConfiguration.java
  3. 34 0
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/controllers/ArbiterServerController.java
  4. 2 1
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/controllers/ProxyController.java
  5. 0 34
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/controllers/ServiceFlowController.java
  6. 25 0
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/listener/ApplicationStartListener.java
  7. 45 0
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/models/ArbiterServer.java
  8. 1 1
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/routers/ServiceFlowEventRouter.java
  9. 77 0
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ArbiterServerService.java
  10. 1 1
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/BrokerServerService.java
  11. 44 16
      hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ServiceFlowService.java
  12. 15 0
      hos-arbiter/src/main/resources/META-INF/additional-spring-configuration-metadata.json
  13. 14 1
      hos-arbiter/src/main/resources/application.yml
  14. 28 0
      hos-arbiter/src/main/resources/log4j2.xml
  15. 8 4
      hos-broker/src/main/java/com/yihu/hos/broker/HosBrokerApplication.java
  16. 0 46
      hos-broker/src/main/java/com/yihu/hos/broker/listeners/ApplicationStartListener.java
  17. 0 18
      hos-broker/src/main/java/com/yihu/hos/broker/models/SystemCamelContext.java
  18. 0 32
      hos-broker/src/main/java/com/yihu/hos/broker/models/SystemClassMapping.java
  19. 0 71
      hos-broker/src/main/java/com/yihu/hos/broker/services/camel/CamelClassLoader.java
  20. 0 180
      hos-broker/src/main/java/com/yihu/hos/broker/services/camel/CamelCompiler.java
  21. 51 0
      hos-broker/src/main/java/com/yihu/hos/broker/services/camel/CamelStartBoot.java
  22. 0 66
      hos-broker/src/main/java/com/yihu/hos/broker/services/camel/ClassParams.java
  23. 51 50
      hos-broker/src/main/java/com/yihu/hos/broker/services/camel/ESBCamelService.java
  24. 59 0
      hos-broker/src/main/java/com/yihu/hos/broker/services/camel/SystemCamelContext.java
  25. 7 0
      hos-broker/src/test/java/com/yihu/hos/HosBrokerApplicationTests.java
  26. 70 0
      hos-broker/src/test/java/com/yihu/hos/broker/services/camel/ESBCamelServiceTest.java
  27. 7 2
      hos-core/src/main/java/com/yihu/hos/core/http/DefaultClientImpl.java
  28. 1 1
      hos-core/src/main/java/com/yihu/hos/core/http/HTTPClient.java
  29. 5 1
      hos-core/src/main/java/com/yihu/hos/core/http/HttpClientKit.java
  30. 2 1
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ServiceFlowConstant.java
  31. 2 1
      src/main/java/com/yihu/hos/ESBApplication.java
  32. 2 99
      src/main/java/com/yihu/hos/services/ServiceFlowEventService.java
  33. 41 16
      src/main/java/com/yihu/hos/system/service/FlowManager.java

+ 11 - 6
hos-arbiter/src/main/java/com/yihu/hos/arbiter/HosArbiterApplication.java

@ -1,5 +1,6 @@
package com.yihu.hos.arbiter;
import com.yihu.hos.arbiter.listener.ApplicationStartListener;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -9,13 +10,17 @@ import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfigurat
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class HosArbiterApplication implements CommandLineRunner {
    public static void main(String[] args) {
//        SpringApplication.run(HosArbiterApplication.class, args);
	public static void main(String[] args) {
		SpringApplication.run(HosArbiterApplication.class, args);
	}
        SpringApplication app = new SpringApplication(HosArbiterApplication.class);
        app.addListeners(new ApplicationStartListener());
        app.run(args);
    }
	@Override
	public void run(String... strings) throws Exception {
    @Override
    public void run(String... strings) throws Exception {
    }
	}
}

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

@ -0,0 +1,40 @@
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.Configuration;
/**
 * @author Airhead
 * @since 2016/12/9.
 */
@Configuration
public class ArbiterServerConfiguration {
    @Value("${arbiter.central.url}")
    private String centralUrl;
    @Value("${arbiter.terminal.url}")
    private String terminalUrl;
    @Value("${arbiter.tenant.name}")
    private String tenant;
    public String getCentralUrl() {
        return centralUrl;
    }
    public String getTerminalUrl() {
        return terminalUrl;
    }
    public String getTenant() {
        return tenant;
    }
    public boolean isCentral() {
        return StringUtil.isEmpty(centralUrl);
    }
//    public boolean isTerminal() {
//        return !isCentral();
//    }
}

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

@ -0,0 +1,34 @@
package com.yihu.hos.arbiter.controllers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.arbiter.models.ArbiterServer;
import com.yihu.hos.arbiter.services.ArbiterServerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
/**
 * @author Airhead
 * @since 2016/12/9.
 */
@RestController
@RequestMapping("/arbiter")
public class ArbiterServerController {
    @Autowired
    private ArbiterServerService arbiterServerService;
    @Autowired
    private ObjectMapper objectMapper;
    @RequestMapping()
    public void register(@RequestBody String body) {
        try {
            ArbiterServer arbiterServer = objectMapper.readValue(body, ArbiterServer.class);
            arbiterServerService.save(arbiterServer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

+ 2 - 1
hos-arbiter/src/main/java/com/yihu/hos/arbiter/controllers/ProxyController.java

@ -1,5 +1,6 @@
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;
@ -28,6 +29,6 @@ public class ProxyController {
        header.put("event", headers.get("event"));
        ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
        producerTemplate.sendBodyAndHeader("service.flow.event", body, header);
        producerTemplate.sendBodyAndHeaders(ServiceFlowConstant.FLOW_EVENT_ENDPOINT, body, header);
    }
}

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

@ -1,34 +0,0 @@
package com.yihu.hos.arbiter.controllers;
import com.yihu.hos.arbiter.services.ServiceFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
 * @created Airhead 2016/8/16.
 */
@RestController
@RequestMapping("/serviceFlow")
public class ServiceFlowController {
    @Autowired
    private ServiceFlowService serviceFlowService;
    @RequestMapping(method = RequestMethod.POST)
    public void save(String serviceFlow) {
        serviceFlowService.save(null);
    }
    @RequestMapping(method = RequestMethod.GET)
    public String get(String serviceFlow) {
        return serviceFlowService.get(serviceFlow);
    }
    @RequestMapping(method = RequestMethod.PUT)
    public String put(String serviceFlow, String clientInfo) {
        return serviceFlowService.put(serviceFlow, clientInfo);
    }
}

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

@ -0,0 +1,25 @@
package com.yihu.hos.arbiter.listener;
import com.yihu.hos.arbiter.services.ArbiterServerService;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class ApplicationStartListener implements ApplicationListener<ContextRefreshedEvent> {
    private static Logger logger = LogManager.getLogger(ApplicationStartListener.class);
    @Autowired
    private ArbiterServerService arbiterServerService;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        arbiterServerStart();
    }
    public void arbiterServerStart(){
        arbiterServerService.start();
    }
}

+ 45 - 0
hos-arbiter/src/main/java/com/yihu/hos/arbiter/models/ArbiterServer.java

@ -0,0 +1,45 @@
package com.yihu.hos.arbiter.models;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
/**
 * @author Airhead
 * @since 2016/12/9.
 */
@Document
public class ArbiterServer {
    @Id
    private String id;
    @Indexed
    private String tenant;
    private String url;
    public ArbiterServer() {
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTenant() {
        return tenant;
    }
    public void setTenant(String tenant) {
        this.tenant = tenant;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
}

+ 1 - 1
hos-arbiter/src/main/java/com/yihu/hos/arbiter/routers/ServiceFlowEventRouter.java

@ -26,7 +26,7 @@ public class ServiceFlowEventRouter extends RouteBuilder {
                activemqConfiguration.getUser(), activemqConfiguration.getPassword(), activemqConfiguration.getBrokerURL());
        // Note we can explicit name the component
        context.addComponent("service.flow.event", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
        from("service.flow.event:queue:configuration.service.flow")
        from(ServiceFlowConstant.FLOW_EVENT_ENDPOINT)
                .choice()
                .when(header("tenant").isNotNull()).to("bean:serviceFlowService?method=proxy")
                .when(header("event").isEqualTo(ServiceFlowConstant.SERVICE_FLOW_STARTED)).to("bean:serviceFlowService?method=serviceFlowStarted")

+ 77 - 0
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ArbiterServerService.java

@ -0,0 +1,77 @@
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;
import org.springframework.data.mongodb.core.MongoOperations;
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;
/**
 * @author Airhead
 * @since 2016/12/9.
 */
@Service
public class ArbiterServerService {
    private static final Logger logger = LogManager.getLogger(BrokerServerService.class);
    @Autowired
    private MongoOperations mongoOperations;
    @Autowired
    private ArbiterServerConfiguration configuration;
    @Autowired
    private ObjectMapper objectMapper;
    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(), jsonBody);
            if (response.getStatusCode() != 200) {
                logger.error("register terminal arbiter server failed");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }
    public void save(ArbiterServer arbiterServer) {
        Query query = new Query();
        query.addCriteria(Criteria.where("tenant").is(arbiterServer.getTenant()));
        Update update = new Update();
        update.set("tenant", arbiterServer.getTenant());
        update.set("url", arbiterServer.getUrl());
        mongoOperations.upsert(query, update, ArbiterServer.class);
    }
    public ArbiterServer get(String tenant) {
        Query query = new Query();
        query.addCriteria(Criteria.where("tenant").is(tenant));
        return mongoOperations.findOne(query, ArbiterServer.class);
    }
}

+ 1 - 1
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/BrokerServerService.java

@ -80,7 +80,7 @@ public class BrokerServerService {
            ProducerTemplate producerTemplate = createProducerTemplate();
            Map<String, Object> header = new HashMap<>();
            header.put("event", ServiceFlowConstant.BROKER_SERVER_ON);
            producerTemplate.sendBodyAndHeaders("service.flow.event:queue:configuration.service.flow", msg, header);
            producerTemplate.sendBodyAndHeaders(ServiceFlowConstant.FLOW_EVENT_ENDPOINT, msg, header);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            logger.error(e.getMessage());

+ 44 - 16
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ServiceFlowService.java

@ -1,7 +1,7 @@
package com.yihu.hos.arbiter.services;
import com.fasterxml.jackson.core.JsonProcessingException;
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;
@ -18,6 +18,7 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@ -33,24 +34,39 @@ import java.util.Map;
@Service("serviceFlowService")
public class ServiceFlowService {
    private static final Logger logger = LogManager.getLogger(BrokerServerService.class);
    @Autowired
    private MongoOperations mongoOperations;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private BrokerServerService brokerServerService;
    @Autowired
    private ArbiterServerService arbiterServerService;
    public void save(ServiceFlow serviceFlow) {
        if (serviceFlow == null) {
            logger.error("ServiceFlow is null");
            return;
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("routeCode").is(serviceFlow.getRouteCode()));
        ServiceFlow flow = mongoOperations.findOne(query, ServiceFlow.class);
        Update update = new Update();
        update.set("routeCode", serviceFlow.getRouteCode());
        update.set("handleFiles", serviceFlow.getHandleFiles());
        update.set("updated", serviceFlow.getUpdated());
        update.set("flowType", serviceFlow.getFlowType());
        if (flow != null) {
            HashSet<ServiceFlow.HandleFile> flowSets = new HashSet<>(flow.getHandleFiles());
            HashSet<ServiceFlow.HandleFile> serviceFlowSets = new HashSet<>(serviceFlow.getHandleFiles());
            flowSets.addAll(serviceFlowSets);
            ArrayList<ServiceFlow.HandleFile> handleFiles = new ArrayList<>(flowSets);
            update.set("handleFiles", handleFiles); //没有用原生语法比较复杂
        } else {
            update.set("handleFiles", serviceFlow.getHandleFiles());
        }
        mongoOperations.upsert(query, update, ServiceFlow.class);
    }
@ -63,15 +79,22 @@ public class ServiceFlowService {
        return mongoOperations.findAll(ServiceFlow.class);
    }
    public String put(String serviceName, String ClientInfo) {
        return null;
    }
    /**
     * admin发过来的服务流程启动事件处理。
     *
     * @param msg serviceFlow
     */
    public void serviceFlowStarted(String msg) {
        flowController("post", "/esb/serviceFlow/start", msg);
    }
    public void serviceFlowStarted(String msg, BrokerServer brokerServer) {
    /**
     * 没有使用重载,是因为Camel在判断路由时会产生歧义,而无法路由。
     *
     * @param msg          serviceFlow
     * @param brokerServer brokerServer Info
     */
    public void serviceFlowStart(String msg, BrokerServer brokerServer) {
        flowController("post", "/esb/serviceFlow/start", msg, brokerServer);
    }
@ -101,9 +124,7 @@ public class ServiceFlowService {
            try {
                BrokerServer brokerServer = objectMapper.readValue(msg, BrokerServer.class);
                String serviceFlowMsg = objectMapper.writeValueAsString(serviceFlow);
                serviceFlowStarted(serviceFlowMsg, brokerServer);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                serviceFlowStart(serviceFlowMsg, brokerServer);
            } catch (IOException e) {
                e.printStackTrace();
            }
@ -122,7 +143,11 @@ public class ServiceFlowService {
     * @param header 消息头部信息
     * @param msg    消息
     */
    public void proxy(Map<String, Object> header, String msg) {
    public void proxy(Map<String, String> header, String msg) {
        String tenant = header.get("tenant");
        ArbiterServer arbiterServer = arbiterServerService.get(tenant);
        header.remove("tenant");
        HttpClientKit.post(arbiterServer.getUrl(), msg, header);
    }
    private void flowController(String method, String path, String msg) {
@ -131,10 +156,9 @@ public class ServiceFlowService {
    private void flowController(String method, String path, String msg, BrokerServer brokerServer) {
        try {
            ServiceFlow serviceFlow = objectMapper.readValue(msg, ServiceFlow.class);
            this.save(serviceFlow);
            ServiceFlow serviceFlow = getServiceFlow(msg);
//            this.save(serviceFlow); //需要改造??
            boolean one = ServiceFlowConstant.JAVA.equals(serviceFlow.getFlowType());   //有cron表达式,就是采集任务。
            if (one) {
@ -179,4 +203,8 @@ public class ServiceFlowService {
        }
    }
    private ServiceFlow getServiceFlow(String msg) throws IOException {
        return objectMapper.readValue(msg, ServiceFlow.class);
    }
}

+ 15 - 0
hos-arbiter/src/main/resources/META-INF/additional-spring-configuration-metadata.json

@ -4,6 +4,21 @@
      "name": "arbiter.timer.period",
      "type": "java.lang.String",
      "description": "Description for arbiter.timer.period."
    },
    {
      "name": "arbiter.central.url",
      "type": "java.lang.String",
      "description": "Description for arbiter.central.url."
    },
    {
      "name": "arbiter.terminal.url",
      "type": "java.lang.String",
      "description": "Description for arbiter.terminal.url."
    },
    {
      "name": "arbiter.tenant.name",
      "type": "java.lang.String",
      "description": "Description for arbiter.tenant.name."
    }
  ]
}

+ 14 - 1
hos-arbiter/src/main/resources/application.yml

@ -3,6 +3,8 @@ server:
spring:
  application:
    name: ArbiterServer
  central:
    url: http://127.0.0.1:10135
---
spring:
@ -22,6 +24,8 @@ spring:
arbiter:
  timer:
      period: 10000
  central:
    url: http://127.0.0.1:10135
---
spring:
@ -41,6 +45,8 @@ spring:
arbiter:
  timer:
      period: 10000
  central:
    url: http://127.0.0.1:10135
---
spring:
@ -60,7 +66,8 @@ spring:
arbiter:
  timer:
      period: 10000
  central:
    url: http://127.0.0.1:10135
---
spring:
  profiles: lfq
@ -79,3 +86,9 @@ spring:
arbiter:
  timer:
      period: 10000
  central:
    url:
  terminal:
    url: http://127.0.0.1:10135
  tenant:
    name: jkzl

+ 28 - 0
hos-arbiter/src/main/resources/log4j2.xml

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration status ="ALL"  monitorInterval="1800">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout charset="UTF-8" pattern="%d{HH:mm:ss}[%-5p][%t][%c]: %m%n"/>
        </Console>
        <RollingFile name="RollingFile" filename="/usr/local/esb/log/CrunchifyTest.log"
                     filepattern="/usr/local/esb/log/rolling/%d{yyyyMMddHHmmss}-fargo.log">
            <PatternLayout charset="UTF-8" pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="RollingFile" />
        </Root>
        <Logger name="org.hibernate" level="warn" additivity="false">
        </Logger>
    </Loggers>
</configuration>

+ 8 - 4
hos-broker/src/main/java/com/yihu/hos/broker/HosBrokerApplication.java

@ -1,6 +1,7 @@
package com.yihu.hos.broker;
import com.yihu.hos.broker.listeners.ApplicationStartListener;
import com.yihu.hos.broker.services.camel.CamelStartBoot;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
@ -11,18 +12,21 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@EnableScheduling
public class HosBrokerApplication extends SpringBootServletInitializer {
public class HosBrokerApplication extends SpringBootServletInitializer implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(HosBrokerApplication.class);
//        app.addListeners(new ApplicationStartListener());
        app.run(args);
    }
    @Override
    public void run(String... strings) throws Exception {
        new CamelStartBoot().start();
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        builder.sources(this.getClass());
        builder.listeners(new ApplicationStartListener());
        return super.configure(builder);
    }
}

+ 0 - 46
hos-broker/src/main/java/com/yihu/hos/broker/listeners/ApplicationStartListener.java

@ -1,46 +0,0 @@
package com.yihu.hos.broker.listeners;
import com.yihu.hos.broker.models.SystemCamelContext;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
public class ApplicationStartListener implements ApplicationListener<ContextRefreshedEvent> {
    private static Logger logger = LogManager.getLogger(ApplicationStartListener.class);
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            camelRouteStart(contextRefreshedEvent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 这是一个固定的存储class文件的根路径
     * 正式系统中,这个值可来自于系统的配置文件
     */
    private void camelRouteStart(ContextRefreshedEvent contextRefreshedEvent) throws Exception {
        logger.info("Apache Camel Context 启动...");
        // 加载和设置ClassLoader
        List<URL> URLs = new ArrayList<>();
        ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
        ClassLoader camelESBClassLoader = new URLClassLoader(URLs.toArray(new URL[]{}), currentClassLoader);
        Thread.currentThread().setContextClassLoader(camelESBClassLoader);
        SystemCamelContext.getContext().setApplicationContextClassLoader(camelESBClassLoader);
        // 然后就可以进行RouteBuilder的加载
        SystemCamelContext.getContext().setTracing(true);
        SystemCamelContext.getContext().setUseMDCLogging(true);
        SystemCamelContext.getContext().start();
        logger.info("Apache Camel Context 启动完成...");
    }
}

+ 0 - 18
hos-broker/src/main/java/com/yihu/hos/broker/models/SystemCamelContext.java

@ -1,18 +0,0 @@
package com.yihu.hos.broker.models;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
/**
 * Created by lingfeng on 2016/8/9.
 */
public class SystemCamelContext {
    private static CamelContext context;
    public static CamelContext getContext() {
        if (context == null) {
            context = new DefaultCamelContext();
        }
        return context;
    }
}

+ 0 - 32
hos-broker/src/main/java/com/yihu/hos/broker/models/SystemClassMapping.java

@ -1,32 +0,0 @@
package com.yihu.hos.broker.models;
import com.yihu.hos.core.constants.CoreConstant;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
 * 加载的类文件列表
 * <p>
 * Created by lingfeng on 2016/8/4.
 */
public class SystemClassMapping {
    private static Map<String, String> mapping = new HashMap<>();
    public static Map<String, String> getMapping() {
        return mapping;
    }
    public static void put(String routeCode, String packageName, String className, String type) {
        mapping.put(routeCode + type + className, packageName + CoreConstant.DOT + className);
    }
    public static String get(String routeCode, String className, String type) {
        return mapping.get(routeCode + type + className);
    }
    public static URL getResource(Object o) {
        return o.getClass().getProtectionDomain().getClassLoader().getResource("");
    }
}

+ 0 - 71
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/CamelClassLoader.java

@ -1,71 +0,0 @@
package com.yihu.hos.broker.services.camel;
import com.yihu.hos.broker.common.constants.BrokerConstant;
import com.yihu.hos.core.constants.CoreConstant;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class CamelClassLoader extends ClassLoader {
    public CamelClassLoader(ClassLoader parent) {
        super(parent);
    }
    @SuppressWarnings("unchecked")
    public Class<?> loadClass(String classPath, String className)
            throws ClassNotFoundException {
        try {
            className = className + CoreConstant.DOT + BrokerConstant.CLASS;
            String url = classPathParser(classPath)
                    + classNameParser(className);
            URL myUrl = new URL(url);
            URLConnection connection = myUrl.openConnection();
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int data = input.read();
            while (data != -1) {
                buffer.write(data);
                data = input.read();
            }
            input.close();
            byte[] classData = buffer.toByteArray();
            return defineClass(noSuffix(className), classData, 0,
                    classData.length);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    private String pathParser(String path) {
        return path.replaceAll("\\\\", "/");
    }
    private String classPathParser(String path) {
        String classPath = pathParser(path);
        if (!classPath.startsWith("file:")) {
            classPath = "file:" + classPath;
        }
        if (!classPath.endsWith("/")) {
            classPath = classPath + "/";
        }
        return classPath;
    }
    private String classNameParser(String className) {
        return className.substring(0, className.lastIndexOf(".")).replaceAll(
                "\\.", "/")
                + className.substring(className.lastIndexOf("."));
    }
    private String noSuffix(String className) {
        return className.substring(0, className.lastIndexOf("."));
    }
}

+ 0 - 180
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/CamelCompiler.java

@ -1,14 +1,9 @@
package com.yihu.hos.broker.services.camel;
import com.yihu.hos.broker.common.constants.BrokerConstant;
import com.yihu.hos.broker.models.SystemClassMapping;
import com.yihu.hos.core.file.FileUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.util.GridFSUtil;
import javax.tools.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
@ -23,181 +18,6 @@ import java.util.List;
 */
public class CamelCompiler {
    private static final Logger logger = LoggerFactory.getLogger(CamelCompiler.class);
    private static String packagePathTemplate = System.getProperty("user.dir")//获取到项目的根路径
            + "/hos-broker/src/main/java/";
    private static String classPathTemplate = System.getProperty("user.dir")//获取到项目的根路径
            + "/hos-broker/src/main/java/%s/%s.java";
    /**
     * 编译java模板文件,生成class
     *
     * @param params 参数对象
     * @throws IOException
     */
    public static String genRouteClass(ClassParams params) throws IOException {
        String targetPath = CamelCompiler.class.getProtectionDomain().getCodeSource().getLocation().getPath();//项目class根目录
        String copyClassPath = params.getFilePath().replace(".java", ".class");//数据库保存的class路径
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        // 建立DiagnosticCollector对象
        DiagnosticCollector diagnostics = new DiagnosticCollector();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, Charset.forName("UTF-8"));
        // 建立源文件对象,根据java模板文件生成要加载的java类
        File loadJavaFile = genRouteJavaFile(params);
        if (loadJavaFile != null) {
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(loadJavaFile.getAbsolutePath());
            // options命令行选项
            Iterable<String> options = Arrays.asList("-d", targetPath, "-sourcepath", targetPath);// 指定的路径一定要存在,javac不会自己创建文件夹
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
            // 编译源程序
            boolean success = task.call();
            fileManager.close();
            System.out.println((success) ? "编译成功" : "编译失败");
            if (!success) {
                //错误信息打印
                List diagnostics1 = diagnostics.getDiagnostics();
                for (int i = 0; i < diagnostics1.size(); i++) {
                    System.out.println(diagnostics1.get(i).toString());
                }
                return null;
            } else {
                //添加加载类
                String dotPackageName = params.getPackageName().replace("/", "."); //将带“/"的包名转为”.";
                SystemClassMapping.getMapping().put(params.getRouteId() + BrokerConstant.ROUTE + params.getNewClassName(), dotPackageName + params.getNewClassName());
                String loadClassName = loadJavaFile.getName().replace(".java", ".class");
                targetPath = targetPath.substring(1);
                String loadClassPath = targetPath + params.getPackageName() + loadClassName;//加载的class路径
                copyClassPath = GridFSUtil.uploadFile("upload", loadClassPath, params.getFilePath().replace(".java", ".class"));
                return copyClassPath;
            }
        }
        return null;
    }
    /**
     * 根据java模板生成新的class文件
     *
     * @param routeId
     * @param filePath    java模板路径
     * @param packageName java模板包名
     * @param className   java模板类名
     * @return
     * @throws IOException
     */
    public static String genProcessClass(String routeId, String filePath, String packageName, String className) throws IOException {
        String targetPath = CamelCompiler.class.getProtectionDomain().getCodeSource().getLocation().getPath();//项目class根目录
        String copyClassPath = filePath.replace(".java", ".class");//管理端 数据库保存的class路径
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        // 建立DiagnosticCollector对象
        DiagnosticCollector diagnostics = new DiagnosticCollector();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, Charset.forName("UTF-8"));
        // 建立源文件对象,创建父文件夹
        File fPath = new File(packagePathTemplate + packageName);
        if (!fPath.exists()) fPath.mkdirs();
        File loadFIle = genProcessorJavaFile(routeId, filePath, packageName, className);
        if (loadFIle.exists()) {
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(loadFIle.getAbsolutePath());
            // options命令行选项
            Iterable<String> options = Arrays.asList("-d", targetPath, "-sourcepath", targetPath);// 指定的路径一定要存在,javac不会自己创建文件夹
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
            // 编译源程序
            boolean success = task.call();
            System.out.println((success) ? className + "编译成功" : className + "编译失败");
            fileManager.close();
            if (!success) {
                //失败信息打印
                List diagnostics1 = diagnostics.getDiagnostics();
                for (int i = 0; i < diagnostics1.size(); i++) {
                    System.out.println(diagnostics1.get(i).toString());
                }
                return null;
            } else {
                String dotPackageName = packageName.replace("/", ".");//将带“/"的包名转为”.";
                SystemClassMapping.getMapping().put(routeId + BrokerConstant.PROCESSOR + className, dotPackageName + className);
                String loadPath = loadFIle.getName().replace(".java", ".class");
                targetPath = targetPath.substring(1);
                String loadClassPath = targetPath + packageName + loadPath;//要加载的class路径
//                FileUtils.copyFile(new File(loadClassPath), new File(copyClassPath));
                copyClassPath = GridFSUtil.uploadFile("upload", loadClassPath, filePath.replace(".java", ".class"));
                return copyClassPath;
            }
        }
        System.out.println("生成processor的java文件失败");
        return null;
    }
    /**
     * 修改cron表达式,生成新java文件
     *
     * @param params 生成camel的参数
     */
    public static File genRouteJavaFile(ClassParams params) {
        try {
//            String oldPath = String.format(classPathTemplate, packageName, oldClassName);
            String newPath = String.format(classPathTemplate, params.getPackageName(), params.getOldClassName() + params.getRouteId());
            newPath = GridFSUtil.downFile("upload", newPath, params.getFilePath());
            String text = FileUtil.readFileText(new File(newPath));
            if (text.contains("?cron=")) {
                String oldStr = text.substring(text.indexOf("?cron=") + 6);
                String cron = oldStr.substring(0, oldStr.indexOf("\""));
                text = text.replace(cron, params.getCron());
            }
            //修改java类名
            if (text.contains(params.getOldClassName())) {
                text = text.replace(params.getOldClassName(), params.getNewClassName());
            }
            //修改routeId;模板规则 routeId("routeId")
            text = text.replace("routeId(\"routeId\")", "routeId(\"" + params.getRouteId() + "\")");
            File fPath = new File(packagePathTemplate + params.getPackageName());
            if (!fPath.exists()) fPath.mkdirs();
            File f = new File(newPath);
            boolean b = FileUtil.writeFile(newPath, text, "UTF-8");
//            FileWriter fw = new FileWriter(f);
//            fw.write(text);
//            fw.flush();
//            fw.close();//这里只是产生一个JAVA文件,简单的IO操作
            return f;
        } catch (Exception e) {
            System.out.println("修改Route文件操作出错");
            e.printStackTrace();
        }
        return null;
    }
    public static File genProcessorJavaFile(String routId, String filePath, String packageName, String className) {
        try {
            String newPath = String.format(classPathTemplate, packageName, className);
            newPath = GridFSUtil.downFile("upload", newPath, filePath);
            String text = FileUtil.readFileText(new File(newPath));
            File fPath = new File(packagePathTemplate + packageName);
            if (!fPath.exists()) fPath.mkdirs();
            File f = new File(newPath);
            boolean b = FileUtil.writeFile(newPath, text, "UTF-8");
//            FileWriter fw = new FileWriter(f);
//            fw.write(text);
//            fw.flush();
//            fw.close();//这里只是产生一个JAVA文件,简单的IO操作
            return f;
        } catch (Exception e) {
            System.out.println("撑撑processor文件操作出错");
            e.printStackTrace();
        }
        return null;
    }
    public static boolean compile(String sourcePath, String targetPath) throws IOException {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

+ 51 - 0
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/CamelStartBoot.java

@ -0,0 +1,51 @@
package com.yihu.hos.broker.services.camel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.SynchronousQueue;
/**
 * @author Airhead
 * @since 2016/12/9.
 */
public class CamelStartBoot {
    private static Logger logger = LogManager.getLogger(ESBCamelService.class);
    public void start() {
        logger.info("Apache Camel Context 启动...");
        try {
            SystemCamelContext.getContext().setTracing(true);
            SystemCamelContext.getContext().setUseMDCLogging(true);
            SystemCamelContext.getContext().start();
            List<URL> URLs = new ArrayList<>();
            ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
            ClassLoader camelClassLoader = new URLClassLoader(URLs.toArray(new URL[]{}), currentClassLoader);
            Thread.currentThread().setContextClassLoader(camelClassLoader);
            SystemCamelContext.getContext().setApplicationContextClassLoader(camelClassLoader);
            logger.info("Apache Camel Context 启动完成...");
            SynchronousQueue<String> camelContextOperateQueue = SystemCamelContext.getQueue();
            String className = null;
            // 如果没有收到其它线程的加载请求,主线程将停止在这里
            while ((className = camelContextOperateQueue.take()) != null) {
                Class<RouteBuilder> routeBuilderClass = (Class<RouteBuilder>) camelClassLoader.loadClass(className);
                if (routeBuilderClass != null) {
                    RouteBuilder routeBuilder = routeBuilderClass.newInstance();
                    SystemCamelContext.getContext().addRoutes(routeBuilder);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Apache Camel Context 启动失败...");
        }
    }
}

+ 0 - 66
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/ClassParams.java

@ -1,66 +0,0 @@
package com.yihu.hos.broker.services.camel;
/**
 *  请求参数封装类-(camel文件生成)
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/11/25.
 */
public class ClassParams {
    private String routeId;             //routeId
    private String filePath;            //文件名,用于mongodb存储获取
    private String packageName;        //包名
    private String oldClassName;      //旧java文件名
    private String newClassName;      //新java文件名
    private String cron;               //新cron表达式
    public String getRouteId() {
        return routeId;
    }
    public void setRouteId(String routeId) {
        this.routeId = routeId;
    }
    public String getFilePath() {
        return filePath;
    }
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
    public String getPackageName() {
        return packageName;
    }
    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }
    public String getOldClassName() {
        return oldClassName;
    }
    public void setOldClassName(String oldClassName) {
        this.oldClassName = oldClassName;
    }
    public String getNewClassName() {
        return newClassName;
    }
    public void setNewClassName(String newClassName) {
        this.newClassName = newClassName;
    }
    public String getCron() {
        return cron;
    }
    public void setCron(String cron) {
        this.cron = cron;
    }
}

+ 51 - 50
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/ESBCamelService.java

@ -3,16 +3,14 @@ package com.yihu.hos.broker.services.camel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.client.MongoDatabase;
import com.yihu.hos.broker.configurations.MongoConfiguration;
import com.yihu.hos.broker.models.SystemCamelContext;
import com.yihu.hos.broker.models.SystemClassMapping;
import com.yihu.hos.core.constants.CoreConstant;
import com.yihu.hos.core.datatype.ClassFileUtil;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.encrypt.DES;
import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.model.bo.ServiceFlow;
import com.yihu.hos.web.framework.util.GridFSUtil;
import org.apache.camel.builder.RouteBuilder;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
@ -56,24 +54,34 @@ public class ESBCamelService {
            if (serviceFlowValid.is()) return Result.error("必要的入参数据不正确,请检查!");
            ServiceFlow serviceFlow = serviceFlowValid.getServiceFlow();
            ServiceFlow.HandleFile handleFile = serviceFlowValid.getHandleFile();
            boolean created;
            if ("java".equals(handleFile.getFileType())) {
                created = this.generateClassFile(handleFile);
            } else {
                created = this.createClassFile(handleFile);
            }
            if (!created) {
                return Result.error("服务流程变更增加失败!");
            ArrayList<ServiceFlow.HandleFile> handleFiles = serviceFlowValid.getHandleFiles();
            for (ServiceFlow.HandleFile handleFile : handleFiles) {
                boolean created;
                if ("java".equals(handleFile.getFileType())) {
                    logger.debug("generate class file...");
                    created = this.generateClassFile(handleFile);
                } else {
                    logger.debug("create class file");
                    created = this.createClassFile(handleFile);
                }
                if (!created) {
                    logger.debug("create class file failed");
                    return Result.error("服务流程增加失败!");
                }
            }
            this.addRouter(handleFile);
            this.startRouter(serviceFlow.getRouteCode());
            logger.debug("add camel router" + serviceFlow.getRouteCode());
            this.addRouter(serviceFlow.getHandleFiles());
            return Result.error("服务流程变更增加成功!");
            logger.debug("start camel router," + serviceFlow.getRouteCode());
            SystemCamelContext.startRouter(serviceFlow.getRouteCode());
            logger.debug("start camel router success," + serviceFlow.getRouteCode());
            return Result.error("服务流程增加成功!");
        } catch (Exception e) {
            logger.error(e);
            return Result.error("服务流程变更增加失败!");
            return Result.error("服务流程增加失败!");
        }
    }
@ -97,10 +105,10 @@ public class ESBCamelService {
                return Result.error("服务流程变更增加失败!");
            }
            this.stopRouter(serviceFlow.getRouteCode());
            this.removeRouter(serviceFlow.getRouteCode());
            this.addRouter(handleFile);
            this.startRouter(serviceFlow.getRouteCode());
            SystemCamelContext.stopRouter(serviceFlow.getRouteCode());
            SystemCamelContext.removeRouter(serviceFlow.getRouteCode());
            this.addRouter(serviceFlowValid.getHandleFiles());
            SystemCamelContext.startRouter(serviceFlow.getRouteCode());
            return Result.error("服务流程变更增加成功!");
        } catch (Exception e) {
@ -123,8 +131,8 @@ public class ESBCamelService {
            SystemCamelContext.getContext().stopRoute(routeCode);
            SystemCamelContext.getContext().removeRoute(routeCode);
            this.deleteClassFile(handleFile);
            this.addRouter(handleFile);
            this.startRouter(serviceFlow.getRouteCode());
            this.addRouter(serviceFlowValid.getHandleFiles());
            SystemCamelContext.startRouter(serviceFlow.getRouteCode());
            return Result.success("服务流程变更减少成功!");
        } catch (Exception e) {
@ -171,14 +179,15 @@ public class ESBCamelService {
                if (!created) {
                    return Result.error("服务流程启动失败!");
                }
                this.addRouter(handleFile);
            }
            this.startRouter(serviceFlow.getRouteCode());
            this.addRouter(handleFiles);
            SystemCamelContext.startRouter(serviceFlow.getRouteCode());
            return Result.success("服务流程启动成功!");
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Result.error("服务流程启动失败!");
        }
    }
@ -204,8 +213,8 @@ public class ESBCamelService {
        if (handleFile == null) {
            return false;
        }
        SystemClassMapping.put(handleFile.getRouteCode(), handleFile.getPackageName(), handleFile.getClassName(), handleFile.getUsage());
        URL resource = SystemClassMapping.getResource(this);
        SystemCamelContext.putClassMapping(handleFile.getRouteCode(), handleFile.getPackageName(), handleFile.getUsage(), handleFile.getClassName());
        URL resource = SystemCamelContext.getResource(this);
        FileOutputStream outputStream = ClassFileUtil.createFile(resource, handleFile.getPackageName(), handleFile.getClassName(), ClassFileUtil.CLASS_FILE);
        String fileName = DES.decrypt(handleFile.getFilePath(), DES.COMMON_PASSWORD);
@ -223,8 +232,8 @@ public class ESBCamelService {
        if (handleFile == null) {
            return false;
        }
        SystemClassMapping.put(handleFile.getRouteCode(), handleFile.getPackageName(), handleFile.getClassName(), handleFile.getUsage());
        URL resource = SystemClassMapping.getResource(this);
        SystemCamelContext.putClassMapping(handleFile.getRouteCode(), handleFile.getPackageName(), handleFile.getUsage(), handleFile.getClassName());
        URL resource = SystemCamelContext.getResource(this);
        FileOutputStream outputStream = ClassFileUtil.createFile(resource, handleFile.getPackageName(), handleFile.getClassName(), ClassFileUtil.JAVA_FILE);
        String fileName = DES.decrypt(handleFile.getFilePath(), DES.COMMON_PASSWORD);
@ -242,7 +251,7 @@ public class ESBCamelService {
    }
    private void deleteClassFile(ServiceFlow.HandleFile handleFile) {
        String className = SystemClassMapping.get(handleFile.getRouteCode(), handleFile.getClassName(), handleFile.getUsage());
        String className = SystemCamelContext.getClassMapping(handleFile.getRouteCode(), handleFile.getClassName(), handleFile.getUsage());
        if (StringUtil.isEmpty(className)) {
            return;
        }
@ -259,37 +268,29 @@ public class ESBCamelService {
    }
    private void addRouter(ArrayList<ServiceFlow.HandleFile> handleFiles) throws Exception {
        ArrayList<ServiceFlow.HandleFile> routerFiles = new ArrayList<>();
        handleFiles.forEach(handleFile -> {
            try {
                addRouter(handleFile);
                if (handleFile.getUsage().equals(ServiceFlowConstant.FLOW_TYPE_ROUTE)) {
                    String className = SystemCamelContext.getClassMapping(handleFile.getRouteCode(), handleFile.getClassName(), handleFile.getUsage());
                    SystemCamelContext.getQueue().put(className);
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        });
    }
    private void addRouter(ServiceFlow.HandleFile handleFile) throws Exception {
        CamelClassLoader classLoader = new CamelClassLoader(CamelClassLoader.class.getClassLoader());
        String path = ClassLoader.getSystemResource(CoreConstant.EMPTY).getPath();
        String className = SystemClassMapping.get(handleFile.getRouteCode(), handleFile.getUsage(), handleFile.getClassName());
        Class<RouteBuilder> routeBuilderClass = (Class<RouteBuilder>) classLoader.loadClass(path, className);
        if (routeBuilderClass != null) {
            RouteBuilder routeBuilder = routeBuilderClass.newInstance();
            SystemCamelContext.getContext().addRoutes(routeBuilder);
        }
    }
        routerFiles.forEach(handleFile -> {
            try {
    private void startRouter(String routeCode) throws Exception {
        SystemCamelContext.getContext().startRoute(routeCode);
    }
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        });
    private void stopRouter(String routeCode) throws Exception {
        SystemCamelContext.getContext().stopRoute(routeCode);
    }
    private boolean removeRouter(String routeCode) throws Exception {
        return SystemCamelContext.getContext().removeRoute(routeCode);
    }
    private class ServiceFlowValid {

+ 59 - 0
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/SystemCamelContext.java

@ -0,0 +1,59 @@
package com.yihu.hos.broker.services.camel;
import com.yihu.hos.core.constants.CoreConstant;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.SynchronousQueue;
/**
 * Created by lingfeng on 2016/8/9.
 */
public class SystemCamelContext {
    private static CamelContext context;
    private static SynchronousQueue<String> queue = new SynchronousQueue<>();
    private static Map<String, String> mapping = new HashMap<>();
    public static Map<String, String> getMapping() {
        return mapping;
    }
    public static void putClassMapping(String routeCode, String packageName, String type, String className) {
        mapping.put(routeCode + "|" + type + "|" + className, packageName + CoreConstant.DOT + className);
    }
    public static String getClassMapping(String routeCode, String className, String type) {
        return mapping.get(routeCode + "|" + type + "|" + className);
    }
    public static URL getResource(Object o) {
        return o.getClass().getProtectionDomain().getClassLoader().getResource("");
    }
    public static CamelContext getContext() {
        if (context == null) {
            context = new DefaultCamelContext();
        }
        return context;
    }
    public static SynchronousQueue<String> getQueue() {
        return queue;
    }
    public static void startRouter(String routeCode) throws Exception {
        getContext().startRoute(routeCode);
    }
    public static void stopRouter(String routeCode) throws Exception {
        getContext().stopRoute(routeCode);
    }
    public static boolean removeRouter(String routeCode) throws Exception {
        return getContext().removeRoute(routeCode);
    }
}

+ 7 - 0
hos-broker/src/test/java/com/yihu/hos/HosBrokerApplicationTests.java

@ -1,7 +1,14 @@
package com.yihu.hos;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class HosBrokerApplicationTests {
    @Test

+ 70 - 0
hos-broker/src/test/java/com/yihu/hos/broker/services/camel/ESBCamelServiceTest.java

@ -1,14 +1,80 @@
package com.yihu.hos.broker.services.camel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.io.File;
import java.net.URI;
/**
 * @author Airhead
 * @since 2016/12/6.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class ESBCamelServiceTest {
    @Autowired
    private ESBCamelService esbCamelService;
    @Test
    public void onServiceFlowAdd() throws Exception {
    String msg="{\n" +
            "    \"routeCode\" : \"invokeSync\",\n" +
            "    \"updated\" : null,\n" +
            "    \"flowType\" : \"class\",\n" +
            "    \"handleFiles\" : [ \n" +
            "        {\n" +
            "            \"usage\" : \"processor\",\n" +
            "            \"packageName\" : \"apisync.processor\",\n" +
            "            \"className\" : \"ApiProcessor\",\n" +
            "            \"filePath\" : \"22241906357fac850e39df5dd74e7ddc4f1c6808019c571a98e96ad7e01a635afe687822969a785b523d97cbc5d33904b5296227c61c08bb\",\n" +
            "            \"fileType\" : \"class\",\n" +
            "            \"routeCode\" : \"invokeSync\"\n" +
            "        }, \n" +
            "        {\n" +
            "            \"usage\" : \"route\",\n" +
            "            \"packageName\" : \"apisync.route\",\n" +
            "            \"className\" : \"ApiRouteBulider\",\n" +
            "            \"filePath\" : \"89108d6cbec5e48ae19806476e1e946fb10e5656424326c288c69dcfda6a3add873b0c64959cb310e96e4cd4f3c0d627f82f813633c2f8ebe73a3fa3a83feb15\",\n" +
            "            \"fileType\" : \"class\",\n" +
            "            \"routeCode\" : \"invokeSync\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    esbCamelService.onServiceFlowAdd(msg);
    }
    @Test
    public void onServiceFlowModifyAdd() throws Exception {
    }
    @Test
    public void onServiceFlowModifyReduce() throws Exception {
    }
    @Test
    public void onServiceFlowDelete() throws Exception {
    }
    @Test
    public void onServiceFlowStart() throws Exception {
    }
    @Test
    public void onServiceFlowStop() throws Exception {
    }
    @Test
    public void onProcessorAdded() throws Exception {
        String url = this.getClass().getProtectionDomain().getClassLoader().getResource("").toString();
@ -18,6 +84,10 @@ public class ESBCamelServiceTest {
        String sysPath = systemClassFlowPath.toURI().toURL().toString();
        System.out.println(sysPath);
        URI uri = ESBCamelService.class.getResource("").toURI();
        File file  = new File("d:/usr");
        URI uri1 = file.toURI();
        uri1.toURL();
    }

+ 7 - 2
hos-core/src/main/java/com/yihu/hos/core/http/DefaultClientImpl.java

@ -89,11 +89,16 @@ class DefaultClientImpl implements HTTPClient {
    }
    @Override
    public HTTPResponse post(String url, String json) {
    public HTTPResponse post(String url, String json, Map<String, String> headers) {
        try {
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
            Request request = builder
                    .url(url)
                    .post(body)
                    .build();

+ 1 - 1
hos-core/src/main/java/com/yihu/hos/core/http/HTTPClient.java

@ -24,7 +24,7 @@ public interface HTTPClient {
    HTTPResponse post(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse post(String url, String json);
    HTTPResponse post(String url, String json, Map<String, String> headers);
    HTTPResponse postFile(String url, String path);

+ 5 - 1
hos-core/src/main/java/com/yihu/hos/core/http/HttpClientKit.java

@ -67,7 +67,11 @@ public class HttpClientKit {
    }
    public static HTTPResponse post(String url, String json) {
        return use().post(url, json);
        return use().post(url, json, null);
    }
    public static HTTPResponse post(String url, String json, Map<String, String> headers){
        return use().post(url, json, headers);
    }
    public static HTTPResponse post(String url, Map<String, String> params, Map<String, String> headers) {

+ 2 - 1
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ServiceFlowConstant.java

@ -6,7 +6,8 @@ package com.yihu.hos.web.framework.constant;
 */
public interface ServiceFlowConstant {
    //流程-队列名称
    String FLOW_QUEUE_NAME = "configuration.service.flow";
    String FLOW_EVENT_QUEUE = "configuration.service.flow";
    String FLOW_EVENT_ENDPOINT = "service.flow.event:queue:configuration.service.flow";
    //流程-模板类型
    String JAVA = "java";

+ 2 - 1
src/main/java/com/yihu/hos/ESBApplication.java

@ -1,5 +1,6 @@
package com.yihu.hos;
import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -16,6 +17,6 @@ public class ESBApplication {
    @Bean
    public Queue queue() {
        return new ActiveMQQueue("configuration.service.flow");
        return new ActiveMQQueue(ServiceFlowConstant.FLOW_EVENT_QUEUE);
    }
}

+ 2 - 99
src/main/java/com/yihu/hos/services/ServiceFlowEventService.java

@ -43,15 +43,7 @@ public class ServiceFlowEventService {
    /**
     * 当外界组件通知一个新的processor处理器被定义时,该事件被触发。
     *
     * @param serviceFlow 本次processor处理器变化,所涉及的服务流程Code标识。
     * @param packageName processor处理器定义涉及的class包名
     * @param className   processor处理器定义涉及的class类名
     * @param path        processor处理器定义涉及的class内容,如果zookeeper数据结构中class分片存储,在业务级接口层面上也进行了合并
     */
//    public void serviceFlowAdded(String serviceFlow, String packageName, String className, String path) {
//        sendMsg(ServiceFlowConstant.SERVICE_FLOW_ADDED, serviceFlow, packageName, className, path);
//    }
    public void serviceFlowAdded(ServiceFlow serviceFlow) {
        this.sendMsg(ServiceFlowConstant.SERVICE_FLOW_ADDED, serviceFlow);
    }
@ -59,17 +51,10 @@ public class ServiceFlowEventService {
    /**
     * 当外界组件通知一个已有的processor处理器data部分发生变化时,该事件被触发。
     */
//    public void serviceFlowModifiedAdd(String routeCode, String packageName, String className, String path) {
//        this.sendMsg(ServiceFlowConstant.SERVICE_FLOW_MODIFIED_ADD, routeCode, packageName, className, path);
//    }
    public void serviceFlowModifiedAdd(ServiceFlow serviceFlow) {
        this.sendMsg(ServiceFlowConstant.SERVICE_FLOW_MODIFIED_ADD, serviceFlow);
    }
//    public void serviceFlowModifiedReduce(String routeCode, String packageName, String className) {
//        this.sendMsg(ServiceFlowConstant.SERVICE_FLOW_MODIFIED_REDUCE, routeCode, packageName, className, null);
//
//    }
    public void serviceFlowModifiedReduce(ServiceFlow serviceFlow) {
        this.sendMsg(ServiceFlowConstant.SERVICE_FLOW_MODIFIED_REDUCE, serviceFlow);
@ -78,93 +63,11 @@ public class ServiceFlowEventService {
    /**
     * 当外界组件通知一个新的RouteDefine路由被定义时,该事件被触发
     */
//    public void serviceFlowDelete(String routeCode, String packageName, String className, String path) {
//        this.sendMsg(ServiceFlowConstant.SERVICE_FLOW_DELETED, routeCode, packageName, className, path);
//    }
    public void serviceFlowDelete(ServiceFlow serviceFlow) {
        this.sendMsg(ServiceFlowConstant.SERVICE_FLOW_DELETED, serviceFlow);
    }
//
//    /**
//     * 当外界组件通知一个已有的RouteDefine路由定义被改变时,主要就是路由定义内容被改变时,该事件被触发。
//     */
//    public void routeDefineChanged(String routeCode, String packageName, String className, String path) {
//        this.sendMsg(ServiceFlowConstant.ROUTE_DEFINE_CHANGED, routeCode, packageName, className, path);
//    }
//
//    public void routeDefineChanged(ServiceFlow serviceFlow) {
//        this.sendMsg(ServiceFlowConstant.ROUTE_DEFINE_CHANGED, serviceFlow);
//    }
//
//    /**
//     * 当外界组件通知一个已有的RouteDefine路由定义被删除时,该事件被触发。
//     */
//    public void routeDefineDelete(String routeCode, String packageName, String className) {
//        this.sendMsg(ServiceFlowConstant.ROUTE_DEFINE_DELETED, routeCode, packageName, className, null);
//    }
//
//    public void routeDefineDelete(ServiceFlow serviceFlow) {
//        this.sendMsg(ServiceFlowConstant.ROUTE_DEFINE_DELETED, serviceFlow);
//    }
//
//    public void routeClassAdded(String routeCode, String packageName, String className, String path, String cron) {
//        this.sendGenMsg(ServiceFlowConstant.ROUTE_CLASS_ADDED, routeCode, packageName, className, path, cron);
//    }
//
//    public void routeClassAdded(ServiceFlow serviceFlow) {
//        this.sendMsg(ServiceFlowConstant.ROUTE_CLASS_ADDED, serviceFlow);
//    }
//
//    public void routeClassChanged(String routeCode, String packageName, String className, String path, String cron) {
//        this.sendGenMsg(ServiceFlowConstant.ROUTE_CLASS_CHANGED, routeCode, packageName, className, path, cron);
//    }
//
//    public void routeClassChanged(ServiceFlow serviceFlow) {
//        this.sendMsg(ServiceFlowConstant.ROUTE_CLASS_CHANGED, serviceFlow);
//    }
//
//    public void processorClassAdded(String routeCode, String packageName, String className, String path) {
//        this.sendMsg(ServiceFlowConstant.PROCESSOR_CLASS_ADDED, routeCode, packageName, className, path);
//    }
//
//    public void processorClassAdded(ServiceFlow serviceFlow) {
//        this.sendMsg(ServiceFlowConstant.PROCESSOR_CLASS_ADDED, serviceFlow);
//    }
//
//    public void processorClassChanged(String routeCode, String packageName, String className, String path) {
//        this.sendMsg(ServiceFlowConstant.PROCESSOR_CLASS_CHANGED, routeCode, packageName, className, path);
//    }
//
//    public void processorClassChanged(ServiceFlow serviceFlow) {
//        this.sendMsg(ServiceFlowConstant.PROCESSOR_CLASS_CHANGED, serviceFlow);
//    }
//
//    private void sendMsg(String event, String routeCode, String packageName, String className, String path) {
//        ServiceFlow flow = new ServiceFlow();
//        flow.setRouteCode(routeCode);
//        ServiceFlow.HandleFile handleFile = new ServiceFlow.HandleFile();
//        handleFile.setPackageName(packageName);
//        handleFile.setClassName(className);
//        handleFile.setFilePath(path);
//        handleFile.setFileType(ServiceFlowConstant.CLASS);
//        handleFile.setRouteCode(routeCode);
//        flow.addHandleFile(handleFile);
//
//        this.sendMsg(event, flow);
//    }
//
//    private void sendGenMsg(String event, String routeCode, String packageName, String className, String path, String cron) {
//        ServiceFlow flow = new ServiceFlow();
//        flow.setRouteCode(routeCode);
//        ServiceFlow.HandleFile handleFile = new ServiceFlow.HandleFile();
//        handleFile.setPackageName(packageName);
//        handleFile.setClassName(className);
//        handleFile.setFilePath(path);
//        handleFile.setFileType(ServiceFlowConstant.JAVA);
//        handleFile.setRouteCode(routeCode);
//        flow.addHandleFile(handleFile);
//        this.sendMsg(event, flow);
//    }
    private void sendMsg(String event, ServiceFlow serviceFlow) {
        try {

+ 41 - 16
src/main/java/com/yihu/hos/system/service/FlowManager.java

@ -225,18 +225,49 @@ public class FlowManager implements IFlowManage {
        if (ServiceFlowConstant.CLASS.equals(obj.getFileType())) {
            List<SystemServiceFlowClass> flowClassList = obj.getFlowClassArray();
            ServiceFlow serviceFlow = new ServiceFlow();
            serviceFlow.setRouteCode(obj.getCode());
            serviceFlow.setFlowType(ServiceFlowConstant.CLASS);
            for (SystemServiceFlowClass flowClass : flowClassList) {
                flowClass.setFlowId(obj.getId());
                flowDao.saveEntity(flowClass);
                //发送消息到MQ对列
                sendUpdateMessage(obj.getCode(), flowClass, ServiceFlowConstant.FLOW_OP_ADD);
                ServiceFlow.HandleFile handleFile = new ServiceFlow.HandleFile();
                handleFile.setRouteCode(obj.getCode());
                handleFile.setFileType(ServiceFlowConstant.CLASS);
                handleFile.setPackageName(flowClass.getPackageName());
                handleFile.setClassName(flowClass.getClassName());
                handleFile.setFilePath(flowClass.getClassPath());
                handleFile.setUsage(flowClass.getType());
                serviceFlow.addHandleFile(handleFile);
            }
            serviceFlowEventService.serviceFlowAdded(serviceFlow);
        } else if (ServiceFlowConstant.JAVA.equals(obj.getFileType())) {
            List<SystemServiceFlowTemp> flowTempList = obj.getFlowTempArray();
//            ServiceFlow serviceFlow = new ServiceFlow();
//            serviceFlow.setRouteCode(obj.getCode());
//            serviceFlow.setFlowType(ServiceFlowConstant.JAVA);
            for (SystemServiceFlowTemp flowTemp : flowTempList) {
                flowTemp.setFlowId(obj.getId());
                flowDao.saveEntity(flowTemp);
//                ServiceFlow.HandleFile handleFile = new ServiceFlow.HandleFile();
//                handleFile.setRouteCode(obj.getCode());
//                handleFile.setFileType(ServiceFlowConstant.JAVA);
//                handleFile.setPackageName(flowTemp.getPackageName());
//                handleFile.setClassName(flowTemp.getClassName());
//                handleFile.setFilePath(flowTemp.getClassPath());
//                handleFile.setUsage(flowTemp.getType());
//                serviceFlow.addHandleFile(handleFile);
            }
//            serviceFlowEventService.serviceFlowAdded(serviceFlow);
        }
        return Result.success("保存成功");
@ -315,23 +346,17 @@ public class FlowManager implements IFlowManage {
    public Result deleteFlow(Integer id) throws Exception {
        SystemServiceFlow flow = flowDao.getEntity(SystemServiceFlow.class, id);
        List<SystemServiceFlowClass> flowClassList = flowClassDao.getFlowClassByFlowId(id);
        List<SystemServiceFlowClass> processorFlowClassList = new ArrayList<>();
        if (ServiceFlowConstant.JAVA.equals(flow.getFileType())) {
            flowTempDao.deleteFlowTempByFlowId(id);
        } else {
            for (SystemServiceFlowClass flowClass : flowClassList) {
                flowClassDao.deleteEntity(flowClass);
                flowClass.setIsUpdate("1");
                //发送消息到MQ对列
                if (flowClass.getType().equals(ServiceFlowConstant.FLOW_TYPE_ROUTE)) {
                    sendUpdateMessage(flow.getCode(), flowClass, ServiceFlowConstant.FLOW_OP_DELETE);
                } else {
                    processorFlowClassList.add(flowClass);
                }
            }
            for (SystemServiceFlowClass serviceFlowClass : processorFlowClassList) {
                sendUpdateMessage(flow.getCode(), serviceFlowClass, ServiceFlowConstant.FLOW_OP_DELETE);
            }
            ServiceFlow serviceFlow = new ServiceFlow();
            serviceFlow.setRouteCode(flow.getCode());
            serviceFlow.setFlowType(ServiceFlowConstant.CLASS);
            serviceFlowEventService.serviceFlowDelete(serviceFlow);
        }
        flowDao.deleteEntity(flow);
@ -435,11 +460,11 @@ public class FlowManager implements IFlowManage {
            serviceFlow.addHandleFile(handleFile);
            switch (operate) {
                case "add":
                case "update":
                case ServiceFlowConstant.FLOW_OP_ADD:
                case ServiceFlowConstant.FLOW_OP_UPDATE:
                    serviceFlowEventService.serviceFlowModifiedAdd(serviceFlow);
                    break;
                case "delete":
                case ServiceFlowConstant.FLOW_OP_DELETE:
                    serviceFlowEventService.serviceFlowModifiedReduce(serviceFlow);
                    break;
                default: