Browse Source

首次提交

huangzhiyong 6 years ago
parent
commit
590192054a
92 changed files with 1590918 additions and 0 deletions
  1. 6 0
      .gitignore
  2. 20 0
      hos-camel2/.gitignore
  3. 7 0
      hos-camel2/ReadMe.md
  4. 193 0
      hos-camel2/pom.xml
  5. 47 0
      hos-camel2/src/main/java/camel/HosCamelApplication.java
  6. 60 0
      hos-camel2/src/main/java/camel/central/archives/processor/ArchivesService.java
  7. 59 0
      hos-camel2/src/main/java/camel/central/archives/route/ArchivesRouterBuilder.java
  8. 53 0
      hos-camel2/src/main/java/camel/central/gateway/processor/ApiParam.java
  9. 149 0
      hos-camel2/src/main/java/camel/central/gateway/processor/AppApi.java
  10. 54 0
      hos-camel2/src/main/java/camel/central/gateway/processor/ErrorHandle.java
  11. 323 0
      hos-camel2/src/main/java/camel/central/gateway/processor/GatewayProcessor.java
  12. 60 0
      hos-camel2/src/main/java/camel/central/gateway/processor/ParamVerifyBean.java
  13. 86 0
      hos-camel2/src/main/java/camel/central/gateway/processor/SignProcessor.java
  14. 204 0
      hos-camel2/src/main/java/camel/central/gateway/route/GatewayRouterBuilder.java
  15. 19 0
      hos-camel2/src/main/java/camel/central/qlc/processor/Processor0.java
  16. 24 0
      hos-camel2/src/main/java/camel/central/qlc/processor/Processor1.java
  17. 26 0
      hos-camel2/src/main/java/camel/central/qlc/processor/Processor2.java
  18. 22 0
      hos-camel2/src/main/java/camel/central/qlc/route/QlcRouteBulider.java
  19. 171 0
      hos-camel2/src/main/java/camel/central/webservice/processor/WsProcessor.java
  20. 32 0
      hos-camel2/src/main/java/camel/central/webservice/processor/WsService.java
  21. 33 0
      hos-camel2/src/main/java/camel/central/webservice/route/WsGatewayRouterBuilder.java
  22. 112 0
      hos-camel2/src/main/java/camel/config/BeanConfig.java
  23. 14 0
      hos-camel2/src/main/java/camel/demo/api1/processor/ApiProcessor.java
  24. 32 0
      hos-camel2/src/main/java/camel/demo/api1/route/ApiRouteBulider.java
  25. 14 0
      hos-camel2/src/main/java/camel/demo/api7/processor/ApiProcessor.java
  26. 20 0
      hos-camel2/src/main/java/camel/demo/api7/processor/TestClient.java
  27. 32 0
      hos-camel2/src/main/java/camel/demo/api7/processor/TestWService.java
  28. 37 0
      hos-camel2/src/main/java/camel/demo/api7/processor/TestWsConfig.java
  29. 124 0
      hos-camel2/src/main/java/camel/demo/api7/processor/ToWsProcessor.java
  30. 13 0
      hos-camel2/src/main/java/camel/demo/api7/route/ApiRouteBulider.java
  31. 34 0
      hos-camel2/src/main/java/camel/demo/api7/route/CxfConsumerTest.java
  32. 59 0
      hos-camel2/src/main/java/camel/demo/jdbcdemo/processor/JdbcProcessor.java
  33. 135 0
      hos-camel2/src/main/java/camel/demo/jdbcdemo/route/ApiRouteBulider.java
  34. 20 0
      hos-camel2/src/main/java/camel/demo/quartz2/processor/Quartz2Processor.java
  35. 11 0
      hos-camel2/src/main/java/camel/demo/quartz2/route/Quartz2Route.java
  36. 21 0
      hos-camel2/src/main/java/camel/log/JmsAppender.java
  37. 66 0
      hos-camel2/src/main/java/camel/log/TracerFormatter.java
  38. 52 0
      hos-camel2/src/main/java/camel/monitor/processor/LogOffset.java
  39. 143 0
      hos-camel2/src/main/java/camel/monitor/processor/MonitorService.java
  40. 36 0
      hos-camel2/src/main/java/camel/monitor/route/MonitorRouter.java
  41. 16 0
      hos-camel2/src/main/java/camel/terminal/collect/processor/CollectProcessor0.java
  42. 12 0
      hos-camel2/src/main/java/camel/terminal/collect/route/CollectQuartzRoute.java
  43. 19 0
      hos-camel2/src/main/java/camel/terminal/crawler/processor/Aggregate.java
  44. 32 0
      hos-camel2/src/main/java/camel/terminal/crawler/processor/AggregateProcessor.java
  45. 35 0
      hos-camel2/src/main/java/camel/terminal/crawler/processor/DefaultHttpProcessor.java
  46. 19 0
      hos-camel2/src/main/java/camel/terminal/crawler/processor/HttpProcessor.java
  47. 13 0
      hos-camel2/src/main/java/camel/terminal/crawler/processor/Split.java
  48. 19 0
      hos-camel2/src/main/java/camel/terminal/crawler/route/CrawlerQuartzRoute.java
  49. 31 0
      hos-camel2/src/main/java/camel/terminal/crawler/route/CrawlerRouteBulider.java
  50. 25 0
      hos-camel2/src/main/java/camel/terminal/crawler/route/QuartzRoute.java
  51. 23 0
      hos-camel2/src/main/java/camel/terminal/crawler/route/RouteBulider1.java
  52. 20 0
      hos-camel2/src/main/java/camel/terminal/qcrule/processor/PatientProcessor.java
  53. 159 0
      hos-camel2/src/main/java/camel/terminal/qcrule/processor/QcHttpProcessor.java
  54. 63 0
      hos-camel2/src/main/java/camel/terminal/qcrule/router/QcCrawlerRoute.java
  55. 32 0
      hos-camel2/src/main/java/camel/terminal/tenant/processor/AddMongoProcessor.java
  56. 31 0
      hos-camel2/src/main/java/camel/terminal/tenant/processor/CrawlerMongoProcessor.java
  57. 39 0
      hos-camel2/src/main/java/camel/terminal/tenant/route/CrawlerMongoRouter.java
  58. 44 0
      hos-camel2/src/main/resources/application.yml
  59. 8 0
      hos-camel2/src/main/resources/jndi.properties
  60. 60 0
      hos-camel2/src/main/resources/logback-spring.xml
  61. BIN
      hos-camel2/src/main/resources/tomcat.keystore
  62. 19 0
      hos-camel2/src/test/java/camel/SpringbootApplicationTests.java
  63. 20 0
      hos-docker/.gitignore
  64. 13 0
      hos-docker/Dockerfile
  65. BIN
      hos-docker/esb/activemq/apache-activemq-5.14.0-bin.tar.gz
  66. 141 0
      hos-docker/pom.xml
  67. 39 0
      hos-docker/readme.md
  68. 14 0
      hos-docker/src/main/docker/Dockerfile
  69. 6 0
      hos-docker/src/main/esb/activemq/Dockerfile
  70. 68 0
      hos-docker/src/main/esb/central-docker-compose/docker-compose.yml
  71. 54 0
      hos-docker/src/main/esb/docker-compose.yml
  72. 9 0
      hos-docker/src/main/esb/hos-arbiter/Dockerfile
  73. 1 0
      hos-docker/src/main/esb/hos-arbiter/jar/remind.txt
  74. 12 0
      hos-docker/src/main/esb/hos-broker/Dockerfile
  75. BIN
      hos-docker/src/main/esb/hos-broker/apache-tomcat-8.5.11.tar.gz
  76. 1 0
      hos-docker/src/main/esb/hos-broker/jar/remind.txt
  77. 14 0
      hos-docker/src/main/esb/hos-dfs/Dockerfile
  78. 10 0
      hos-docker/src/main/esb/hos-rest/Dockerfile
  79. 1 0
      hos-docker/src/main/esb/hos-rest/jar/remind.txt
  80. 3 0
      hos-docker/src/main/esb/mongodb/Dockerfile
  81. 11 0
      hos-docker/src/main/esb/mongodb/fit_mongo1.js
  82. 11 0
      hos-docker/src/main/esb/mongodb/fit_mongo2.js
  83. 10 0
      hos-docker/src/main/esb/mysql/Dockerfile
  84. 1586821 0
      hos-docker/src/main/esb/mysql/data.sql
  85. 4 0
      hos-docker/src/main/esb/mysql/mysql.cnf
  86. 3 0
      hos-docker/src/main/esb/mysql/user.sql
  87. 27 0
      hos-docker/src/main/esb/start.sh
  88. 21 0
      hos-docker/src/main/java/com/yihu/hos/central/controller/DemoController.java
  89. 166 0
      hos-docker/src/main/java/com/yihu/hos/central/model/InpatientIdex.java
  90. 69 0
      hos-docker/src/main/java/com/yihu/hos/central/service/event/DemoEvent.java
  91. 9 0
      hos-docker/src/main/java/com/yihu/hos/central/service/event/InpatientOutEvent.java
  92. 18 0
      hos-docker/src/main/resources/application.yml

+ 6 - 0
.gitignore

@ -9,6 +9,12 @@
*.war
*.ear
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

+ 20 - 0
hos-camel2/.gitignore

@ -0,0 +1,20 @@
# ---> Java
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

+ 7 - 0
hos-camel2/ReadMe.md

@ -0,0 +1,7 @@
# hos-camel2
Spring的Camel项目,用于直接执行流程,而不需要用走admin上传流程,broker执行的流程,简化开发过程。
## 目录结构
根据场景和业务添加文件夹;业务需要有两个文件夹processor和route,processor文件夹主要放置流程相关的一些业务和方法,route中放置主体的流程代码
## 编码规范
1. route中使用 ModelCamelContext 添加组件时,需要先做 removeComponent(String componentName) 操作,防止更新流程时,与旧流程添加的组件冲突而导致流程启动失败
2. 

+ 193 - 0
hos-camel2/pom.xml

@ -0,0 +1,193 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yihu.hos</groupId>
        <artifactId>ehr-eip</artifactId>
        <version>1.3.0</version>
        <relativePath>../../pom.xml</relativePath>
        <!-- lookup parent from repository -->
    </parent>
    <artifactId>hos-camel2</artifactId>
    <name>hos-camel2</name>
    <dependencyManagement>
        <dependencies>
            <!-- import Spring Boot before Camel -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- import Camel -->
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-parent</artifactId>
                <version>${camel-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-netflix</artifactId>
                <version>1.2.6.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <!-- spring-boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- camel -->
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring-boot-starter</artifactId>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>com.yihu.hos</groupId>-->
            <!--<artifactId>hos-core</artifactId>-->
            <!--<version>1.3.0</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jetty</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-restlet</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jms</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-quartz</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-stream</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-cxf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-http4</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http-jetty</artifactId>
            <version>3.1.10</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.hos</groupId>
            <artifactId>hos-web-framework</artifactId>
            <version>${hos-version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-data-jpa</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>api-dict</artifactId>
            <version>1.6.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>core-rpc</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>api-config</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>core-db</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>
    </dependencies>
</project>

+ 47 - 0
hos-camel2/src/main/java/camel/HosCamelApplication.java

@ -0,0 +1,47 @@
package camel;
import camel.log.TracerFormatter;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.processor.interceptor.Tracer;
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.cloud.netflix.eureka.EnableEurekaClient;
/**
 * Basic Spring Boot application.
 */
@EnableEurekaClient
@SpringBootApplication
//        (exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class HosCamelApplication implements CommandLineRunner {
    @Autowired
    private CamelContext context;
    public static void main(String[] args) {
        SpringApplication.run(HosCamelApplication.class, args);
    }
    @Override
    public void run(String... strings) throws Exception {
        context.setUseMDCLogging(true);
        context.setTracing(true);
        Tracer tracer = new Tracer();
        TracerFormatter formatter = new TracerFormatter();
        formatter.setShowHeaders(true);
        formatter.setShowBody(true);
        formatter.setShowBodyType(true);
        formatter.setShowOutHeaders(true);
        formatter.setShowOutBody(true);
        formatter.setShowOutBodyType(true);
        tracer.setFormatter(formatter);
        context.addInterceptStrategy(tracer);
        context.getGlobalOptions().put(Exchange.LOG_DEBUG_BODY_STREAMS, "true");
        context.getGlobalOptions().put(Exchange.BEAN_MULTI_PARAMETER_ARRAY, "true");
    }
}

+ 60 - 0
hos-camel2/src/main/java/camel/central/archives/processor/ArchivesService.java

@ -0,0 +1,60 @@
package camel.central.archives.processor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.IOException;
/**
 * 数据入库
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/06/26.
 */
@Component
public class ArchivesService {
    private static final Logger logger = LoggerFactory.getLogger(ArchivesService.class);
    private ObjectMapper objectMapper = new ObjectMapper();
    public void bodyValue(Exchange exchange) {
        Message in = exchange.getIn();
        String body = in.getBody(String.class);
        System.out.println("入库解析结果:"+body);
//        exchange.getOut().setBody(body);
    }
    //入库服务参数设置
    public void storageArchive(Exchange exchange) {
        Message in = exchange.getIn();
        String body = in.getBody(String.class);
        if (!StringUtils.isEmpty(body)){
            try {
                ObjectNode objectNode = objectMapper.readValue(body,ObjectNode.class);
                String packageId = objectNode.get("id").asText();
                String clientId = objectNode.get("clientId").asText();
                String query = "&packageId="+packageId+"&clientId="+clientId+"&echo="+false;
                exchange.getOut().setHeader(Exchange.REST_HTTP_QUERY,query);
                System.out.println("入库参数:"+query);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("上传档案失败处理,body: "+exchange.getIn().getBody(String.class));
        }
    }
//    public static void main(String[] args) throws Exception {
//        String value= MD5.getMd5ByFile(new File("E:\\test\\可使用包\\dc3ec66729fef8f1311f247a34fa7e_4.zip"));
//        System.out.println(value);
//    }
}

+ 59 - 0
hos-camel2/src/main/java/camel/central/archives/route/ArchivesRouterBuilder.java

@ -0,0 +1,59 @@
package camel.central.archives.route;
import com.yihu.hos.web.framework.constant.ArchivesConstant;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jms.JmsComponent;
import org.apache.camel.model.ModelCamelContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.jms.ConnectionFactory;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/3/13.
 */
@Component
public class ArchivesRouterBuilder extends RouteBuilder {
    @Value("${spring.activemq.broker-url}")
    private String brokerURL;
    @Value("${spring.activemq.user}")
    private String user;
    @Value("${spring.activemq.password}")
    private String password;
    @Override
    public void configure() throws Exception {
        ModelCamelContext context = this.getContext();
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                "user", "admin", "tcp://172.19.103.42:61616");
        // Note we can explicit name the component
        context.removeComponent(ArchivesConstant.CAMEL_COMPONENT);
        context.addComponent(ArchivesConstant.CAMEL_COMPONENT, JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
        from("jetty:http://0.0.0.0:9999/api/datasetPackages?enableMultipartFilter=false").routeId("datasetUpload2")
//                .bean(ArchivesService.class,"bodyValue")
//                .removeHeaders("CamelHttp*")
//                .to("http4://192.168.131.106:10140/api/v1.0/datasetPackages?bridgeEndpoint=true&throwExceptionOnFailure=false")//上传档案
                .to("jetty:http://192.168.1.221:10140/api/v1.0/datasetPackages?bridgeEndpoint=true&throwExceptionOnFailure=false")//上传档案
                .choice()
                .when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo("200")).to(ExchangePattern.InOnly, ArchivesConstant.CAMEL_ENDPOINT)//成功:发送入库消息
                .otherwise().log("上传失败").to("stream:out")
                .endChoice()
        ;
        //入库请求(消费MQ消息,发送入库接口请求)
        from(ArchivesConstant.CAMEL_ENDPOINT)
                .to("bean:archivesService?method=storageArchive")//参数设置
                .to("restlet:http://192.168.1.221:10170/api/v1.0/datasetPackages/resolve?restletMethod=PUT")
//                .to("bean:archivesService?method=bodyValue")//返回值
        ;
    }
}

+ 53 - 0
hos-camel2/src/main/java/camel/central/gateway/processor/ApiParam.java

@ -0,0 +1,53 @@
package camel.central.gateway.processor;
/**
 * @author Airhead
 * @since 2017/3/17.
 */
public class ApiParam {
    private String name;
    private String type;
    private String dataType;
    private String required;
    private String defaultValue;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getDataType() {
        return dataType;
    }
    public void setDataType(String dataType) {
        this.dataType = dataType;
    }
    public String getRequired() {
        return required;
    }
    public void setRequired(String required) {
        this.required = required;
    }
    public String getDefaultValue() {
        return defaultValue;
    }
    public void setDefaultValue(String defaultValue) {
        this.defaultValue = defaultValue;
    }
}

+ 149 - 0
hos-camel2/src/main/java/camel/central/gateway/processor/AppApi.java

@ -0,0 +1,149 @@
package camel.central.gateway.processor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
/**
 * @author Airhead
 * @since 2017/3/15.
 */
public class AppApi {
    private String name;
    private String type;
    private String method;
    private String protocol;
    private String version;
    private String methodName;
    private String microServiceUri;
    private String msMethodName;
    private String microServiceName;
    private Collection<ApiParam> parameters;
    public AppApi() {
    }
    public static AppApi parse(String apiInfo) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readValue(apiInfo, JsonNode.class);
        JsonNode detailModelList = jsonNode.get("detailModelList");
        if (detailModelList != null && detailModelList.isArray() && detailModelList.size() != 0) {
            JsonNode apiNode = detailModelList.get(0);
            AppApi appApi = new AppApi();
            appApi.setName(apiNode.path("name").asText());
            appApi.setType(apiNode.path("type").asText());
            appApi.setMethod(apiNode.path("method").asText());
            appApi.setProtocol(apiNode.path("protocol").asText());
            appApi.setVersion(apiNode.path("version").asText());
            appApi.setMethodName(apiNode.path("methodName").asText());
            appApi.setMicroServiceUri(apiNode.path("microServiceUri").asText());
            appApi.setMsMethodName(apiNode.path("msMethodName").asText());
            appApi.setMethodName(apiNode.path("methodName").asText());
            appApi.setMicroServiceName(apiNode.path("microServiceName").asText());
            JsonNode parametersNode = apiNode.get("parameters");
            Collection<ApiParam> parameters = new ArrayList<>();
            if (parametersNode != null && parametersNode.size() != 0) {
                parametersNode.forEach(paramNode -> {
                    ApiParam apiParam = new ApiParam();
                    apiParam.setName(paramNode.path("name").asText());
                    apiParam.setType(paramNode.path("type").asText());
                    apiParam.setDataType(paramNode.path("dataType").asText());
                    apiParam.setDefaultValue(paramNode.path("defaultValue").asText());
                    parameters.add(apiParam);
                });
            }
            appApi.setParameters(parameters);
            return appApi;
        }
        return null;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getMethod() {
        return method;
    }
    public void setMethod(String method) {
        this.method = method;
    }
    public String getProtocol() {
        return protocol;
    }
    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    public String getMethodName() {
        return methodName;
    }
    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }
    public String getMicroServiceUri() {
        return microServiceUri;
    }
    public void setMicroServiceUri(String microServiceUri) {
        this.microServiceUri = microServiceUri;
    }
    public String getMsMethodName() {
        return msMethodName;
    }
    public void setMsMethodName(String msMethodName) {
        this.msMethodName = msMethodName;
    }
    public String getMicroServiceName() {
        return microServiceName;
    }
    public void setMicroServiceName(String microServiceName) {
        this.microServiceName = microServiceName;
    }
    public Collection<ApiParam> getParameters() {
        return parameters;
    }
    public void setParameters(Collection<ApiParam> parameters) {
        this.parameters = parameters;
    }
}

+ 54 - 0
hos-camel2/src/main/java/camel/central/gateway/processor/ErrorHandle.java

@ -0,0 +1,54 @@
package camel.central.gateway.processor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.camel.Exchange;
import org.springframework.stereotype.Component;
/**
 * @author Airhead
 * @since 2017/3/17.
 */
@Component("errorHandle")
public class ErrorHandle {
    private ObjectMapper objectMapper = new ObjectMapper();
    public void paramError(Exchange exchange) {
        exchange.getOut().setHeader("errorCode", "{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"paramError!\",\"errorCode\":10000}");
        exchange.getOut().setBody("{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"paramError!\",\"errorCode\":10000}");
    }
    public void outdateError(Exchange exchange) {
        exchange.getOut().setHeader("errorCode", "{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"outdateError!\",\"errorCode\":0}");
        exchange.getOut().setBody("{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"outdateError!\",\"errorCode\":0}");
    }
    public void signValidError(Exchange exchange) {
        exchange.getOut().setHeader("errorCode", "{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"signValidError!\",\"errorCode\":10007}");
        exchange.getOut().setBody("{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"signValidError!\",\"errorCode\":10007}");
    }
    public void unauthorizedError(Exchange exchange) {
        exchange.getOut().setHeader("errorCode", "{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"unauthorizedError!\",\"errorCode\":0}");
        exchange.getOut().setBody("{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"unauthorizedError!\",\"errorCode\":0}");
    }
    public String paramError() {
        return "{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"paramError!\",\"errorCode\":10000}";
    }
    public String outdateError() {
        return "{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"outdateError!\",\"errorCode\":0}";
    }
    public String signValidError() {
        return "{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"signValidError!\",\"errorCode\":10007}";
    }
    public String unauthorizedError() {
        return "{\"successFlg\":false,\"pageSize\":10,\"currPage\":0,\"totalPage\":0,\"totalCount\":0,\"detailModelList\":null,\"obj\":null,\"errorMsg\":\"unauthorizedError!\",\"errorCode\":0}";
    }
}

+ 323 - 0
hos-camel2/src/main/java/camel/central/gateway/processor/GatewayProcessor.java

@ -0,0 +1,323 @@
package camel.central.gateway.processor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.http.HTTPResponse;
import com.yihu.hos.core.http.HttpClientKit;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class GatewayProcessor implements Processor {
        static final String agUrl = "http://192.168.220.84:10000";
    static final String brokerUrl = "http://192.168.200.62:8099";
//    static final String agUrl = "http://172.19.103.73:10000";
//    static final String brokerUrl = "http://10.176.97.14:8099";
    static Map<String, AppApi> apiMap = new HashMap<>();
    @Autowired
    private DiscoveryClient discoveryClient;
    private ErrorHandle errorHandle = new ErrorHandle();
    public void process(Exchange exchange) throws Exception {
    }
    public String route(Exchange exchange) throws Exception {
        System.out.println("进入同一网关route流程!");
//        body = URLDecoder.decode(body, "UTF-8");
        Map<String, Object> params = exchange.getIn().getHeaders();
        if (params.get("appKey") == null) {
            exchange.getOut().setHeader(Exchange.HTTP_URI, "paramError");
            System.out.println("进入route:appKey is null ");
            return errorHandle.paramError();
        }
        String appKey = params.get("appKey").toString();
        String secret = getSecret(appKey);
        if (secret.equals("")) {
            exchange.getOut().setHeader(Exchange.HTTP_URI, "paramError");
            System.out.println("appKey 获取到的secret是空的  ");
            return errorHandle.paramError();
        }
        boolean pass = checkParams(params);
        if (!pass) {
            exchange.getOut().setHeader(Exchange.HTTP_URI, "paramError");
            System.out.println("a参数校验失败  "+ params);
            return errorHandle.paramError();
        }
        pass = checkTimeStamp(params);
        if (!pass) {
            exchange.getOut().setHeader(Exchange.HTTP_URI, "outdateError");
            return errorHandle.outdateError();
        }
        //获取secret接口,不做sign验证
        if (!"admin.apps.get".equals(params.get("api"))) {
            pass = checkSign(params, secret);
            if (!pass) {
                exchange.getOut().setHeader(Exchange.HTTP_URI, "signValidError");
                return errorHandle.signValidError();
            }
        }
        pass = checkAuthorized(params);
        if (!pass) {
            exchange.getOut().setHeader(Exchange.HTTP_URI, "unauthorizedError");
            return errorHandle.unauthorizedError();
        }
        return handle(params, exchange);
    }
    /**
     * 通过服务名获取微服务地址
     *
     * @param serviceName 微服务名
     * @return
     */
    public String serviceUrl(String serviceName) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        if (instances != null && !instances.isEmpty()) {
            int index = (int) (Math.random() * instances.size());   //随机获取其中一个服务
            ServiceInstance serviceInstance = instances.get(index);
            return serviceInstance.getUri().toString();
        } else {
            return null;
        }
    }
    public String nodeValue(JsonNode node) {
        Object value = null;
        try {
            switch (node.getNodeType().name()) {
                case "NUMBER":
                    value = node.asInt();
                    break;
                case "STRING":
                    value = node.asText();
                    break;
                case "BOOLEAN":
                    value = node.asBoolean();
                    break;
                case "OBJECT":
                    value = node.toString();
                    break;
                default:
                    value = "";
                    break;
            }
            return URLEncoder.encode(value.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }
    private boolean checkParams(Map<String, Object> params) {
        Object api = params.get("api");                     // API接口名称
        Object sign = params.get("sign");                     // 簽名
        Object timestamp = params.get("timestamp");        // 时间戳
        Object appKey = params.get("appKey");               // HOP分配给应用的AppKey ,创建应用时可获得
        Object version = params.get("v");                   // API协议版本
        StringBuilder sb = new StringBuilder();
        sb.append("api:").append(api)
                .append(",sign:").append(sign)
                .append(",timestamp:").append(timestamp)
                .append(",appKey:").append(appKey)
                .append(",v").append(version);
        System.out.println("检查参数,"+ sb.toString());
        return !(StringUtil.isEmpty(api) || StringUtil.isEmpty(timestamp)
                || StringUtil.isEmpty(appKey) || StringUtil.isEmpty(version)
                || StringUtil.isEmpty(sign));
    }
    private boolean checkTimeStamp(Map<String, Object> params) throws ParseException {
        final long ONE_MIN = 60000; //millisecond
        String timestamp = params.get("timestamp").toString();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        java.util.Date ts = format.parse(timestamp);
        if (ts == null) {
            return false;   //时间格式不正确
        }
        Calendar date = Calendar.getInstance();
        long timeInMillis = date.getTimeInMillis();
        java.util.Date min = new java.util.Date(timeInMillis - 30 * ONE_MIN);
        java.util.Date max = new java.util.Date(timeInMillis + 30 * ONE_MIN);
        return ts.after(min) && ts.before(max);
    }
    private boolean checkSign(Map<String, Object> params, String secret) {
        try {
            String sign = params.get("sign").toString();                     // 簽名
            ParamVerifyBean paramSign = new ParamVerifyBean();
            paramSign.addParam(params);
//            paramSign.genParam();
            //TODO 获取app secret传入验证
            String md5Sign = paramSign.signParam(secret);
            if (!md5Sign.equals(sign)) {
                System.out.println("传递的签名:" + sign);
                System.out.println("生成的签名:" + md5Sign);
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    private boolean checkAuthorized(Map<String, Object> params) {
        ObjectMapper objectMapper = new ObjectMapper();
        //TODO 设置固定的验证入口地址
        HTTPResponse response = HttpClientKit.get(agUrl + "/api/v1.0/admin/appApiAuth?appId=" + params.get("appKey") + "&apiName=" + params.get("api"));
        if (response.getStatusCode() != 200) {
            System.out.println("验证API权限,请求失败!");
            return false;
        }
        try {
            Map map = objectMapper.readValue(response.getBody(), Map.class);
            if ((Boolean) map.get("successFlg")) {
                return true;
            } else {
                System.out.println("验证失败:" + map.get("errorMsg"));
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    private String handle(Map<String, Object> params, Exchange exchange) {
        String api = params.get("api").toString();                     // API接口名称
        String param = params.get("param").toString();
        AppApi appApi = getApiInfo(api);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (appApi == null) {
                return "appApi is null";
            }
            Map<String, String> methodMap = new HashMap<>();
            methodMap.put("0", "get");
            methodMap.put("1", "post");
            methodMap.put("2", "delete");
            methodMap.put("3", "put");
            JsonNode jsonNode = objectMapper.readValue(param, JsonNode.class);
            String url = appApi.getMicroServiceUri();
            final String[] endPoint = {"restlet:" + url + appApi.getMsMethodName() + "?socketTimeout=60000&connectionTimeout=60000&restletMethod=" + methodMap.get(appApi.getMethod())};
            final String[] body = {""};
            appApi.getParameters().forEach(p -> {
                System.out.println(p.getName());
                JsonNode paramNode = jsonNode.get(p.getName());
                System.out.println(paramNode);
                if (paramNode == null) {
                    return;
                }
                Object value = nodeValue(paramNode);
                if (p.getType().equals("0")) { //path param
                    endPoint[0] = endPoint[0].replaceAll("\\{[^}]*\\}", value.toString());
                } else if (p.getType().equals("2")) { //head param
                    exchange.getOut().setHeader(p.getName(), value);
                } else {
                    body[0] += ("&" + p.getName() + "=" + value);
                }
            });
            CamelContext context = exchange.getContext();
            ProducerTemplate producerTemplate = context.createProducerTemplate();
            return producerTemplate.requestBody(endPoint[0], body[0], String.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    private AppApi getApiInfo(String api) {
        AppApi appApi = apiMap.get(api);
        if (appApi != null) {
            return appApi;
        }
        HTTPResponse response = HttpClientKit.get(agUrl + "/api/v1.0/admin/appApi/search?filters=methodName%3D" + api + "&size=15&page=1");
        if (response.getStatusCode() != 200) {
            return null;
        }
        try {
            appApi = AppApi.parse(response.getBody());
            apiMap.put(api, appApi);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return appApi;
    }
    private String getSecret(String appKey) {
        ObjectMapper objectMapper = new ObjectMapper();
        //TODO 设置固定的验证入口地址
        HTTPResponse response = HttpClientKit.get(agUrl + "/api/v1.0/admin/apps/" + appKey);
        if (response.getStatusCode() != 200) {
            System.out.println("获取app的secret请求失败,status: " + response.getStatusCode() + "error: " + response.getBody());
            return "";
        }
        try {
            Map map = objectMapper.readValue(response.getBody(), Map.class);
            if ((Boolean) map.get("successFlg")) {
                Map<String, Object> obj = (Map) map.get("obj");
                if (obj == null) {
                    return "";
                }
                String secret = obj.get("secret").toString();
                return secret;
            } else {
                System.out.println("验证失败:" + map.get("errorMsg"));
                return "";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}

+ 60 - 0
hos-camel2/src/main/java/camel/central/gateway/processor/ParamVerifyBean.java

@ -0,0 +1,60 @@
package camel.central.gateway.processor;
import com.yihu.hos.core.encrypt.MD5;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/3/15.
 */
public class ParamVerifyBean {
    private final String version = "1.0";
    private TreeMap<String, String> paramMap = new TreeMap<>();
    public void addParam(Map<String, Object> params) throws Exception {
        if (params != null) {
            params.remove("sign");
            paramMap.put("api", params.get("api").toString());
            paramMap.put("v", params.get("v").toString());
            paramMap.put("timestamp", params.get("timestamp").toString());
            paramMap.put("param", params.get("param").toString());
            paramMap.put("appKey", params.get("appKey").toString());
        } else {
            return;
        }
    }
    /**
     * sign 签名生成  (   md5(secret + params拼接字符串 + secret)   )
     *
     * @return
     */
    public String signParam(String secret) {
        Iterator<Map.Entry<String, String>> iterator = paramMap.entrySet().iterator();
        StringBuilder builder = new StringBuilder();
        builder.append(secret);
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            String key = next.getKey();
            String value = next.getValue();
            builder.append(key);
            builder.append(value);
        }
        builder.append(secret);
        try {
            return MD5.hash(builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

+ 86 - 0
hos-camel2/src/main/java/camel/central/gateway/processor/SignProcessor.java

@ -0,0 +1,86 @@
package camel.central.gateway.processor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.http.HTTPResponse;
import com.yihu.hos.core.http.HttpClientKit;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import java.io.IOException;
import java.util.Map;
/**
 * 测试使用,用户获取sign
 */
public class SignProcessor implements Processor {
    static final String agUrl = "http://192.168.220.84:10000";
//    static final String agUrl = "http://172.19.103.73:10000";
    public void process(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        Message inMessage = exchange.getIn();
        String camelHttpMethod = inMessage.getHeader("CamelHttpMethod").toString();
        if (!"POST".equals(camelHttpMethod)) {
            outMessage.setBody("请求类型必须为POST");
            return;
        }
        if (inMessage.getHeaders().get("appKey") == null) {
            outMessage.setBody("appKey不能为空");
            return;
        }
        String appKey = inMessage.getHeaders().get("appKey").toString();
        String secret = getSecret(appKey);
        if (StringUtil.isEmpty(secret)) {
            outMessage.setBody("获取secret失败,APPKey不存在对应的应用");
        } else {
            Map<String, Object> params = inMessage.getHeaders();
            String sign = getSign(params, secret);
            outMessage.setBody("sign," + sign);
        }
    }
    private String getSecret(String appKey) {
        ObjectMapper objectMapper = new ObjectMapper();
        //TODO 设置固定的验证入口地址
        HTTPResponse response = HttpClientKit.get(agUrl + "/api/v1.0/admin/apps/" + appKey);
        if (response.getStatusCode() != 200) {
            System.out.println("获取app的secret请求失败,status: "+response.getStatusCode() + "error: "+response.getBody());
            return "";
        }
        try {
            Map map = objectMapper.readValue(response.getBody(), Map.class);
            if ((Boolean) map.get("successFlg")) {
                Map<String, Object> obj = (Map) map.get("obj");
                if (obj == null) {
                    return "";
                }
                String secret = obj.get("secret").toString();
                return secret;
            } else {
                System.out.println("验证失败:" + map.get("errorMsg"));
                return "";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
    private String getSign(Map<String, Object> params, String secret) {
        try {
            ParamVerifyBean paramSign = new ParamVerifyBean();
            paramSign.addParam(params);
            String md5Sign = paramSign.signParam(secret);
            System.out.println("生成的签名:" + md5Sign);
            return md5Sign;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

+ 204 - 0
hos-camel2/src/main/java/camel/central/gateway/route/GatewayRouterBuilder.java

@ -0,0 +1,204 @@
package camel.central.gateway.route;
import camel.central.gateway.processor.ErrorHandle;
import camel.central.gateway.processor.GatewayProcessor;
import camel.central.gateway.processor.SignProcessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/3/13.
 */
@Component
public class GatewayRouterBuilder extends RouteBuilder {
    private ExecutorService threadPool;
    @Override
    public void configure() throws Exception {
        threadPool = Executors.newCachedThreadPool();
//        getContext().setTracing(true);
        getContext().setStreamCaching(true);
        enableSSL();
        apiRoute();
        errorHandleRoute();
        logRoute();
        toolRoute();
    }
    private void enableSSL() {
//        if (httpsEnable) {
//            //全局ssl设置
//            KeyStoreParameters ksparams = new KeyStoreParameters();
//            ksparams.setResource("tomcat.keystore");
//            ksparams.setPassword("123456");
//
//            KeyManagersParameters kmp = new KeyManagersParameters();
//            kmp.setKeyStore(ksparams);
//            kmp.setKeyPassword("123456");
//
//            SSLContextParameters scp = new SSLContextParameters();
//            scp.setKeyManagers(kmp);
//
//            JettyHttpComponent jettyComponent = getContext().getComponent("jetty", JettyHttpComponent.class);
//            jettyComponent.setSslContextParameters(scp);
//        }
    }
    private void apiRoute() {
        //EHR 解析服务代理
        from("jetty:http://0.0.0.0:9999/resolve?matchOnUriPrefix=true").routeId("resolveProxy")
//                .to("jetty:http://172.19.103.74:10170?bridgeEndpoint=true&throwExceptionOnFailure=false");
                .to("jetty:http://192.168.200.83:10170?bridgeEndpoint=true&throwExceptionOnFailure=false");
        //EHR ag-admin网关代理
        from("jetty:http://0.0.0.0:9998?matchOnUriPrefix=true").routeId("proxy")
//                .to("jetty:http://172.19.103.73:10000?bridgeEndpoint=true&throwExceptionOnFailure=false");
        .to("jetty:http://192.168.220.84:10000?bridgeEndpoint=true&throwExceptionOnFailure=false");
        //EHR 公钥获取
        from("jetty:http://0.0.0.0:9999/api/v1.0/organizations/{org_code}/key").routeId("publicKey")
//                .to("jetty:http://172.19.103.73:10400?bridgeEndpoint=true&throwExceptionOnFailure=false");
        .to("jetty:http://192.168.220.85:10400?bridgeEndpoint=true&throwExceptionOnFailure=false");
        // 非病人维度 档案上传接口代理
        from("jetty:http://0.0.0.0:9999/api/dataset/packages?bridgeEndpoint=true&enableMultipartFilter=false").routeId("proxyUploadPack")
                .removeHeaders("CamelHttp*")
//                .to("jetty:http://172.19.103.74:10140/api/v1.0/packages");
                .to("jetty:http://192.168.200.69:10140/api/v1.0/datasetPackages");
        // 档案上传接口代理
        from("jetty:http://0.0.0.0:9999/api/packages?bridgeEndpoint=true&enableMultipartFilter=false").routeId("proxyUploadPackage")
                .removeHeaders("CamelHttp*")
//                .to("jetty:http://172.19.103.74:10140/api/v1.0/packages");
        .to("jetty:http://192.168.220.233/packmgr/api/v1.0/packages");
        // 质控包上传接口代理
        from("jetty:http://0.0.0.0:9999/api/qcPackages?bridgeEndpoint=true&enableMultipartFilter=false").routeId("proxyQcPackUpload")
                .removeHeaders("CamelHttp*")
//                .to("jetty:http://172.19.103.73:10300/api/v1.0/report/receiveReportFile");
        .to("jetty:http://192.168.40.120:10300/api/v1.0/report/receiveReportFile");
        //统一网关入口(restful)
        from("jetty:http://0.0.0.0:9999/api").routeId("api")
                .wireTap("direct:gatewayLog").executorService(threadPool)
                .bean(method(GatewayProcessor.class, "route"))
                .wireTap("direct:gatewayLog").executorService(threadPool);
    }
    /**
     * 统一网关错误代码返回
     */
    private void errorHandleRoute() {
        from("direct:errorHandle").routeId("errorHandle")
                .choice()
                .when(header(Exchange.HTTP_URI).contains("paramError")).bean(new ErrorHandle(), "paramError")
                .when(header(Exchange.HTTP_URI).contains("outdateError")).bean(new ErrorHandle(), "outdateError")
                .when(header(Exchange.HTTP_URI).contains("signValidError")).bean(new ErrorHandle(), "signValidError")
                .when(header(Exchange.HTTP_URI).contains("unauthorizedError")).bean(new ErrorHandle(), "unauthorizedError")
                .endChoice();
    }
    private void toolRoute() {
        //流程健康测试接口
        from("jetty:http://0.0.0.0:9999/healthy").routeId("healthy")
                .log("=========================心跳测试=====================");
        //网关辅助工具路由,用于生成签名等内容。不要要发布到生产环境中。
        from("jetty:http://0.0.0.0:9999/sign").routeId("sign")
                .process(new SignProcessor());
    }
    private void logRoute() {
        from("direct:gatewayLog").aggregate(header("breadcrumbId"), (oldExchange, newExchange) -> {
            if (oldExchange == null) {
                Date date = new Date();
                newExchange.getIn().setHeader("time", date);
                return newExchange;
            } else {
                Date end = new Date();
                Date begin = oldExchange.getIn().getHeader("time", Date.class);
                long responseTime = end.getTime() - begin.getTime();
                oldExchange.getIn().setHeader("responseTime", responseTime);
                String body = newExchange.getIn().getBody(String.class);
                oldExchange.getIn().setBody(body);
                return oldExchange;
            }
        }).process(exchange -> {
            Message in = exchange.getIn();
            String api = in.getHeader("api", String.class);
            String appKey = in.getHeader("appKey", String.class);
            String sign = in.getHeader("sign", String.class);
            String timestamp = in.getHeader("timestamp", String.class);
            String v = in.getHeader("v", String.class);
            String param = in.getHeader("param", String.class);
            String token = in.getHeader("token", String.class);
            Date time = in.getHeader("time", Date.class);
            String requestTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);
            Long responseTime = in.getHeader("responseTime", Long.class);
            String url = in.getHeader("CamelHttpUrl", String.class);
            String method = in.getHeader("CamelHttpMethod", String.class);
            HttpServletResponse response = in.getHeader("CamelHttpServletResponse", HttpServletResponse.class);
            in.getHeader("CamelHttpServletResponse", HttpServletResponse.class);
            String body = in.getBody(String.class);
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode objectNode = objectMapper.createObjectNode();
            objectNode.put("time", requestTime);
            objectNode.put("logType", 1);
            objectNode.put("caller", appKey);
            ObjectNode dataNode = objectMapper.createObjectNode();
            dataNode.put("responseTime", responseTime);
            dataNode.put("url", url);
            dataNode.put("responseCode", response.getStatus());
            dataNode.put("response", body);
            dataNode.put("api", api);
            dataNode.put("appKey", appKey);
            dataNode.put("method", method);
            ObjectNode paramNode = objectMapper.createObjectNode();
            paramNode.put("api", api);
            paramNode.put("appKey", appKey);
            paramNode.put("sign", sign);
            paramNode.put("timestamp", timestamp);
            paramNode.put("v", v);
            if (param != null) {
                paramNode.put("param", param);
            }
            if (token != null) {
                paramNode.put("token", token);
            }
            dataNode.set("params", paramNode);
            objectNode.set("data", dataNode);
            String content = objectMapper.writeValueAsString(objectNode);
            exchange.getOut().setBody(content);
        }).completionSize(2).to("file://e:/gatewayLog");
    }
}

+ 19 - 0
hos-camel2/src/main/java/camel/central/qlc/processor/Processor0.java

@ -0,0 +1,19 @@
package camel.central.qlc.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.http.common.HttpMessage;
/**
 * Created by Zdm on 2016/7/13.
 */
public class Processor0 implements Processor {
    public void process(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        HttpMessage inMessage = (HttpMessage) exchange.getIn();
        String queryString = "api=camel.central.qlc&param=" + inMessage.getRequest().getParameterValues("data")[0];
        outMessage.setHeader(Exchange.HTTP_QUERY, queryString);
    }
}

+ 24 - 0
hos-camel2/src/main/java/camel/central/qlc/processor/Processor1.java

@ -0,0 +1,24 @@
package camel.central.qlc.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.http.common.HttpMessage;
import java.util.Map;
/**
 * Created by Zdm on 2016/7/13.
 */
public class Processor1 implements Processor {
    public void process(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        HttpMessage inMessage = (HttpMessage) exchange.getIn();
        outMessage.setHeader(Exchange.HTTP_QUERY, inMessage.getRequest().getQueryString());
        Map paramMap = inMessage.getRequest().getParameterMap();
        for (Object key : paramMap.keySet()) {
            exchange.setProperty(key.toString(), paramMap.get(key));
        }
    }
}

+ 26 - 0
hos-camel2/src/main/java/camel/central/qlc/processor/Processor2.java

@ -0,0 +1,26 @@
package camel.central.qlc.processor;
import net.sf.json.JSONObject;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import java.util.Map;
/**
 * Created by Zdm on 2016/7/13.
 */
public class Processor2 implements Processor {
    public void process(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        Message inMessage = exchange.getIn();
        String body = inMessage.getBody(String.class);
        Map<String, Object> mapJson = JSONObject.fromObject(body);
        String queryString = "";
        for (String key : mapJson.keySet()) {
            queryString += key + "=" + mapJson.get(key) + "&";
        }
        outMessage.setHeader(Exchange.HTTP_QUERY, queryString);
    }
}

+ 22 - 0
hos-camel2/src/main/java/camel/central/qlc/route/QlcRouteBulider.java

@ -0,0 +1,22 @@
package camel.central.qlc.route;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import camel.central.qlc.processor.Processor1;
import camel.central.qlc.processor.Processor2;
/**
 * Created by lingfeng on 2016/7/25.
 */
public class QlcRouteBulider extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("jetty:http4://172.17.110.178:9088/camel.central.qlc").routeId("camel/central/qlc")
                .process(new Processor1()).setHeader(Exchange.HTTP_METHOD, constant("POST")).log("servers: 3,code: queryUserInfo,order: 1")
                .to("http4://172.19.103.89:8088/api/v1.0/camel.central.qlc/queryUserInfo").log("servers: 3,code: queryUserInfo,order: 1")
                .process(new Processor2()).setHeader(Exchange.HTTP_METHOD, constant("POST")).log("servers: 3,code: patientInformation,order: 1")
                .to("http4://172.19.103.89:8088/api/v1.0/camel.central.qlc/patientInformation").log("servers: 3,code: patientInformation,order: 1")
                .process(new Processor2()).setHeader(Exchange.HTTP_METHOD, constant("POST")).to("stream:out"); // 2. 为路由配置组件或终端节点.
    }
}

+ 171 - 0
hos-camel2/src/main/java/camel/central/webservice/processor/WsProcessor.java

@ -0,0 +1,171 @@
package camel.central.webservice.processor;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.message.MessageContentsList;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Component("wsProcessor")
public class WsProcessor implements Processor {
    private XmlMapper xmlMapper = new XmlMapper();
    private ObjectMapper objectMapper = new ObjectMapper();
    public void process(Exchange exchange) throws Exception {
        MessageContentsList args = exchange.getIn().getBody(MessageContentsList.class);
        exchange.getOut().setHeader("api", args.get(0));
        String xmlParam = args.get(1).toString();
        String rootName = parseXMLDocument(xmlParam).getDocumentElement().getLocalName();//获取根节点
        ObjectNode param = xmlMapper.readValue(xmlParam, ObjectNode.class);//解析参数内容
        ObjectNode paramNode = objectMapper.createObjectNode();
        paramNode.set(rootName, param);
        exchange.getOut().setHeader("param", paramNode);
        exchange.getOut().setHeader("timestamp", args.get(2));
        exchange.getOut().setHeader("v", args.get(3));
        exchange.getOut().setHeader("appKey", args.get(4));
        exchange.getOut().setHeader("sign", args.get(5));
    }
    public  String convertXmlToJson(String xml) {
        StringWriter w = new StringWriter();
        try {
            JsonParser jp = xmlMapper.getFactory().createParser(xml);
            JsonGenerator jg = objectMapper.getFactory().createGenerator(w);
            while (jp.nextToken() != null) {
                jg.copyCurrentEvent(jp);
            }
            jp.close();
            jg.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return w.toString();
    }
    //webservice 接口请求返回
    public SOAPBody responseWs(Exchange exchange) {
        XmlMapper xmlMapper = new XmlMapper();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Object errorCode = exchange.getIn().getHeader("errorCode");
            if (errorCode!=null){
                //错误信息返回
//                Map<Object, Object> errorMap = objectMapper.readValue(errorCode.toString(),Map.class);
                LinkedHashMap<Object, Object> errorMap = new LinkedHashMap<>();
                errorMap.put("errorCode",errorCode);
                String xmlResponse = xmlMapper.writeValueAsString(errorMap);
                return createDefaultSoapMessage(xmlResponse);
            }
            //返回请求结果
            Map<String,Object> map = objectMapper.readValue(exchange.getIn().getBody().toString(),Map.class);
            String xmlResponse = xmlMapper.writeValueAsString(map);
            return createDefaultSoapMessage(xmlResponse);
        } catch (Exception e) {
                e.printStackTrace();
            return createDefaultSoapMessage(e.getClass().getName());
        }
    }
    public SOAPBody request(Exchange exchange) {
        String wsdl = "http://127.0.0.1:8001/esb/ws?wsdl";
        SOAPMessage soapMessage = (SOAPMessage) exchange.getIn().getBody(List.class).get(0);
        if (soapMessage == null) {
            System.out.println("Incoming null message detected...");
            return createDefaultSoapMessage("null");
        }
        try {
            String requestText = requestWs(exchange, wsdl, "plus");
            return createDefaultSoapMessage(requestText);
        } catch (Exception e) {
            e.printStackTrace();
            return createDefaultSoapMessage(e.getClass().getName());
        }
    }
    /**
     * 请求ws
     *
     * @param exchange
     * @param method
     * @return
     * @throws Exception
     */
    public String requestWs(Exchange exchange, String wsdl, String method) throws Exception {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        org.apache.cxf.endpoint.Client client = dcf.createClient(wsdl);
        //getUser 为接口中定义的方法名称  张三为传递的参数   返回一个Object数组
        Object[] objects = client.invoke(method);
        //输出调用结果
        System.out.println("*****" + objects[0].toString());
        return objects[0].toString();
    }
    /**
     * 生成ws返回内容
     *
     * @param requestMessage
     * @return
     */
    public static SOAPBody createDefaultSoapMessage(String requestMessage) {
        try {
            SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
            SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();
//            QName payloadName = new QName("http://gateway.api", "test", "ns1");
//            SOAPBodyElement payload = body.addBodyElement(payloadName);
//            SOAPElement message = payload.addChildElement("body");
            body.addDocument(parseXMLDocument(requestMessage));
            return body;
        } catch (SOAPException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    /**
     * 解析XML字符串
     * @param xmlString
     * @return
     */
    public static Document parseXMLDocument(String xmlString) {
        if (xmlString == null) {
            throw new IllegalArgumentException();
        }
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
            return documentBuilder.parse(
                    new InputSource(new StringReader(xmlString)));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}

+ 32 - 0
hos-camel2/src/main/java/camel/central/webservice/processor/WsService.java

@ -0,0 +1,32 @@
package camel.central.webservice.processor;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/4/14.
 */
@WebService(name = "esbWService")
public interface WsService {
    @WebMethod
    public Object test();
    @WebMethod
    public Object requestWs(
            @WebParam(name = "api") String api,
            @WebParam(name = "param") String param,
            @WebParam(name = "timestamp") String timestamp,
            @WebParam(name = "v") String v,
            @WebParam(name = "appKey") String appKey,
            @WebParam(name = "sign") String sign
    );
    @WebMethod
    public Object AddProvider(@WebParam(name = "doctor_id") long doctor_id);
}

+ 33 - 0
hos-camel2/src/main/java/camel/central/webservice/route/WsGatewayRouterBuilder.java

@ -0,0 +1,33 @@
package camel.central.webservice.route;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/3/13.
 */
@Component
public class WsGatewayRouterBuilder extends RouteBuilder {
    protected static final String SIMPLE_ENDPOINT_ADDRESS = "http://0.0.0.0:9998/ws/api";
    protected static final String SIMPLE_ENDPOINT_URI = "cxf:" + SIMPLE_ENDPOINT_ADDRESS
            + "?serviceClass=camel.central.gateway.processor.WsService"
//            + "&dataFormat=CXF_MESSAGE"
            ;
    @Override
    public void configure() throws Exception {
        //统一网关入口(web-service)
//        from(SIMPLE_ENDPOINT_URI)
//                .setHeader(Exchange.BEAN_MULTI_PARAMETER_ARRAY, constant(true))
//                .process(new WsProcessor())
//                .routingSlip(method(GatewayProcessor.class, "route"))
//                .to("bean:wsProcessor?method=responseWs");
        //心跳接口
        from("jetty:http://0.0.0.0:9998/heartbeat").routeId("heartbeat")
                .log("=========================心跳测试=====================");
    }
}

+ 112 - 0
hos-camel2/src/main/java/camel/config/BeanConfig.java

@ -0,0 +1,112 @@
package camel.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/8/5.
 */
@Configuration
@EnableTransactionManagement
@ComponentScan("camel")
//@ImportResource({"classpath:spring/applicationContext.xml"}) //applicationContext相关bean创建
public class BeanConfig {
    @Autowired
    private DataSource dataSource;
    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
        localSessionFactoryBean.setDataSource(this.dataSource);
        Properties properties1 = new Properties();
        properties1.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        properties1.setProperty("hibernate.show_sql", "false");
        properties1.setProperty("hibernate.format_sql", "true");
        localSessionFactoryBean.setHibernateProperties(properties1);
        localSessionFactoryBean.setPackagesToScan("camel.*");
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        //设置拦截器
        return localSessionFactoryBean;
    }
    @Bean
    public JdbcTemplate jdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        try {
            jdbcTemplate.setDataSource(this.dataSource);
            jdbcTemplate.setLazyInit(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jdbcTemplate;
    }
    //Hibernate模版配置
    @Bean
    public HibernateTemplate hibernateTemplate() throws SQLException {
        HibernateTemplate hibernateTemplate = new HibernateTemplate();
        LocalSessionFactoryBean sessionFactory = this.sessionFactory();
        hibernateTemplate.setSessionFactory(sessionFactory.getObject());
        return hibernateTemplate;
    }
    @Bean
    public Session getSession() throws HibernateException {
        LocalSessionFactoryBean sessionFactory = this.sessionFactory();
        return sessionFactory.getObject().openSession();
    }
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(5);
        threadPoolTaskExecutor.setMaxPoolSize(10);
        threadPoolTaskExecutor.setQueueCapacity(25);
        threadPoolTaskExecutor.setKeepAliveSeconds(300);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }
    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }
}

+ 14 - 0
hos-camel2/src/main/java/camel/demo/api1/processor/ApiProcessor.java

@ -0,0 +1,14 @@
package camel.demo.api1.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
public class ApiProcessor implements Processor {
    public void process(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        System.out.println("测试,helloWorld 打印camel接口");
        outMessage.setBody("hello,api1xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    }
}

+ 32 - 0
hos-camel2/src/main/java/camel/demo/api1/route/ApiRouteBulider.java

@ -0,0 +1,32 @@
package camel.demo.api1.route;
import camel.demo.api1.processor.ApiProcessor;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
@Component("ApiRouteBulider2")
public class ApiRouteBulider extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("jetty:http://0.0.0.0:9097/api/v1").routeId("camel/demo/api1")
                .process(new ApiProcessor()).log("servers: 0,code: ,order: 0").log("打印222222222222222222222222");
        from("jetty:http://0.0.0.0:9097/rest").routeId("restTest")
                .to("restlet:http://192.168.1.221:10000/api/v1.0/admin/doctors/admin/13?autoCloseStream=true");
        from("jetty:http://0.0.0.0:8330/load?bridgeEndpoint=true&enableMultipartFilter=false").routeId("jettyLoda")
                .removeHeaders("CamelHttp*")
                .to("jetty:http://127.0.0.1:8331/healthy","jetty:http://127.0.0.1:8332/healthy","jetty:http://127.0.0.1:8333/healthy");
        from("jetty:http://0.0.0.0:8331/healthy").routeId("healthy1")
                .log("=========================心跳测试1111111=====================");
        from("jetty:http://0.0.0.0:8332/healthy").routeId("healthy2")
                .log("=========================心跳测试22222222=====================");
        from("jetty:http://0.0.0.0:8333/healthy").routeId("healthy3")
                .log("=========================心跳测试33333333=====================");
    }
}

+ 14 - 0
hos-camel2/src/main/java/camel/demo/api7/processor/ApiProcessor.java

@ -0,0 +1,14 @@
package camel.demo.api7.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
public class ApiProcessor implements Processor {
    public void process(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        System.out.println("测试,helloWorld 打印camel接口");
        outMessage.setBody("hello,api7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    }
}

+ 20 - 0
hos-camel2/src/main/java/camel/demo/api7/processor/TestClient.java

@ -0,0 +1,20 @@
package camel.demo.api7.processor;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/4/20.
 */
public class TestClient {
    public static void main(String args[]) throws Exception{
                 JaxWsDynamicClientFactory dcf =JaxWsDynamicClientFactory.newInstance();
                 org.apache.cxf.endpoint.Client client =dcf.createClient("http://192.168.131.101:3333/soap/ws?wsdl");
                 //getUser 为接口中定义的方法名称  张三为传递的参数   返回一个Object数组
                 Object[] objects=client.invoke("test");
                 //输出调用结果
                 System.out.println("*****"+objects[0].toString());
    }
}

+ 32 - 0
hos-camel2/src/main/java/camel/demo/api7/processor/TestWService.java

@ -0,0 +1,32 @@
package camel.demo.api7.processor;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/4/14.
 */
@WebService(name = "testWService")
public interface TestWService {
    @WebMethod
    public Object test();
    @WebMethod
    public Object requestWs (
            @WebParam(name = "api") String api,
            @WebParam(name = "param") String param,
            @WebParam(name = "timestamp") String timestamp,
            @WebParam(name = "v") String v,
            @WebParam(name = "appKey") String appKey,
            @WebParam(name = "sign") String sign
    );
    @WebMethod
    public Object AddProvider (@WebParam(name = "doctor_id") long doctor_id );
}

+ 37 - 0
hos-camel2/src/main/java/camel/demo/api7/processor/TestWsConfig.java

@ -0,0 +1,37 @@
package camel.demo.api7.processor;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/4/20.
 */
//@Configuration
public class TestWsConfig {
    @Bean
    public ServletRegistrationBean dispatcherServlet() {
        return new ServletRegistrationBean(new CXFServlet(), "/esb/*");
    }
    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }
//    @Bean
//    public TestWService testWService() {
//        return new TestWServiceImpl();
//    }
//    @Bean
//    public Endpoint endpoint() {
//        EndpointImpl endpoint = new EndpointImpl(springBus(), testWService());
//        endpoint.publish("/ws");
//        return endpoint;
//    }
}

+ 124 - 0
hos-camel2/src/main/java/camel/demo/api7/processor/ToWsProcessor.java

@ -0,0 +1,124 @@
package camel.demo.api7.processor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.message.MessageContentsList;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.*;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
@Component("toWsProcessor")
public class ToWsProcessor implements Processor {
    public void process(Exchange exchange) throws Exception {
        MessageContentsList args = exchange.getIn().getBody(MessageContentsList.class);
        exchange.getOut().setHeader("api", args.get(0));
        exchange.getOut().setHeader("param", args.get(1));
        exchange.getOut().setHeader("timestamp", args.get(2));
        exchange.getOut().setHeader("v", args.get(3));
        exchange.getOut().setHeader("appKey", args.get(4));
        exchange.getOut().setHeader("sign", args.get(5));
    }
    public SOAPBody responseWs(Exchange exchange) {
        try {
            XmlMapper xmlMapper = new XmlMapper();
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String,Object> map = objectMapper.readValue(exchange.getIn().getBody().toString(),Map.class);
            String xmlResponse = xmlMapper.writeValueAsString(map);
            return createDefaultSoapMessage(xmlResponse);
        } catch (Exception e) {
            e.printStackTrace();
            return createDefaultSoapMessage(e.getClass().getName());
        }
    }
    public SOAPBody request(Exchange exchange) {
        String wsdl = "http://127.0.0.1:8001/esb/ws?wsdl";
        SOAPMessage soapMessage = (SOAPMessage) exchange.getIn().getBody(List.class).get(0);
        if (soapMessage == null) {
            System.out.println("Incoming null message detected...");
            return createDefaultSoapMessage("null");
        }
        try {
            String requestText = requestWs(exchange, wsdl, "plus");
            return createDefaultSoapMessage(requestText);
        } catch (Exception e) {
            e.printStackTrace();
            return createDefaultSoapMessage(e.getClass().getName());
        }
    }
    /**
     * 请求ws
     *
     * @param exchange
     * @param method
     * @return
     * @throws Exception
     */
    public String requestWs(Exchange exchange, String wsdl, String method) throws Exception {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        org.apache.cxf.endpoint.Client client = dcf.createClient(wsdl);
        //getUser 为接口中定义的方法名称  张三为传递的参数   返回一个Object数组
        Object[] objects = client.invoke(method);
        //输出调用结果
        System.out.println("*****" + objects[0].toString());
        return objects[0].toString();
    }
    /**
     * 生成ws返回内容
     *
     * @param requestMessage
     * @return
     */
    public static SOAPBody createDefaultSoapMessage(String requestMessage) {
        try {
            SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
            SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();
//            QName payloadName = new QName("http://gateway.api", "test", "ns1");
//            SOAPBodyElement payload = body.addBodyElement(payloadName);
//            SOAPElement message = payload.addChildElement("body");
            body.addDocument(parseXMLDocument(requestMessage));
            return body;
        } catch (SOAPException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    /**
     * 解析XML字符串
     * @param xmlString
     * @return
     */
    public static Document parseXMLDocument(String xmlString) {
        if (xmlString == null) {
            throw new IllegalArgumentException();
        }
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
            return documentBuilder.parse(
                    new InputSource(new StringReader(xmlString)));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}

+ 13 - 0
hos-camel2/src/main/java/camel/demo/api7/route/ApiRouteBulider.java

@ -0,0 +1,13 @@
package camel.demo.api7.route;
import camel.demo.api7.processor.ApiProcessor;
import org.apache.camel.builder.RouteBuilder;
public class ApiRouteBulider extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("jetty:http://0.0.0.0:9097/api/v1").routeId("camel/demo/api7")
                .process(new ApiProcessor()).log("servers: 0,code: ,order: 0").log("servers: 0,code: ,order: 0");
    }
}

+ 34 - 0
hos-camel2/src/main/java/camel/demo/api7/route/CxfConsumerTest.java

@ -0,0 +1,34 @@
package camel.demo.api7.route;
import camel.demo.api7.processor.ToWsProcessor;
import camel.central.gateway.processor.GatewayProcessor;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
@Component
public class CxfConsumerTest extends RouteBuilder {
    protected static final String SIMPLE_ENDPOINT_ADDRESS = "http://127.0.0.1:4445/soap/ws";
    protected static final String SIMPLE_ENDPOINT_URI = "cxf:" + SIMPLE_ENDPOINT_ADDRESS
            + "?serviceClass=camel.demo.api7.processor.TestWService"
//            + "&dataFormat=CXF_MESSAGE"
            ;
    // START SNIPPET: example
    public void configure() {
        from(SIMPLE_ENDPOINT_URI)
                .setHeader(Exchange.BEAN_MULTI_PARAMETER_ARRAY, constant(true))
                .process(new ToWsProcessor())
                .routingSlip(method(GatewayProcessor.class, "route"))
                .to("bean:toWsProcessor?method=responseWs")
        ;
    }
};

+ 59 - 0
hos-camel2/src/main/java/camel/demo/jdbcdemo/processor/JdbcProcessor.java

@ -0,0 +1,59 @@
package camel.demo.jdbcdemo.processor;
import com.yihu.hos.core.datatype.DateUtil;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class JdbcProcessor implements Processor {
    @Override
    public void process(Exchange exchange) throws Exception {
        Message intMessage = exchange.getIn();
        String dataSetCode = (String) intMessage.getHeader("dataSetCode");
        System.out.println("dataSetCode:"+dataSetCode);
//        System.out.println("存入mongodb:" + intMessage.getBody());
    }
    //生成sql查询语法
    public void setSqlBody(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        outMessage.setBody("select * from HDSC02_09 t\n" +
                "where  t.HDSD00_01_185 >= to_date('2016-07-01 0:00:00','yyyy-mm-dd hh24:mi:ss') and \n" +
                "t.HDSD00_01_185 < to_date('2016-07-31 0:00:00','yyyy-mm-dd hh24:mi:ss') \n");
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
        String format = sdf.format(new Date());
//        System.out.println(format+":查询病人列表sql::" + outMessage.getBody());
    }
    //日志打印,用来测试quartz触发时间
    public void logOut(Exchange exchange) throws Exception {
        Message intMessage = exchange.getIn();
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
        String format = sdf.format(new Date());
        String dataSetCode = (String) intMessage.getHeader("dataSetCode");
        System.out.println(format+ "---" + dataSetCode +":intMessage日志打印::" + intMessage.getBody());
    }
    //存入mongodb
    public void intoMongo(Exchange exchange) throws Exception {
        Message intMessage = exchange.getIn();
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
        String format = sdf.format(new Date());
        String dataSetCode = (String) intMessage.getHeader("dataSetCode");
        System.out.println(format+ "==" + dataSetCode +":存入mongodb:" + intMessage.getBody());
    }
    public void aggreeOpera(Exchange exchange) throws Exception {
        Message intMessage = exchange.getIn();
        System.out.println("联合查詢結果2:" + intMessage.getBody());
    }
}

+ 135 - 0
hos-camel2/src/main/java/camel/demo/jdbcdemo/route/ApiRouteBulider.java

@ -0,0 +1,135 @@
package camel.demo.jdbcdemo.route;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.SimpleRegistry;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.stereotype.Component;
@Component
public class ApiRouteBulider extends RouteBuilder {
    final String url = "jdbc:mysql://172.19.103.57:8066/hos2?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true";
public void dataSource1(){
    ModelCamelContext context = this.getContext();
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
    basicDataSource.setUsername("hos");
    basicDataSource.setPassword("123456");
    basicDataSource.setUrl(url);
    SimpleRegistry simpleregistry = new SimpleRegistry();
    simpleregistry.put("myDataSource", basicDataSource);
    context = new DefaultCamelContext(simpleregistry);
}
    @Override
    public void configure() throws Exception {
//9.31
//        from("quartz://myGroup/testTimer1?cron=0 56/2 14 23 4 ? 2018").routeId("testTimer1")
//                .to("bean:jdbcProcessor?method=logOut");
        //事件 查询主线
        from("direct:patientList").routeId("camel/demo/jdbc")
//                .setBody(constant("select * from HDSC02_09  "))
                .to("bean:jdbcProcessor?method=setSqlBody")
                .to("jdbc:dataSource?outputType=SelectList")
                .setHeader("dataSetCode",constant("HDSC02_09"))
//                .setHeader("HDSC02_09",simple("${body}"))
//                .split(body())
//                .wireTap("direct:relationTable1")// 结果消息传递到下一个表
//                .wireTap("direct:relationTable2")// 结果消息传递到
//                .wireTap("direct:relationTable3")// 结果消息传递到
//                .aggregate(header("dataSetCode"))
//                .end()
//                .process(new JdbcProcessor())
//                .wireTap("bean:jdbcProcessor?method=logOut")
        ;
        // 关联查询表
        from("direct:relationTable1").routeId("relationTable1")
                .setHeader("dataSetCode",constant("HDSC02_17"))
                .setHeader("PATIENT_ID",simple("${body['PATIENT_ID']}"))
                .setHeader("HDSD00_01_579",simple("${body['HDSD00_01_579']}"))
                .setHeader("HDSD00_01_185",simple("${body['HDSD00_01_185']}"))
//                .setBody(constant("select :?PATIENT_ID as PATIENT_ID,:?HDSD00_01_579 as HDSD00_01_579,:?HDSD00_01_185 as HDSD00_01_185,a.* from HDSC02_17 a WHERE a.PATIENT_ID=:?PATIENT_ID,a.HDSD00_01_579=:?HDSD00_01_579"))
                .setBody(constant("select a.* from HDSC02_17 a WHERE a.PATIENT_ID=:?PATIENT_ID and a.HDSD00_01_579=:?HDSD00_01_579"))
                .wireTap("bean:jdbcProcessor?method=logOut")
                .to("jdbc:dataSource?useHeadersAsParameters=true")
//                .setHeader("HDSC02_17",simple("${body}"))
//                .split(body())
//                .to("bean:jdbcProcessor?method=aggreeOpera")
//                .end()
        ;
        // 下一张表2 查询 HDSA00_1
        from("direct:relationTable2").routeId("relationTable2")
                .setHeader("dataSetCode",constant("HDSA00_1"))
                .setHeader("PATIENT_ID",simple("${body['PATIENT_ID']}"))
                .wireTap("bean:jdbcProcessor?method=logOut")
                .setBody(constant("select a.* from HDSA00_1 a WHERE a.PATIENT_ID=:?PATIENT_ID"))
                .to("jdbc:dataSource?useHeadersAsParameters=true")
//                .setHeader("HDSA00_1",simple("${body}"))
//                .split(body())
        ;
        // 下一张表3 查询 HDSC02_14
        from("direct:relationTable3").routeId("relationTable3")
                .setHeader("dataSetCode",constant("HDSC02_14"))
                .setHeader("PATIENT_ID",simple("${body['PATIENT_ID']}"))
                .setHeader("HDSD00_01_579",simple("${body['HDSD00_01_579']}"))
                .setHeader("HDSD00_01_185",simple("${body['HDSD00_01_185']}"))
                .wireTap("bean:jdbcProcessor?method=logOut")
                .setBody(constant("select a.* from HDSC02_14 a WHERE a.PATIENT_ID=:?PATIENT_ID nad a.HDSD00_01_579=:?HDSD00_01_579"))
                .to("jdbc:dataSource?useHeadersAsParameters=true")
//                .setHeader("HDSC02_14",simple("${body}"))
//                .split(body())
        .end()
        ;
        from("jetty:http://0.0.0.0:9094/demo/jdbc").to("direct:patientList")
                .split(body())
                .multicast(new MyAggregationStrategy()).to("direct:relationTable1,direct:relationTable2,direct:relationTable3").parallelProcessing()
                .end()
                .to("direct:upload")
                .end();
        from("direct:t0").setBody(constant("p1,p2,p3,p4")).log("t0:" + body().toString());
        from("direct:ta").log("ta:" + body().toString());
        from("direct:tb").log("tb:" + body().toString());
        from("direct:tc").log("tc:" + body().toString());
        from("direct:upload").log("upload:" + body().toString());
    }
    public class MyAggregationStrategy implements AggregationStrategy {
        @Override
        public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
            if (oldExchange == null) {
                return newExchange;
            } else {
                String body1 = oldExchange.getIn().getBody(String.class);
                String body2 = newExchange.getIn().getBody(String.class);
                String merged = (body1 == null) ? body2 : body1 + "," + body2;
                oldExchange.getIn().setBody(merged);
                return oldExchange;
            }
        }
    }
}

+ 20 - 0
hos-camel2/src/main/java/camel/demo/quartz2/processor/Quartz2Processor.java

@ -0,0 +1,20 @@
package camel.demo.quartz2.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
/**
 * Created by Zdm on 2016/7/13.
 */
public class Quartz2Processor extends ClassLoader implements Processor {
    public void process(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        System.out.println("测试,quartz ####################################");
        for (int i=0;i<30;i++){
            Thread.sleep(1000*3);
            System.out.println(i);
        }
        outMessage.setBody("hello,quartz========================");
    }
}

+ 11 - 0
hos-camel2/src/main/java/camel/demo/quartz2/route/Quartz2Route.java

@ -0,0 +1,11 @@
package camel.demo.quartz2.route;
import camel.demo.quartz2.processor.Quartz2Processor;
import org.apache.camel.builder.RouteBuilder;
public class Quartz2Route  extends RouteBuilder {
    public void configure() throws Exception {
        from("quartz://myGroup2/quartz2?cron=0 0/1 * * * ?").routeId("routeId").process(new Quartz2Processor())
               ;
    }
}

+ 21 - 0
hos-camel2/src/main/java/camel/log/JmsAppender.java

@ -0,0 +1,21 @@
package camel.log;
import ch.qos.logback.classic.net.JMSTopicAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
import java.util.Map;
/**
 * Created by l4qiang on 2017-04-12.
 */
public class JmsAppender extends JMSTopicAppender {
    @Override
    public void append(ILoggingEvent event) {
        Map<String, String> mdcPropertyMap = event.getMDCPropertyMap();
        if (mdcPropertyMap.size() == 0) {
            return;
        }
        System.out.println(event.getMessage());
        super.append(event);
    }
}

+ 66 - 0
hos-camel2/src/main/java/camel/log/TracerFormatter.java

@ -0,0 +1,66 @@
package camel.log;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.processor.interceptor.DefaultTraceFormatter;
import org.apache.camel.processor.interceptor.TraceInterceptor;
import java.util.Map;
/**
 * Created by l4qiang on 2017-04-14.
 */
public class TracerFormatter extends DefaultTraceFormatter {
    @Override
    public Object format(TraceInterceptor interceptor, ProcessorDefinition<?> node, Exchange exchange) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            ObjectNode rootNode = objectMapper.createObjectNode();
            {
                Message in = exchange.getIn();
                ObjectNode inNode = rootNode.with("in");
                Map<String, Object> headers = in.getHeaders();
                headers.forEach((key, value) -> {
                    if (value == null) {
                        return;
                    }
                    inNode.put(key, value.toString());
                });
                if (in.getBody() != null) {
                    inNode.put("body", in.getBody(String.class));
                }
            }
            {
                ObjectNode outNode = rootNode.with("out");
                Message out = exchange.getOut();
                Map<String, Object> headers = out.getHeaders();
                headers.forEach((key, value) -> {
                    if (value == null) {
                        return;
                    }
                    outNode.put(key, value.toString());
                });
                if (out.getBody() != null) {
                    outNode.put("body", out.getBody(String.class));
                }
            }
            return objectMapper.writeValueAsString(rootNode);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return exchange.getIn().getBody();
    }
}

+ 52 - 0
hos-camel2/src/main/java/camel/monitor/processor/LogOffset.java

@ -0,0 +1,52 @@
package camel.monitor.processor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Date;
/**
 * Created by l4qiang on 2017-06-16.
 */
@Document
public class LogOffset {
    @Id
    private String id;
    @Indexed(unique = true)
    private String name;    //需要采集的目标
    private long offset;
    private Date createTime;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public long getOffset() {
        return offset;
    }
    public void setOffset(long offset) {
        this.offset = offset;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 143 - 0
hos-camel2/src/main/java/camel/monitor/processor/MonitorService.java

@ -0,0 +1,143 @@
package camel.monitor.processor;
import com.mongodb.MongoClient;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import com.yihu.hos.core.datatype.DateUtil;
import org.bson.Document;
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.stereotype.Service;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
 * 统计流程信息
 * <p>
 * Created by chenweida on 2016/1/27.
 */
@Service("monitorService")
public class MonitorService {
    private static final String DATABASE = "log";
    private static final String SERVICE = "service";
    private static final String SERVICE_METRICS = "serviceMetrics";
    private static final String BUSINESS = "business";
    @Autowired
    private MongoClient mongoClient;
    @Autowired
    private MongoOperations mongoOperations;
    public void monitor() {
        try {
            System.out.println("进入monitor 流程。。。。");
            System.out.println("mongoClient:"+(mongoClient==null));
            System.out.println("mongoOperations:"+(mongoOperations==null));
            MongoDatabase database = mongoClient.getDatabase(DATABASE);
            Query query = new Query();
            query.addCriteria(Criteria.where("name").is(SERVICE));  //Service表中已有的数据时间。
            LogOffset offset = mongoOperations.findOne(query, LogOffset.class);
            Date begin = new Date();
            Date end = new Date();
            if (offset != null) {
                long lngOffset = offset.getOffset();
                begin = DateUtil.toDateFromTime(lngOffset);
            }
            DateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z", Locale.ENGLISH);
//            begin = DateUtil.formatCharDateYMDHMS("2017-06-12 00:00:00");
//            end = DateUtil.formatCharDateYMDHMS("2017-06-20 00:00:00");
            String beginTime = df.format(begin);
            String endTime = df.format(end);
            mapReduce(database, beginTime, endTime);
            AggregateIterable<Document> documents = aggregate(database, beginTime, endTime);
            outPut(database, documents);
            if (offset == null) {
                offset = new LogOffset();
                offset.setName(SERVICE);
            }
            offset.setOffset(end.getTime());
            mongoOperations.save(offset);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void mapReduce(MongoDatabase database, String beginTime, String endTime) {
        Document document = new Document("mapReduce", BUSINESS);
        String mapFunc = "function(){emit(this.breadcrumbId, {fireTime:this.fireTime, createTime:this.createTime, bodyLength:this.bodyLength, tenant:this.tenant, routeId:this.routeId});}";
        document = document.append("map", mapFunc);
        String reduceFunc = "function(key, values){" +
                "var len=values.length;" +
                "var delay=values[len-1].fireTime-values[0].fireTime;" +
                "if(len == 1){delay=values[0].createTime-values[0].fireTime;}" +
                "return {fireTime: values[0].fireTime, in:values[0].bodyLength, out:values[len-1].bodyLength, delay:delay, tenant:values[0].tenant, routeId:values[0].routeId}}";
        document = document.append("reduce", reduceFunc);
        String query = "{fireTime:{$gte:new Date(\"" + beginTime + "\"), $lt:new Date(\"" + endTime + "\")}}";
        document = document.append("query", Document.parse(query));
        document = document.append("out", new Document("merge", SERVICE));
        database.runCommand(document);
    }
    private AggregateIterable<Document> aggregate(MongoDatabase database, String beginTime, String endTime) {
        MongoCollection<Document> serviceCollection = database.getCollection(SERVICE);
        List<Document> pipeline = new ArrayList<>();
        Document match = new Document();
        String query = "{\"value.fireTime\":{$gte:new Date(\"" + beginTime + "\"), $lt:new Date(\"" + endTime + "\")}}";
        match.put("$match", Document.parse(query));
        pipeline.add(match);
        Document group = new Document();
        group.append("_id", Document.parse("{" +
                "year:{\"$year\":\"$value.fireTime\"}," +
                "month:{\"$month\":\"$value.fireTime\"}," +
                "day:{\"$dayOfMonth\":\"$value.fireTime\"}," +
                "hour:{\"$hour\":\"$value.fireTime\"}," +
                "minute:{\"$minute\": \"$value.fireTime\"}" +
                "routeId:\"$value.routeId\"" +
                "tenant:\"$value.tenantId\"" +
                "}"));
        group.append("pv", Document.parse("{$sum:1}"));
        group.append("successful", Document.parse("{$sum:1}"));
        group.append("failure", Document.parse("{$sum:0}"));    //TODO:暂时为空
        group.append("delay", Document.parse("{$sum:\"$value.delay\"}"));
        group.append("avgDelay", Document.parse("{$avg:\"$value.delay\"}"));
        group.append("in", Document.parse("{$sum:\"$value.in\"}"));
        group.append("out", Document.parse("{$sum:\"$value.out\"}"));
        pipeline.add(new Document("$group", group));
        pipeline.add(new Document("$sort", Document.parse("{\"_id\":1}")));
        return serviceCollection.aggregate(pipeline);
    }
    private void outPut(MongoDatabase database, AggregateIterable<Document> documents) {
        MongoCollection<Document> serviceMetrics = database.getCollection(SERVICE_METRICS);
        for (Document document : documents) {
            Document id = (Document) document.get("_id");
            String time = String.format("%04d", (int) id.get("year")) + String.format("%02d", (int) id.get("month")) + String.format("%02d", (int) id.get("day")) +
                    String.format("%02d", (int) id.get("hour")) + String.format("%02d", (int) id.get("minute"));
            document.put("time", time);
            document.put("routeId", id.get("routeId"));
            document.put("tenant", id.get("tenant"));
            document.putIfAbsent("avgDelay", 0);
            Document query = new Document("_id", id);
            Document update = new Document("$set", document);
            serviceMetrics.updateOne(query, update, new UpdateOptions().upsert(true));
        }
    }
}

+ 36 - 0
hos-camel2/src/main/java/camel/monitor/route/MonitorRouter.java

@ -0,0 +1,36 @@
package camel.monitor.route;
import com.mongodb.MongoClient;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Component;
/**
 * Created by l4qiang on 2017-06-16.
 */
@Component
public class MonitorRouter extends RouteBuilder {
    @Autowired
    private MongoClient mongoClient;
    @Autowired
    private MongoOperations mongoOperations;
    @Override
    public void configure() throws Exception {
        System.out.println("MonitorRouterBulider configure 111111111----------------");
        System.out.println("mongoClient:"+(mongoClient==null));
        System.out.println("mongoOperations:"+(mongoOperations==null));
//        from("quartz://monitor/logMonitorRoute?cron=0 0/1 * * * ?").routeId("logMonitorRoute")
//                .to("bean:monitorService?method=monitor")
////        .bean(MonitorService.class,"monitor")
//        ;
    }
}

+ 16 - 0
hos-camel2/src/main/java/camel/terminal/collect/processor/CollectProcessor0.java

@ -0,0 +1,16 @@
package camel.terminal.collect.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
/**
 * Created by Zdm on 2016/7/13.
 */
public class CollectProcessor0 implements Processor {
    @Override
    public void process(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        outMessage.setHeader(Exchange.HTTP_QUERY, "jobId=jobId");
    }
}

+ 12 - 0
hos-camel2/src/main/java/camel/terminal/collect/route/CollectQuartzRoute.java

@ -0,0 +1,12 @@
package camel.terminal.collect.route;
import camel.terminal.collect.processor.CollectProcessor0;
import org.apache.camel.builder.RouteBuilder;
public class CollectQuartzRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("quartz://myGroup/collectTimer?cron=0/3 * * * * ?").routeId("routeId").process(new CollectProcessor0())
                .to("http4://172.19.103.58:8088/crawler/collect").to("stream:out");
    }
}

+ 19 - 0
hos-camel2/src/main/java/camel/terminal/crawler/processor/Aggregate.java

@ -0,0 +1,19 @@
package camel.terminal.crawler.processor;
import org.apache.camel.Exchange;
import org.apache.camel.processor.aggregate.AggregationStrategy;
public class Aggregate implements AggregationStrategy {
    public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
        //如果oldExchange为null,则说明是第一个分解包
        if (oldExchange == null) {
            return newExchange;
        }
        String oldBody = oldExchange.getIn().getBody(String.class);
        String newBody = newExchange.getIn().getBody(String.class);
        //将新与旧包进行合并,再设置进Message的body中
        oldExchange.getIn().setBody(oldBody + "\n" + newBody);
        return oldExchange;
    }
}

+ 32 - 0
hos-camel2/src/main/java/camel/terminal/crawler/processor/AggregateProcessor.java

@ -0,0 +1,32 @@
package camel.terminal.crawler.processor;
import net.sf.json.JSONObject;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import java.util.Iterator;
public class AggregateProcessor implements Processor {
    private String paramJson;
    public AggregateProcessor(String paramJson) {
        this.paramJson = paramJson;
    }
    public void process(Exchange exchange) throws Exception {
        Message inMessage = exchange.getIn();
        Message outMessage = exchange.getOut();
        JSONObject jsonObject = JSONObject.fromObject(paramJson);
        Iterator iterator = jsonObject.keys();
        while (iterator.hasNext()) {
            String name = (String) iterator.next();
            String value = (String) jsonObject.get(name);
            outMessage.setHeader(name, value);
        }
        String body = inMessage.getBody(String.class);
        outMessage.setBody(body);
    }
}

+ 35 - 0
hos-camel2/src/main/java/camel/terminal/crawler/processor/DefaultHttpProcessor.java

@ -0,0 +1,35 @@
package camel.terminal.crawler.processor;
import com.yihu.hos.core.datatype.StringUtil;
import net.sf.json.JSONObject;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import java.util.Iterator;
/**
 *  采集上传流程操作类
 *  用于参数解析
 */
public class DefaultHttpProcessor implements Processor {
    private String paramJson;
    public DefaultHttpProcessor(String paramJson) {
        this.paramJson = paramJson;
    }
    public void process(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        JSONObject jsonObject = JSONObject.fromObject(paramJson);
        Iterator iterator = jsonObject.keys();
        String queryStr = "";
        while (iterator.hasNext()) {
            String name = (String) iterator.next();
            String value = (String) jsonObject.get(name);
            queryStr += name + "=" + value + "&&";
        }
        queryStr = StringUtil.substring(queryStr, 0, queryStr.length() - 2);
        outMessage.setHeader(Exchange.HTTP_QUERY, queryStr);
    }
}

+ 19 - 0
hos-camel2/src/main/java/camel/terminal/crawler/processor/HttpProcessor.java

@ -0,0 +1,19 @@
package camel.terminal.crawler.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
public class HttpProcessor implements Processor {
    private String paramName;
    public HttpProcessor(String paramName) {
        this.paramName = paramName;
    }
    public void process(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        Message inMessage = exchange.getIn();
        outMessage.setHeader(Exchange.HTTP_QUERY, paramName + "=" + inMessage.getBody(String.class));
    }
}

+ 13 - 0
hos-camel2/src/main/java/camel/terminal/crawler/processor/Split.java

@ -0,0 +1,13 @@
package camel.terminal.crawler.processor;
import net.sf.json.JSONArray;
import org.apache.camel.Body;
import java.io.IOException;
public class Split {
    public JSONArray splitJsonArray(@Body String jsonArrayStr) throws IOException {
        return JSONArray.fromObject(jsonArrayStr);
    }
}

+ 19 - 0
hos-camel2/src/main/java/camel/terminal/crawler/route/CrawlerQuartzRoute.java

@ -0,0 +1,19 @@
package camel.terminal.crawler.route;
import camel.terminal.crawler.processor.DefaultHttpProcessor;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
/**
 * 采集上传流程
 *  此类为camel-quartz 采集使用的模板类,
 *  格式要求:1.routeId("routeId")
 *            2."{\"jobId\": \"jobId\"}"
 * @author HZY * @vsrsion 1.0 * Created at 2016/11/17.
 */
public class CrawlerQuartzRoute extends RouteBuilder {
    public void configure() throws Exception {
        from("quartz://myGroup/crawlerTimer?cron=0/3 * * * * ?").routeId("routeId").process(new DefaultHttpProcessor("{\"jobId\": \"jobId\"}"))
                .setHeader(Exchange.HTTP_METHOD, constant("POST")).to("http4://localhost:8088/crawler/patientList").to("stream:out");
    }
}

+ 31 - 0
hos-camel2/src/main/java/camel/terminal/crawler/route/CrawlerRouteBulider.java

@ -0,0 +1,31 @@
package camel.terminal.crawler.route;
import camel.terminal.crawler.processor.DefaultHttpProcessor;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
/**
 * Created by lingfeng on 2016/7/25.
 */
public class CrawlerRouteBulider extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("jetty:http://192.168.131.96:8066/crawlerPull").routeId("crawlerPull")
                .process(new DefaultHttpProcessor("{\"jobId\":\"5ad5c11655d443c30155d477a6b10000\"}")).setHeader(Exchange.HTTP_METHOD, constant("POST"))
                .to("http://192.168.131.96:8088/camel.terminal.crawler/patientList");
        from("jetty:http://192.168.131.96:8066/crawlerPush").routeId("crawlerPush")
                .process(new DefaultHttpProcessor("{\"jobId\":\"5ad5c11655d443c30155d477a6b10000\"}")).setHeader(Exchange.HTTP_METHOD, constant("POST"))
                .to("http://192.168.131.96:8088/camel.terminal.crawler/patient");
        from("jetty:http://192.168.131.96:8066/crawlerFlowPull").routeId("crawlerFlowPull")
                .process(new DefaultHttpProcessor("{\"jobId\":\"5ad5c11655d443c30155d477a6b10000\"}")).setHeader(Exchange.HTTP_METHOD, constant("POST"))
                .to("http://192.168.131.96:8088/camel.terminal.crawler/patientListFlow");
        from("jetty:http://192.168.131.96:8066/crawlerFlowPush").routeId("crawlerFlowPush")
                .process(new DefaultHttpProcessor("{\"jobId\":\"5ad5c11655d443c30155d477a6b10000\"}")).setHeader(Exchange.HTTP_METHOD, constant("POST"))
                .to("http://192.168.131.96:8088/camel.terminal.crawler/patientFlow");
    }
}

+ 25 - 0
hos-camel2/src/main/java/camel/terminal/crawler/route/QuartzRoute.java

@ -0,0 +1,25 @@
package camel.terminal.crawler.route;
import camel.terminal.crawler.processor.DefaultHttpProcessor;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/11/17.
 */
public class QuartzRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("quartz://myGroupName/myTimerName?cron=0/5+*+*+*+*+?")
                .process(new DefaultHttpProcessor("{\"jobId\":\"5ad5c11655d443c30155d477a6b10000\"}") {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        System.out.println("I'm running every 5 sec...Change by XXXX===========");
                    }
                });
    }
}

+ 23 - 0
hos-camel2/src/main/java/camel/terminal/crawler/route/RouteBulider1.java

@ -0,0 +1,23 @@
package camel.terminal.crawler.route;
import camel.terminal.crawler.processor.Aggregate;
import camel.terminal.crawler.processor.AggregateProcessor;
import camel.terminal.crawler.processor.HttpProcessor;
import camel.terminal.crawler.processor.Split;
import org.apache.camel.builder.RouteBuilder;
/**
 * Created by lingfeng on 2016/7/25.
 */
public class RouteBulider1 extends RouteBuilder {
    public void configure() throws Exception {
        from("quartz://myGroup/myTimerName?cron=0/5 * * * * ? ").routeId("list")
                .to("http://localhost:9999/list")
                .split().method(Split.class, "splitJsonArray")
                .process(new HttpProcessor("str")).to("http://localhost:9999/str")
                .process(new AggregateProcessor("key1"))
                .aggregate(header("test_correlation_key"), new Aggregate()).completionSize(3).to("stream:out");
    }
}

+ 20 - 0
hos-camel2/src/main/java/camel/terminal/qcrule/processor/PatientProcessor.java

@ -0,0 +1,20 @@
package camel.terminal.qcrule.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
public class PatientProcessor implements Processor {
    public PatientProcessor() {
    }
    public void process(Exchange exchange) throws Exception {
        Message inMessage = exchange.getIn();
        Message outMessage = exchange.getOut();
        String body = inMessage.getBody(String.class);
        outMessage.setBody(body);
    }
}

+ 159 - 0
hos-camel2/src/main/java/camel/terminal/qcrule/processor/QcHttpProcessor.java

@ -0,0 +1,159 @@
package camel.terminal.qcrule.processor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.core.datatype.StringUtil;
import net.sf.json.JSONObject;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Iterator;
import java.util.Map;
/**
 * 采集上传流程操作类
 * 用于参数解析
 */
@Component
public class QcHttpProcessor implements Processor {
    private String paramJson;
    public QcHttpProcessor() {
    }
    public QcHttpProcessor(String paramJson) {
        this.paramJson = paramJson;
    }
    public void process(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        JSONObject jsonObject = JSONObject.fromObject(paramJson);
        Iterator iterator = jsonObject.keys();
        String queryStr = "";
        while (iterator.hasNext()) {
            String name = (String) iterator.next();
            String value = (String) jsonObject.get(name);
            queryStr += name + "=" + value + "&&";
        }
        queryStr = StringUtil.substring(queryStr, 0, queryStr.length() - 2);
        outMessage.setHeader(Exchange.HTTP_QUERY, queryStr);
    }
    //跳转到质控采集接口
    public String toQc(Exchange exchange) throws Exception {
        Message outMessage = exchange.getOut();
        JSONObject jsonObject = JSONObject.fromObject(paramJson);
        Iterator iterator = jsonObject.keys();
        String queryStr = "jetty:http://0.0.0.0:8088/crawler/qc/patient";
        while (iterator.hasNext()) {
            String name = (String) iterator.next();
            String value = (String) jsonObject.get(name);
            queryStr += name + "=" + value + "&&";
        }
        queryStr = StringUtil.substring(queryStr, 0, queryStr.length() - 2);
        return queryStr;
//        outMessage.setHeader(Exchange.HTTP_QUERY, queryStr);
    }
    public void patient(Exchange exchange) throws Exception {
        Message inMessage = exchange.getIn();
        JSONObject jsonObject = JSONObject.fromObject(inMessage.getBody());
        exchange.getOut().setBody(jsonObject.toString());
        System.out.println(inMessage.getBody());
    }
    public String routeUploadPatient(Exchange exchange) throws IOException, ParseException {
//        body = URLDecoder.decode(body, "UTF-8");
        Map<String, Object> params = exchange.getIn().getHeaders();
//        String api = params.get("api").toString();                     // API接口名称
        String param = params.get("param").toString();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode jsonNode = objectMapper.readValue(param, JsonNode.class);
            String url = "jetty:http://0.0.0.0:8088/crawler/patient";
            final String[] endPoint = {url};
            final String[] body = {""};
//            body[0] += ("&" + p.getName() + "=" + value);
            if (body[0].length() != 0) {
                exchange.getOut().setHeader(Exchange.REST_HTTP_QUERY, body[0].substring(1));
            }
//            exchange.getOut().setBody(null);
            return endPoint[0];
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    public String routeUploadQc(Exchange exchange) throws IOException, ParseException {
//        body = URLDecoder.decode(body, "UTF-8");
        Map<String, Object> params = exchange.getIn().getHeaders();
        String patient = URLEncoder.encode(params.get("patient").toString(), "UTF-8"); //病人信息
        String rules = exchange.getIn().getBody(String.class);//规则队列
        try {
            String endPoint = "jetty:http://0.0.0.0:8088/crawler/qc/patient";
            final String queryParams = "checkType=" + rules + "&patient=" + patient;
            exchange.getOut().setHeader(Exchange.REST_HTTP_QUERY, queryParams);
            return endPoint;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 根据job上传质控数据和档案包
     * @param exchange
     * @return
     * @throws IOException
     * @throws ParseException
     */
    public String routeUploadQcByJob(Exchange exchange) throws IOException, ParseException {
//        body = URLDecoder.decode(body, "UTF-8");
        Map<String, Object> params = exchange.getIn().getHeaders();
        String jobId = (String) exchange.getIn().getHeader(Exchange.HTTP_QUERY);
        String rules = exchange.getIn().getBody(String.class);//规则队列
        try {
            String endPoint = "jetty:http://0.0.0.0:8088/crawler/qc/crawlerPatientList";
            final String queryParams = "checkType=" + rules + "&" + jobId;
            exchange.getOut().setHeader(Exchange.REST_HTTP_QUERY, queryParams);
            return endPoint;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 统计规则,返回规则列表
     *
     * @param exchange
     * @throws Exception
     */
    public void coutType(Exchange exchange) throws Exception {
        Message inMessage = exchange.getIn();
        String newType = (String) inMessage.getHeader("checkType");
        Object countType = inMessage.getHeader("countType");
        if (countType != null && !StringUtil.isEmpty(countType)) {
            newType = newType + "," + countType;
        }
        exchange.getOut().setHeader("countType", newType);
        exchange.getOut().setBody(inMessage.getBody());
    }
}

+ 63 - 0
hos-camel2/src/main/java/camel/terminal/qcrule/router/QcCrawlerRoute.java

@ -0,0 +1,63 @@
package camel.terminal.qcrule.router;
import camel.terminal.crawler.processor.Split;
import camel.terminal.qcrule.processor.PatientProcessor;
import camel.terminal.qcrule.processor.QcHttpProcessor;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
/**
 * 采集上传流程
 *  此类为camel-quartz 采集使用的模板类,
 *  格式要求:1.routeId("routeId")
 *            2."{\"jobId\": \"jobId\"}"
 * @author HZY * @vsrsion 1.0 * Created at 2016/11/17.
 */
@Component
public class QcCrawlerRoute extends RouteBuilder {
    public void configure() throws Exception {
        from("jetty:http://0.0.0.0:8888/qc/crawler").routeId("creawrouteId").process(new QcHttpProcessor("{\"jobId\": \"4028cb815c7c0770015c7c0bbc3f0000\"}"))
                .setHeader(Exchange.HTTP_METHOD, constant("POST"))
                .to("jetty:http://0.0.0.0:8088/crawler/qc/patientList")
                .split().method(Split.class, "splitJsonArray")//循环
                .to("direct:splitPatient");
        from("direct:splitPatient")
                .process(new PatientProcessor())
                .multicast().parallelProcessing()//多播
                //新增规则
                .to("direct:uploadQc", "direct:uploadPatient")
        .end();
        from("direct:uploadQc")
                .setHeader("patient", body())
                .to("jetty:http://0.0.0.0:8088/crawler/qc/rules")//获取规则列表
                .routingSlip(method(QcHttpProcessor.class, "routeUploadQc"))//质控采集路由
                .to("jetty:http://0.0.0.0:8088/crawler/test");
        from("direct:uploadPatient")
//                .routingSlip(method(QcHttpProcessor.class, "routeUploadPatient"));
                .to("jetty:http://0.0.0.0:8088/crawler/test2");
        from("jetty:http://0.0.0.0:7777/qc/{checkType}")
                .choice()
                .when(header(Exchange.HTTP_URI).contains("checkNull")).setHeader("checkType", constant("emptry")).bean(method(QcHttpProcessor.class, "coutType"))
                .when(header(Exchange.HTTP_URI).contains("checkRight")).setHeader("checkType", constant("error")).bean(method(QcHttpProcessor.class, "coutType"))
                .endChoice();
        //通过任务直接采集质控数据和档案数据
        from("jetty:http://0.0.0.0:8999/qc/crawler").routeId("crawlerQcList").process(new QcHttpProcessor("{\"jobId\": \"4028cb815c7c0770015c7c0bbc3f0000\"}"))
                .setHeader(Exchange.HTTP_METHOD, constant("POST"))
                .to("jetty:http://0.0.0.0:8088/crawler/qc/rules")//获取规则列表
                .routingSlip(method(QcHttpProcessor.class, "routeUploadQcByJob"))//根据job采集质控路由
                ;
    }
}

+ 32 - 0
hos-camel2/src/main/java/camel/terminal/tenant/processor/AddMongoProcessor.java

@ -0,0 +1,32 @@
package camel.terminal.tenant.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
/**
 * 
 * Created by Zdm on 2016/7/13.
 */
public class AddMongoProcessor implements Processor {
    private String database;
    private String collection;
    public AddMongoProcessor(String database, String collection) {
        this.database = database;
        this.collection = collection;
    }
    @Override
    public void process(Exchange exchange) throws Exception {
//        Map record = exchange.getIn().getBody(Map.class);
//        Map info = new HashMap();
//        info.put("database", database);
//        info.put("collection", collection);
//        ObjectId objectId = (ObjectId) record.get("_id");
//        record.put("_id", objectId.toString());
//        JSONArray jsonArray = new JSONArray();
//        jsonArray.put(info);
//        jsonArray.put(record);
//        exchange.getIn().setBody(jsonArray);
    }
}

+ 31 - 0
hos-camel2/src/main/java/camel/terminal/tenant/processor/CrawlerMongoProcessor.java

@ -0,0 +1,31 @@
package camel.terminal.tenant.processor;
import com.mongodb.BasicDBObject;
import com.mongodb.QueryOperators;
import com.yihu.hos.core.datatype.DateUtil;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import java.util.Date;
/**
 * Created by Zdm on 2016/7/13.
 */
public class CrawlerMongoProcessor implements Processor {
    @Override
    public void process(Exchange exchange) throws Exception {
        Message out = exchange.getOut();
        Date now = new Date();
        Date beforeDate = new Date(now.getTime() - 60000);
        String beginTime = DateUtil.toString(beforeDate, DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
        String endTime = DateUtil.toString(now, DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
        BasicDBObject queryObject = new BasicDBObject().append(QueryOperators.AND,
                new BasicDBObject[]{
                        new BasicDBObject().append("create_time",
                                new BasicDBObject().append(QueryOperators.GTE, beginTime)),
                        new BasicDBObject().append("create_time",
                                new BasicDBObject().append(QueryOperators.LT, endTime))});
        out.setBody(queryObject.toJson());
    }
}

+ 39 - 0
hos-camel2/src/main/java/camel/terminal/tenant/route/CrawlerMongoRouter.java

@ -0,0 +1,39 @@
package camel.terminal.tenant.route;
import camel.terminal.tenant.processor.AddMongoProcessor;
import camel.terminal.tenant.processor.CrawlerMongoProcessor;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
@Component
public class CrawlerMongoRouter extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("quartz://myGroup/myTimerName?cron=0 0/1 * * * ? ")
            .process(new CrawlerMongoProcessor())
            .to("mongodb:mongo?database=runtime&collection=arbiterServer&operation=findOneByQuery")
            .split(simple("${body}"))
            .process(new AddMongoProcessor("runtime", "arbiterServer"))
            .to("bean:centerMongoService?method=save")
            .process(new CrawlerMongoProcessor())
            .to("mongodb:mongo?database=runtime&collection=brokerServer&operation=findOneByQuery")
            .split(simple("${body}"))
            .process(new AddMongoProcessor("runtime", "brokerServer"))
            .to("bean:centerMongoService?method=save")
            .process(new CrawlerMongoProcessor())
            .to("mongodb:mongo?database=runtime&collection=endpoint&operation=findOneByQuery")
            .split(simple("${body}"))
            .process(new AddMongoProcessor("runtime", "endpoint"))
            .to("bean:centerMongoService?method=save")
            .process(new CrawlerMongoProcessor())
            .to("mongodb:mongo?database=log&collection=server&operation=findOneByQuery")
            .split(simple("${body}"))
            .process(new AddMongoProcessor("log", "server"))
            .to("bean:centerMongoService?method=save")
            .process(new CrawlerMongoProcessor())
            .to("mongodb:mongo?database=log&collection=service&operation=findOneByQuery")
            .split(simple("${body}"))
            .process(new AddMongoProcessor("log", "service"))
            .to("bean:centerMongoService?method=save");
    }
}

+ 44 - 0
hos-camel2/src/main/resources/application.yml

@ -0,0 +1,44 @@
application:
  message: test
server:
  context-path: /
  port: 8001
  session-timeout:  3000
---
spring:
  profiles: dev
  datasource:
    driverClassName: oracle.jdbc.OracleDriver
    url: jdbc:oracle:thin:@//219.139.128.22:1521/orcl
    username: rhc_his
    password: rhc_his
    test-on-borrow: true
    validation-query: SELECT 1
    test-while-idle: true
    max-total: 100
    default-auto-commit: true
    max-idle: 50
    min-idle: 20
    initial-size: 10
  data:
    mongodb:
      host: 172.19.103.57
      port: 27017
      username: esb
      password: esb
      authenticationDatabase: admin
      database: log
      gridFsDatabase: dfs
  activemq:
    broker-url: tcp://172.19.103.57:61616
    user: admin
    password: admin
eureka:
  client:
    serviceUrl:
      defaultZone: http://172.19.103.73:8761/eureka/
hos:
  https:
    enable: false

+ 8 - 0
hos-camel2/src/main/resources/jndi.properties

@ -0,0 +1,8 @@
connectionFactoryNames = ConnectionFactory
# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
#queue.logback-queue = business.log.queue
# queue.[jndiName] = [physicalName]
topic.logback-queue = business.log.queue

+ 60 - 0
hos-camel2/src/main/resources/logback-spring.xml

@ -0,0 +1,60 @@
<configuration>
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%date [%thread] %-5level %logger{25} - %msg%n</Pattern>
        </layout>
    </appender>
    <appender name="file" class="ch.qos.logback.core.FileAppender">
        <file>logs/main.log</file>
        <append>true</append>
        <encoder>
            <Pattern>%date [%thread] %-5level %logger{25} - %msg%n</Pattern>
        </encoder>
    </appender>
    <appender name="queue" class="camel.log.JmsAppender">
        <InitialContextFactoryName>
            org.apache.activemq.jndi.ActiveMQInitialContextFactory
        </InitialContextFactoryName>
        <ProviderURL>tcp://172.19.103.57:61616</ProviderURL>
        <userName>admin</userName>
        <password>admin</password>
        <TopicConnectionFactoryBindingName>ConnectionFactory</TopicConnectionFactoryBindingName>
        <TopicBindingName>logback-queue</TopicBindingName>
    </appender>
    <logger name="org.apache.camel" level="INFO" additivity="false">
        <appender-ref ref="queue"/>
    </logger>
    <!-- 开发环境配置 -->
    <springProfile name="dev">
        <logger name="org.apache.camel" level="INFO" additivity="false">
            <appender-ref ref="queue"/>
        </logger>
        <logger name="org.hibernate" level="WARN"/>
        <logger name="org.springframework" level="WARN"/>
        <logger name="springfox.documentation" level="WARN"/>
        <root level="INFO">
            <appender-ref ref="file"/>
            <appender-ref ref="console"/>
        </root>
    </springProfile>
    <!-- 测试服务器配置 -->
    <springProfile name="test">
        <logger name="org.apache.camel" level="INFO" additivity="false">
            <appender-ref ref="queue"/>
        </logger>
        <logger name="org.hibernate" level="WARN"/>
        <logger name="org.springframework" level="WARN"/>
        <logger name="springfox.documentation" level="WARN"/>
        <root level="WARN">
            <appender-ref ref="file"/>
            <appender-ref ref="console"/>
        </root>
    </springProfile>
</configuration>

BIN
hos-camel2/src/main/resources/tomcat.keystore


+ 19 - 0
hos-camel2/src/test/java/camel/SpringbootApplicationTests.java

@ -0,0 +1,19 @@
package camel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
 * Empty test to test that Spring Boot can startup
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {
    @Test
    public void contextLoads() {
    }
}

+ 20 - 0
hos-docker/.gitignore

@ -0,0 +1,20 @@
# ---> Java
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

+ 13 - 0
hos-docker/Dockerfile

@ -0,0 +1,13 @@
FROM daocloud.io/library/java
ENV spring_profiles_active default,test
ADD ./jar /hos-parse
WORKDIR /hos-parse
VOLUME /hos-parse
EXPOSE 5050
#ENTRYPOINT nohup java -Djava.security.egd=file:/dev/./urandom -jar hos-parse.jar >/dev/null 2>&1 &
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","hos-parse.jar"]

BIN
hos-docker/esb/activemq/apache-activemq-5.14.0-bin.tar.gz


+ 141 - 0
hos-docker/pom.xml

@ -0,0 +1,141 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yihu.hos</groupId>
    <artifactId>hos-parse</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>
    <name>hos-parse</name>
    <description>Demo project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <docker.image.prefix>eip2</docker.image.prefix>
        <docker.imageName>eip-parase</docker.imageName>
        <docker.maintainer>hos-parse</docker.maintainer>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.yihu.hos</groupId>
            <artifactId>hos-web-framework</artifactId>
            <version>1.3.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-data-mongodb</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.3</version>
        </dependency>
    </dependencies>
    <build>
        <!-- Dockerfile文件路径配置 -->
        <resources>
            <resource>
                <directory>src/main/docker</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/Dockerfile</include>
                </includes>
                <targetPath>src/main/docker</targetPath>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!--<plugin>-->
            <!--<groupId>com.spotify</groupId>-->
            <!--<artifactId>docker-maven-plugin</artifactId>-->
            <!--<configuration>-->
            <!--<serverId>docker-hub</serverId>-->
            <!--<registryUrl>${docker.image.prefix}</registryUrl>-->
            <!--<dockerHost>http://172.19.103.37:2377</dockerHost>-->
            <!--<dockerCertPath>C:\Users\admin\.docker\machine\machines\manager</dockerCertPath>-->
            <!--<imageName>${docker.image.prefix}/${docker.imageName}:${project.version}</imageName>-->
            <!--<baseImage>java:8</baseImage>-->
            <!--<maintainer>${docker.maintainer}</maintainer>-->
            <!--<volumes>/tmp</volumes>-->
            <!--<entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>-->
            <!--<resources>-->
            <!--<resource>-->
            <!--<targetPath>/</targetPath>-->
            <!--<directory>${project.build.directory}</directory>-->
            <!--<include>${project.build.finalName}.jar</include>-->
            <!--</resource>-->
            <!--</resources>-->
            <!--</configuration>-->
            <!--</plugin>-->
            <!--<plugin>-->
            <!--<groupId>com.spotify</groupId>-->
            <!--<artifactId>dockerfile-maven-plugin</artifactId>-->
            <!--<version>1.4.0</version>-->
            <!--<configuration>-->
            <!--<repository>${docker.image.prefix}/${project.artifactId}</repository>-->
            <!--<buildArgs>-->
            <!--<JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>-->
            <!--</buildArgs>-->
            <!--</configuration>-->
            <!--</plugin>-->
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <configuration>
                    <imageName>${project.name}:${project.version}</imageName>
                    <dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
                    <skipDockerBuild>false</skipDockerBuild>
                    <resources>
                        <resource>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

+ 39 - 0
hos-docker/readme.md

@ -0,0 +1,39 @@
备注:${}和<> 指变量
##hos-docker
 ###   1.服务说明:  
        该服务的主要功能是作为docker打包发布的demo工程
 ###   2.配置说明:  
 参考地址:https://blog.csdn.net/weixin_36667844/article/details/74644233
 #### a . 开启docker远程API
 修改docker配置文件#vi /usr/lib/systemd/system/docker.service   ,进入编辑模式后,将ExecStart这一行后面加上 -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock ,改完后如下所示  
 
 ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2377 -H unix:///var/run/docker.sock
 #### b . 本地环境变量配置
 添加系统环境变量:DOCKER_HOST:tcp://172.19.103.37:2377 //用于远程操作docker
 
 #### c . pom配置
        <plugin>
            <groupId>com.spotify</groupId>
            <artifactId>docker-maven-plugin</artifactId>
            <configuration> //配置镜像名称
                <imageName>${project.name}:${project.version}</imageName>
                <dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
                <skipDockerBuild>false</skipDockerBuild>
                <resources>
                    <resource>
                        <directory>${project.build.directory}</directory>
                        <include>${project.build.finalName}.jar</include>
                    </resource>
                </resources>
            </configuration>
        </plugin>
        
 #### d . 编写dockerFile
 #### e . 打包发布:  
    clean package docker:build -DskipTests //打包并发布到docker仓库
 #### f . 运行镜像
 初次使用,运行镜像,生成对应容器
 docker images
 docker run -d -p 5050:5050  <imageId> //启动
 

+ 14 - 0
hos-docker/src/main/docker/Dockerfile

@ -0,0 +1,14 @@
FROM daocloud.io/library/java
VOLUME /tmp
ENV spring_profiles_active default,test
ADD  ./hos-parse-1.0.0.jar /hos-parse/
WORKDIR /hos-parse
VOLUME /hos-parse
EXPOSE 5050
#ENTRYPOINT nohup java -Djava.security.egd=file:/dev/./urandom -jar hos-parse-1.0.0.jar >/dev/null 2>&1 &
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","hos-parse-1.0.0.jar"]

+ 6 - 0
hos-docker/src/main/esb/activemq/Dockerfile

@ -0,0 +1,6 @@
FROM daocloud.io/library/java
ADD apache-activemq-5.14.0-bin.tar.gz /
WORKDIR apache-activemq-5.14.0/bin/
ENTRYPOINT ./activemq start && tail -f /apache-activemq-5.14.0/data/activemq.log
EXPOSE 8161
EXPOSE 61616

+ 68 - 0
hos-docker/src/main/esb/central-docker-compose/docker-compose.yml

@ -0,0 +1,68 @@
version: "2"
services:
    admin:
        build: /usr/local/esb/hos-admin
        container_name: admin
        ports:
            - "8080:8080"
            - "15555:15555"
        volumes:
            - /usr/local/esb/hos-admin/jar:/hos-admin/jar
        depends_on:
            - "mongodb"
            - "mysql"
            - "activemq"
    broker:
        build: /usr/local/esb/hos-broker
        container_name: broker
        ports:
            - "8099-10000:8099-10000"
        volumes:
            - /usr/local/esb/hos-broker/jar:/hos-broker/jar
        environment:
            - host=172.19.103.67
        depends_on:
            - "arbiter"
            - "rest"
            - "mongodb"
            - "mysql"
            - "activemq"
    arbiter:
        build: /usr/local/esb/hos-arbiter
        container_name: arbiter
        ports:
            - "10135:10135"
        volumes:
            - /usr/local/esb/hos-arbiter/jar:/hos-arbiter/jar
        depends_on:
            - "mongodb"
            - "mysql"
            - "activemq"
    rest:
        build: /usr/local/esb/hos-rest
        container_name: rest
        ports:
            - "8088:8088"
        volumes:
            - /usr/local/esb/hos-rest/jar:/hos-rest/jar
        depends_on:
            - "mongodb"
            - "mysql"
            - "activemq"
    mongodb:
        build: /usr/local/esb/mongodb
        container_name: mongodb
        ports:
            - "27017:27017"
    mysql:
        build: /usr/local/esb/mysql
        container_name: mysql
        ports:
            - "3306:3306"
    activemq:
        build: /usr/local/esb/activemq
        container_name: activemq
        ports:
            - "61616:61616"
            - "8161:8161"
      

+ 54 - 0
hos-docker/src/main/esb/docker-compose.yml

@ -0,0 +1,54 @@
version: "2"
services:
    broker:
        build: /usr/local/esb/hos-broker
        container_name: broker
        ports:
            - "8099:8099"
        volumes:
            - /usr/local/esb/hos-broker/jar:/hos-broker/jar
        depends_on:
            - "arbiter"
            - "rest"
            - "mongodb"
            - "mysql"
            - "activemq"
    arbiter:
        build: /usr/local/esb/hos-arbiter
        container_name: arbiter
        ports:
            - "10135:10135"
        volumes:
            - /usr/local/esb/hos-arbiter/jar:/hos-arbiter/jar
        depends_on:
            - "mongodb"
            - "mysql"
            - "activemq"
    rest:
        build: /usr/local/esb/hos-rest
        container_name: rest
        ports:
            - "8088:8088"
        volumes:
            - /usr/local/esb/hos-rest/jar:/hos-rest/jar
        depends_on:
            - "mongodb"
            - "mysql"
            - "activemq"
    mongodb:
        build: /usr/local/esb/mongodb
        container_name: mongodb
        ports:
            - "27017:27017"
    mysql:
        build: /usr/local/esb/mysql
        container_name: mysql
        ports:
            - "3306:3306"
    activemq:
        build: /usr/local/esb/activemq
        container_name: activemq
        ports:
            - "61616:61616"
            - "8161:8161"
      

+ 9 - 0
hos-docker/src/main/esb/hos-arbiter/Dockerfile

@ -0,0 +1,9 @@
FROM daocloud.io/library/java
 
RUN mkdir -p /hos-arbiter
  
WORKDIR /hos-arbiter
ENV spring_profiles_active test
 
EXPOSE 10135
CMD tail -f /var/log/bootstrap.log

+ 1 - 0
hos-docker/src/main/esb/hos-arbiter/jar/remind.txt

@ -0,0 +1 @@
hos-arbiter程序包下载路径

+ 12 - 0
hos-docker/src/main/esb/hos-broker/Dockerfile

@ -0,0 +1,12 @@
FROM daocloud.io/library/java
ENV spring_profiles_active test
ENV host 127.0.0.1
ADD apache-tomcat-8.5.11.tar.gz /
RUN touch /apache-tomcat-8.5.11/logs/catalina.out
WORKDIR /apache-tomcat-8.5.11/bin/
VOLUME ["/var/log/hos-broker/"]
CMD tail -f /apache-tomcat-8.5.11/logs/catalina.out
WORKDIR /apache-tomcat-8.5.11/bin/
EXPOSE 8099-10000

BIN
hos-docker/src/main/esb/hos-broker/apache-tomcat-8.5.11.tar.gz


+ 1 - 0
hos-docker/src/main/esb/hos-broker/jar/remind.txt

@ -0,0 +1 @@
hos-broker程序包下载路径

+ 14 - 0
hos-docker/src/main/esb/hos-dfs/Dockerfile

@ -0,0 +1,14 @@
FROM daocloud.io/library/java
ENV spring_profiles_active default,dev
ADD ./jar /hos-dfs
WORKDIR /hos-dfs
VOLUME /hos-dfs
EXPOSE 9010
EXPOSE 9020
#ENTRYPOINT nohup java -Djava.security.egd=file:/dev/./urandom -jar hos-dfs.jar >/dev/null 2>&1 &
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","hos-dfs.jar"]

+ 10 - 0
hos-docker/src/main/esb/hos-rest/Dockerfile

@ -0,0 +1,10 @@
FROM daocloud.io/library/java
RUN mkdir -p /hos-rest
  
WORKDIR /hos-rest
ENV spring_profiles_active test
 
VOLUME ["/var/log/hos-rest/"]
 
EXPOSE 8088
CMD tail -f /var/log/bootstrap.log

+ 1 - 0
hos-docker/src/main/esb/hos-rest/jar/remind.txt

@ -0,0 +1 @@
hos-rest程序包下载路径

+ 3 - 0
hos-docker/src/main/esb/mongodb/Dockerfile

@ -0,0 +1,3 @@
FROM daocloud.io/library/mongo
ADD fit_mongo1.js /
ADD fit_mongo2.js /

+ 11 - 0
hos-docker/src/main/esb/mongodb/fit_mongo1.js

@ -0,0 +1,11 @@
try{
    var db = connect('admin');
    if(db.system.users.find({'user':'root'}).count() == 0){
        print('Ready to addUser...');
        db.createUser({ user: 'root', pwd: 'xmjkzl', roles: [ { role:"userAdminAnyDatabase", db: "admin" } ,{ role:"readWriteAnyDatabase", db: "admin" }] });
    }else{
        print('Already exist user.')
    }
}catch(err){
    print('Error occured:' + err);
}

+ 11 - 0
hos-docker/src/main/esb/mongodb/fit_mongo2.js

@ -0,0 +1,11 @@
try{
    var db = connect('admin');
    if(db.system.users.find({'user':'esb'}).count() == 0){
        print('Ready to addUser...');
        db.createUser({ user: 'esb', pwd: 'esb', roles: [ { role:"readWriteAnyDatabase", db: "admin" } ] });
    }else{
        print('Already exist user.')
    }
}catch(err){
    print('Error occured:' + err);
}

+ 10 - 0
hos-docker/src/main/esb/mysql/Dockerfile

@ -0,0 +1,10 @@
FROM daocloud.io/library/mysql
ADD user.sql /
ADD data.sql /
ADD mysql.cnf /
RUN rm /etc/mysql/conf.d/mysql.cnf
RUN cp mysql.cnf /etc/mysql/conf.d/
ENV MYSQL_ROOT_PASSWORD=123456
VOLUME ["/etc/mysql/conf.d"]
EXPOSE 3306

File diff suppressed because it is too large
+ 1586821 - 0
hos-docker/src/main/esb/mysql/data.sql


+ 4 - 0
hos-docker/src/main/esb/mysql/mysql.cnf

@ -0,0 +1,4 @@
[mysqld]
sql_mode=STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
[client]
default-character-set=utf8

+ 3 - 0
hos-docker/src/main/esb/mysql/user.sql

@ -0,0 +1,3 @@
create database hos1;
grant all privileges on *.* to hos@"%" identified by "123456";
flush privileges;

+ 27 - 0
hos-docker/src/main/esb/start.sh

@ -0,0 +1,27 @@
mkdir /usr/local/esb;
yum update;
chmod -R 777 /usr/local/esb;
yum -y install docker-io;
service docker start;
chkconfig docker on;
yum -y install epel-release
yum -y install python-pip
pip install docker-compose
cd /usr/local/esb;
docker-compose up --no-recreate
docker exec -it mysql /bin/bash -c "exec mysql -h localhost -u root -p123456 < /user.sql && exit;";
docker exec -it mysql /bin/bash -c "exec mysql -h localhost -u root -p123456 hos1 < /data.sql && exit;";
docker exec -it mongodb /bin/bash -c "exec mongo --host 127.0.0.1:27017 admin fit_mongo1.js && exit;";
docker exec -it mongodb /bin/bash -c "exec mongo --host 127.0.0.1:27017 -u root -p xmjkzl --authenticationDatabase admin fit_mongo2.js && exit;";
docker exec -it rest /bin/bash -c "java -Djava.security.egd=file:/dev/./urandom -jar /hos-rest/jar/hos-rest-1.3.0.jar && exit;";
docker exec -it arbiter /bin/bash -c "java -Djava.security.egd=file:/dev/./urandom -jar /hos-arbiter/jar/hos-arbiter-1.3.0.jar && exit;";
docker exec -it broker /bin/bash -c "rm -rf /apache-tomcat-8.5.11/webapps/ROOT && unzip -oq /hos-broker/jar/hos-broker-1.3.0.war -d /apache-tomcat-8.5.11/webapps/ROOT && ./startup.sh && tail -f /apache-tomcat-8.5.11/logs/catalina.out && exit;";
docker exec -it admin /bin/bash -c "rm -rf /apache-tomcat-8.5.11/webapps/ROOT && unzip -oq /hos-admin/jar/hos-admin-1.3.0.war -d /apache-tomcat-8.5.11/webapps/ROOT && ./startup.sh && tail -f /apache-tomcat-8.5.11/logs/catalina.out && exit;";
scp root@172.19.0.1:/usr/local/esb/docker-compose.yml /

+ 21 - 0
hos-docker/src/main/java/com/yihu/hos/central/controller/DemoController.java

@ -0,0 +1,21 @@
package com.yihu.hos.central.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author HZY
 * @created 2018/8/15 8:46
 */
@RequestMapping("/demo")
@RestController
public class DemoController {
    @RequestMapping(value = "test", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String test() {
        return "test=================";
    }
}

+ 166 - 0
hos-docker/src/main/java/com/yihu/hos/central/model/InpatientIdex.java

@ -0,0 +1,166 @@
package com.yihu.hos.central.model;
import java.io.Serializable;
import java.util.List;
/**
 * 病案首页-数据模型类
 *
 * @author HZY
 * @created 2018/8/13 14:28
 */
public class InpatientIdex implements Serializable {
    private String orgCode;
    private String orgName;
    private String patientId;
    private String eventNo;
    private String eventDate;
    private String partName;
    private String name;
    private Integer age;
    private String nation;
    private String inCheck; //入院诊断
    private String masterResult;//主诉
    //中医 望闻问切
    private List<String> seeCheck;//望诊
    private List<String> smellCheck;//闻诊
    private List<String> askCheck;//问诊
    private List<String> cutCheck;//切诊
    //主要护理措施
    private String primaryCare;
    public String getOrgCode() {
        return orgCode;
    }
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    public String getPatientId() {
        return patientId;
    }
    public void setPatientId(String patientId) {
        this.patientId = patientId;
    }
    public String getEventNo() {
        return eventNo;
    }
    public void setEventNo(String eventNo) {
        this.eventNo = eventNo;
    }
    public String getEventDate() {
        return eventDate;
    }
    public void setEventDate(String eventDate) {
        this.eventDate = eventDate;
    }
    public String getPartName() {
        return partName;
    }
    public void setPartName(String partName) {
        this.partName = partName;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getNation() {
        return nation;
    }
    public void setNation(String nation) {
        this.nation = nation;
    }
    public String getInCheck() {
        return inCheck;
    }
    public void setInCheck(String inCheck) {
        this.inCheck = inCheck;
    }
    public String getMasterResult() {
        return masterResult;
    }
    public void setMasterResult(String masterResult) {
        this.masterResult = masterResult;
    }
    public List<String> getSeeCheck() {
        return seeCheck;
    }
    public void setSeeCheck(List<String> seeCheck) {
        this.seeCheck = seeCheck;
    }
    public List<String> getSmellCheck() {
        return smellCheck;
    }
    public void setSmellCheck(List<String> smellCheck) {
        this.smellCheck = smellCheck;
    }
    public List<String> getAskCheck() {
        return askCheck;
    }
    public void setAskCheck(List<String> askCheck) {
        this.askCheck = askCheck;
    }
    public List<String> getCutCheck() {
        return cutCheck;
    }
    public void setCutCheck(List<String> cutCheck) {
        this.cutCheck = cutCheck;
    }
    public String getPrimaryCare() {
        return primaryCare;
    }
    public void setPrimaryCare(String primaryCare) {
        this.primaryCare = primaryCare;
    }
}

+ 69 - 0
hos-docker/src/main/java/com/yihu/hos/central/service/event/DemoEvent.java

@ -0,0 +1,69 @@
package com.yihu.hos.central.service.event;
import com.yihu.hos.central.model.InpatientIdex;
import com.yihu.hos.core.file.FileUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.select.NodeFilter;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * @author HZY
 * @created 2018/8/13 11:13
 */
@Component
public class DemoEvent {
//    public static void testParse() throws Exception {
//        String filePath = "E:\\test\\data\\demo.html";
////        String filePath = "E:\\test\\data\\demo1.json";
//        File file = new File(filePath);
//        String fileEncode=FileUtil.getCharSet(filePath);
//        String content = FileUtil.readFileText(file,fileEncode);
//        Document doc = Jsoup.parse(content);
//        Elements headers = doc.select("header p");
//
//        Elements macroList =  headers.get(1).getElementsByTag("macro");
//
//        String orgName = headers.get(0).select("span").get(0).text();
//        String name = macroList.select("macro[name='姓名']").get(0).text();
//        String dept = macroList.select("macro[name='科室']").get(0).text();
//        String eventNo = macroList.select("macro[name='住院号']").get(0).text();
//
//        for(int i=1;i<macroList.size();i++) { // 通过FileBug发现这个网页里面第一个li不是我们要的类型,所以从1开始
//            InpatientIdex inpatientIdex = new InpatientIdex();
//            Element macro_ = macroList.get(i);
//            System.out.println(macro_);
//
//        }
//
//
//    }
//    public static void main(String[] args) throws Exception {
////        testParse();
//        testFile();
//    }
//    public static void testFile() throws IOException {
//        String filePath = "C:\\Users\\HZY\\Desktop\\testData.txt";
//        String newFilePath = "C:\\Users\\HZY\\Desktop\\testData.doc";
//        File file = new File(filePath);
//        String str = FileUtil.readFileText(file);
////        BASE64Decoder decoder = new BASE64Decoder();
////        byte[] newBy = decoder.decodeBuffer(str);
//        FileUtil.writeFileByString(newFilePath,str,"UTF-8");
//
//        String str2 = FileUtil.file2Base64String(filePath);
//        System.out.println(str2);
//
//    }
}

+ 9 - 0
hos-docker/src/main/java/com/yihu/hos/central/service/event/InpatientOutEvent.java

@ -0,0 +1,9 @@
package com.yihu.hos.central.service.event;
/**
 * @author hzy
 * @created 2018/8/13 10:35
 */
public class InpatientOutEvent {
}

+ 18 - 0
hos-docker/src/main/resources/application.yml

@ -0,0 +1,18 @@
server:
  port: 5050
---
spring:
  profiles: dev
---
spring:
  profiles: test
---
spring:
  profiles: prod