Browse Source

参数转换

Airhead 8 years ago
parent
commit
41cb4b259f

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

@ -26,7 +26,7 @@ public class GatewayController {
        this.gatewayService = gatewayService;
    }
    @RequestMapping(value = "/gateway", method = RequestMethod.POST)
    @RequestMapping(value = "/camel.gateway", method = RequestMethod.POST)
    public void transfer(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

+ 3 - 3
hos-broker/src/main/resources/application.yml

@ -43,7 +43,7 @@ spring:
      authenticationDatabase: admin
      database: log
      gridFsDatabase: dfs
  gateway:
  camel.gateway:
    ip: localhost
    port: 8066
hos:
@ -96,7 +96,7 @@ spring:
      authenticationDatabase: admin
      database: log
      gridFsDatabase: dfs
  gateway:
  camel.gateway:
    ip: localhost
    port: 8066
hos:
@ -135,7 +135,7 @@ spring:
      authenticationDatabase: admin
      database: log
      gridFsDatabase: dfs
  gateway:
  camel.gateway:
    ip: localhost
    port: 8066
server:

+ 338 - 0
hos-camel-parent/pom.xml

@ -0,0 +1,338 @@
<?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-camel-parent</artifactId>
    <packaging>pom</packaging>
    <version>1.3.0</version>
    <properties>
        <activemq-version>5.14.4</activemq-version>
        <activemq-karaf-version>5.13.5</activemq-karaf-version>
        <camel-version>2.18.3</camel-version>
        <cxf-version>3.1.9</cxf-version>
        <hawtio-version>1.5.0</hawtio-version>
        <bundle-plugin-version>2.3.7</bundle-plugin-version>
        <commons-dbcp2-version>2.1.1</commons-dbcp2-version>
        <deltaspike-version>1.7.2</deltaspike-version>
        <hystrix-version>1.5.9</hystrix-version>
        <jackson-version>2.8.5</jackson-version>
        <javax-mail-version>1.5.5</javax-mail-version>
        <jolokia-version>1.3.5</jolokia-version>
        <jetty-plugin-version>8.1.17.v20150415</jetty-plugin-version>
        <jetty9-plugin-version>9.2.19.v20160908</jetty9-plugin-version>
        <junit-version>4.12</junit-version>
        <karaf-version>4.0.8</karaf-version>
        <log4j-version>1.2.17</log4j-version>
        <!-- TODO need to update to 3.2.0 for everything like in chapter19/hawtio-custom-plugin -->
        <maven-bundle-plugin-version>2.3.7</maven-bundle-plugin-version>
        <mock-javamail-version>1.9</mock-javamail-version>
        <slf4j-version>1.7.21</slf4j-version>
        <spring-version>4.3.7.RELEASE</spring-version>
        <spring-boot-version>1.4.2.RELEASE</spring-boot-version>
        <swagger-version>1.5.12</swagger-version>
        <xbean-version>3.18</xbean-version>
        <verx-version>3.3.3</verx-version>
        <weld-version>2.4.2.Final</weld-version>
        <wildfly-swarm-version>2017.3.3</wildfly-swarm-version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>
    <build>
        <defaultGoal>install</defaultGoal>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.3</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <maxmem>512M</maxmem>
                        <showDeprecation>true</showDeprecation>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-eclipse-plugin</artifactId>
                    <version>2.9</version>
                    <configuration>
                        <downloadSources>true</downloadSources>
                        <downloadJavadocs>false</downloadJavadocs>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>2.4.3</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>2.4.1</version>
                    <configuration>
                        <filesets>
                            <fileset>
                                <directory>activemq-data</directory>
                            </fileset>
                        </filesets>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-remote-resources-plugin</artifactId>
                    <version>1.5</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>2.6</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>2.10</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.18.1</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-checkstyle-plugin</artifactId>
                    <version>2.15</version>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>
                    <version>1.4.0</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.camel</groupId>
                    <artifactId>camel-maven-plugin</artifactId>
                    <version>${camel-version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.camel</groupId>
                    <artifactId>camel-package-maven-plugin</artifactId>
                    <version>${camel-version}</version>
                </plugin>
                <plugin>
                    <groupId>io.hawt</groupId>
                    <artifactId>hawtio-maven-plugin</artifactId>
                    <version>${hawtio-version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.felix</groupId>
                    <artifactId>maven-bundle-plugin</artifactId>
                    <version>${bundle-plugin-version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.camel</groupId>
                    <artifactId>camel-api-component-maven-plugin</artifactId>
                    <version>${camel-version}</version>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>build-helper-maven-plugin</artifactId>
                    <version>1.10</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <childDelegation>false</childDelegation>
                    <useFile>true</useFile>
                    <failIfNoTests>false</failIfNoTests>
                    <includes>
                        <include>**/*Test.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencyManagement>
        <dependencies>
            <!-- Camel -->
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-parent</artifactId>
                <version>${camel-version}</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>spi-annotations</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-jetty</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <!-- ActiveMQ -->
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-all</artifactId>
                <version>${activemq-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-camel</artifactId>
                <version>${activemq-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-pool</artifactId>
                <version>${activemq-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.xbean</groupId>
                <artifactId>xbean-spring</artifactId>
                <version>${xbean-version}</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <!-- Logging -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j-version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>${slf4j-version}</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j-version}</version>
            </dependency>
            <!-- Testing -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit-version}</version>
            </dependency>
            <!-- Jolokia -->
            <dependency>
                <groupId>org.jolokia</groupId>
                <artifactId>jolokia-core</artifactId>
                <version>${jolokia-version}</version>
            </dependency>
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jms</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>${spring-version}</version>
            </dependency>
            <!-- Java FTP server -->
            <dependency>
                <groupId>org.apache.ftpserver</groupId>
                <artifactId>ftpserver-core</artifactId>
                <version>1.0.0</version>
            </dependency>
            <dependency>
                <groupId>org.apache.ftpserver</groupId>
                <artifactId>ftplet-api</artifactId>
                <version>1.0.0</version>
            </dependency>
            <dependency>
                <groupId>org.apache.mina</groupId>
                <artifactId>mina-core</artifactId>
                <version>2.0.9</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

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

@ -0,0 +1,53 @@
package camel.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;
    }
}

+ 1 - 1
hos-camel/src/main/java/gateway/processor/AppApi.java

@ -1,4 +1,4 @@
package gateway.processor;
package camel.gateway.processor;
import com.fasterxml.jackson.databind.ObjectMapper;

+ 26 - 0
hos-camel/src/main/java/gateway/processor/ErrorHandle.java

@ -0,0 +1,26 @@
package camel.gateway.processor;
import org.springframework.stereotype.Component;
/**
 * @author Airhead
 * @since 2017/3/17.
 */
@Component("errorHandle")
public class ErrorHandle {
    public String paramError(){
        return "paramError";
    }
    public String outdataError(){
        return "outdataError";
    }
    public String signValidError(){
        return "signValidError";
    }
    public String unauthorizedError(){
        return "unauthorizedError";
    }
}

+ 3 - 3
hos-camel/src/main/java/gateway/processor/GatewayProcessor.java

@ -1,4 +1,4 @@
package gateway.processor;
package camel.gateway.processor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -132,7 +132,7 @@ public class GatewayProcessor implements Processor {
                .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
    }
    private String genEndpoint(Map<String, Object> params, String[] requestBody) {
    private String genEndpoint(Map<String, Object> params, Exchange exchange) {
        String api = params.get("api").toString();                     // API接口名称
        String param = params.get("param").toString();
@ -158,7 +158,7 @@ public class GatewayProcessor implements Processor {
            });
            if (body[0].length() != 0) {
                requestBody[0] = body[0].substring(1);
                exchange.getOut().setBody(body[0].substring(1));
            }
        } catch (IOException e) {
            e.printStackTrace();

+ 1 - 1
hos-camel/src/main/java/gateway/processor/ParamVerifyBean.java

@ -1,4 +1,4 @@
package gateway.processor;
package camel.gateway.processor;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.encrypt.MD5;

+ 3 - 3
hos-camel/src/main/java/gateway/route/GatewayRouterBuilder.java

@ -1,6 +1,6 @@
package gateway.route;
package camel.gateway.route;
import gateway.processor.GatewayProcessor;
import camel.gateway.processor.GatewayProcessor;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
@ -14,7 +14,7 @@ public class GatewayRouterBuilder extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("jetty:http://0.0.0.0:8888/api/v1").routeId("mock:collect")
        from("jetty:http://0.0.0.0:9999/api").routeId("mock:collect")
                .process(new GatewayProcessor())
                .routingSlip(method(GatewayProcessor.class, "secret"))
                .routingSlip(method(GatewayProcessor.class, "route"));

+ 26 - 0
hos-camel2/ReadMe.md

@ -0,0 +1,26 @@
chapter7 - spring-boot-camel
----------------------------
Running Spring Boot and using Camel route to define REST service using Servlet
### 7.2.4  Spring Boot with Camel as microservice 
You need to build this example first
    mvn install
    
And then you can run the example using
    
    mvn spring-boot:run
    
And from a web browser open the following url:
    http://localhost:8080/camel/hello
You can also run the example as a fat-jar using: 
    java -jar target/chapter7-springboot-camel-2.0.0.jar
    
Notice this example uses online internet access to lookup your current location.
This is done using the camel-geocoder component.

+ 95 - 0
hos-camel2/pom.xml

@ -0,0 +1,95 @@
<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>hos-camel-parent</artifactId>
        <version>1.3.0</version>
        <relativePath>../hos-camel-parent</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>
        </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>
        <!-- notice we use -starter components from Camel which are designed to use with Spring Boot -->
        <!--<dependency>-->
            <!--<groupId>org.apache.camel</groupId>-->
            <!--<artifactId>camel-geocoder-starter</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jetty</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <!-- allows to run with mvn spring-boot:run -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot-version}</version>
                <executions>
                    <execution>
                        <goals>
                            <!-- to build fat-jar -->
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

+ 15 - 0
hos-camel2/src/main/java/camel/SpringbootApplication.java

@ -0,0 +1,15 @@
package camel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * Basic Spring Boot application.
 */
@SpringBootApplication
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

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

@ -0,0 +1,53 @@
package camel.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/gateway/processor/AppApi.java

@ -0,0 +1,149 @@
package camel.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;
    }
}

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

@ -0,0 +1,26 @@
package camel.gateway.processor;
import org.springframework.stereotype.Component;
/**
 * @author Airhead
 * @since 2017/3/17.
 */
@Component("errorHandle")
public class ErrorHandle {
    public String paramError(){
        return "paramError";
    }
    public String outdataError(){
        return "outdataError";
    }
    public String signValidError(){
        return "signValidError";
    }
    public String unauthorizedError(){
        return "unauthorizedError";
    }
}

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

@ -0,0 +1,189 @@
package camel.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.Body;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GatewayProcessor implements Processor {
    static Map<String, AppApi> apiMap = new HashMap<>();
    public void process(Exchange exchange) throws Exception {
    }
    public String secret(@Body String body, Exchange exchange) throws IOException, ParseException {
        System.out.println(body);
        String appKey = exchange.getIn().getHeaders().get("appKey").toString();
        return "restlet:http://sdw2:10000/api/v1.0/admin/apps/" + appKey;
    }
    public String route(@Body Map<String, Object> body, Exchange exchange) throws IOException, ParseException {
//        body = URLDecoder.decode(body, "UTF-8");
        if ("true".equals(body.get("successFlg"))) {
            return "jetty:http://0.0.0.0:9999/error/paramError";    //TODO:
        }
        Map<String, Object> obj = (Map) body.get("obj");
        if (obj == null) {
            return "jetty:http://0.0.0.0:9999/error/paramError";    //TODO:
        }
        String secret = obj.get("secret").toString();
        Map<String, Object> params = exchange.getIn().getHeaders();
        boolean pass = checkParams(params);
        if (!pass) {
            return "jetty:http://0.0.0.0:9999/error/paramError";    //TODO:
        }
        pass = checkTimeStamp(params);
        if (!pass) {
            return "jetty:http://0.0.0.0:9999/error/outdataError";    //TODO:
        }
        pass = checkSign(params, secret);
        if (!pass) {
            return "jetty:http://0.0.0.0:9999/error/signValidError";    //TODO:
        }
        pass = checkAuthorized(params);
        if (!pass) {
            return "jetty:http://0.0.0.0:9999/error/unauthorizedError";    //TODO:
        }
        return genEndpoint(params, exchange);
    }
    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协议版本
        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 - 5 * ONE_MIN);
        java.util.Date max = new java.util.Date(timeInMillis + 5 * 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) {
        return true;
    }
    private Map<String, String> parseBody(String body) throws IOException {
        return Stream.of(body.split("&")).map(obj -> obj.split("="))
                .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
    }
    private String genEndpoint(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 "";
            }
            JsonNode jsonNode = objectMapper.readValue(param, JsonNode.class);
            String host = appApi.getMicroServiceUri().split(",")[0];
            String endPoint = "restlet:http://" + host + appApi.getMethodName() + "restletMethods=" + appApi.getMethod();
            final String[] body = {""};
            appApi.getParameters().forEach(p -> {
                String value = jsonNode.asText(p.getName());
                if (p.getType().equals("2")) { //path param
                    endPoint.replace("{" + p.getName() + "}", value);
                }
                body[0] += ("&" + p.getName() + "=" + value);
            });
            if (body[0].length() != 0) {
                exchange.getOut().setBody(body[0].substring(1));
            }
        } 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("http://localhost:10000/api/v1.0/admin/appApi/search?filters=msMethodName%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;
    }
}

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

@ -0,0 +1,153 @@
package camel.gateway.processor;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.encrypt.MD5;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
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<>();
    private String timestamp;
    //TODO 配置文件中配置
    private String gatewayUrl = "seb-gatewayUrl";
    private String api;
    private String appKey = "esb-key";
    private String token;
    public static void main(String[] args) throws Exception {
        ParamVerifyBean paramSignUtil = new ParamVerifyBean();
        paramSignUtil.setApi("collect");
        paramSignUtil.addParam("patientId", "11111", true);
        paramSignUtil.addParam("eventNo", "2222222", true);
        paramSignUtil.genParam();
        String s = paramSignUtil.signParam("secret");
        System.out.println(s);
    }
    public void setApi(String api) {
        this.api = api;
    }
    public void setGatewayUrl(String gatewayUrl) {
        this.gatewayUrl = gatewayUrl;
    }
    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;
    }
    /**
     * http请求 参数拼接
     *
     * @return
     * @throws Exception
     */
    public String genParam() throws Exception {
        Iterator<Map.Entry<String, String>> iterator = paramMap.entrySet().iterator();
        StringBuilder builder = new StringBuilder();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            String key = next.getKey();
            String value = next.getValue();
            if (value == null) {
                throw new Exception("参数错误:参数" + key + "值为空.");
            }
            if (builder.length() == 0) {
                builder.append("?");
            } else {
                builder.append("&");
            }
            builder.append(key);
            builder.append("=");
            builder.append(URLEncoder.encode(value, "UTF-8"));
        }
        return builder.toString();
    }
    //TODO 获取应用token
    public String getToken() {
        return null;
    }
    public void setToken(String token) {
        this.token = token;
    }
    private void addParam(String paramName, String paramValue, boolean bMust) throws Exception {
        if (StringUtil.isEmpty(paramValue)) {
            if (bMust) {
                throw new Exception(paramName + "参数不能为空.");
            } else {
                return;
            }
        }
        String encodeValue = URLEncoder.encode(paramValue, "UTF-8");
        paramMap.put(paramName, encodeValue);
    }
    /**
     * 获取 ISO 8601格式的时间戳
     *
     * @return
     */
    private String getTimestamp() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSZ");
        timestamp = format.format(new Date());
        return timestamp;
    }
}

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

@ -0,0 +1,35 @@
package camel.gateway.route;
import camel.gateway.processor.ErrorHandle;
import camel.gateway.processor.GatewayProcessor;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/3/13.
 */
@Component
public class GatewayRouterBuilder extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("jetty:http://0.0.0.0:9998?matchOnUriPrefix=true").routeId("proxy")
                .to("jetty:http://127.0.0.1:10000?bridgeEndpoint=true&throwExceptionOnFailure=false");
        from("jetty:http://0.0.0.0:9999/api").routeId("api")
                .process(new GatewayProcessor())
                .routingSlip(method(GatewayProcessor.class, "route"));
        from("jetty:http://0.0.0.0:9999/error")
                .choice()
                .when(header(Exchange.HTTP_URI).contains("paramError")).bean(new ErrorHandle(), "paramError")
                .when(header(Exchange.HTTP_URI).contains("outdataError")).bean(new ErrorHandle(), "outdataError")
                .when(header(Exchange.HTTP_URI).contains("signValidError")).bean(new ErrorHandle(), "signValidError")
                .when(header(Exchange.HTTP_URI).contains("unauthorizedError")).bean(new ErrorHandle(), "unauthorizedError")
                .endChoice();
    }
}

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


+ 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() {
	}
}

+ 4 - 1
pom.xml

@ -6,7 +6,10 @@
    <groupId>com.yihu.hos</groupId>
    <artifactId>hos-admin</artifactId>
    <version>1.3.0</version>
    <packaging>war</packaging>
    <modules>
        <module>hos-camel-parent</module>
    </modules>
    <packaging>pom</packaging>
    <name>esb</name>
    <description>ESB管理平台</description>

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

@ -10,5 +10,5 @@ sslPassword = 123456
clientId = 1FtXTrSL8D
clientKey = MUZ0WFRyU0w4RDp1c3ZOeWxWc0ZvdFVlQ2tE
httpGateway=http://192.168.131.6:8081/gateway/transfer
httpGateway=http://192.168.131.6:8081/camel.gateway/transfer