Commit 66f14f4f authored by zhangc's avatar zhangc

Merge branch 'master' into dm_dev

parents fd185271 b02e361c
<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">
<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>
<parent>
<groupId>com.jz.dm</groupId>
......@@ -8,4 +9,68 @@
<artifactId>jz-dm-apigateway</artifactId>
<name>jz-dm-apigateway</name>
<description>jz-dm-apigateway</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>1.5.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<!--<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.0.RELEASE</version>
<scope>compile</scope>
</dependency>-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.7</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>com.jz.common</groupId>
<artifactId>jz-dm-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.jz.dm.mall;
package com.jz.dm.gateway;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.context.annotation.ComponentScan;
/**
* @author key
*/
@SpringBootApplication
@EnableRedisHttpSession
public class Application {
@ComponentScan(basePackages = {"com.jz.dm"})
@MapperScan("com.jz.dm.mapper")
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
SpringApplication.run(ApiGatewayApplication.class, args);
}
......
package com.jz.dm.gateway.common.exception;
import com.jz.dm.gateway.common.util.ResultCode;
/**
* 网关异常
*
*/
public class GatewayException extends OpenApiException {
/** 序列号 */
private static final long serialVersionUID = 3391018902219700916L;
/**
* 构造函数
*
* @param resultCode
*/
public GatewayException(ResultCode resultCode) {
super(resultCode);
}
/**
* 构造函数
*
* @param resultCode
* @param cause
*/
public GatewayException(ResultCode resultCode, Throwable cause) {
super(resultCode, cause);
}
/**
* 构造函数
*
* @param resultCode
* @param detailMessage
*/
public GatewayException(ResultCode resultCode, String detailMessage) {
super(resultCode, detailMessage);
}
/**
* 构造函数
*
* @param code
* @param msg
*/
public GatewayException(String code, String msg) {
this(code, msg, (Throwable) null);
}
/**
* 构造函数
*
* @param code
* @param msg
* @param cause
*/
public GatewayException(String code, String msg, Throwable cause) {
super(code, msg, cause);
}
/**
* 构造函数
*
* @param code
* @param msg
* @param detailMessage
*/
public GatewayException(String code, String msg, String detailMessage) {
super(code, msg, detailMessage);
}
}
\ No newline at end of file
package com.jz.dm.gateway.common.exception;
import com.jz.dm.gateway.common.util.ResultCode;
/**
* 信息摘要异常
*
*/
public class MessageDigestException extends OpenApiException {
private static final long serialVersionUID = 477249046784548217L;
/**
* 构造函数
* @param resultCode
*/
public MessageDigestException(ResultCode resultCode) {
super(resultCode);
}
/**
* 构造函数
* @param resultCode
* @param detailMessage
*/
public MessageDigestException(ResultCode resultCode, String detailMessage) {
super(resultCode, detailMessage);
}
/**
* 构造函数
* @param resultCode
* @param cause
*/
public MessageDigestException(ResultCode resultCode, Throwable cause) {
super(resultCode, cause);
}
/**
* 构造函数
* @param resultCode
* @param detailMessage
* @param cause
*/
public MessageDigestException(ResultCode resultCode, String detailMessage, Throwable cause) {
super(resultCode, detailMessage, cause);
}
}
package com.jz.dm.gateway.common.exception;
import com.jz.dm.gateway.common.util.ResultCode;
/**
* 通知异常
*
*/
public class NotifyException extends OpenApiException {
/** 序列号 */
private static final long serialVersionUID = 3391018902219700916L;
/**
* 构造函数
*
* @param resultCode
*/
public NotifyException(ResultCode resultCode) {
super(resultCode);
}
/**
* 构造函数
*
* @param resultCode
* @param cause
*/
public NotifyException(ResultCode resultCode, Throwable cause) {
super(resultCode, cause);
}
/**
* 构造函数
*
* @param resultCode
* @param detailMessage
*/
public NotifyException(ResultCode resultCode, String detailMessage) {
super(resultCode, detailMessage);
}
/**
* 构造函数
*
* @param code
* @param msg
*/
public NotifyException(String code, String msg) {
this(code, msg, (Throwable) null);
}
/**
* 构造函数
*
* @param code
* @param msg
* @param cause
*/
public NotifyException(String code, String msg, Throwable cause) {
super(code, msg, cause);
}
/**
* 构造函数
*
* @param code
* @param msg
* @param detailMessage
*/
public NotifyException(String code, String msg, String detailMessage) {
super(code, msg, detailMessage);
}
}
\ No newline at end of file
package com.jz.dm.gateway.common.exception;
import com.jz.dm.gateway.common.util.ResultCode;
/**
* openapi异常
*
*/
public class OpenApiException extends RuntimeException {
private static final long serialVersionUID = -3963657380514719229L;
/**
* 结果码
*/
private ResultCode resultCode;
/**
* 构造函数
*
* @param resultCode
*/
public OpenApiException(ResultCode resultCode) {
this.resultCode = new ResultCodeImpl(resultCode);
}
/**
* 构造函数
*
* @param resultCode
* @param cause
*/
public OpenApiException(ResultCode resultCode, Throwable cause) {
super(cause);
this.resultCode = new ResultCodeImpl(resultCode);
}
/**
* 构造函数
*
* @param resultCode
* @param detailMessage
*/
public OpenApiException(ResultCode resultCode, String detailMessage) {
super(detailMessage);
this.resultCode = new ResultCodeImpl(resultCode);
}
/**
* 构造函数
*
* @param resultCode
* @param detailMessage
* @param cause
*/
public OpenApiException(ResultCode resultCode, String detailMessage, Throwable cause) {
super(detailMessage, cause);
this.resultCode = new ResultCodeImpl(resultCode);
}
/**
* 构造函数
*
* @param code
* @param msg
*/
public OpenApiException(String code, String msg) {
this(new ResultCodeImpl(code, msg));
}
/**
* 构造函数
*
* @param code
* @param msg
* @param cause
*/
public OpenApiException(String code, String msg, Throwable cause) {
this(new ResultCodeImpl(code, msg), cause);
}
/**
* 构造函数
*
* @param code
* @param msg
* @param detailMessage
*/
public OpenApiException(String code, String msg, String detailMessage) {
this(new ResultCodeImpl(code, msg), detailMessage);
}
/**
* Getter method for property <tt>resultCode</tt>.
*
* @return property value of resultCode
*/
public ResultCode getResultCode() {
return resultCode;
}
public static class ResultCodeImpl implements ResultCode {
private String code;
private String msg;
public ResultCodeImpl(ResultCode resultCode) {
this.code = resultCode.getCode();
this.msg = resultCode.getMsg();
}
public ResultCodeImpl(String code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public String getCode() {
return code;
}
@Override
public String getMsg() {
return msg;
}
}
}
package com.jz.dm.gateway.common.exception;
import com.jz.dm.gateway.common.util.ResultCode;
/**
* 加密异常
*
*/
public class SecretException extends OpenApiException {
private static final long serialVersionUID = -8597436175649786898L;
/**
* 构造函数
* @param resultCode
*/
public SecretException(ResultCode resultCode) {
super(resultCode);
}
/**
* 构造函数
* @param resultCode
* @param detailMessage
*/
public SecretException(ResultCode resultCode, String detailMessage) {
super(resultCode, detailMessage);
}
/**
* 构造函数
* @param resultCode
* @param cause
*/
public SecretException(ResultCode resultCode, Throwable cause) {
super(resultCode, cause);
}
/**
* 构造函数
* @param resultCode
* @param detailMessage
* @param cause
*/
public SecretException(ResultCode resultCode, String detailMessage, Throwable cause) {
super(resultCode, detailMessage, cause);
}
}
package com.jz.dm.gateway.common.exception;
import com.jz.dm.gateway.common.util.ResultCode;
/**
* 签名异常
*
*/
public class SignatureException extends OpenApiException {
private static final long serialVersionUID = 6551962245794846748L;
/**
* 构造函数
*
* @param resultCode
*/
public SignatureException(ResultCode resultCode) {
super(resultCode);
}
/**
* 构造函数
* @param resultCode
* @param detailMessage
*/
public SignatureException(ResultCode resultCode, String detailMessage) {
super(resultCode, detailMessage);
}
/**
* 构造函数
* @param resultCode
* @param cause
*/
public SignatureException(ResultCode resultCode, Throwable cause) {
super(resultCode, cause);
}
/**
* 构造函数
* @param resultCode
* @param detailMessage
* @param cause
*/
public SignatureException(ResultCode resultCode, String detailMessage, Throwable cause) {
super(resultCode, detailMessage, cause);
}
}
package com.jz.dm.gateway.constant;
/**
* 常量
*
*/
public class Constants {
public static final String SIGN_TYPE_RSA = "RSA";
/**
* sha256WithRsa 算法请求类型
*/
public static final String SIGN_TYPE_RSA2 = "RSA2";
public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
public static final String SIGN_SHA256RSA_ALGORITHMS = "SHA256WithRSA";
public static final String ENCRYPT_TYPE_AES = "AES";
public static final String APP_KEY = "app_key";
public static final String FORMAT = "format";
public static final String METHOD = "method";
public static final String TIMESTAMP = "timestamp";
public static final String VERSION = "version";
public static final String SIGN_TYPE = "sign_type";
public static final String SIGN = "sign";
public static final String CHARSET = "charset";
//public static final String NOTIFY_URL = "notify_url";
//
//public static final String RETURN_URL = "return_url";
public static final String ENCRYPT_TYPE = "encrypt_type";
public static final String PARAMS = "params";
public static final String RESPONSE = "response";
public static final String SUCCESS = "SUCCESS";
/** 默认时间格式 **/
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/** Date默认时区 **/
public static final String DATE_TIMEZONE = "GMT+8";
/** UTF-8字符集 **/
public static final String CHARSET_UTF8 = "UTF-8";
/** GBK字符集 **/
public static final String CHARSET_GBK = "GBK";
/** JSON 应格式 */
public static final String FORMAT_JSON = "JSON";
/** XML 应格式 */
public static final String FORMAT_XML = "XML";
/** 默认版本 */
public static final String DEFAULT_VERSION = "1.0.0";
public static final int FILTER_ORDER_0 = 0;
public static final int FILTER_ORDER_1 = 1;
public static final int FILTER_ORDER_2 = 2;
public static final int FILTER_ORDER_3 = 3;
public static final int FILTER_ORDER_4 = 4;
public static final int FILTER_ORDER_5 = 5;
public static final int FILTER_ORDER_6 = 6;
}
package com.jz.dm.gateway.constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 日志常量
*
*/
public class LoggingConstants {
/** 业务摘要日志 */
public static final Logger DIGEST_LOGGER = LoggerFactory.getLogger("GATEWAY-DIGEST");
/** 报警日志,内容关键字用##号包括,便于报警信息归类 */
public static final Logger ALERT_LOGGER = LoggerFactory.getLogger("GATEWAY-ALERT");
/** 网关路由分发 */
public static final Logger DISPATCHER_LOGGER = LoggerFactory
.getLogger("GATEWAY-DISPATCHER");
public static final Logger REGISTRY_LOGGER = LoggerFactory.getLogger("GATEWAY-REGISTRY");
/** 分隔符*/
public static final String SEP = ",";
/** 点分割符*/
public static final String DOT_SEP = ".";
/** 默认值*/
public static final String DEFAULT_STR = "-";
/** 冒号 */
public static final String COLON = ":";
/** 金额币种分隔 */
public static final String AMOUNT_CURRENCY_SPLIT = "^";
/** 左中括号 */
public static final String LBRACKET = "[";
/** 右中括号 */
public static final String RBRACKET = "]";
/** "@" 符号*/
public static final String MONKEYS_AT = "@";
}
package com.jz.dm.gateway.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.jz.dm.gateway.common.util.JsonUtil;
import com.jz.dm.gateway.gateway.GatewayService;
import com.jz.dm.gateway.model.GatewayRequest;
import com.jz.dm.gateway.model.GatewayResponse;
import com.jz.dm.gateway.model.RequestContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* 网关请求
* @author key
*/
@RestController
public class GatewayController {
@Autowired
private GatewayService gatewayService;
@RequestMapping(value = "/gateway", consumes = "application/json")
public String gateway(@RequestBody String json, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
GatewayRequest gatewayRequest = JSON.parseObject(json, GatewayRequest.class);
return doGateway(gatewayRequest, httpServletRequest, httpServletResponse);
}
@RequestMapping(value = "/gateway")
public String gateway(GatewayRequest gatewayRequest, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
return doGateway(gatewayRequest, httpServletRequest, httpServletResponse);
}
private String doGateway(GatewayRequest gatewayRequest, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
try {
RequestContext requestContext = RequestContext.getCurrentContext();
requestContext.setRequest(httpServletRequest);
requestContext.setResponse(httpServletResponse);
GatewayResponse gatewayResponse = gatewayService.invoke(gatewayRequest);
JSONObject result = new JSONObject();
convertResponse(result, gatewayResponse);
return JsonUtil.toJSONString(result, PropertyNamingStrategy.SnakeCase);
} finally {
RequestContext.getCurrentContext().reset();
}
}
private void convertResponse(JSONObject result, GatewayResponse gatewayResponse) {
result.put("code", gatewayResponse.getCode());
result.put("msg", gatewayResponse.getMsg());
Map<String, Object> data = gatewayResponse.getResponse();
data.remove("code");
data.remove("msg");
if (!CollectionUtils.isEmpty(data)) {
result.put("data", data);
if (StringUtils.isNotBlank(gatewayResponse.getEncryptData())) {
result.put("data", gatewayResponse.getEncryptData());
}
}
result.put("sign", gatewayResponse.getSign());
}
}
package com.jz.dm.gateway.filter;
import com.jz.dm.gateway.model.GatewayRequest;
import com.jz.dm.gateway.model.GatewayResponse;
import com.jz.dm.gateway.model.RequestContext;
import org.springframework.core.Ordered;
/**
* 抽象过滤器
* @author key
*/
public abstract class AbstractFilter implements Filter, Ordered {
@Override
public void doFilter(GatewayRequest request, GatewayResponse response, FilterChain chain) {
RequestContext context = RequestContext.getCurrentContext();
if (context.isExcludeFilter(getFilterName())) {
chain.doFilter(request, response);
} else {
internalDoFilter(request, response, chain);
}
}
/**
* 执行过滤
*
* @param request
* @param response
* @param chain
*/
protected abstract void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain);
}
package com.jz.dm.gateway.filter;
import com.jz.dm.gateway.common.util.StringUtil;
import com.jz.dm.gateway.common.exception.GatewayException;
import com.jz.dm.gateway.common.util.SignType;
import com.jz.dm.gateway.gateway.common.Constants;
import com.jz.dm.gateway.model.enums.Format;
import com.jz.dm.gateway.model.GatewayRequest;
import com.jz.dm.gateway.model.GatewayResponse;
import com.jz.dm.gateway.model.enums.GatewayResultCode;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
/**
* 参数检查过滤器
*
* @author key
*/
@Component
public class CheckArgsFilter extends AbstractFilter {
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) {
// 校验参数非空
if (StringUtil.isEmpty(request.getAppKey()) || StringUtil.isEmpty(request.getMethod())
|| StringUtil.isEmpty(request.getCharset()) || StringUtil.isEmpty(request.getSignType())
|| StringUtil.isEmpty(request.getSign()) || StringUtil.isEmpty(request.getTimestamp())
|| StringUtil.isEmpty(request.getVersion())
|| StringUtil.isEmpty(request.getParams())) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT);
}
// 设置默认值
if (StringUtil.isEmpty(request.getFormat())) {
request.setFormat(Format.JSON.name());
}
try {
Format.valueOf(request.getFormat());
Charset.forName(request.getCharset());
SignType.valueOf(request.getSignType());
} catch (Exception ex) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT);
}
chain.doFilter(request, response);
}
/**
* @see org.springframework.core.Ordered#getOrder()
*/
@Override
public int getOrder() {
return Constants.FILTER_ORDER_2;
}
@Override
public String getFilterName() {
return "CheckArgsFilter";
}
}
package com.jz.dm.gateway.filter;
import com.jz.dm.gateway.common.exception.GatewayException;
import com.jz.dm.gateway.gateway.common.Constants;
import com.jz.dm.gateway.model.GatewayRequest;
import com.jz.dm.gateway.model.GatewayResponse;
import com.jz.dm.gateway.model.enums.GatewayResultCode;
import com.jz.dm.gateway.model.RequestContext;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
/**
* 检查提交数据大小
*
*/
@Component("CheckPostSizeFilter")
public class CheckPostSizeFilter extends AbstractFilter {
@Override
public String getFilterName() {
return "CheckPostSizeFilter";
}
/**
* @see org.springframework.core.Ordered#getOrder()
*/
@Override
public int getOrder() {
return Constants.FILTER_ORDER_1;
}
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) {
HttpServletRequest httpServletRequest = RequestContext.getCurrentContext().getRequest();
Boolean postDataTooLarge = (Boolean) httpServletRequest.getAttribute("postDataTooLarge");
if (postDataTooLarge != null && postDataTooLarge) {
Integer maxPostSize = (Integer) httpServletRequest.getAttribute("maxPostSize");
Integer postSize = (Integer) httpServletRequest.getAttribute("postSize");
throw new GatewayException(GatewayResultCode.POST_DATA_TOO_LARGE,
"maxPostSize:" + maxPostSize + ", postSize:" + postSize);
}
chain.doFilter(request, response);
}
}
package com.jz.dm.gateway.filter;
import com.jz.dm.gateway.common.exception.GatewayException;
import com.jz.dm.gateway.gateway.common.Constants;
import com.jz.dm.gateway.model.GatewayRequest;
import com.jz.dm.gateway.model.GatewayResponse;
import com.jz.dm.gateway.model.enums.GatewayResultCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 时间戳校验过滤器
*
* @author key
*/
@Component
public class CheckTimestampFilter extends AbstractFilter {
@Value("${api.skipFilter}")
private boolean skipFilter;
/**
* 时间戳超时分钟,10分钟
*/
private static final long max = 1000 * 60 * 10; //10分钟
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response, FilterChain chain) {
if (!skipFilter) {
String timestamp = request.getTimestamp();
long time = 0;
try {
time = Long.valueOf(timestamp);
} catch (Exception ex) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT);
}
if (System.currentTimeMillis() - time > max) {//无效时间戳
throw new GatewayException(GatewayResultCode.ILLEGAL_TIMETEMP);
}
}
chain.doFilter(request, response);
}
/**
* @see org.springframework.core.Ordered#getOrder()
*/
@Override
public int getOrder() {
return Constants.FILTER_ORDER_5;
}
@Override
public String getFilterName() {
return "CheckTimestampFilter";
}
}
package com.jz.dm.gateway.filter;
import com.jz.dm.gateway.model.GatewayRequest;
import com.jz.dm.gateway.model.GatewayResponse;
/**
* 过滤器
*
* @author key
*/
public interface Filter {
/**
* Returns the filter-name of this filter as defined in the deployment
* descriptor.
* @return
*/
public String getFilterName();
/**
* 执行过滤
*
* @param request gateway request
* @param response gateway response
* @param chain filter chain
*/
void doFilter(GatewayRequest request, GatewayResponse response, FilterChain chain);
}
package com.jz.dm.gateway.filter;
import com.jz.dm.gateway.model.GatewayRequest;
import com.jz.dm.gateway.model.GatewayResponse;
/**
* 请求过滤链
* @author key
*/
public interface FilterChain {
/**
* 请求过滤
*
* @param request gateway request
* @param response gateway response
*/
void doFilter(GatewayRequest request, GatewayResponse response);
}
package com.jz.dm.gateway.filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 过滤链工厂
*
*/
@Component
public class FilterChainFactory {
@Autowired
private FilterFactory filterFactory;
/**
* 获取过滤链
*
*/
public FilterChain getFilterChain() {
List<Filter> filters = filterFactory.getFilters();
return new FilterChainImpl(filters);
}
}
package com.jz.dm.gateway.filter;
import com.jz.dm.gateway.common.exception.OpenApiException;
import com.jz.dm.gateway.common.util.LogUtil;
import com.jz.dm.gateway.common.util.ResultCode;
import com.jz.dm.gateway.model.GatewayRequest;
import com.jz.dm.gateway.model.GatewayResponse;
import com.jz.dm.gateway.model.enums.GatewayResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* 过滤链
*
*/
public class FilterChainImpl implements FilterChain {
private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
private int pos = 0;
private final List<Filter> filters = new ArrayList<Filter>();
public FilterChainImpl() { }
public FilterChainImpl(List<Filter> filters) {
addFilters(filters);
}
@Override
public void doFilter(GatewayRequest request, GatewayResponse response) {
Filter nextFilter = nextFilter();
if (nextFilter == null) {
return;
}
try {
nextFilter.doFilter(request, response, this);
} catch (OpenApiException ex) {
ResultCode resultCode = ex.getResultCode();
LogUtil.error(LOGGER, ex, "doFilter occur exception,code=" + resultCode.getCode()
+ ",msg=" + resultCode.getMsg() + ",request=" + request);
response.setCode(ex.getResultCode().getCode());
response.setMsg(ex.getResultCode().getMsg());
} catch (Throwable ex) {
LogUtil.error(LOGGER, ex, "doFilter occur unknown exception,request=" + request);
response.setCode(GatewayResultCode.UNKNOWN_EXCEPTION.getCode());
response.setMsg(GatewayResultCode.UNKNOWN_EXCEPTION.getMsg());
}
}
public Filter nextFilter() {
if (pos < filters.size()) {
return filters.get(pos++);
}
return null;
}
public void addFilters(List<Filter> filters) {
this.filters.addAll(filters);
}
public void addFilter(Filter filter) {
this.filters.add(filter);
}
public void addFilter(int index, Filter filter) {
this.filters.add(index, filter);
}
}
package com.jz.dm.gateway.filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* 过滤器工厂
*
*/
@Component
public class FilterFactory {
/**
* 过滤器列表
*/
@Autowired
private final List<Filter> filters = new ArrayList<Filter>();
/**
* 获取过滤器列表
*
* @return
*/
public List<Filter> getFilters() {
return filters;
}
}
package com.jz.dm.gateway.filter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jz.dm.gateway.common.exception.GatewayException;
import com.jz.dm.gateway.common.util.LogUtil;
import com.jz.dm.gateway.constant.LoggingConstants;
import com.jz.dm.gateway.gateway.DefaultOpenApiDispatcher;
import com.jz.dm.gateway.gateway.common.Constants;
import com.jz.dm.gateway.model.*;
import com.jz.dm.gateway.model.enums.GatewayResultCode;
import com.jz.dm.gateway.model.enums.RouteType;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 网关路由过滤器
*
*/
@Component
public class InvokeRouteFilter extends AbstractFilter {
/** openapi dispatcher logger */
private static final Logger DISPATCHER_LOGGER = LoggingConstants.DISPATCHER_LOGGER;
@Autowired
DefaultOpenApiDispatcher defaultOpenApiDispatcher;
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) {
String openApiResponse = null;
//当前系统时间戳
long startTime = System.currentTimeMillis();
try {
OpenApi openApi = (OpenApi) RequestContext.getCurrentContext().get("openApi");
if (openApi.getRouteType() == null) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ROUTE_TYPE);
}
if (openApi.getRouteType() != RouteType.SRPING) {
chain.doFilter(request, response);
return;
}
DispatchContext context = new DispatchContext();
context.setAppId(request.getAppKey());
context.setApplication(openApi.getApplication());
context.setOpenApiMethod(request.getMethod());
context.setOpenApiParams(request.getParams());
context.setOpenApiVersion(request.getVersion());
for (GatewayRequest.Attribute attribute : request.getExtAttributes().values()) {
if (attribute != null && attribute.isPass) {
context.setExtAttribute(attribute.name, attribute.value);
}
}
openApiResponse = defaultOpenApiDispatcher.doDispatch(context);
JSONObject jsonObject = (JSONObject) JSON.parse(openApiResponse);
response.setAttribute(jsonObject);
} finally {
long elapseTime = System.currentTimeMillis() - startTime;
LogUtil.info(DISPATCHER_LOGGER,
"gateway do default dispatch,request=" + request + ",response=" + openApiResponse
+ "," + elapseTime + "ms");
}
}
/**
* @see org.springframework.core.Ordered#getOrder()
*/
@Override
public int getOrder() {
return Constants.FILTER_ORDER_6;
}
@Override
public String getFilterName() {
return "InvokeRouteFilter";
}
}
package com.jz.dm.gateway.filter;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.jz.dm.gateway.common.util.StringUtil;
import com.jz.dm.gateway.common.exception.SignatureException;
import com.jz.dm.gateway.common.util.*;
import com.jz.dm.gateway.gateway.common.Constants;
import com.jz.dm.gateway.model.GatewayRequest;
import com.jz.dm.gateway.model.GatewayResponse;
import com.jz.dm.gateway.model.enums.GatewayResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.HashMap;
import java.util.Map;
/**
* 签名过滤器
*/
@Component
public class SignatureFilter extends AbstractFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(SignatureFilter.class);
// @Autowired
// private IApiWhiteService apiWhiteService;
@Value("${secret_private}")
private String secretPrivate;
private String encryptData;
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) {
try {
chain.doFilter(request, response);
} finally {
String responseJson = null;
String sign = StringUtil.EMPTY_STRING;
String privatekey = null;
if (StringUtil.isEmpty(request.getAppKey())) {
return;
}
//ApiWhite apiWhite = apiWhiteService.byMerchantId(request.getAppId());
//if (apiWhite == null) {
// return;
//}
//是否提供密码
//boolean providePublicKey = false;
//if ("0".equals(apiWhite.getProvideSecret())) {
// privatekey = apiWhite.getSecretKey();
//} else if ("1".equals(apiWhite.getProvideSecret())) {
// privatekey = secretPrivate;
// providePublicKey = true;
//}
try {
responseJson = JsonUtil.toJSONString(response.getResponse(),
PropertyNamingStrategy.SnakeCase);
if (StringUtil.isNotEmpty(request.getSignType())) {
String charset = request.getCharset();
if (StringUtil.isEmpty(charset)) {
charset = Constants.CHARSET_UTF8;
}
//if (providePublicKey) {
// sign = SignatureUtil.sign(convertResult(response.getResponse(), response, apiWhite), privatekey, charset, SignType.valueOf(request.getSignType()), SignatureUtil.SIGN_REQUEST, providePublicKey);
//} else {
// sign = SignatureUtil.sign(convertResult(response.getResponse(), response, apiWhite), privatekey, charset, SignType.valueOf(request.getSignType()), SignatureUtil.SIGN_REQUEST, providePublicKey);
//}
}
} catch (JSONException e) {
LogUtil.error(LOGGER, e,
"serializer response to json string error. response=" + response.getResponse());
response.clearAttributes();
response.setCode(OpenApiResultCode.RESPONSE_DATA_FORMAT_ERROR.getCode());
response.setMsg(OpenApiResultCode.RESPONSE_DATA_FORMAT_ERROR.getMsg());
// sign = signatureException(request, response, privatekey, providePublicKey);
} catch (SignatureException ex) {
LogUtil.error(LOGGER, ex,
"sign response error. response=" + response.getResponse());
response.clearAttributes();
response.setCode(ex.getResultCode().getCode());
response.setMsg(ex.getResultCode().getMsg());
} catch (Throwable ex) {
LogUtil.error(LOGGER, ex,
"signatureFilter doFilter error. response=" + response.getResponse());
response.clearAttributes();
response.setCode(GatewayResultCode.UNKNOWN_EXCEPTION.getCode());
response.setMsg(GatewayResultCode.UNKNOWN_EXCEPTION.getMsg());
// sign = signatureException(request, response, privatekey, providePublicKey);
}
response.setSign(sign);
//if (apiWhite.getIsEncrypt()) {
// response.setEncryptData(encryptData);
//}
}
}
private Map<String, Object> convertResult(Map<String, Object> attributes, GatewayResponse response) {
Map<String, Object> mapResult = new HashMap<>();
mapResult.put("code", response.getCode());
mapResult.put("msg", response.getMsg());
Object code = attributes.get("code");
Object msg = attributes.get("msg");
attributes.remove("code");
attributes.remove("msg");
if (!CollectionUtils.isEmpty(attributes)) {
mapResult.put("data", JsonUtil.toJSONString(attributes, PropertyNamingStrategy.SnakeCase));
//if (apiWhite.getIsEncrypt()) {
// String string = (String) mapResult.get("data");
// try {
// RSAPrivateKey privateKey = RSAUtils.getPrivateKey(secretPrivate);
// String encrypt = RSAUtils.privateEncrypt(string, privateKey);
// mapResult.put("data", encrypt);
// encryptData = encrypt;
// } catch (Exception e) {
// e.printStackTrace();
// }
//}
}
attributes.put("code", code);
attributes.put("msg", msg);
return mapResult;
}
private String signatureException(GatewayRequest request, GatewayResponse response,
String privateKey, boolean providePublicKey) {
String responseJson = null;
String sign = StringUtil.EMPTY_STRING;
try {
responseJson = JsonUtil.toJSONString(response.getResponse(),
PropertyNamingStrategy.SnakeCase);
} catch (JSONException e1) {
LogUtil.error(LOGGER, e1,
"serializer response to json string error. response=" + response.getResponse());
return sign;
}
try {
sign = SignatureUtil.sign(responseJson, privateKey, request.getCharset(), SignType.valueOf(request.getSignType()), SignatureUtil.SIGN_REQUEST, providePublicKey);
} catch (SignatureException ex) {
LogUtil.error(LOGGER, ex, "sign response error. response=" + response.getResponse());
}
return sign;
}
/**
* @see org.springframework.core.Ordered#getOrder()
*/
@Override
public int getOrder() {
return Constants.FILTER_ORDER_0;
}
@Override
public String getFilterName() {
return "SignatureFilter";
}
}
package com.jz.dm.gateway.filter;
import com.jz.dm.gateway.common.util.HddHashMap;
import com.jz.dm.gateway.common.util.RSAUtils;
import com.jz.dm.gateway.constant.Constants;
import com.jz.dm.gateway.model.*;
import com.jz.dm.gateway.model.enums.RouteType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.security.interfaces.RSAPublicKey;
/**
* 验签过滤器
*/
@Slf4j
@Component
public class VerifySignFilter extends AbstractFilter {
//@Autowired
//private IApiWhiteService apiWhiteService;
@Value("${api.skipFilter}")
private boolean skipFilter;
private final static String CHARSET = "UTF-8";
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) {
HddHashMap params = new HddHashMap();
params.put("app_id", request.getAppKey());
params.put("method", request.getMethod());
params.put("charset", request.getCharset());
params.put("sign", request.getSign());
params.put("sign_type", request.getSignType());
params.put("timestamp", request.getTimestamp());
params.put("version", request.getVersion());
params.put("params", request.getParams());
//ApiWhite apiWhite = apiWhiteService.byMerchantId(request.getAppId());
//if (apiWhite != null) {
// String publicKey = apiWhite.getSecretKey();
//
// if (!skipFilter) {
// boolean verify = SignatureUtil.verify(params, publicKey, request.getCharset(), SignType.valueOf(request.getSignType()));
// if (!verify) {
// throw new SignatureException(OpenApiResultCode.SIGN_VERIFY_ERROR);
// }
//
// //参数解密
// if (apiWhite.getIsEncrypt()) {
// String decryptParams = decryptParams(request.getParams(), publicKey);
// request.setParams(decryptParams);
// }
// }
//}
// 后期再扩展
OpenApi openApi = new OpenApi();
openApi.setApplication("HDD_API_GATEWAY");
openApi.setRouteType(RouteType.SRPING);
RequestContext.getCurrentContext().set("openApi", openApi);
chain.doFilter(request, response);
}
private String decryptParams(String params, String publicKey) {
log.info("解密前请求参数,{}", params);
try {
RSAPublicKey key = RSAUtils.getPublicKey(publicKey);
String decrypt = RSAUtils.publicDecrypt(params, key);
log.info("解密后请求参数,{}", decrypt);
return decrypt;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @see org.springframework.core.Ordered#getOrder()
*/
@Override
public int getOrder() {
return Constants.FILTER_ORDER_4;
}
@Override
public String getFilterName() {
return "VerifySignFilter";
}
}
package com.jz.dm.gateway.gateway;
import com.alibaba.fastjson.JSON;
import com.jz.dm.gateway.common.util.StringUtil;
import com.jz.dm.gateway.common.exception.OpenApiException;
import com.jz.dm.gateway.common.util.OpenApiRequest;
import com.jz.dm.gateway.common.util.OpenApiResponse;
import com.jz.dm.gateway.common.util.OpenApiResultCode;
import com.jz.dm.gateway.model.DispatchContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 默认openapi分发器
*
*/
@Component
public class DefaultOpenApiDispatcher implements OpenApiDispatcher {
private static final Logger LOGGER = LoggerFactory
.getLogger(DefaultOpenApiDispatcher.class);
/**
* openapi服务
*/
private final Map<String, OpenApiService> openApiServices = new ConcurrentHashMap<String, OpenApiService>();
/**
* 服务注入可参考: /openapi-demo/src/main/resources/META-INF/application-context.xml
* @param openApiServiceList
* <pre>
* &lt;!-- 定义开放接口服务 -->
* &lt;bean id="addUserOpenApiService" class="com.xxx.openapi.demo.openapi.AddUserOpenApiService" /&gt;
* &lt;bean id="getUserOpenApiService" class="com.xxx.openapi.demo.openapi.GetUserOpenApiService" /&gt;
* </pre>
*/
@Resource
public void setOpenApiServices(List<OpenApiService> openApiServiceList) {
for (OpenApiService openApiService : openApiServiceList) {
String openApiServiceKey = getOpenApiServiceKey(openApiService.getOpenApiMethod(),
openApiService.getOpenApiVersion());
openApiServices.put(openApiServiceKey, openApiService);
}
}
private String getOpenApiServiceKey(String openApiMethod, String openApiVersion) {
return openApiMethod + "&" + openApiVersion;
}
@Override
public String doDispatch(DispatchContext context) {
OpenApiResponse response = new OpenApiResponse();
String openApiServiceKey = getOpenApiServiceKey(context.getOpenApiMethod(),
context.getOpenApiVersion());
OpenApiService openApiService = openApiServices.get(openApiServiceKey);
if (openApiService == null) {
response.setCode(OpenApiResultCode.ILLEGAL_INTERFACE.getCode());
response.setMsg(OpenApiResultCode.ILLEGAL_INTERFACE.getMsg());
return JSON.toJSONString(response.getAttributes());
}
try {
OpenApiRequest request = new OpenApiRequest(context.getOpenApiParams());
request.setAppId(context.getAppId());
request.setExtAttributes(context.getExtAttributes());
openApiService.doService(request, response);
} catch (Throwable ex) {
if (ex instanceof OpenApiException) {
OpenApiException oae = (OpenApiException) ex;
response.setCode(oae.getResultCode().getCode());
response.setMsg(oae.getResultCode().getMsg());
} else {
LOGGER.error("OpenApiService doService error,DispatchContext=" + context, ex);
response.setCode(OpenApiResultCode.UNKNOWN_EXCEPTION.getCode());
response.setMsg(OpenApiResultCode.UNKNOWN_EXCEPTION.getMsg());
}
return JSON.toJSONString(response.getAttributes());
}
if (StringUtil.isEmpty(response.getCode())) {
response.setCode(OpenApiResultCode.SUCCESS.getCode());
response.setMsg(OpenApiResultCode.SUCCESS.getMsg());
}
return JSON.toJSONString(response.getAttributes());
}
}
package com.jz.dm.gateway.gateway;
import com.jz.dm.gateway.model.GatewayRequest;
import com.jz.dm.gateway.model.GatewayResponse;
/**
* GatewayService
*/
public interface GatewayService {
GatewayResponse invoke(GatewayRequest gatewayRequest);
}
package com.jz.dm.gateway.gateway;
import com.jz.dm.gateway.model.DispatchContext;
/**
* openapi分发器
*
*/
public interface OpenApiDispatcher {
/**
* openapi dispatch
*
* @param context dispatch context
*
* @return
*/
public String doDispatch(DispatchContext context);
}
package com.jz.dm.gateway.gateway;
import com.jz.dm.gateway.common.util.OpenApiRequest;
import com.jz.dm.gateway.common.util.OpenApiResponse;
/**
* openapi服务
*
*/
public interface OpenApiService {
/**
* 获取openapi接口名
*
* @return
*/
public String getOpenApiMethod();
/**
* 获取openapi接口版本
*
* @return
*/
public String getOpenApiVersion();
/**
* openapi服务调用
*
* @param request
* @param response
*/
public void doService(OpenApiRequest request, OpenApiResponse response);
}
/**
* Copyright (c) 2011-2019 All Rights Reserved.
*/
package com.jz.dm.gateway.gateway.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* API白名单表 服务实现类
*
* @author zengxx
* @version $Id: ApiWhiteServiceImpl.java 2020-04-02 $
*/
//@Service("apiWhiteService")
//public class ApiWhiteServiceImpl implements IApiWhiteService {
//@Resource
//private ApiWhiteMapper apiWhiteMapper;
//@Resource
//private MeasureRecordMapper measureRecordMapper;
//
//@Override
//public ApiWhite byMerchantId(String merchantId) throws TtyException {
// return apiWhiteMapper.byMerchantId(merchantId);
//}
//
//@Override
//@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
//public long adjustAmt(String merchantId, long amt) {
// if (amt == 0) {
// return amt;
// }
// BigDecimal adjustAmt = new BigDecimal(amt).divide(new BigDecimal(100));
// ApiWhite apiWhite = apiWhiteMapper.byMerchantId(merchantId);
// long result = apiWhiteMapper.adjustAmt(merchantId, adjustAmt);
// if (result != 1) {
// return 0;
// } else {
// MeasureRecord measure = new MeasureRecord();
// //已用金额
// BigDecimal sumUseAmt = apiWhiteMapper.sumUseAmt(merchantId);
// if (sumUseAmt == null) {
// sumUseAmt = BigDecimal.ZERO;
// }
// if (amt > 0) {
// measure.setChangType("0");
// measure.setUseAmount(sumUseAmt.subtract(adjustAmt));
// } else {
// measure.setChangType("1");
// measure.setUseAmount(sumUseAmt.add(adjustAmt.abs()));
// }
// measure.setChangeAmount(adjustAmt.abs());
// measure.setAfterAmount(apiWhite.getUsableAmount().add(adjustAmt));
//
// measure.setMerchantId(apiWhite.getMerchantId());
// measure.setName(apiWhite.getName());
// measure.setBeforeAmount(apiWhite.getUsableAmount());
// measure.setChangDate(LocalDateTime.now());
// measure.setCreateUser("API");
// measure.setCreateDate(LocalDateTime.now());
// //插入流水信息
// if (measureRecordMapper.insert(measure) > 0) {
// return 1;
// }
// }
// return 0;
//}
//@Override
//@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
//public void invoke3bcCount(String merchantId) {
// apiWhiteMapper.invoke3bcCount(merchantId);
//}
//}
package com.jz.dm.gateway.gateway.impl;
import com.jz.dm.gateway.filter.FilterChain;
import com.jz.dm.gateway.filter.FilterChainFactory;
import com.jz.dm.gateway.gateway.GatewayService;
import com.jz.dm.gateway.model.GatewayRequest;
import com.jz.dm.gateway.model.GatewayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 网关服务
*
*/
@Service
public class GatewayServiceImpl implements GatewayService {
@Autowired
private FilterChainFactory filterChainFactory;
@Override
public GatewayResponse invoke(GatewayRequest gatewayRequest) {
GatewayResponse gatewayResponse = new GatewayResponse();
FilterChain filterChain = filterChainFactory.getFilterChain();
filterChain.doFilter(gatewayRequest, gatewayResponse);
return gatewayResponse;
}
}
package com.jz.dm.gateway.model;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Dispatch Context
*/
public class DispatchContext implements Serializable {
/**
* 序列号
*/
private static final long serialVersionUID = -3448256355423553719L;
/**
* 商户应用id
*/
private String appId;
/**
* 应用
*/
private String application;
/**
* openapi接口
*/
private String openApiMethod;
/**
* openapi接口参数,json格式
*/
private String openApiParams;
/**
* openapi接口版本
*/
private String openApiVersion;
/**
* 扩展属性
*/
private final Map<String, Object> extAttributes = new HashMap<String, Object>();
/**
* Getter method for property <tt>appId</tt>.
*
* @return property value of appId
*/
public String getAppId() {
return appId;
}
/**
* Setter method for property <tt>appId</tt>.
*
* @param appId value to be assigned to property appId
*/
public void setAppId(String appId) {
this.appId = appId;
}
/**
* Getter method for property <tt>application</tt>.
*
* @return property value of application
*/
public String getApplication() {
return application;
}
/**
* Setter method for property <tt>application</tt>.
*
* @param application value to be assigned to property application
*/
public void setApplication(String application) {
this.application = application;
}
/**
* Getter method for property <tt>openApiMethod</tt>.
*
* @return property value of openApiMethod
*/
public String getOpenApiMethod() {
return openApiMethod;
}
/**
* Setter method for property <tt>openApiMethod</tt>.
*
* @param openApiMethod value to be assigned to property openApiMethod
*/
public void setOpenApiMethod(String openApiMethod) {
this.openApiMethod = openApiMethod;
}
/**
* Getter method for property <tt>openApiParams</tt>.
*
* @return property value of openApiParams
*/
public String getOpenApiParams() {
return openApiParams;
}
/**
* Setter method for property <tt>openApiParams</tt>.
*
* @param openApiParams value to be assigned to property openApiParams
*/
public void setOpenApiParams(String openApiParams) {
this.openApiParams = openApiParams;
}
/**
* Getter method for property <tt>openApiVersion</tt>.
*
* @return property value of openApiVersion
*/
public String getOpenApiVersion() {
return openApiVersion;
}
/**
* Setter method for property <tt>openApiVersion</tt>.
*
* @param openApiVersion value to be assigned to property openApiVersion
*/
public void setOpenApiVersion(String openApiVersion) {
this.openApiVersion = openApiVersion;
}
/**
* 获取扩展属性
*
* @param attributeName
* @return
*/
@SuppressWarnings("unchecked")
public <T> T getExtAttribute(String attributeName) {
return (T) extAttributes.get(attributeName);
}
/**
* 设置属性
*
* @param attributeName
* @param attributeValue
*/
public void setExtAttribute(String attributeName, Object attributeValue) {
extAttributes.put(attributeName, attributeValue);
}
/**
* Getter method for property <tt>extAttributes</tt>.
*
* @return property value of extAttributes
*/
public Map<String, Object> getExtAttributes() {
return extAttributes;
}
/**
* @see Object#toString()
*/
@Override
public String toString() {
return "DispatchContext [application=" + application + ", openApiMethod=" + openApiMethod
+ ", openApiParams=" + openApiParams + ", openApiVersion=" + openApiVersion + "]";
}
}
package com.jz.dm.gateway.model;
import com.jz.dm.gateway.web.annotation.ParamName;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* api请求
*
* @author key
*/
public class GatewayRequest implements Serializable {
/**
* 分配的ID
*/
@ParamName("app_key")
private String appKey;
/**
* 接口名称
*/
private String method;
/**
* 格式,目前仅支持JSON
*/
private String format;
/**
* 请求使用的编码格式,如UTF-8,GBK,GB2312等
*/
private String charset;
/**
* 生成签名字符串所使用的签名算法类型
*/
@ParamName("sign_type")
private String signType;
/**
* 请求参数的签名串
*/
private String sign;
/**
* 发送请求的时间,格式"yyyy-MM-dd HH:mm:ss"
*/
private String timestamp;
/**
* 调用的接口版本,固定为:1.0
*/
private String version;
///**
// * 回调通知地址
// */
//@ParamName("notify_url")
//private String notifyUrl;
///**
// * 返回地址
// */
//@ParamName("return_url")
//private String returnUrl;
/**
* 请求参数,JSON格式
*/
private String params;
/**
* 扩展属性
*/
private final Map<String, Attribute> extAttributes = new HashMap<String, Attribute>();
/**
* Getter method for property <tt>appId</tt>.
*
* @return property value of appId
*/
public String getAppKey() {
return appKey;
}
/**
* Setter method for property <tt>appId</tt>.
*
* @param appKey value to be assigned to property appId
*/
public void setAppKey(String appKey) {
this.appKey = appKey;
}
/**
* Getter method for property <tt>method</tt>.
*
* @return property value of method
*/
public String getMethod() {
return method;
}
/**
* Setter method for property <tt>method</tt>.
*
* @param method value to be assigned to property method
*/
public void setMethod(String method) {
this.method = method;
}
/**
* Getter method for property <tt>format</tt>.
*
* @return property value of format
*/
public String getFormat() {
return format;
}
/**
* Setter method for property <tt>format</tt>.
*
* @param format value to be assigned to property format
*/
public void setFormat(String format) {
this.format = format;
}
/**
* Getter method for property <tt>charset</tt>.
*
* @return property value of charset
*/
public String getCharset() {
return charset;
}
/**
* Setter method for property <tt>charset</tt>.
*
* @param charset value to be assigned to property charset
*/
public void setCharset(String charset) {
this.charset = charset;
}
/**
* Getter method for property <tt>signType</tt>.
*
* @return property value of signType
*/
public String getSignType() {
return signType;
}
/**
* Setter method for property <tt>signType</tt>.
*
* @param signType value to be assigned to property signType
*/
public void setSignType(String signType) {
this.signType = signType;
}
/**
* Getter method for property <tt>sign</tt>.
*
* @return property value of sign
*/
public String getSign() {
return sign;
}
/**
* Setter method for property <tt>sign</tt>.
*
* @param sign value to be assigned to property sign
*/
public void setSign(String sign) {
this.sign = sign;
}
/**
* Getter method for property <tt>timestamp</tt>.
*
* @return property value of timestamp
*/
public String getTimestamp() {
return timestamp;
}
/**
* Setter method for property <tt>timestamp</tt>.
*
* @param timestamp value to be assigned to property timestamp
*/
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
/**
* Getter method for property <tt>version</tt>.
*
* @return property value of version
*/
public String getVersion() {
return version;
}
/**
* Setter method for property <tt>version</tt>.
*
* @param version value to be assigned to property version
*/
public void setVersion(String version) {
this.version = version;
}
/**
* Getter method for property <tt>notifyUrl</tt>.
*
* @return property value of notifyUrl
*/
// public String getNotifyUrl() {
// return notifyUrl;
//}
/**
* Setter method for property <tt>notifyUrl</tt>.
*
* @param notifyUrl value to be assigned to property notifyUrl
*/
//public void setNotifyUrl(String notifyUrl) {
// this.notifyUrl = notifyUrl;
//}
/**
* Getter method for property <tt>returnUrl</tt>.
*
* @return property value of returnUrl
*/
//public String getReturnUrl() {
// return returnUrl;
//}
/**
* Setter method for property <tt>returnUrl</tt>.
*
* @param returnUrl value to be assigned to property returnUrl
*/
// public void setReturnUrl(String returnUrl) {
// this.returnUrl = returnUrl;
// }
/**
* Getter method for property <tt>params</tt>.
*
* @return property value of params
*/
public String getParams() {
return params;
}
/**
* Setter method for property <tt>params</tt>.
*
* @param params value to be assigned to property params
*/
public void setParams(String params) {
this.params = params;
}
/**
* 获取扩展属性
*
* @param attributeName
* @return
*/
public Attribute getExtAttribute(String attributeName) {
return extAttributes.get(attributeName);
}
/**
* 设置属性
*
* @param attribute
*/
public void setExtAttribute(Attribute attribute) {
if (attribute == null) {
return;
}
extAttributes.put(attribute.name, attribute);
}
/**
* Getter method for property <tt>extAttributes</tt>.
*
* @return property value of extAttributes
*/
public Map<String, Attribute> getExtAttributes() {
return extAttributes;
}
/**
* @see Object#toString()
*/
@Override
public String toString() {
return "GatewayRequest [appId=" + appKey + ", method=" + method + ", format=" + format
+ ", charset=" + charset + ", signType=" + signType + ", sign=" + sign
+ ", timestamp=" + timestamp + ", version=" + version
+ ", params=" + params + ", extAttributes="
+ extAttributes + "]";
}
public static class Attribute {
/**
*  熟悉名称
*/
public String name;
/**
* 属性值
*/
public Object value;
/**
* 是否传递到业务系统
*/
public boolean isPass;
public Attribute(String name, Object value) {
this(name, value, false);
}
public Attribute(String name, Object value, boolean isPass) {
this.name = name;
this.value = value;
this.isPass = isPass;
}
/**
* @see Object#toString()
*/
@Override
public String toString() {
return "Attribute [name=" + name + ", value=" + value + ", isPass=" + isPass + "]";
}
}
}
package com.jz.dm.gateway.model;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.annotation.JSONType;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.HashMap;
import java.util.Map;
/**
* api响应
*
* @author key
*/
@JSONType(orders = { "response", "sign" })
public class GatewayResponse {
/**
* 结果码
*/
private static final String ATTRIBUTE_NAME_CODE = "code";
/**
* 结果消息
*/
private static final String ATTRIBUTE_NAME_MSG = "msg";
/**
* 数据签名
*/
private String sign;
/**
* 属性信息
*/
private final Map<String, Object> attributes = new HashMap<String, Object>();
/**
* 加密后参数密文
*/
@JsonIgnore
private String encryptData;
public String getEncryptData() {
return encryptData;
}
public void setEncryptData(String encryptData) {
this.encryptData = encryptData;
}
/**
* 默认构造函数