├── gateway-core
├── src
│ └── main
│ │ ├── webapp
│ │ ├── index.jsp
│ │ └── WEB-INF
│ │ │ └── web.xml
│ │ ├── java
│ │ └── com
│ │ │ └── z
│ │ │ └── gateway
│ │ │ ├── package-info.java
│ │ │ ├── handler
│ │ │ ├── ThreadPoolHandler.java
│ │ │ ├── OpenApiHandlerExecuteTemplate.java
│ │ │ ├── OpenApiAcceptHandler.java
│ │ │ └── support
│ │ │ │ ├── OpenApiTokenHandlerExecuteTemplateImpl.java
│ │ │ │ ├── OpenApiServiceHandlerExecuteTemplateImpl.java
│ │ │ │ ├── ThreadPoolHandlerImpl.java
│ │ │ │ ├── AsynOpenApiAcceptHandlerImpl.java
│ │ │ │ └── OpenApiAcceptHandlerImpl.java
│ │ │ ├── protocol
│ │ │ ├── AbstractTask.java
│ │ │ ├── OpenApiHttpSessionBean.java
│ │ │ ├── OpenApiHttpReqTask.java
│ │ │ └── OpenApiContext.java
│ │ │ ├── interceptor
│ │ │ ├── OpenApiTokenParamValidateInterceptor.java
│ │ │ ├── AbstractOpenApiValidateInterceptor.java
│ │ │ └── OpenApiServiceParamValidateInterceptor.java
│ │ │ ├── exception
│ │ │ └── OpenApiExceptionHandler.java
│ │ │ ├── filter
│ │ │ ├── GateWayFilter.java
│ │ │ └── GateWayRequestWrapper.java
│ │ │ ├── core
│ │ │ ├── OpenApiHttpClientService.java
│ │ │ ├── AbstractOpenApiHandler.java
│ │ │ ├── OpenApiRouteBean.java
│ │ │ └── support
│ │ │ │ ├── OpenApiRspHandler.java
│ │ │ │ ├── OpenApiReqAdapter.java
│ │ │ │ ├── OpenApiReqHandler.java
│ │ │ │ ├── OpenApiHttpClientServiceImpl.java
│ │ │ │ └── OpenApiHttpAsynClientServiceImpl.java
│ │ │ ├── web
│ │ │ └── GateWayController.java
│ │ │ └── util
│ │ │ ├── UrlUtil.java
│ │ │ ├── OpenApiResponseUtils.java
│ │ │ └── ApiHttpUtil.java
│ │ └── resources
│ │ ├── config
│ │ ├── thread_poll.properties
│ │ └── cfg-app.properties
│ │ ├── log4j.properties
│ │ └── spring
│ │ ├── applicationContext.xml
│ │ └── spring-mvc.xml
└── pom.xml
├── gateway-service
├── src
│ └── main
│ │ └── java
│ │ └── com
│ │ └── z
│ │ └── gateway
│ │ └── service
│ │ ├── package-info.java
│ │ ├── IdService.java
│ │ ├── AuthenticationService.java
│ │ ├── CacheService.java
│ │ ├── support
│ │ ├── DefaultAuthenticationServiceImpl.java
│ │ ├── DefaultIdServiceImpl.java
│ │ ├── DefaultCacheServiceImpl.java
│ │ ├── SnowFlakeIdServiceImpl.java
│ │ ├── DubboRestfulApiInterfaceServiceImpl.java
│ │ ├── TestApiInterfaceServiceImpl.java
│ │ └── StringSnowFlakeIdServiceImpl.java
│ │ └── ApiInterfaceService.java
└── pom.xml
├── gateway-common
├── src
│ └── main
│ │ └── java
│ │ └── com
│ │ └── z
│ │ └── gateway
│ │ └── common
│ │ ├── package-info.java
│ │ ├── exception
│ │ ├── OpenApiException.java
│ │ ├── OpenApiServiceErrorEnum.java
│ │ └── OauthErrorEnum.java
│ │ ├── resp
│ │ └── CommonResponse.java
│ │ ├── entity
│ │ └── ApiInterface.java
│ │ ├── util
│ │ ├── NetworkUtil.java
│ │ ├── CommonCodeConstants.java
│ │ └── StringUtil.java
│ │ └── OpenApiHttpRequestBean.java
└── pom.xml
├── pom.xml
└── readme.md
/gateway-core/src/main/webapp/index.jsp:
--------------------------------------------------------------------------------
1 |
2 |
3 | Hello World!
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/package-info.java:
--------------------------------------------------------------------------------
1 | /**网关服务
2 | * @author Administrator
3 | *
4 | */
5 | package com.z.gateway;
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/package-info.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * @author Administrator
4 | *
5 | */
6 | package com.z.gateway.service;
--------------------------------------------------------------------------------
/gateway-common/src/main/java/com/z/gateway/common/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | /**
5 | * @author Administrator
6 | *
7 | */
8 | package com.z.gateway.common;
--------------------------------------------------------------------------------
/gateway-core/src/main/resources/config/thread_poll.properties:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | threadpool.keepAliveSeconds=30000
5 |
6 | threadpool.maxPoolSize=20
7 |
8 | threadpool.queueCapacity=1000
9 |
10 |
11 | threadpool.corePoolSize=10
12 |
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/IdService.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.service;
5 |
6 | /**
7 | * @author Administrator
8 | *
9 | */
10 | public interface IdService {
11 |
12 |
13 | String genInnerRequestId();//生成请求的内部id,即traceid
14 | }
15 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/handler/ThreadPoolHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.handler;
5 |
6 | import com.z.gateway.protocol.AbstractTask;
7 |
8 | /**
9 | * @author Administrator
10 | *
11 | */
12 | public interface ThreadPoolHandler {
13 |
14 |
15 | public Object addTask(AbstractTask task);
16 | }
17 |
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/AuthenticationService.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.service;
5 |
6 | import com.z.gateway.common.OpenApiHttpRequestBean;
7 |
8 | /**认证服务类
9 | * @author Administrator
10 | *
11 | */
12 | public interface AuthenticationService {
13 |
14 | public void doAuthOpenApiHttpRequestBean(OpenApiHttpRequestBean requestBean);
15 | }
16 |
--------------------------------------------------------------------------------
/gateway-core/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.rootLogger = info,stdout
2 |
3 | ### \u8F93\u51FA\u4FE1\u606F\u5230\u63A7\u5236\u62AC ###
4 | log4j.appender.stdout = org.apache.log4j.ConsoleAppender
5 | log4j.appender.stdout.Target = System.out
6 | log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
7 | log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/CacheService.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.service;
5 |
6 | /**
7 | * 缓存接口,主要是对路由结果的缓存
8 | * @author Administrator
9 | *
10 | */
11 | @Deprecated
12 | public interface CacheService {
13 |
14 |
15 | public void put(String key,Object obj);
16 |
17 | public Object get(String key);
18 |
19 | public void remove(String key);
20 | }
21 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/handler/OpenApiHandlerExecuteTemplate.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.handler;
5 |
6 | import org.apache.commons.chain.Chain;
7 | import org.apache.commons.chain.Context;
8 |
9 | /**
10 | * @author Administrator
11 | *
12 | */
13 | public interface OpenApiHandlerExecuteTemplate extends Chain{
14 |
15 | /**
16 | * @param blCtx
17 | */
18 | boolean execute(Context chainContext) throws Exception ;
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/support/DefaultAuthenticationServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.service.support;
2 |
3 | import com.z.gateway.common.OpenApiHttpRequestBean;
4 | import com.z.gateway.service.AuthenticationService;
5 |
6 | public class DefaultAuthenticationServiceImpl implements AuthenticationService {
7 |
8 | /**
9 | * 鉴定该接口是否对于该app进行授权
10 | */
11 | @Override
12 | public void doAuthOpenApiHttpRequestBean(OpenApiHttpRequestBean requestBean) {
13 |
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/handler/OpenApiAcceptHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.handler;
5 |
6 | import javax.servlet.http.HttpServletRequest;
7 | import javax.servlet.http.HttpServletResponse;
8 |
9 | /**
10 | * @author Administrator
11 | *
12 | */
13 | public interface OpenApiAcceptHandler {
14 |
15 | /**
16 | * @param request
17 | * @param response
18 | */
19 | void acceptRequest(HttpServletRequest request, HttpServletResponse response);
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/ApiInterfaceService.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.service;
5 |
6 | import com.z.gateway.common.entity.ApiInterface;
7 |
8 | /**
9 | * @author Administrator
10 | *
11 | */
12 | public interface ApiInterfaceService {
13 |
14 | /**
15 | * 根据apiId及版本号,获取一个后端服务api接口服务的信息
16 | * @param apiId
17 | * @param version
18 | * @return
19 | */
20 | ApiInterface findOne(String apiId,String version); //这个接口方法暂定两个
21 |
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/protocol/AbstractTask.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.protocol;
2 |
3 | import java.util.concurrent.Callable;
4 |
5 | public abstract class AbstractTask implements Callable{
6 |
7 | public AbstractTask(){
8 | }
9 |
10 | @Override
11 | public OpenApiHttpSessionBean call() throws Exception {
12 | OpenApiHttpSessionBean obj = doBussiness();
13 | return obj;
14 | }
15 |
16 |
17 | public abstract OpenApiHttpSessionBean doBussiness() throws Exception;
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/support/DefaultIdServiceImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.service.support;
5 |
6 | import java.util.concurrent.atomic.AtomicInteger;
7 |
8 | import com.z.gateway.service.IdService;
9 |
10 | /**
11 | * @author Administrator
12 | *
13 | */
14 |
15 | public class DefaultIdServiceImpl implements IdService {
16 |
17 | private AtomicInteger ai = new AtomicInteger(1);
18 |
19 | @Override
20 | public String genInnerRequestId() {
21 | return String.valueOf(ai.getAndIncrement());
22 | }
23 |
24 |
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.aldb.gateway
5 | gateway
6 | pom
7 | 1.0.0-SNAPSHOT
8 | gateway Maven Webapp
9 | http://maven.apache.org
10 |
11 |
12 | gateway-common
13 | gateway-service
14 | gateway-core
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/handler/support/OpenApiTokenHandlerExecuteTemplateImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.handler.support;
5 |
6 | import org.apache.commons.chain.Command;
7 | import org.apache.commons.chain.Context;
8 |
9 | import com.z.gateway.handler.OpenApiHandlerExecuteTemplate;
10 |
11 | /**
12 | * @author Administrator
13 | *
14 | */
15 | public class OpenApiTokenHandlerExecuteTemplateImpl implements OpenApiHandlerExecuteTemplate {
16 |
17 | @Override
18 | public void addCommand(Command command) {
19 |
20 | }
21 |
22 | @Override
23 | public boolean execute(Context chainContext) throws Exception {
24 | return false;
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/interceptor/OpenApiTokenParamValidateInterceptor.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.interceptor;
5 |
6 | import javax.servlet.http.HttpServletRequest;
7 |
8 | import com.z.gateway.common.OpenApiHttpRequestBean;
9 | import com.z.gateway.common.util.CommonCodeConstants;
10 |
11 | /**
12 | * @author Administrator
13 | *
14 | */
15 | public class OpenApiTokenParamValidateInterceptor extends AbstractOpenApiValidateInterceptor {
16 |
17 | @Override
18 | protected OpenApiHttpRequestBean iniOpenApiHttpRequestBean(HttpServletRequest request) {
19 | OpenApiHttpRequestBean bean = new OpenApiHttpRequestBean();
20 | bean.setOperationType(CommonCodeConstants.API_TOKEN_KEY);
21 | return bean;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/support/DefaultCacheServiceImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.service.support;
5 |
6 | import java.util.HashMap;
7 | import java.util.Map;
8 |
9 | import com.z.gateway.service.CacheService;
10 |
11 | /**
12 | * @author Administrator
13 | *
14 | */
15 |
16 | public class DefaultCacheServiceImpl implements CacheService {
17 |
18 | private Map m = new HashMap();
19 |
20 | @Override
21 | public void put(String key, Object obj) {
22 | m.put(key, obj);
23 | }
24 |
25 | @Override
26 | public Object get(String key) {
27 | return m.get(key);
28 | }
29 |
30 | @Override
31 | public void remove(String key) {
32 | m.remove(key);
33 |
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/gateway-core/src/main/resources/config/cfg-app.properties:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | #internal resource view resolver
5 | web.view.prefix=/WEB-INF/views/
6 | web.view.suffix=.jsp
7 |
8 | #max upload size. 10M=10*1024*1024(B)=10485760 bytes
9 | web.maxUploadSize=10485760
10 |
11 | #Thread pool param
12 | openapi.threadpool.corePoolSize=10
13 | openapi.threadpool.keepAliveSeconds=30000
14 | openapi.threadpool.maxPoolSize=30
15 | openapi.threadpool.queueCapacity=100
16 |
17 | #des key
18 | openapi.des.key=&^*(*#)
19 |
20 | #============================#
21 | #=== Oauth settings =====#
22 | #============================#
23 | oauth.token.validityseconds=21600
24 |
25 | #============================#
26 | #=== HttpClient settings =====#
27 | #============================#
28 | http.client.maxTotalConnections=200
29 | http.client.defaultMaxConnectionsPerHost=2
30 | http.client.soTimeout=10000
31 | http.client.connectionTimeout=10000
32 | http.client.staleCheckingEnabled=true
33 |
34 |
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/support/SnowFlakeIdServiceImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.service.support;
5 |
6 | import org.springframework.beans.factory.InitializingBean;
7 |
8 | import com.sohu.idcenter.IdWorker;
9 | import com.z.gateway.common.util.NetworkUtil;
10 | import com.z.gateway.service.IdService;
11 |
12 | /**
13 | * @author sunff
14 | *
15 | */
16 | public class SnowFlakeIdServiceImpl implements IdService, InitializingBean {
17 |
18 | private IdWorker idWorker;
19 |
20 | @Override
21 | public String genInnerRequestId() {
22 | return String.valueOf(idWorker.getId());
23 | }
24 |
25 | @Override
26 | public void afterPropertiesSet() throws Exception {
27 |
28 | int workerId = Math.abs(NetworkUtil.getLocalMac().hashCode()) % 31;
29 | int dataCenterId = Math.abs(NetworkUtil.getLocalHost().hashCode()) % 31;
30 | idWorker = new IdWorker(workerId, dataCenterId, workerId + dataCenterId);
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/protocol/OpenApiHttpSessionBean.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.protocol;
5 |
6 | import java.io.Serializable;
7 |
8 | import com.z.gateway.common.OpenApiHttpRequestBean;
9 |
10 | /**
11 | * @author Administrator
12 | *
13 | */
14 | public class OpenApiHttpSessionBean implements Serializable{
15 |
16 | /**
17 | *
18 | */
19 | private static final long serialVersionUID = 1L;
20 | private OpenApiHttpRequestBean request;
21 |
22 | /**
23 | * @param reqBean
24 | */
25 | public OpenApiHttpSessionBean(OpenApiHttpRequestBean reqBean) {
26 | this.request = reqBean;
27 | }
28 |
29 | public OpenApiHttpRequestBean getRequest() {
30 | return request;
31 | }
32 |
33 | public void setRequest(OpenApiHttpRequestBean request) {
34 | this.request = request;
35 | }
36 |
37 | @Override
38 | public String toString() {
39 | return "OpenApiHttpSessionBean [request=" + request + "]";
40 | }
41 |
42 |
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/exception/OpenApiExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.exception;
2 |
3 | import javax.servlet.http.HttpServletRequest;
4 | import javax.servlet.http.HttpServletResponse;
5 |
6 | import org.springframework.web.servlet.HandlerExceptionResolver;
7 | import org.springframework.web.servlet.ModelAndView;
8 |
9 | import com.alibaba.fastjson.JSON;
10 | import com.z.gateway.common.OpenApiHttpRequestBean;
11 | import com.z.gateway.common.util.CommonCodeConstants;
12 | import com.z.gateway.util.OpenApiResponseUtils;
13 |
14 | public class OpenApiExceptionHandler implements HandlerExceptionResolver {
15 |
16 | @Override
17 | public ModelAndView resolveException(HttpServletRequest request,
18 | HttpServletResponse response, Object handler, Exception ex) {
19 |
20 | OpenApiHttpRequestBean reqBean = (OpenApiHttpRequestBean) request
21 | .getAttribute(CommonCodeConstants.REQ_BEAN_KEY);
22 |
23 | reqBean.setPrintStr(JSON.toJSONString(ex));
24 | OpenApiResponseUtils.writeRsp(response, reqBean);
25 |
26 | return null;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/filter/GateWayFilter.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.filter;
5 |
6 | import java.io.IOException;
7 |
8 | import javax.servlet.Filter;
9 | import javax.servlet.FilterChain;
10 | import javax.servlet.FilterConfig;
11 | import javax.servlet.ServletException;
12 | import javax.servlet.ServletRequest;
13 | import javax.servlet.ServletResponse;
14 | import javax.servlet.http.HttpServletRequest;
15 |
16 | /**
17 | * @author Administrator
18 | *
19 | */
20 | public class GateWayFilter implements Filter {
21 |
22 | public void destroy() {
23 |
24 | }
25 |
26 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
27 | ServletException {
28 | ServletRequest requestWrapper = null;
29 | if (request instanceof HttpServletRequest) {
30 | requestWrapper = new GateWayRequestWrapper((HttpServletRequest) request);
31 | }
32 | if (requestWrapper == null) {
33 | chain.doFilter(request, response);
34 | } else {
35 | chain.doFilter(requestWrapper, response);
36 | }
37 | }
38 |
39 | public void init(FilterConfig arg0) throws ServletException {
40 |
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/core/OpenApiHttpClientService.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.core;
5 |
6 | import java.util.Map;
7 |
8 |
9 | /**
10 | * @author Administrator
11 | *
12 | */
13 | public interface OpenApiHttpClientService {
14 |
15 | // get请求
16 | public String doGet(String webUrl,Map requestHeader);
17 | public String doGet(String webUrl, Map paramMap,Map requestHeader);
18 | public String doHttpsGet(String webUrl,Map requestHeader);
19 |
20 | public String doHttpsGet(String webUrl, Map paramMap,Map requestHeader);
21 |
22 |
23 | public String doHttpsPost(String url, String reqData, Map requestHeader);
24 |
25 | public String doPost(String url, String reqData, Map requestHeader);
26 |
27 | /*public Map HttpGet(String webUrl, Map paramMap);
28 |
29 | public Map HttpGet(String url, String method, Map paramMap);
30 | */
31 | /*public String doPost(String url, String reqData, String contentType, String params);
32 | public String HttpPost(String webUrl, Map paramMap);
33 |
34 | public String HttpPost(String url, String method, Map paramMap);
35 | */
36 | }
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/protocol/OpenApiHttpReqTask.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.protocol;
2 |
3 | import com.z.gateway.handler.OpenApiHandlerExecuteTemplate;
4 |
5 | public class OpenApiHttpReqTask extends AbstractTask {
6 | private OpenApiHttpSessionBean httpSessionBean;
7 | private OpenApiHandlerExecuteTemplate handlerExecuteTemplate;
8 |
9 | public OpenApiHttpReqTask(OpenApiHttpSessionBean httpSessionBean,
10 | OpenApiHandlerExecuteTemplate handlerExecuteTemplate) {
11 | this.httpSessionBean = httpSessionBean;
12 | this.handlerExecuteTemplate = handlerExecuteTemplate;
13 | }
14 |
15 | public OpenApiHttpSessionBean getHttpSessionBean() {
16 | return httpSessionBean;
17 | }
18 |
19 | public void setHttpSessionBean(OpenApiHttpSessionBean httpSessionBean) {
20 | this.httpSessionBean = httpSessionBean;
21 | }
22 |
23 | public OpenApiHandlerExecuteTemplate getHandlerExecuteTemplate() {
24 | return handlerExecuteTemplate;
25 | }
26 |
27 | public void setHandlerExecuteTemplate(OpenApiHandlerExecuteTemplate handlerExecuteTemplate) {
28 | this.handlerExecuteTemplate = handlerExecuteTemplate;
29 | }
30 |
31 | @Override
32 | public OpenApiHttpSessionBean doBussiness() throws Exception {
33 | OpenApiContext context = new OpenApiContext();
34 | context.setOpenApiHttpSessionBean(httpSessionBean);
35 | this.handlerExecuteTemplate.execute(context);
36 | return context.getOpenApiHttpSessionBean();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/web/GateWayController.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.web;
5 |
6 | import javax.servlet.http.HttpServletRequest;
7 | import javax.servlet.http.HttpServletResponse;
8 |
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.stereotype.Controller;
11 | import org.springframework.web.bind.annotation.RequestMapping;
12 | import org.springframework.web.bind.annotation.RequestMethod;
13 |
14 | import com.z.gateway.handler.OpenApiAcceptHandler;
15 |
16 | /**
17 | * @author Administrator
18 | *
19 | */
20 | @Controller
21 | public class GateWayController {
22 |
23 |
24 |
25 | @Autowired
26 | private OpenApiAcceptHandler acceptHandler;
27 | //这个供外部使用
28 | @RequestMapping(value = "index",method = {RequestMethod.POST,RequestMethod.GET})
29 | public void service(HttpServletRequest request, HttpServletResponse response) {
30 | this.acceptHandler.acceptRequest(request, response);
31 | }
32 | //这个供内部使用
33 | @RequestMapping(value = "getToken",method = {RequestMethod.POST,RequestMethod.GET})
34 | public void getToken(HttpServletRequest request, HttpServletResponse response) {
35 | this.acceptHandler.acceptRequest(request, response);
36 | }
37 | //这个供内部使用
38 | @RequestMapping(value = "indexInner",method = {RequestMethod.POST,RequestMethod.GET})
39 | public void serviceInner(HttpServletRequest request, HttpServletResponse response) {
40 | this.acceptHandler.acceptRequest(request, response);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/util/UrlUtil.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.util;
5 |
6 | import java.util.Map;
7 | import java.util.Properties;
8 |
9 | import org.springframework.util.PropertyPlaceholderHelper;
10 |
11 | /**
12 | * url处理类
13 | *
14 | * @author Administrator
15 | *
16 | */
17 | public class UrlUtil {
18 |
19 | public static String dealUrl(String targetUrl, Map params) {
20 | if (params == null) {
21 | return targetUrl;
22 | }
23 | Properties properties = new Properties();
24 | for (Map.Entry strs : params.entrySet()) {
25 | properties.put(strs.getKey(), strs.getValue());
26 | }
27 | return propertyPlaceHolder.replacePlaceholders(targetUrl, properties);
28 | }
29 |
30 | /**
31 | * 对于gateway请求后端restful服务,对于get方法提供的restful服务,
32 | * 在进行服务注册时,如果请求路径中需要参数,则一律使用${参数名}的形式出现,在此解析
33 | *
34 | * @param targetUrl
35 | * @param params
36 | * @return
37 | */
38 | /*
39 | * public static String dealUrl(String targetUrl, Properties properties) {
40 | * if (properties == null) { return targetUrl; }
41 | *
42 | * return propertyPlaceHolder.replacePlaceholders(targetUrl, properties);
43 | *
44 | * }
45 | */
46 |
47 | private static PropertyPlaceholderHelper propertyPlaceHolder = new PropertyPlaceholderHelper("{", "}");
48 |
49 | /* public static void main(String args[]) {
50 | String targetUrl = "/deptname/{deptId}/{user}/{userId}";
51 | Properties properties = new Properties();
52 | properties.put("deptId", "10");
53 | properties.put("user", "zhuzhong");
54 | properties.put("userId", "002");
55 | String result = dealUrl(targetUrl, properties);
56 | System.out.println(result);
57 | }*/
58 | }
59 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/handler/support/OpenApiServiceHandlerExecuteTemplateImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.handler.support;
5 |
6 | import java.util.ArrayList;
7 | import java.util.Iterator;
8 | import java.util.List;
9 |
10 | import org.apache.commons.chain.Command;
11 | import org.apache.commons.chain.Context;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | import com.z.gateway.handler.OpenApiHandlerExecuteTemplate;
16 |
17 | /**
18 | * @author Administrator
19 | *
20 | */
21 | public class OpenApiServiceHandlerExecuteTemplateImpl implements OpenApiHandlerExecuteTemplate {
22 |
23 | private static Logger logger = LoggerFactory.getLogger(OpenApiServiceHandlerExecuteTemplateImpl.class);
24 | private List commands = new ArrayList();
25 |
26 | public OpenApiServiceHandlerExecuteTemplateImpl(List commands) {
27 | this.commands = commands;
28 | }
29 |
30 | @Override
31 | public void addCommand(Command command) {
32 | this.commands.add(command);
33 | }
34 |
35 | @Override
36 | public boolean execute(Context context) throws Exception {
37 | logger.info("executing all handlers,have a good journey!");
38 | if (context == null || null == this.commands) {
39 | throw new IllegalArgumentException();
40 | }
41 | Iterator cmdIterator = commands.iterator();
42 | Command cmd = null;
43 | while (cmdIterator.hasNext()) {
44 | cmd = (Command) cmdIterator.next();
45 | if (cmd.execute(context)) {
46 | break; //有一个处理它了,就直接跳出
47 | }
48 | }
49 | return false;
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/gateway-common/src/main/java/com/z/gateway/common/exception/OpenApiException.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.common.exception;
2 |
3 |
4 | public class OpenApiException extends RuntimeException {
5 | /**
6 | *
7 | */
8 | private static final long serialVersionUID = 8710396445793589764L;
9 |
10 | private String errorCode = null;
11 |
12 | private String errorMsg = null;
13 |
14 | public String getErrorCode() {
15 | return errorCode;
16 | }
17 |
18 | public void setErrorCode(String errorCode) {
19 | this.errorCode = errorCode;
20 | }
21 |
22 | public String getErrorMsg() {
23 | return errorMsg;
24 | }
25 |
26 | public void setErrorMsg(String errorMsg) {
27 | this.errorMsg = errorMsg;
28 | }
29 |
30 | public OpenApiException() {
31 |
32 | }
33 |
34 |
35 | public OpenApiException(OpenApiServiceErrorEnum error) {
36 | super(error.getErrMsg());
37 | this.errorCode = error.getErrCode();
38 | this.errorMsg = error.getErrMsg();
39 | }
40 |
41 | public OpenApiException(OpenApiServiceErrorEnum error, Throwable cause) {
42 | super(error.getErrMsg(), cause);
43 | this.errorCode = error.getErrCode();
44 | this.errorMsg = error.getErrMsg();
45 | }
46 |
47 | public OpenApiException(String message) {
48 | super(message);
49 | }
50 |
51 | public OpenApiException(String message, Throwable cause) {
52 | super(message, cause);
53 | }
54 |
55 | public OpenApiException(String code, String message) {
56 | super(message);
57 | this.errorCode = code;
58 | this.errorMsg = message;
59 | }
60 |
61 | public OpenApiException(Throwable cause) {
62 | super(cause);
63 | }
64 |
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # 网关系统
2 |
3 | ## 为什么要开发网关系统
4 | 为了统一前端系统调用后端服务接口,以及为了更好的解决前后端开发分离的问题.
5 |
6 | ## 功能
7 |
8 | 目前只支持GET,POST方法请求,所使用的协议及数据格式为http+json.
9 |
10 |
11 | ## 关于鉴权
12 | 鉴权需要调用gateway_register工程的服务进行鉴权。下一步开发gateway_register工程中关于api注册及app订阅api功能。
13 |
14 | ## deviceToken获取调用方式
15 |
16 | ## appToken获取调用方式
17 |
18 |
19 |
20 |
21 | ## 业务方法调用方式
22 | 前端请求统一的url地址/gateway/gateway.do,然后根据请求方法的不同拼接不同的url参数或提交相应的请求体。
23 | ### 业务方法的公共请求参数:
24 |
25 | |参数名称|参数类型|最大长度|是否必须|说明|
26 | |-------|-------|-------|-------|----|
27 | |method| String| 64 | 是 | API编码即api的唯一标识|
28 | |appId | String| 16| 否 |打包app的唯一标识|
29 | |v |String | 8 | 否 | API版本号|
30 | |appToken|String| 32| 否 | app授权令牌,用于授权|
31 | |timestamp|String|19|是| 时间戳,对应时间的毫秒数|
32 | |signMethod|String|8|否|生成服务请求签名字符串所使用的算法类型,目前仅支持MD5|
33 | |sign|String|32|否|服务请求的签名字符串|
34 | |deviceToken|String|16|否|硬件标识token,app首次安装时发放的硬件唯一性标识|
35 | |userToken | String | 16 | 否 | 用户token|
36 |
37 | ### GET请求
38 |
39 | 对于get请求方法,则直接将相应的业务参数及公共的请求参数,串在url地址后面,类似这样的形式:
40 |
41 | http://localhost:8080/gateway/index.do?method=test&apiVersion=1.1.0&appToken=token&timeStamp=123456789&signMethod=md5&sign=223&deviceToken=444&userToken=66&format=json&testa=0000000 其中testa=000000为业务参数其他参数为公共的请求参数
42 |
43 | ### POST请求
44 | 对于post请求,则相应格式如下:
45 |
46 | { "pub_json":{}, "param_json":{} }
47 |
48 | 其只pub_json 中放的是公共请求参数,param_json为业务请求参数,并且格式为application/json,目前也只支持这种请求格式
49 |
50 | ## 如何开始
51 |
52 | gateway网关系统,可以不依赖任何外部系统测试运行。对于api服务默认实现在
53 |
54 | com.aldb.gateway.service.support.TestApiInterfaceServiceImpl
55 |
56 | 只需要将该实现类配置在spring配置文件即可进行测试,测试类似如下:
57 |
58 | http://localhost:8080/gateway/index.do?method=1&v=1.1.0&appToken=token×tamp=123456789&signMethod=md5&sign=223&deviceToken=444&userToken=66&format=json&testa=0000000
59 |
60 | method=1 为百度
61 | method=2 为sina
62 | method=3为jd.com
63 |
64 | 其他的参数均没有校验
65 |
66 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/interceptor/AbstractOpenApiValidateInterceptor.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.interceptor;
5 |
6 | import javax.servlet.http.HttpServletRequest;
7 | import javax.servlet.http.HttpServletResponse;
8 |
9 | import org.springframework.web.servlet.HandlerInterceptor;
10 | import org.springframework.web.servlet.ModelAndView;
11 |
12 | import com.z.gateway.common.OpenApiHttpRequestBean;
13 | import com.z.gateway.common.util.CommonCodeConstants;
14 |
15 | /**请求拦截器
16 | * @author Administrator
17 | *
18 | */
19 | public abstract class AbstractOpenApiValidateInterceptor implements HandlerInterceptor {
20 |
21 |
22 | public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
23 | throws Exception {
24 | // TODO Auto-generated method stub
25 |
26 | }
27 |
28 |
29 | public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
30 | throws Exception {
31 | // TODO Auto-generated method stub
32 |
33 | }
34 |
35 |
36 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
37 | String requestMethod=request.getMethod();
38 | if(!requestMethod.equals(CommonCodeConstants.REQUEST_METHOD.GET.name())&&!requestMethod.equals(CommonCodeConstants.REQUEST_METHOD.POST.name())){
39 | throw new RuntimeException("请求方法不对,请求方法必须是 GET 或POST");
40 | }
41 | // 初始化请求bean
42 | OpenApiHttpRequestBean reqBean = iniOpenApiHttpRequestBean(request);
43 | request.setAttribute(CommonCodeConstants.REQ_BEAN_KEY, reqBean);
44 | return true;
45 | }
46 |
47 | protected abstract OpenApiHttpRequestBean iniOpenApiHttpRequestBean(
48 | HttpServletRequest request);
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/gateway-common/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.aldb.gateway
5 | gateway-common
6 | jar
7 | 1.0.0-SNAPSHOT
8 | gateway Maven Webapp
9 | http://maven.apache.org
10 |
11 |
12 | UTF-8
13 | 4.3.13.RELEASE
14 | 2.9.5
15 |
16 |
17 |
18 |
19 |
20 | javax.servlet
21 | javax.servlet-api
22 | 3.0.1
23 | provided
24 |
25 |
26 | org.apache.commons
27 | commons-lang3
28 | 3.5
29 |
30 |
31 |
32 | com.alibaba
33 | fastjson
34 | 1.2.46
35 |
36 |
37 |
38 |
39 |
40 |
41 | org.slf4j
42 | slf4j-api
43 | 1.7.2
44 |
45 |
46 |
47 |
48 | junit
49 | junit
50 | 4.12
51 | test
52 |
53 |
54 |
55 |
56 |
57 |
58 | org.apache.maven.plugins
59 | maven-compiler-plugin
60 |
61 | 1.8
62 | 1.8
63 |
64 |
65 |
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/gateway-common/src/main/java/com/z/gateway/common/resp/CommonResponse.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.common.resp;
2 |
3 | import java.io.Serializable;
4 |
5 | import org.apache.commons.lang3.StringUtils;
6 |
7 | import com.alibaba.fastjson.JSON;
8 |
9 | public class CommonResponse implements Serializable {
10 |
11 | private static final long serialVersionUID = 6238235564764746187L;
12 |
13 | private T respObj;
14 |
15 | private boolean isResp;
16 |
17 | private String errorCode;
18 |
19 | private String errorMsg;
20 |
21 | private String CORRECT_PREFIX = "200.";
22 |
23 | public CommonResponse() {
24 |
25 | }
26 |
27 | public CommonResponse(boolean isResp) {
28 | this.isResp = isResp;
29 | }
30 |
31 | public CommonResponse(boolean isResp, T respObj) {
32 | this.isResp = isResp;
33 | this.respObj = respObj;
34 | }
35 |
36 | public CommonResponse(Boolean isResp, String errorCode, String errorMsg) {
37 | this.isResp = isResp;
38 | this.errorCode = errorCode;
39 | this.errorMsg = errorMsg;
40 | }
41 |
42 | public boolean isSuccess() {
43 | if (StringUtils.startsWithAny(errorCode, new String[] { CORRECT_PREFIX })) {
44 | return true;
45 | }
46 | return errorCode == null;
47 | }
48 |
49 | public T getRespObj() {
50 | return respObj;
51 | }
52 |
53 | public void setRespObj(T respObj) {
54 | this.respObj = respObj;
55 | }
56 |
57 | public String getErrorCode() {
58 | return errorCode;
59 | }
60 |
61 | public boolean isResp() {
62 | return isResp;
63 | }
64 |
65 | public void setResp(boolean isResp) {
66 | this.isResp = isResp;
67 | }
68 |
69 | public void setErrorCode(String errorCode) {
70 | this.errorCode = errorCode;
71 | }
72 |
73 | public String getErrorMsg() {
74 | return errorMsg;
75 | }
76 |
77 | public void setErrorMsg(String errorMsg) {
78 | this.errorMsg = errorMsg;
79 | }
80 |
81 | @Override
82 | public String toString() {
83 | return JSON.toJSONString(this);
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/filter/GateWayRequestWrapper.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.filter;
5 |
6 | import java.io.BufferedReader;
7 | import java.io.ByteArrayInputStream;
8 | import java.io.ByteArrayOutputStream;
9 | import java.io.IOException;
10 | import java.io.InputStream;
11 | import java.io.InputStreamReader;
12 |
13 | import javax.servlet.ServletInputStream;
14 | import javax.servlet.http.HttpServletRequest;
15 | import javax.servlet.http.HttpServletRequestWrapper;
16 |
17 | /**
18 | * @author Administrator
19 | *
20 | */
21 | public class GateWayRequestWrapper extends HttpServletRequestWrapper {
22 |
23 | /**
24 | * @param request
25 | */
26 | public GateWayRequestWrapper(HttpServletRequest request) throws IOException {
27 | super(request);
28 | body = parseInputStream2Byte(request.getInputStream());
29 | }
30 |
31 | private final byte[] body; // 报文
32 | final static int BUFFER_SIZE = 4096;
33 |
34 | /**
35 | * 将InputStream转换成byte数组
36 | *
37 | * @param in
38 | * InputStream
39 | * @return byte[]
40 | * @throws IOException
41 | */
42 | private byte[] parseInputStream2Byte(InputStream in) throws IOException {
43 |
44 | ByteArrayOutputStream outStream = new ByteArrayOutputStream();
45 | byte[] data = new byte[BUFFER_SIZE];
46 | int count = -1;
47 | while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
48 | outStream.write(data, 0, count);
49 | data = outStream.toByteArray();
50 | outStream.close();
51 | in.close();
52 | return data;
53 | }
54 |
55 | @Override
56 | public BufferedReader getReader() throws IOException {
57 | return new BufferedReader(new InputStreamReader(getInputStream()));
58 | }
59 |
60 | @Override
61 | public ServletInputStream getInputStream() throws IOException {
62 | final ByteArrayInputStream bais = new ByteArrayInputStream(body);
63 |
64 | return new ServletInputStream() {
65 |
66 | @Override
67 | public int read() throws IOException {
68 | return bais.read();
69 | }
70 | };
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/gateway-common/src/main/java/com/z/gateway/common/exception/OpenApiServiceErrorEnum.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.common.exception;
2 |
3 | public enum OpenApiServiceErrorEnum {
4 | // TODO:common error errorcode from zz00000 to zz09999
5 | SYSTEM_SUCCESS("zz00000", "success"), SYSTEM_BUSY("zz00001", "server is busy"), SYSTEM_QUEUE_DEEPTH("zz00002",
6 | "the queue reached max deepth"), VALIDATE_PARAM_ERROR("zz00100", "输入参数有误!"), REMOTE_INVOKE_ERROR(
7 | "zz00101", "远程服务错误!"), PARA_NORULE_ERROR("zz00102", "请求参数格式不符合规则"), VALIDATE_ERROR("zz00103", "校验有误"), DATA_OPER_ERROR(
8 | "zz00104", "数据操作异常"), APPLICATION_ERROR("zz00200", "业务逻辑异常"), APPLICATION_OPER_ERROR("zz00201", "系统业务异常"), DATA_EMPTY_ERROR(
9 | "zz00300", "查询结果为空"),
10 | // TODO:gateway error errorcode from zz20000 to zz29999
11 |
12 | // TODO:front error errorcode from zz30000 to zz39999
13 |
14 | // TODO:console error errorcode from zz40000 to zz49999
15 |
16 | // TODO:batch error errorcode from zz50000 to zz59999
17 |
18 | ;
19 | // 成员变量
20 | private String errCode;
21 | private String errMsg;
22 |
23 | // 构造方法
24 | private OpenApiServiceErrorEnum(String errCode, String errMsg) {
25 | this.errCode = errCode;
26 | this.errMsg = errMsg;
27 | }
28 |
29 | // 普通方法
30 | public static String getErrMsg(String errCode) {
31 | for (OpenApiServiceErrorEnum c : OpenApiServiceErrorEnum.values()) {
32 | if (c.getErrCode().equals(errCode)) {
33 | return c.getErrMsg();
34 | }
35 | }
36 | return null;
37 | }
38 |
39 | public static OpenApiServiceErrorEnum getErr(String errCode) {
40 | for (OpenApiServiceErrorEnum c : OpenApiServiceErrorEnum.values()) {
41 | if (c.getErrCode().equals(errCode)) {
42 | return c;
43 | }
44 | }
45 | return null;
46 | }
47 |
48 | public String getErrCode() {
49 | return errCode;
50 | }
51 |
52 | public void setErrCode(String errCode) {
53 | this.errCode = errCode;
54 | }
55 |
56 | public String getErrMsg() {
57 | return errMsg;
58 | }
59 |
60 | public void setErrMsg(String errMsg) {
61 | this.errMsg = errMsg;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/gateway-core/src/main/webapp/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 | Archetype Created Web Application
8 |
9 | contextConfigLocation
10 | classpath:/spring/applicationContext.xml
11 |
12 |
13 |
14 |
15 | org.springframework.web.context.ContextLoaderListener
16 |
17 |
18 |
19 |
20 | encodingFilter
21 | org.springframework.web.filter.CharacterEncodingFilter
22 | true
23 |
24 | encoding
25 | UTF-8
26 |
27 |
28 | forceEncoding
29 | true
30 |
31 |
32 |
33 |
34 | encodingFilter
35 | /*
36 |
37 |
38 |
39 |
40 | requestFilter
41 | com.z.gateway.filter.GateWayFilter
42 | true
43 |
44 |
45 |
46 | requestFilter
47 | *.do
48 |
49 |
50 |
51 |
52 |
53 | springServlet
54 | org.springframework.web.servlet.DispatcherServlet
55 |
56 | contextConfigLocation
57 | classpath*:spring/spring-mvc.xml
58 |
59 | 1
60 | true
61 |
62 |
63 | springServlet
64 | /
65 |
66 |
67 |
68 |
69 | 30
70 |
71 |
72 |
73 |
74 |
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/support/DubboRestfulApiInterfaceServiceImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.service.support;
5 |
6 | import java.util.Collections;
7 | import java.util.HashMap;
8 | import java.util.List;
9 | import java.util.Map;
10 | import java.util.concurrent.ConcurrentHashMap;
11 |
12 | import javax.sql.DataSource;
13 |
14 | import org.slf4j.Logger;
15 | import org.slf4j.LoggerFactory;
16 | import org.springframework.beans.factory.InitializingBean;
17 |
18 | import com.z.gateway.common.entity.ApiInterface;
19 | import com.z.gateway.service.ApiInterfaceService;
20 |
21 | /**
22 | * 当后端的服务是dubbo提供的restful服务时接入
23 | *
24 | * @author zhuzhong
25 | *
26 | */
27 | public class DubboRestfulApiInterfaceServiceImpl implements ApiInterfaceService, InitializingBean {
28 |
29 | private static final Logger logger = LoggerFactory.getLogger(DubboRestfulApiInterfaceServiceImpl.class);
30 | private String zkUrl;// 注册服务器的地址
31 | private DataSource dataSource;
32 |
33 | public void setZkUrl(String zkUrl) {
34 | this.zkUrl = zkUrl;
35 | }
36 |
37 | public void setDataSource(DataSource dataSource) {
38 | this.dataSource = dataSource;
39 | }
40 |
41 | @Override
42 | public ApiInterface findOne(String apiId, String version) {
43 | String contextPath = contextPaths.get(apiId);
44 | String targetUrl = restfulPaths.get(apiId);
45 | List hosts = hostURLs.get(contextPath);
46 | String host = selectOne(targetUrl, hosts);
47 | ApiInterface ret = new ApiInterface();
48 | ret.setApiId(apiId);
49 | ret.setHostAddress(host);
50 | ret.setProtocol("http");
51 | ret.setRequestMethod("POST");
52 | ret.setTargetUrl(targetUrl);
53 | ret.setVersion(version);
54 | return ret;
55 | }
56 |
57 | private String selectOne(String targetPath, List hosts) {
58 | Collections.shuffle(hosts);
59 | return hosts.get(0);
60 | }
61 |
62 | private ConcurrentHashMap/* host地址 */> hostURLs = new ConcurrentHashMap<>();
63 |
64 | private Map restfulPaths = new HashMap<>();
65 | private Map contextPaths = new HashMap<>();
66 |
67 | @Override
68 | public void afterPropertiesSet() throws Exception {
69 | logger.info("从db中获取数据,填充restfulPaths,contextPaths");
70 | logger.info("从注册中心获取数据填充hostURLs,而这个是动态变化的,这个可能时时更新");
71 | }
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/util/OpenApiResponseUtils.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.util;
2 |
3 | import java.io.PrintWriter;
4 | import java.util.Iterator;
5 | import java.util.Map;
6 | import java.util.Map.Entry;
7 |
8 | import javax.servlet.http.HttpServletResponse;
9 |
10 | import org.slf4j.Logger;
11 | import org.slf4j.LoggerFactory;
12 |
13 | import com.z.gateway.common.OpenApiHttpRequestBean;
14 |
15 | public class OpenApiResponseUtils {
16 |
17 |
18 |
19 | private static Logger logger = LoggerFactory.getLogger(OpenApiResponseUtils.class);
20 |
21 |
22 | public static final String CONTENT_TYPE_KEY = "content-type";
23 | public static final String CONTENT_TYPE_XML = "application/xml";
24 | public static final String CONTENT_TYPE_JSON = "application/json";
25 | public static final String HEADER_HOST_KEY = "host";
26 | public static final String HEADER_SERVER_KEY = "server";
27 | // public static Map sessionMap = new HashMap();
28 |
29 | public static void writeRsp(HttpServletResponse response, OpenApiHttpRequestBean requestBean) {
30 | setResponseHeader(response, requestBean.getReqHeader());
31 | try {
32 | PrintWriter writer = response.getWriter();
33 | String body=requestBean.getPrintStr();
34 | logger.debug("响应内容body={}",body);
35 | writer.print(requestBean.getPrintStr());
36 | writer.flush();
37 | writer.close();
38 | } catch (Exception e) {
39 | logger.error("Write body to response error, errorMsg={}" , e.getMessage(),e);
40 | }
41 | /*finally {
42 | sessionMap.remove(requestBean.getReqId());
43 | }*/
44 |
45 | logger.info("requestId={} request end,request={}", requestBean.getTraceId(),requestBean);
46 |
47 | }
48 |
49 | private static void setResponseHeader(HttpServletResponse response, Map httpHeader) {
50 | Iterator> entries = httpHeader.entrySet().iterator();
51 | while (entries.hasNext()) {
52 | Entry entry = entries.next();
53 | if (entry.getKey().equals(CONTENT_TYPE_KEY) || entry.getKey().equals(HEADER_HOST_KEY)) {
54 | response.addHeader(entry.getKey(), entry.getValue());
55 | }
56 | }
57 | response.setHeader(HEADER_SERVER_KEY, null);
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/handler/support/ThreadPoolHandlerImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.handler.support;
5 |
6 | import java.util.concurrent.FutureTask;
7 |
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 | import org.springframework.core.task.TaskRejectedException;
11 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
12 |
13 | import com.z.gateway.common.exception.OpenApiException;
14 | import com.z.gateway.common.exception.OpenApiServiceErrorEnum;
15 | import com.z.gateway.handler.ThreadPoolHandler;
16 | import com.z.gateway.protocol.AbstractTask;
17 | import com.z.gateway.protocol.OpenApiHttpSessionBean;
18 |
19 | /**
20 | * @author Administrator
21 | *
22 | */
23 | public class ThreadPoolHandlerImpl implements ThreadPoolHandler {
24 |
25 | private static Logger logger = LoggerFactory.getLogger(ThreadPoolHandlerImpl.class);
26 |
27 | private ThreadPoolTaskExecutor taskExecutor;
28 |
29 | public void setTaskExecutor(ThreadPoolTaskExecutor taskExecutor) {
30 | this.taskExecutor = taskExecutor;
31 | }
32 |
33 | @Override
34 | public Object addTask(AbstractTask task) {
35 | try {
36 | FutureTask tsFutre = new FutureTask(task);
37 | taskExecutor.execute(tsFutre);
38 | while (!tsFutre.isDone()) {
39 | /*
40 | * try { // logger.debug("waitting for result");
41 | * TimeUnit.MICROSECONDS.sleep(200); } catch
42 | * (InterruptedException e) { logger.error(String.format(
43 | * "exception happend on executing task with ",
44 | * e.getMessage())); }
45 | */
46 | }
47 | return tsFutre.get();
48 | } catch (TaskRejectedException e) {
49 | logger.error("the queue reached max deepth");
50 | throw new OpenApiException(OpenApiServiceErrorEnum.SYSTEM_QUEUE_DEEPTH);
51 | } catch (Throwable e) {
52 | Throwable throwable = e.getCause();
53 | if (throwable instanceof OpenApiException) {
54 | throw (OpenApiException) throwable;
55 | }
56 | logger.error(String.format("exception happend on executing task with %s", e.getMessage()));
57 | OpenApiException ex = new OpenApiException(OpenApiServiceErrorEnum.SYSTEM_BUSY, throwable);
58 | throw ex;
59 | }
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/gateway-common/src/main/java/com/z/gateway/common/entity/ApiInterface.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.common.entity;
5 |
6 | import java.io.Serializable;
7 |
8 | /**
9 | * 后端服务接口信息
10 | *
11 | * @author Administrator
12 | *
13 | */
14 | public class ApiInterface implements Serializable {
15 |
16 | /**
17 | *
18 | */
19 | private static final long serialVersionUID = -2148889461513154891L;
20 | private String apiId;
21 | private String version;// 版本号
22 | private String requestMethod;// 请求方法
23 |
24 | // 下面的数据构成访问地址
25 | private String protocol;// 请求协议,分为http,https
26 | private String hostAddress;// 服务器地址
27 | private Integer port;// 服务端口
28 | private String targetUrl; // 后端接口服务路径
29 |
30 | /**
31 | *
32 | * 以上参数可以组织出api的访问地址 protocol://hostAddress:port//targetUrl
33 | */
34 | private String url; // 解析之后服务路径
35 |
36 | // http://192.168.2.100:8089/targetUrl
37 | public String getUrl() {
38 | StringBuffer sb = new StringBuffer(protocol);
39 | sb.append("://");
40 | sb.append(hostAddress);
41 | if (port != null) {
42 | sb.append(":");
43 | sb.append(port);
44 | }
45 | if (targetUrl != null) {
46 | sb.append("/");
47 | sb.append(targetUrl);
48 | } else {
49 | sb.append("/");
50 | }
51 | this.url = sb.toString();
52 | return url;
53 | }
54 |
55 | public String getTargetUrl() {
56 | return targetUrl;
57 | }
58 |
59 | public String getProtocol() {
60 | return protocol;
61 | }
62 |
63 | public void setProtocol(String protocol) {
64 | this.protocol = protocol;
65 | }
66 |
67 | public void setTargetUrl(String targetUrl) {
68 | this.targetUrl = targetUrl;
69 | }
70 |
71 | public String getApiId() {
72 | return apiId;
73 | }
74 |
75 | public void setApiId(String apiId) {
76 | this.apiId = apiId;
77 | }
78 |
79 | public String getHostAddress() {
80 | return hostAddress;
81 | }
82 |
83 | public void setHostAddress(String hostAddress) {
84 | this.hostAddress = hostAddress;
85 | }
86 |
87 | public Integer getPort() {
88 | return port;
89 | }
90 |
91 | public void setPort(Integer port) {
92 | this.port = port;
93 | }
94 |
95 | public String getRequestMethod() {
96 | return requestMethod;
97 | }
98 |
99 | public void setRequestMethod(String requestMethod) {
100 | this.requestMethod = requestMethod;
101 | }
102 |
103 | public String getVersion() {
104 | return version;
105 | }
106 |
107 | public void setVersion(String version) {
108 | this.version = version;
109 | }
110 |
111 | }
112 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/protocol/OpenApiContext.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.protocol;
5 |
6 | import java.util.Collection;
7 | import java.util.HashMap;
8 | import java.util.Map;
9 | import java.util.Set;
10 |
11 | import org.apache.commons.chain.Context;
12 |
13 | /**
14 | * @author Administrator
15 | *
16 | */
17 | public class OpenApiContext extends HashMap implements Context {
18 |
19 | /**
20 | *
21 | */
22 | private static final long serialVersionUID = 1L;
23 |
24 | private final String SESSION_BEAN_CONTEXT_KEY = "ALD_OPENAPI_SESSION_BEAN_CONTEXT_KEY";
25 |
26 | @Override
27 | public int size() {
28 | return super.size();
29 | }
30 |
31 | @Override
32 | public boolean isEmpty() {
33 | return super.isEmpty();
34 | }
35 |
36 | @Override
37 | public boolean containsKey(Object key) {
38 | return super.containsKey(key);
39 | }
40 |
41 | @Override
42 | public boolean containsValue(Object value) {
43 | return super.containsValue(value);
44 | }
45 |
46 | @Override
47 | public Object get(Object key) {
48 | return (super.get(key));
49 | }
50 |
51 | @SuppressWarnings("unchecked")
52 | @Override
53 | public Object put(Object key, Object value) {
54 | return (super.put(key, value));
55 | }
56 |
57 | @Override
58 | public Object remove(Object key) {
59 | return super.remove(key);
60 | }
61 |
62 | @SuppressWarnings("unchecked")
63 | @Override
64 | public void putAll(Map m) {
65 | super.putAll(m);
66 | }
67 |
68 | @Override
69 | public void clear() {
70 | super.clear();
71 | }
72 |
73 | @Override
74 | public Set keySet() {
75 | return super.keySet();
76 | }
77 |
78 | @Override
79 | public Collection values() {
80 | return super.values();
81 | }
82 |
83 | @Override
84 | public Set entrySet() {
85 | return super.entrySet();
86 | }
87 |
88 | @Override
89 | public boolean equals(Object o) {
90 | return super.equals(o);
91 | }
92 |
93 | @Override
94 | public int hashCode() {
95 | return super.hashCode();
96 | }
97 |
98 | public OpenApiHttpSessionBean getOpenApiHttpSessionBean() {
99 | return (OpenApiHttpSessionBean) this.get(this.SESSION_BEAN_CONTEXT_KEY);
100 | }
101 |
102 | public void setOpenApiHttpSessionBean(OpenApiHttpSessionBean sessionBean) {
103 | this.put(this.SESSION_BEAN_CONTEXT_KEY, sessionBean);
104 | }
105 |
106 | }
107 |
--------------------------------------------------------------------------------
/gateway-service/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.aldb.gateway
5 | gateway-service
6 | jar
7 | 1.0.0-SNAPSHOT
8 | gateway Maven Webapp
9 | http://maven.apache.org
10 |
11 |
12 | UTF-8
13 | 4.3.13.RELEASE
14 | 2.9.5
15 | 1.0.0-SNAPSHOT
16 |
17 |
18 |
19 |
20 |
31 |
32 |
33 |
34 | org.springframework
35 | spring-context
36 | ${spring.version}
37 |
38 |
39 |
40 |
41 |
42 |
45 |
46 |
47 | com.sohu
48 | idcenter
49 | 1.1.1
50 |
51 |
52 |
53 |
54 |
55 |
56 | javax.servlet
57 | javax.servlet-api
58 | 3.0.1
59 | provided
60 |
61 |
62 |
63 |
64 | com.aldb.gateway
65 | gateway-common
66 | ${gateway.verson}
67 |
68 |
69 |
70 | junit
71 | junit
72 | 4.12
73 | test
74 |
75 |
76 |
77 |
78 |
79 |
80 | org.apache.maven.plugins
81 | maven-compiler-plugin
82 |
83 | 1.7
84 | 1.7
85 |
86 |
87 |
88 |
89 |
90 |
91 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/core/AbstractOpenApiHandler.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.core;
2 |
3 | import java.util.Enumeration;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | import javax.servlet.http.HttpServletRequest;
8 |
9 | import org.apache.commons.chain.Command;
10 | import org.apache.commons.chain.Context;
11 | import org.apache.commons.lang3.StringUtils;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | import com.z.gateway.common.OpenApiHttpRequestBean;
16 | import com.z.gateway.common.exception.OauthErrorEnum;
17 | import com.z.gateway.common.exception.OpenApiException;
18 |
19 | public abstract class AbstractOpenApiHandler implements Command {
20 |
21 | protected static Logger logger = LoggerFactory.getLogger(AbstractOpenApiHandler.class);
22 |
23 | // public String accessServiceUri;
24 |
25 | // public String accessTokenUri;
26 |
27 | // public String openApiCacheName;
28 |
29 | protected final String CONTENT_TYPE_KEY = "content-type";
30 | protected final String CONTENT_TYPE_XML = "application/xml";
31 | protected final String CONTENT_TYPE_JSON = "application/json";
32 | protected final String HEADER_HOST_KEY = "host";
33 | protected final String HEADER_SERVER_KEY = "server";
34 |
35 | /*
36 | * public OauthErrorEnum getBlErrorObj(String errorCode) { String
37 | * blErrorCode = OauthErrorEnum.getOauthErrorMap().get(errorCode);
38 | * OauthErrorEnum error = null; if (StringUtils.isBlank(blErrorCode)) {
39 | * error = OauthErrorEnum.ACCESS_DENIED; } else { error =
40 | * OauthErrorEnum.getErr(blErrorCode); } return error; }
41 | */
42 |
43 | protected Map getHeadersInfo(HttpServletRequest request) {
44 | Map map = new HashMap();
45 | Enumeration headerNames = request.getHeaderNames();
46 | while (headerNames.hasMoreElements()) {
47 | String key = (String) headerNames.nextElement();
48 | String value = request.getHeader(key);
49 | map.put(key, value);
50 | }
51 |
52 | return map;
53 | }
54 |
55 | protected void validateRequestHeader(OpenApiHttpRequestBean routeBean) {
56 | String contentType = routeBean.getReqHeader().get(CONTENT_TYPE_KEY);
57 | if (StringUtils.isBlank(contentType)) {
58 | throw new OpenApiException(OauthErrorEnum.CONTENTTYPE.getErrCode(), OauthErrorEnum.CONTENTTYPE.getErrMsg());
59 | }
60 | if (!contentType.contains(CONTENT_TYPE_JSON) && !contentType.contains(CONTENT_TYPE_XML)) {
61 | throw new OpenApiException(OauthErrorEnum.INVALID_CONTENTTYPE.getErrCode(),
62 | OauthErrorEnum.INVALID_CONTENTTYPE.getErrMsg());
63 | }
64 | }
65 |
66 | // step1
67 | @Override
68 | public boolean execute(Context context) {
69 |
70 | return doExcuteBiz(context);
71 | }
72 |
73 | protected abstract boolean doExcuteBiz(Context context);
74 |
75 | /*
76 | * protected CacheService cacheService = new DefaultCacheServiceImpl(); //
77 | * 饿汉模式,注入一个默认的
78 | *
79 | * public void setCacheService(CacheService cacheService) {
80 | * this.cacheService = cacheService; }
81 | */
82 | }
83 |
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/support/TestApiInterfaceServiceImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.service.support;
5 |
6 | import org.apache.commons.logging.Log;
7 | import org.apache.commons.logging.LogFactory;
8 |
9 | import com.z.gateway.common.entity.ApiInterface;
10 | import com.z.gateway.common.util.CommonCodeConstants;
11 | import com.z.gateway.service.ApiInterfaceService;
12 |
13 | /**
14 | * @author Administrator
15 | *
16 | */
17 | public class TestApiInterfaceServiceImpl implements ApiInterfaceService {
18 |
19 | private static Log log = LogFactory.getLog(TestApiInterfaceServiceImpl.class);
20 |
21 | @Override
22 | public ApiInterface findOne(String apiId, String version) {
23 | log.info("为了测试,关于这个接口,现在直接返回一个接口的值");
24 | if (apiId.equals("1")) {
25 |
26 | ApiInterface aif = new ApiInterface();
27 | aif.setApiId(apiId);
28 | aif.setVersion(version);
29 | aif.setProtocol("http");
30 | aif.setHostAddress("www.baidu.com");
31 | // aif.setPort(null);
32 | aif.setRequestMethod(CommonCodeConstants.REQUEST_METHOD.GET.name());
33 | // aif.setTargetUrl("/");
34 | return aif;
35 | } else if (apiId.equals("2")) {
36 | ApiInterface aif = new ApiInterface();
37 | aif.setApiId(apiId);
38 | aif.setVersion(version);
39 | aif.setProtocol("http");
40 | aif.setHostAddress("www.sina.com");
41 | // aif.setPort(null);
42 | aif.setRequestMethod(CommonCodeConstants.REQUEST_METHOD.GET.name());
43 | // aif.setTargetUrl("/");
44 | return aif;
45 | }else if (apiId.equals("3")) {
46 | ApiInterface aif = new ApiInterface();
47 | aif.setApiId(apiId);
48 | aif.setVersion(version);
49 | aif.setProtocol("http");
50 | aif.setHostAddress("www.jd.com");
51 | // aif.setPort(null);
52 | aif.setRequestMethod(CommonCodeConstants.REQUEST_METHOD.GET.name());
53 | // aif.setTargetUrl("/");
54 | return aif;
55 | }else if (apiId.equals("4")) {
56 |
57 | ApiInterface aif = new ApiInterface();
58 | aif.setApiId(apiId);
59 | aif.setVersion(version);
60 | aif.setProtocol("https");
61 | aif.setHostAddress("www.baidu.com");
62 | // aif.setPort(null);
63 | aif.setRequestMethod(CommonCodeConstants.REQUEST_METHOD.GET.name());
64 | // aif.setTargetUrl("/");
65 | return aif;
66 | }else if (apiId.equals("5")) {
67 |
68 | ApiInterface aif = new ApiInterface();
69 | aif.setApiId(apiId);
70 | aif.setVersion(version);
71 | aif.setProtocol("https");
72 | aif.setHostAddress("www.jd.com");
73 | // aif.setPort(null);
74 | aif.setRequestMethod(CommonCodeConstants.REQUEST_METHOD.GET.name());
75 | // aif.setTargetUrl("/");
76 | return aif;
77 | }
78 | return null;
79 |
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/gateway-common/src/main/java/com/z/gateway/common/util/NetworkUtil.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.common.util;
2 |
3 | import java.io.IOException;
4 | import java.net.InetAddress;
5 | import java.net.NetworkInterface;
6 | import java.net.SocketException;
7 | import java.net.UnknownHostException;
8 | import java.util.UUID;
9 |
10 | import javax.servlet.http.HttpServletRequest;
11 |
12 | /**
13 | * 常用获取客户端信息的工具
14 | *
15 | */
16 | public final class NetworkUtil {
17 |
18 | public static String getLocalHost(){
19 | InetAddress ia = null;
20 | try {
21 | ia = InetAddress.getLocalHost();
22 | } catch (UnknownHostException e1) {
23 |
24 | e1.printStackTrace();
25 | return UUID.randomUUID().toString();
26 | }
27 | return ia.toString();
28 | }
29 | public static String getLocalMac() {
30 | InetAddress ia = null;
31 | try {
32 | ia = InetAddress.getLocalHost();
33 | } catch (UnknownHostException e1) {
34 |
35 | e1.printStackTrace();
36 | return UUID.randomUUID().toString();
37 | }
38 |
39 | try {
40 |
41 | byte[] mac = NetworkInterface.getByInetAddress(ia)
42 | .getHardwareAddress();
43 | //System.out.println("mac数组长度:" + mac.length);
44 | StringBuffer sb = new StringBuffer("");
45 | for (int i = 0; i < mac.length; i++) {
46 | if (i != 0) {
47 | sb.append("-");
48 | }
49 | // 字节转换为整数
50 | int temp = mac[i] & 0xff;
51 | String str = Integer.toHexString(temp);
52 | //System.out.println("每8位:" + str);
53 | if (str.length() == 1) {
54 | sb.append("0" + str);
55 | } else {
56 | sb.append(str);
57 | }
58 | }
59 | return sb.toString().toUpperCase();
60 | } catch (SocketException e) {
61 |
62 | e.printStackTrace();
63 | return UUID.randomUUID().toString();
64 | }
65 | }
66 |
67 | /**
68 | * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址;
69 | *
70 | * @param request
71 | * @return
72 | * @throws IOException
73 | */
74 | public final static String getClientIpAddr(HttpServletRequest request) {
75 | String ip = request.getHeader("X-forwarded-for");
76 |
77 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
78 | if (ip == null || ip.length() == 0
79 | || "unknown".equalsIgnoreCase(ip)) {
80 | ip = request.getHeader("Proxy-Client-IP");
81 | }
82 | if (ip == null || ip.length() == 0
83 | || "unknown".equalsIgnoreCase(ip)) {
84 | ip = request.getHeader("WL-Proxy-Client-IP");
85 | }
86 | if (ip == null || ip.length() == 0
87 | || "unknown".equalsIgnoreCase(ip)) {
88 | ip = request.getHeader("HTTP_CLIENT_IP");
89 | }
90 | if (ip == null || ip.length() == 0
91 | || "unknown".equalsIgnoreCase(ip)) {
92 | ip = request.getHeader("HTTP_X_FORWARDED_FOR");
93 | }
94 | if (ip == null || ip.length() == 0
95 | || "unknown".equalsIgnoreCase(ip)) {
96 | ip = request.getRemoteAddr();
97 | }
98 | } else if (ip.length() > 15) {
99 | String[] ips = ip.split(",");
100 | for (int index = 0; index < ips.length; index++) {
101 | String strIp = (String) ips[index];
102 | if (!("unknown".equalsIgnoreCase(strIp))) {
103 | ip = strIp;
104 | break;
105 | }
106 | }
107 | }
108 | return ip;
109 | }
110 | }
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/core/OpenApiRouteBean.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.core;
5 |
6 | import java.io.Serializable;
7 | import java.util.Map;
8 | import java.util.Properties;
9 |
10 | /**去掉中间的routeBean
11 | * @author Administrator
12 | *
13 | */
14 | @Deprecated
15 | public class OpenApiRouteBean implements Serializable {
16 |
17 | /**
18 | *
19 | */
20 | private static final long serialVersionUID = 5437248914612381520L;
21 |
22 | private String traceId; // 内部定义的请求id
23 |
24 | private String apiId;
25 | private String requestMethod;
26 | private String version; // api_version
27 | private String timeStamp;
28 |
29 | private Map reqHeader;
30 |
31 | private String operationType;
32 |
33 | private String serviceReqData;// post请求方法参数
34 | // private String queryString; // 请求string
35 | private Map serviceGetReqData; // get请求参数
36 | private Properties thdApiUrlParams;// 第三方接口所需传入的url参数
37 |
38 | private String serviceRsp; // 后端服务返回值
39 |
40 | public String getServiceRsp() {
41 | return serviceRsp;
42 | }
43 |
44 | public void setServiceRsp(String serviceRsp) {
45 | this.serviceRsp = serviceRsp;
46 | }
47 |
48 | public void setThdApiUrlParams(Properties thdApiUrlParams) {
49 | this.thdApiUrlParams = thdApiUrlParams;
50 | }
51 |
52 | public Map getServiceGetReqData() {
53 | return serviceGetReqData;
54 | }
55 |
56 | public void setServiceGetReqData(Map serviceGetReqData) {
57 | this.serviceGetReqData = serviceGetReqData;
58 | }
59 |
60 | public Properties getThdApiUrlParams() {
61 | return this.thdApiUrlParams;
62 | }
63 |
64 | public void addThdApiUrlParams(String key, String value) {
65 | if (thdApiUrlParams == null) {
66 | this.thdApiUrlParams = new Properties();
67 | }
68 | this.thdApiUrlParams.put(key, value);
69 | }
70 |
71 | public String getRequestMethod() {
72 | return requestMethod;
73 | }
74 |
75 | public void setRequestMethod(String requestMethod) {
76 | this.requestMethod = requestMethod;
77 | }
78 |
79 | public String getVersion() {
80 | return version;
81 | }
82 |
83 | public void setVersion(String version) {
84 | this.version = version;
85 | }
86 |
87 | public String getServiceReqData() {
88 | return serviceReqData;
89 | }
90 |
91 | public void setServiceReqData(String serviceReqData) {
92 | this.serviceReqData = serviceReqData;
93 | }
94 |
95 | public String getOperationType() {
96 | return operationType;
97 | }
98 |
99 | public void setOperationType(String operationType) {
100 | this.operationType = operationType;
101 | }
102 |
103 | public String getTraceId() {
104 | return traceId;
105 | }
106 |
107 | public void setTraceId(String traceId) {
108 | this.traceId = traceId;
109 | }
110 |
111 | public String getApiId() {
112 | return apiId;
113 | }
114 |
115 | public void setApiId(String apiId) {
116 | this.apiId = apiId;
117 | }
118 |
119 | public String getTimeStamp() {
120 | return timeStamp;
121 | }
122 |
123 | public void setTimeStamp(String timeStamp) {
124 | this.timeStamp = timeStamp;
125 | }
126 |
127 | public Map getReqHeader() {
128 | return reqHeader;
129 | }
130 |
131 | public void setReqHeader(Map reqHeader) {
132 | this.reqHeader = reqHeader;
133 | }
134 |
135 | }
136 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/handler/support/AsynOpenApiAcceptHandlerImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.handler.support;
5 |
6 | import javax.servlet.AsyncContext;
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 |
10 | import org.slf4j.Logger;
11 | import org.slf4j.LoggerFactory;
12 | import org.springframework.beans.BeansException;
13 | import org.springframework.context.ApplicationContext;
14 | import org.springframework.context.ApplicationContextAware;
15 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
16 |
17 | import com.z.gateway.common.OpenApiHttpRequestBean;
18 | import com.z.gateway.common.util.CommonCodeConstants;
19 | import com.z.gateway.handler.OpenApiAcceptHandler;
20 | import com.z.gateway.handler.OpenApiHandlerExecuteTemplate;
21 | import com.z.gateway.protocol.OpenApiContext;
22 | import com.z.gateway.protocol.OpenApiHttpSessionBean;
23 | import com.z.gateway.service.IdService;
24 | import com.z.gateway.util.OpenApiResponseUtils;
25 |
26 | /**
27 | * 异步处理请求
28 | *
29 | * @author sunff
30 | *
31 | */
32 | public class AsynOpenApiAcceptHandlerImpl implements OpenApiAcceptHandler, ApplicationContextAware {
33 |
34 | private static Logger logger = LoggerFactory.getLogger(AsynOpenApiAcceptHandlerImpl.class);
35 |
36 | private ThreadPoolTaskExecutor taskExecutor;
37 | private IdService idService;
38 |
39 | public void setTaskExecutor(ThreadPoolTaskExecutor taskExecutor) {
40 | this.taskExecutor = taskExecutor;
41 | }
42 |
43 | public void setIdService(IdService idService) {
44 | this.idService = idService;
45 | }
46 |
47 | @Override
48 | public void acceptRequest(HttpServletRequest request, HttpServletResponse response) {
49 |
50 | final AsyncContext context = request.startAsync(request, response);
51 | taskExecutor.submit(new Runnable() {
52 |
53 | @Override
54 | public void run() {
55 | try {
56 | HttpServletRequest asynRequest = (HttpServletRequest) context.getRequest();
57 |
58 | OpenApiHttpRequestBean reqBean = (OpenApiHttpRequestBean) asynRequest
59 | .getAttribute(CommonCodeConstants.REQ_BEAN_KEY);
60 | String traceId = idService.genInnerRequestId();
61 | reqBean.setTraceId(traceId);
62 | reqBean.getReqHeader().put(CommonCodeConstants.TRACE_ID, traceId);
63 | asynRequest.setAttribute(CommonCodeConstants.REQ_BEAN_KEY, reqBean); // 重新设置bean
64 | logger.info("requestId={} request begin,request={}", traceId, reqBean);
65 | OpenApiHttpSessionBean sessionBean = new OpenApiHttpSessionBean(reqBean);
66 | String operationType = sessionBean.getRequest().getOperationType();
67 | OpenApiHandlerExecuteTemplate handlerExecuteTemplate = applicationContext.getBean(operationType,
68 | OpenApiHandlerExecuteTemplate.class);
69 | OpenApiContext openApiContext = new OpenApiContext();
70 | openApiContext.setOpenApiHttpSessionBean(sessionBean);
71 | try {
72 | handlerExecuteTemplate.execute(openApiContext);
73 | } catch (Exception e) {
74 | e.printStackTrace();
75 | }
76 | // 写入响应
77 | OpenApiResponseUtils.writeRsp((HttpServletResponse) context.getResponse(),
78 | sessionBean.getRequest());
79 | } finally {
80 | context.complete();
81 | }
82 |
83 | }
84 | });
85 | }
86 |
87 | private ApplicationContext applicationContext;
88 |
89 | @Override
90 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
91 | this.applicationContext = applicationContext;
92 | }
93 |
94 | }
95 |
--------------------------------------------------------------------------------
/gateway-common/src/main/java/com/z/gateway/common/exception/OauthErrorEnum.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.common.exception;
2 |
3 |
4 | public enum OauthErrorEnum {
5 | ERROR("zz10000", "service unavailable"),
6 | GRANTTYPE("zz10001", "grant_type is required"),
7 | APP_ID("zz10002", "appid is required"),
8 | SECRET("zz10003", "secret is required"),
9 | TIMSTAMP("zz10004", "timestamp is required"),
10 | SIGN("zz10005", "sign is required"),
11 | INVALID_SIGN("zz10006", "invalid sign"),
12 | INVALID_REQUEST("zz10007", "invalid request"),
13 | INVALID_CLIENT("zz10008", "invalid appId or apptoken"),
14 | INVALID_GRANT("zz10009", "invalid grant"),
15 | UNAUTHORIZED_CLIENT("zz10010", "unauthorized appId"),
16 | UNSUPPORTED_GRANT_TYPE("zz10011", "unsupported grant_type"),
17 | INVALID_TOKEN("zz10012", "invalid token"),
18 | ACCESS_DENIED("zz10013", "access denied"),
19 | API_ID("zz10014", "apiId is required"),
20 | ACCESSTOKEN("zz10015", "appToken is required"),
21 | INVALID_SERVICENAME("zz10016", "invalid service_name"),
22 | CONTENTTYPE("zz10017", "httprequest header content-type is required"),
23 | INVALID_CONTENTTYPE("zz10018", "invalid content-type,just application/xml or application/json"),
24 | INVALID_SECRET("zz10019", "invalid secret"),
25 | UN_VISIBLE_SERVICENAME("zz10021", "service is not visible"),
26 | LOCK_ITEM_APPID("zz10022", "current appid is locked"),
27 | LOCK_ITEM_API("zz10023", "current service is locked"),
28 | APP_UNDEFIND_WHITE("zz10024","undefind in whiteList"),
29 | SERVICE_UNDEFIND_WHITE("zz10025","service_name undefind in whiteList"),
30 | NOT_CALLBACKURL("zz10026","undefind in user's callBackUrl"),
31 | INTERFACE_FREQUENCY("zz10027", "api freq out of limit"),
32 | APP_TOKEN("zz10028", "apptoken is required"),
33 | ;
34 | // 成员变量
35 | private String errCode;
36 | private String errMsg;
37 |
38 | // 构造方法
39 | private OauthErrorEnum(String errCode, String errMsg) {
40 | this.errCode = errCode;
41 | this.errMsg = errMsg;
42 | }
43 | /* // 普通方法
44 | public static String getErrMsg(String errCode) {
45 | for (OauthErrorEnum c : OauthErrorEnum.values()) {
46 | if (c.getErrCode().equals(errCode)) {
47 | return c.getErrMsg();
48 | }
49 | }
50 | return null;
51 | }
52 |
53 | public static OauthErrorEnum getErr(String errCode) {
54 | for (OauthErrorEnum c : OauthErrorEnum.values()) {
55 | if (c.getErrCode().equals(errCode)) {
56 | return c;
57 | }
58 | }
59 | return null;
60 | }*/
61 |
62 | public String getErrCode() {
63 | return errCode;
64 | }
65 |
66 | public String getErrMsg() {
67 | return errMsg;
68 | }
69 | /*public void setErrMsg(String errMsg) {
70 | this.errMsg = errMsg;
71 | }
72 | public void setErrCode(String errCode) {
73 | this.errCode = errCode;
74 | }*/
75 |
76 | /*private static Map oauthErrorMap;
77 | static{
78 | oauthErrorMap = new HashMap();
79 | oauthErrorMap.put("error", "zz10000");
80 | oauthErrorMap.put("invalid_request", "zz10007");
81 | oauthErrorMap.put("invalid_client", "zz10008");
82 | oauthErrorMap.put("invalid_grant", "zz10009");
83 | oauthErrorMap.put("unauthorized_client", "zz10010");
84 | oauthErrorMap.put("401", "zz10010");
85 | oauthErrorMap.put("unsupported_grant_type", "zz10011");
86 | oauthErrorMap.put("invalid_token", "zz10012");
87 | oauthErrorMap.put("access_denied", "zz10013");
88 | }
89 | public static Map getOauthErrorMap() {
90 | return oauthErrorMap;
91 | }
92 | public static void setOauthErrorMap(Map oauthErrorMap) {
93 | OauthErrorEnum.oauthErrorMap = oauthErrorMap;
94 | }*/
95 | }
96 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/handler/support/OpenApiAcceptHandlerImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.handler.support;
5 |
6 | import javax.servlet.http.HttpServletRequest;
7 | import javax.servlet.http.HttpServletResponse;
8 |
9 | import org.slf4j.Logger;
10 | import org.slf4j.LoggerFactory;
11 | import org.springframework.beans.BeansException;
12 | import org.springframework.context.ApplicationContext;
13 | import org.springframework.context.ApplicationContextAware;
14 |
15 | import com.alibaba.fastjson.JSON;
16 | import com.z.gateway.common.OpenApiHttpRequestBean;
17 | import com.z.gateway.common.util.CommonCodeConstants;
18 | import com.z.gateway.handler.OpenApiAcceptHandler;
19 | import com.z.gateway.handler.OpenApiHandlerExecuteTemplate;
20 | import com.z.gateway.handler.ThreadPoolHandler;
21 | import com.z.gateway.protocol.OpenApiHttpReqTask;
22 | import com.z.gateway.protocol.OpenApiHttpSessionBean;
23 | import com.z.gateway.service.IdService;
24 | import com.z.gateway.util.OpenApiResponseUtils;
25 |
26 | /**
27 | * @author Administrator
28 | *
29 | */
30 | @Deprecated
31 | public class OpenApiAcceptHandlerImpl implements OpenApiAcceptHandler, ApplicationContextAware {
32 |
33 | private static Logger logger = LoggerFactory.getLogger(OpenApiAcceptHandlerImpl.class);
34 | private IdService idService;
35 |
36 | private ThreadPoolHandler poolHandler;
37 |
38 | public void setIdService(IdService idService) {
39 | this.idService = idService;
40 | }
41 |
42 | public void setPoolHandler(ThreadPoolHandler poolHandler) {
43 | this.poolHandler = poolHandler;
44 | }
45 |
46 | @Override
47 | public void acceptRequest(HttpServletRequest request, HttpServletResponse response) {
48 | OpenApiHttpRequestBean reqBean = (OpenApiHttpRequestBean) request
49 | .getAttribute(CommonCodeConstants.REQ_BEAN_KEY);
50 | String traceId = idService.genInnerRequestId();
51 | reqBean.getReqHeader().put(CommonCodeConstants.TRACE_ID, traceId);
52 | //reqBean.setTraceId(traceId);
53 | request.setAttribute(CommonCodeConstants.REQ_BEAN_KEY, reqBean); // 重新设置bean
54 | if (logger.isInfoEnabled()) {
55 | logger.info(String.format("requestId=%s request begin,reqeust=%s", traceId, JSON.toJSONString(reqBean)));
56 | }
57 | // 将当前请求放入线程池处理,若超过线程池最大处理数则抛出reach queue max deepth 异常
58 | addTask2Pool(response, new OpenApiHttpSessionBean(reqBean));
59 | }
60 |
61 | private void addTask2Pool(HttpServletResponse response, OpenApiHttpSessionBean sessionBean) {
62 | long currentTime = System.currentTimeMillis();
63 | if (logger.isDebugEnabled()) {
64 | logger.debug(
65 | String.format("begin deal_sessionbean,current_time=%d,sessionbean=%s ", currentTime, sessionBean));
66 | }
67 | logger.info("added one task to thread pool");
68 | OpenApiHttpReqTask task = null;
69 | String operationType = sessionBean.getRequest().getOperationType();
70 |
71 | OpenApiHandlerExecuteTemplate handlerExecuteTemplate = applicationContext.getBean(operationType,
72 | OpenApiHandlerExecuteTemplate.class);
73 | task = new OpenApiHttpReqTask(sessionBean, handlerExecuteTemplate);
74 | /**
75 | * 走责任链,将相关的请求处理
76 | */
77 | OpenApiHttpSessionBean tmp = (OpenApiHttpSessionBean) poolHandler.addTask(task);
78 | // 写入响应
79 | OpenApiResponseUtils.writeRsp(response, tmp.getRequest());
80 | if (logger.isDebugEnabled()) {
81 | logger.debug(String.format("end deal_sessionbean,current_time=%d,elapase_time=%d milseconds,sessionbean=%s",
82 | System.currentTimeMillis(), (System.currentTimeMillis() - currentTime), tmp));
83 | }
84 | }
85 |
86 | private ApplicationContext applicationContext;
87 |
88 | @Override
89 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
90 | this.applicationContext = applicationContext;
91 | }
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/core/support/OpenApiRspHandler.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.core.support;
2 |
3 | import org.apache.commons.chain.Context;
4 | import org.apache.commons.lang3.StringUtils;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | import com.z.gateway.common.OpenApiHttpRequestBean;
9 | import com.z.gateway.common.exception.OpenApiException;
10 | import com.z.gateway.common.exception.OpenApiServiceErrorEnum;
11 | import com.z.gateway.core.AbstractOpenApiHandler;
12 | import com.z.gateway.core.OpenApiRouteBean;
13 | import com.z.gateway.protocol.OpenApiContext;
14 | import com.z.gateway.protocol.OpenApiHttpSessionBean;
15 | import com.z.gateway.service.CacheService;
16 |
17 |
18 | @Deprecated
19 | public class OpenApiRspHandler extends AbstractOpenApiHandler {
20 | private static final Logger logger = LoggerFactory.getLogger(OpenApiRspHandler.class);
21 |
22 | /*
23 | * @Override public boolean execute(Context context) {
24 | * logger.info("step1----"); return doExcuteBiz(context); }
25 | */
26 |
27 | @Override
28 | protected boolean doExcuteBiz(Context context) {
29 | logger.info("step2----");
30 | OpenApiContext blCtx = (OpenApiContext) context;
31 | OpenApiHttpSessionBean httpSessionBean = (OpenApiHttpSessionBean) blCtx.getOpenApiHttpSessionBean();
32 | OpenApiHttpRequestBean request = httpSessionBean.getRequest();
33 | long currentTime = System.currentTimeMillis();
34 |
35 | logger.debug("begin run doExecuteBiz,currentTime={},httpSessonBean={}", currentTime,
36 | httpSessionBean);
37 |
38 | /*String printStr = this.executePrint(request);
39 | request.setPrintStr(printStr);*/
40 |
41 |
42 | logger.debug(
43 | "end run doExecuteBiz,currentTime={},elapase_time={} milseconds,httpSessonBean={}",
44 | System.currentTimeMillis(), (System.currentTimeMillis() - currentTime), httpSessionBean);
45 |
46 |
47 | return false;
48 | }
49 |
50 | private CacheService cacheService;
51 |
52 | public void setCacheService(CacheService cacheService) {
53 | this.cacheService = cacheService;
54 | }
55 |
56 | private String executePrint(OpenApiHttpRequestBean request) {
57 | logger.info("step3...");
58 | try {
59 | return this.getResponseBody(request);
60 | } catch (Exception e) {
61 | OpenApiException ex = null;
62 | if (e instanceof OpenApiException) {
63 | ex = (OpenApiException) e;
64 | } else {
65 | ex = new OpenApiException(OpenApiServiceErrorEnum.SYSTEM_BUSY, e.getCause());
66 | }
67 | logger.error("executePrint error, " + e.getMessage());
68 | // return XmlUtils.bean2xml((ex.getShortMsg("unknow")));
69 | return "error";
70 | } finally {
71 | // 从redis移除当前routebean
72 | String routeBeanKey = request.getRouteBeanKey();
73 | if (StringUtils.isNotBlank(routeBeanKey)) {
74 | cacheService.remove(routeBeanKey);
75 | }
76 |
77 | /*
78 | * // 设置同步信号unlock redisKey =
79 | * request.getUserTokenSyncSingalRedisKey(); if
80 | * (StringUtils.isNotBlank(redisKey)) { Cache redisCache =
81 | * this.cacheManager.getCache(openApiCacheName);
82 | * redisCache.put(request.getUserTokenSyncSingalRedisKey(),
83 | * CommonCodeConstants.SyncSingalType.SingalUnLock.getCode()); }
84 | */
85 | }
86 |
87 | }
88 |
89 | private String getResponseBody(OpenApiHttpRequestBean bean) {
90 | logger.info("step4....");
91 | String routeBeanKey = bean.getRouteBeanKey();
92 | OpenApiRouteBean routeBean = (OpenApiRouteBean) cacheService.get(routeBeanKey);
93 | Object body = (Object) routeBean.getServiceRsp();
94 | if (body instanceof String) {
95 | return body.toString();
96 | } else {
97 | throw new RuntimeException("返回内容格式不对...");
98 | }
99 |
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/gateway-common/src/main/java/com/z/gateway/common/util/CommonCodeConstants.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.common.util;
5 |
6 | /**
7 | * @author Administrator
8 | *
9 | */
10 | public class CommonCodeConstants {
11 |
12 |
13 |
14 | public static final String API_SERVICE_KEY = "openapi.service.HandlerExecuteTemplate";
15 | public static final String API_TOKEN_KEY = "openapi.gettoken.HandlerExecuteTemplate";
16 | public static final String API_WTSERVICE_KEY = "openapi.wtService";
17 | public static final String API_SYSERVICE_KEY = "openapi.syService";
18 | public static final String API_GETDATA_KEY = "openapi.getSyData";
19 |
20 |
21 |
22 | public static final String REQ_BEAN_KEY = "GATE_WAY_BEAN";
23 |
24 |
25 |
26 | public static final String ROUTE_BEAN_KEY = "BL_OPENAPI_ROUTE_BEAN";
27 | public static final String USER_TOKEN_KEY = "BL_OPENAPI_USER_TOKEN";
28 | public static final String USER_TOKEN_SYNC_SINGAL_KEY = "BL_OPENAPI_USER_TOKEN_SYNC_SINGAL";
29 |
30 | public static final String CTRL_STR = "_";
31 | // public static final String ROUTE_APPID_KEY = "appId";
32 | public static final String ROUTE_TOKEN_KEY = "accessToken";
33 |
34 | public static final String SERVICE_TYPE_KEY = "servcieType";
35 | public static final String SERVICE_BODY_KEY = "body";
36 | public static final String SYSTEM_ERROR_KEY = "500";
37 | public static final String SERVICE_INVOKE_DATA = "servcieInvokeData";
38 | public static final String MDF_CHARSET_UTF_8 = "UTF-8";
39 | public static final String LOSE_MESSAGE_SENDSTATUS_UNSEND = "0";
40 | public static final String USER_LOGIN_KEY = "BL_OPENAPI_USER_LOGIN";
41 |
42 | public static final String TRACE_ID="traceId";
43 |
44 | /**
45 |
46 | * 公共的请求参数
47 | appId String 16 是 打包app的唯一标识 not null
48 | appToken String 32 是 app授权令牌,用于授权 not null
49 | method String 64 是 API编码即api的唯一标识 not null
50 | v String 8 是 API版本号 not null
51 | timestamp String 19 是 时间戳,格式为yyyy-mm-dd HH:mm:ss,时区为GMT+8 not null
52 | signMethod String 8 是 生成服务请求签名字符串所使用的算法类型,目前仅支持MD5,
53 | sign String 32 是 服务请求的签名字符串 not null
54 | deviceToken String 16 否 硬件标识token,app首次安装时发放的硬件唯一性标识
55 | userToken String 16 否 用户token
56 |
57 |
58 | application/xxxx-wwww.form
59 |
60 | *
61 | * 请求格式:
62 | * 1.对于post方法: { "pub_json":{}, "param_json":{} } //content_type:application/json
63 | * {}
64 | *
65 | * 2.对于get方法: 公共参数及业务参数直接串接在url地址上 对于后端使用restful格式的get,在进行服务注册时使用方法名
66 | * user/1000 对应的注册格式 user/{userId}
67 | * 然后前端请请使用的参数名为userId,
68 | * 前端请求格式 GET
69 | * /gateway.do
70 | * 而对于使用非restful格式的get方法直接将参数串在url地址上就可以了
71 | */
72 |
73 | public static String pub_attrs = "pub_json";
74 | public static String busi_attrs = "param_json";
75 | public static String content_type = "application/json";
76 |
77 | public static String app_id = "appId";
78 | public static String app_token = "appToken";
79 | public static String api_id = "method";
80 | public static String version = "v";
81 | public static String time_stamp = "timestamp";
82 | public static String sign_method = "signMethod";
83 | public static String sign = "sign";
84 | public static String device_token = "deviceToken";
85 | public static String user_token = "userToken";
86 | public static String format = "format";
87 |
88 | public static String getRouteBeanRedisKey(String key) {
89 | StringBuilder sb = new StringBuilder();
90 | sb.append(ROUTE_BEAN_KEY).append(CTRL_STR).append(key);
91 | return sb.toString();
92 | }
93 |
94 | public static enum REQUEST_METHOD {
95 | POST, GET
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/gateway-core/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.aldb.gateway
5 | gateway-core
6 | war
7 | 1.0.0-SNAPSHOT
8 | gateway Maven Webapp
9 | http://maven.apache.org
10 |
11 |
12 | UTF-8
13 | 4.3.13.RELEASE
14 | 2.9.5
15 | 1.0.0-SNAPSHOT
16 |
17 |
18 |
19 |
20 |
21 | javax.servlet
22 | javax.servlet-api
23 | 3.0.1
24 | provided
25 |
26 |
27 | org.apache.httpcomponents
28 | httpclient
29 | 4.5.3
30 |
31 |
32 | org.apache.httpcomponents
33 | httpasyncclient
34 | 4.1.3
35 |
36 |
37 |
38 | com.fasterxml.jackson.core
39 | jackson-core
40 | ${jackson.version}
41 |
42 |
43 | com.fasterxml.jackson.core
44 | jackson-annotations
45 | ${jackson.version}
46 |
47 |
48 | com.fasterxml.jackson.core
49 | jackson-databind
50 | ${jackson.version}
51 |
52 |
53 |
54 | com.aldb.gateway
55 | gateway-common
56 | ${gateway.version}
57 |
58 |
59 | com.aldb.gateway
60 | gateway-service
61 | ${gateway.version}
62 |
63 |
64 |
65 | commons-chain
66 | commons-chain
67 | 1.2
68 |
69 |
70 |
71 | org.springframework
72 | spring-webmvc
73 | ${spring.version}
74 |
75 |
76 | commons-logging
77 | commons-logging
78 |
79 |
80 |
81 |
82 |
83 | org.springframework
84 | spring-context-support
85 | ${spring.version}
86 |
87 |
88 |
89 |
90 | org.slf4j
91 | slf4j-log4j12
92 | 1.7.2
93 | test
94 |
95 |
96 |
97 | log4j
98 | log4j
99 | 1.2.17
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 | org.apache.maven.plugins
109 | maven-compiler-plugin
110 |
111 | 1.8
112 | 1.8
113 |
114 |
115 |
116 | gateway
117 |
118 |
119 |
--------------------------------------------------------------------------------
/gateway-service/src/main/java/com/z/gateway/service/support/StringSnowFlakeIdServiceImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.service.support;
5 |
6 | import java.text.DateFormat;
7 | import java.text.SimpleDateFormat;
8 | import java.util.Date;
9 |
10 | import com.z.gateway.common.util.NetworkUtil;
11 | import com.z.gateway.service.IdService;
12 |
13 | /**
14 | * @author sunff
15 | *
16 | */
17 | public class StringSnowFlakeIdServiceImpl implements IdService {
18 |
19 | @Override
20 | public String genInnerRequestId() {
21 | // TODO Auto-generated method stub
22 | return nextId();
23 | }
24 |
25 | private final long workerId;
26 | private final long datacenterId;
27 | private final long idepoch;
28 |
29 | private static final long workerIdBits = 5L;
30 | private static final long datacenterIdBits = 5L;
31 | private static final long maxWorkerId = -1L ^ (-1L << workerIdBits);
32 | private static final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
33 |
34 | private static final long sequenceBits = 13L;
35 | // private static final long workerIdShift = sequenceBits;
36 | // private static final long datacenterIdShift = sequenceBits +
37 | // workerIdBits;
38 | private static final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
39 | private static final long sequenceMask = -1L ^ (-1L << sequenceBits);
40 |
41 | private long lastTimestamp = -1L;
42 | private long sequence;
43 |
44 | // private static final Random r = new Random();
45 |
46 | /*
47 | * public StringIdServiceImpl() { int workerId =
48 | * Math.abs(NetworkUtil.getLocalMac().hashCode()) % 31; int datacenterId =
49 | * Math.abs(NetworkUtil.getLocalHost().hashCode()) % 31;
50 | * this(Long.valueOf(workerId+""),Long.valueOf( datacenterId+""), 0L,
51 | * 1344322705519L); }
52 | */
53 |
54 | //
55 | public StringSnowFlakeIdServiceImpl() {
56 | this.workerId = Long.valueOf(Math.abs(NetworkUtil.getLocalMac().hashCode()) % 7);
57 | this.datacenterId = Long.valueOf(Math.abs(NetworkUtil.getLocalHost().hashCode()) % 7);
58 | this.sequence = 0L;
59 | this.idepoch = 1344322705519L;
60 | if (workerId < 0 || workerId > maxWorkerId) {
61 | throw new IllegalArgumentException("workerId is illegal: " + workerId);
62 | }
63 | if (datacenterId < 0 || datacenterId > maxDatacenterId) {
64 | throw new IllegalArgumentException("datacenterId is illegal: " + workerId);
65 | }
66 | if (idepoch >= System.currentTimeMillis()) {
67 | throw new IllegalArgumentException("idepoch is illegal: " + idepoch);
68 | }
69 | }
70 |
71 | public long getDatacenterId() {
72 | return datacenterId;
73 | }
74 |
75 | public long getWorkerId() {
76 | return workerId;
77 | }
78 |
79 | public long getTime() {
80 | return System.currentTimeMillis();
81 | }
82 |
83 | private static final DateFormat f = new SimpleDateFormat("yyyyMMddHHmmssSSS");
84 |
85 | private synchronized String nextId() {
86 | long timestamp = timeGen();
87 | if (timestamp < lastTimestamp) {
88 | throw new IllegalStateException("Clock moved backwards.");
89 | }
90 | if (lastTimestamp == timestamp) {
91 | sequence = (sequence + 1) & sequenceMask;
92 | if (sequence == 0) {
93 | timestamp = tilNextMillis(lastTimestamp);
94 | }
95 | } else {
96 | sequence = 0;
97 | }
98 | lastTimestamp = timestamp;
99 | StringBuilder sb = new StringBuilder(f.format(new Date(timestamp)));
100 | sb.append(datacenterId);
101 | sb.append(workerId);
102 | sb.append(String.format("%04d", sequence));
103 | return sb.toString();
104 | }
105 |
106 | /**
107 | * get the timestamp (millis second) of id
108 | *
109 | * @param id
110 | * the nextId
111 | * @return the timestamp of id
112 | */
113 | public long getIdTimestamp(long id) {
114 | return idepoch + (id >> timestampLeftShift);
115 | }
116 |
117 | private long tilNextMillis(long lastTimestamp) {
118 | long timestamp = timeGen();
119 | while (timestamp <= lastTimestamp) {
120 | timestamp = timeGen();
121 | }
122 | return timestamp;
123 | }
124 |
125 | private long timeGen() {
126 | return System.currentTimeMillis();
127 | }
128 |
129 | }
130 |
--------------------------------------------------------------------------------
/gateway-core/src/main/resources/spring/applicationContext.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 | Spring MVC Configuration
14 |
15 |
16 |
18 |
19 |
23 |
24 |
25 |
27 |
28 |
29 |
30 |
31 |
36 |
37 |
38 |
39 |
40 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
85 |
86 |
89 |
90 |
91 |
92 |
94 |
95 |
96 |
97 |
98 |
99 |
101 |
103 |
104 |
105 |
106 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/core/support/OpenApiReqAdapter.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.core.support;
2 |
3 | import java.util.Map;
4 |
5 | import org.apache.commons.chain.Context;
6 | import org.apache.commons.lang3.StringUtils;
7 |
8 | import com.z.gateway.common.OpenApiHttpRequestBean;
9 | import com.z.gateway.common.exception.OauthErrorEnum;
10 | import com.z.gateway.common.resp.CommonResponse;
11 | import com.z.gateway.core.AbstractOpenApiHandler;
12 | import com.z.gateway.core.OpenApiRouteBean;
13 | import com.z.gateway.protocol.OpenApiContext;
14 | import com.z.gateway.protocol.OpenApiHttpSessionBean;
15 | import com.z.gateway.service.AuthenticationService;
16 | import com.z.gateway.service.CacheService;
17 |
18 | public class OpenApiReqAdapter extends AbstractOpenApiHandler {
19 |
20 | public OpenApiReqAdapter() {
21 | }
22 |
23 | protected OpenApiRouteBean initRouteBean(OpenApiHttpRequestBean request) {
24 |
25 | logger.info("init 路由bean ,using openapihttprequestbean={}", request);
26 | OpenApiRouteBean routeBean = null;
27 | routeBean = new OpenApiRouteBean();
28 | if (request.getTraceId() != null)
29 | routeBean.setTraceId(request.getTraceId()); // 内部请求id,利于跟踪
30 | if (request.getApiId() != null)
31 | routeBean.setApiId(request.getApiId());// 请求api_id
32 | if (request.getVersion() != null)
33 | routeBean.setVersion(request.getVersion());// api_version
34 | if (request.getReqHeader() != null)
35 | routeBean.setReqHeader(request.getReqHeader());// 请求头
36 | if (request.getTimeStamp() != null)
37 | routeBean.setTimeStamp(request.getTimeStamp());// 请求时间
38 | if (request.getOperationType() != null)
39 | routeBean.setOperationType(request.getOperationType()); // 请求操作类型
40 | if (request.getRequestMethod() != null)
41 | routeBean.setRequestMethod(request.getRequestMethod());// 请求方法
42 | if (request.getServiceReqData() != null)
43 | routeBean.setServiceReqData(request.getServiceReqData());// post请求参数
44 | // routeBean.setQueryString(request.getQueryString());// get请求参数
45 | if (request.getServiceGetReqData() != null)
46 | routeBean.setServiceGetReqData(request.getServiceGetReqData()); // get请求参数
47 | if (request.getThdApiUrlParams() != null) {
48 | for (Map.Entry maps : request.getThdApiUrlParams().entrySet()) {
49 | routeBean.addThdApiUrlParams(maps.getKey(), maps.getValue());
50 | }
51 | }
52 | cacheService.put(request.getRouteBeanKey(), routeBean);
53 | return routeBean;
54 | }
55 |
56 | private CacheService cacheService;
57 |
58 | public void setCacheService(CacheService cacheService) {
59 | this.cacheService = cacheService;
60 | }
61 |
62 | private void setError(String errorCode, String errMsg, OpenApiHttpRequestBean requestBean) {
63 | CommonResponse r = new CommonResponse(false);
64 | r.setErrorCode(errorCode);
65 | r.setErrorMsg(errMsg);
66 | requestBean.setPrintStr(r.toString());
67 | }
68 |
69 | protected void validateParam(OpenApiHttpRequestBean requestBean) {
70 | /*
71 | * String appId = requestBean.getAppId(); if
72 | * (StringUtils.isBlank(appId)) { // appId为空
73 | * setError(OauthErrorEnum.APP_ID.getErrCode(),
74 | * OauthErrorEnum.APP_ID.getErrMsg(), requestBean); return; } String
75 | * appToken = requestBean.getAppToken();
76 | *
77 | * if (StringUtils.isBlank(appToken)) {// appToken为空
78 | * setError(OauthErrorEnum.APP_TOKEN.getErrCode(),
79 | * OauthErrorEnum.APP_TOKEN.getErrMsg(), requestBean); return; }
80 | */
81 | if (StringUtils.isBlank(requestBean.getApiId())) {
82 | setError(OauthErrorEnum.API_ID.getErrCode(), OauthErrorEnum.API_ID.getErrMsg(), requestBean);
83 | return;
84 | }
85 |
86 | if (StringUtils.isBlank(requestBean.getTimeStamp())) {
87 | setError(OauthErrorEnum.TIMSTAMP.getErrCode(), OauthErrorEnum.TIMSTAMP.getErrMsg(), requestBean);
88 | return;
89 | }
90 | /*
91 | * String accessToken = requestBean.getAppToken(); if
92 | * (StringUtils.isBlank(accessToken)) { throw new
93 | * OpenApiException(OauthErrorEnum.ACCESSTOKEN.getErrCode(),
94 | * OauthErrorEnum.ACCESSTOKEN.getErrMsg()); }
95 | */
96 | }
97 |
98 | protected void authRequestBean(OpenApiHttpRequestBean requestBean) {
99 | // 对于请求信息进行审计
100 | logger.info("authRequestBean权限校验...");
101 | if (this.authenticationService != null) {
102 | this.authenticationService.doAuthOpenApiHttpRequestBean(requestBean);
103 | }
104 | }
105 |
106 | @Override
107 | protected boolean doExcuteBiz(Context context) {
108 | OpenApiContext openApiContext = (OpenApiContext) context;
109 | OpenApiHttpSessionBean httpSessionBean = (OpenApiHttpSessionBean) openApiContext.getOpenApiHttpSessionBean();
110 | OpenApiHttpRequestBean request = httpSessionBean.getRequest();
111 | long currentTime = System.currentTimeMillis();
112 |
113 | logger.debug("begin run doExectuteBiz,currentTImd={},httpSessionBean={}", currentTime, httpSessionBean);
114 |
115 | // 参数校验
116 | validateParam(request);
117 | // 权限校验
118 | authRequestBean(request);
119 |
120 | //initRouteBean(httpSessionBean.getRequest()); // 初始化路由bean
121 |
122 | logger.debug("end rn doExecuteBiz,currentTime={},elaspsed_time={} milseconds,httpSessionBean={}",System.currentTimeMillis(),(System.currentTimeMillis() - currentTime), httpSessionBean);
123 |
124 | if (StringUtils.isNotBlank(request.getPrintStr())) {
125 | return true;
126 | }
127 | return false;
128 | }
129 |
130 | // 外部依赖的服务--------------------------------------
131 | private AuthenticationService authenticationService;
132 |
133 | public void setAuthenticationService(AuthenticationService authenticationService) {
134 | this.authenticationService = authenticationService;
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/gateway-core/src/main/resources/spring/spring-mvc.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 | Spring MVC Configuration
14 |
15 |
16 |
17 |
19 |
20 |
21 |
23 |
25 |
26 |
27 |
28 |
29 |
30 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
78 |
79 |
80 |
81 |
82 |
83 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
95 |
96 |
97 |
98 | classpath:i18n/osp-web-msg
99 | classpath*:org/hibernate/validator/ValidationMessages
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
111 |
112 |
113 |
114 |
115 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
--------------------------------------------------------------------------------
/gateway-common/src/main/java/com/z/gateway/common/OpenApiHttpRequestBean.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.common;
5 |
6 | import java.io.Serializable;
7 | import java.util.Date;
8 | import java.util.HashMap;
9 | import java.util.Map;
10 |
11 | import com.z.gateway.common.util.CommonCodeConstants;
12 |
13 | /**
14 | *
15 | *
16 | * @author Administrator
17 | *
18 | */
19 | public class OpenApiHttpRequestBean implements Serializable {
20 |
21 | /**
22 | *
23 | */
24 | private static final long serialVersionUID = 1L;
25 |
26 | private Map reqHeader;
27 |
28 | private String operationType;
29 |
30 | private String clientAddr;
31 | private String localAddr;
32 | private int localPort;
33 |
34 | private Map thdApiUrlParams;
35 | private String serviceReqData;
36 | private String requestMethod;
37 |
38 | private Map serviceGetReqData;
39 | private String queryString;
40 |
41 | private Date requestTime;
42 | private Date responseTime;
43 | private Long elapsedTime;
44 |
45 | private String traceId;
46 |
47 | private String printStr;
48 |
49 | private String appId;
50 | private String appToken;
51 | private String apiId;
52 | private String version;
53 |
54 | private String timeStamp;
55 | private String signMethod;
56 | private String sign;
57 | private String deviceToken;
58 | private String userToken;
59 |
60 | private String format;
61 |
62 | public Date getRequestTime() {
63 | return requestTime;
64 | }
65 |
66 | public void setRequestTime(Date requestTime) {
67 | this.requestTime = requestTime;
68 | }
69 |
70 | public Date getResponseTime() {
71 | return responseTime;
72 | }
73 |
74 | public void setResponseTime(Date responseTime) {
75 | this.responseTime = responseTime;
76 | }
77 |
78 | public Long getElapsedTime() {
79 | return elapsedTime;
80 | }
81 |
82 | public void setElapsedTime(Long elapsedTime) {
83 | this.elapsedTime = elapsedTime;
84 | }
85 |
86 | public Map getServiceGetReqData() {
87 | return serviceGetReqData;
88 | }
89 |
90 | public void addServiceGetReqData(String key, String value) {
91 | if (this.serviceGetReqData == null) {
92 | this.serviceGetReqData = new HashMap();
93 | }
94 | this.serviceGetReqData.put(key, value);
95 | }
96 |
97 | public String getRequestMethod() {
98 | return requestMethod;
99 | }
100 |
101 | public void setRequestMethod(String requestMethod) {
102 | this.requestMethod = requestMethod;
103 | }
104 |
105 | public String getPrintStr() {
106 | return printStr;
107 | }
108 |
109 | public void setPrintStr(String printStr) {
110 | this.printStr = printStr;
111 | }
112 |
113 | public String getServiceReqData() {
114 | return serviceReqData;
115 | }
116 |
117 | public void setServiceReqData(String serviceReqData) {
118 | this.serviceReqData = serviceReqData;
119 | }
120 |
121 | public String getOperationType() {
122 | return operationType;
123 | }
124 |
125 | public void setOperationType(String operationType) {
126 | this.operationType = operationType;
127 | }
128 |
129 | public String getClientAddr() {
130 | return clientAddr;
131 | }
132 |
133 | public void setClientAddr(String clientAddr) {
134 | this.clientAddr = clientAddr;
135 | }
136 |
137 | public String getLocalAddr() {
138 | return localAddr;
139 | }
140 |
141 | public void setLocalAddr(String localAddr) {
142 | this.localAddr = localAddr;
143 | }
144 |
145 | public int getLocalPort() {
146 | return localPort;
147 | }
148 |
149 | public void setLocalPort(int localPort) {
150 | this.localPort = localPort;
151 | }
152 |
153 | public String getQueryString() {
154 | return queryString;
155 | }
156 |
157 | public void setQueryString(String queryString) {
158 | this.queryString = queryString;
159 | }
160 |
161 | public Map getThdApiUrlParams() {
162 | return thdApiUrlParams;
163 | }
164 |
165 | public void setThdApiUrlParams(Map thdApiUrlParams) {
166 | this.thdApiUrlParams = thdApiUrlParams;
167 | }
168 |
169 | public Map getReqHeader() {
170 | return reqHeader;
171 | }
172 |
173 | public void setReqHeader(Map reqHeader) {
174 | this.reqHeader = reqHeader;
175 | }
176 |
177 | public String getAppToken() {
178 | return appToken;
179 | }
180 |
181 | public void setAppToken(String appToken) {
182 | this.appToken = appToken;
183 | }
184 |
185 | public String getTimeStamp() {
186 | return timeStamp;
187 | }
188 |
189 | public void setTimeStamp(String timeStamp) {
190 | this.timeStamp = timeStamp;
191 | }
192 |
193 | public String getFormat() {
194 | return format;
195 | }
196 |
197 | public void setFormat(String format) {
198 | this.format = format;
199 | }
200 |
201 | public String getApiId() {
202 | return apiId;
203 | }
204 |
205 | public void setApiId(String apiId) {
206 | this.apiId = apiId;
207 | }
208 |
209 | public String getTraceId() {
210 | return traceId;
211 | }
212 |
213 | public void setTraceId(String traceId) {
214 | this.traceId = traceId;
215 | }
216 |
217 | public String getRouteBeanKey() {
218 | if (this.operationType.equals(CommonCodeConstants.API_SERVICE_KEY)) {
219 | return CommonCodeConstants.getRouteBeanRedisKey(traceId);
220 | }
221 |
222 | return CommonCodeConstants.getRouteBeanRedisKey("");
223 | }
224 |
225 | public String getAppId() {
226 | return appId;
227 | }
228 |
229 | public void setAppId(String appId) {
230 | this.appId = appId;
231 | }
232 |
233 | public String getVersion() {
234 | return version;
235 | }
236 |
237 | public void setVersion(String version) {
238 | this.version = version;
239 | }
240 |
241 | public String getSignMethod() {
242 | return signMethod;
243 | }
244 |
245 | public void setSignMethod(String signMethod) {
246 | this.signMethod = signMethod;
247 | }
248 |
249 | public String getSign() {
250 | return sign;
251 | }
252 |
253 | public void setSign(String sign) {
254 | this.sign = sign;
255 | }
256 |
257 | public String getDeviceToken() {
258 | return deviceToken;
259 | }
260 |
261 | public void setDeviceToken(String deviceToken) {
262 | this.deviceToken = deviceToken;
263 | }
264 |
265 | public String getUserToken() {
266 | return userToken;
267 | }
268 |
269 | public void setUserToken(String userToken) {
270 | this.userToken = userToken;
271 | }
272 |
273 | @Override
274 | public String toString() {
275 | return "OpenApiHttpRequestBean [reqHeader=" + reqHeader + ", operationType=" + operationType + ", clientAddr="
276 | + clientAddr + ", localAddr=" + localAddr + ", localPort=" + localPort + ", thdApiUrlParams="
277 | + thdApiUrlParams + ", serviceReqData=" + serviceReqData + ", requestMethod=" + requestMethod
278 | + ", serviceGetReqData=" + serviceGetReqData + ", queryString=" + queryString + ", requestTime="
279 | + requestTime + ", responseTime=" + responseTime + ", elapsedTime=" + elapsedTime + ", traceId="
280 | + traceId + ", printStr=" + printStr + ", appId=" + appId + ", appToken=" + appToken + ", apiId="
281 | + apiId + ", version=" + version + ", timeStamp=" + timeStamp + ", signMethod=" + signMethod + ", sign="
282 | + sign + ", deviceToken=" + deviceToken + ", userToken=" + userToken + ", format=" + format + "]";
283 | }
284 |
285 | }
286 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/core/support/OpenApiReqHandler.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.core.support;
2 |
3 | import org.apache.commons.chain.Context;
4 | import org.apache.commons.lang3.StringUtils;
5 |
6 | import com.z.gateway.common.OpenApiHttpRequestBean;
7 | import com.z.gateway.common.entity.ApiInterface;
8 | import com.z.gateway.common.exception.OauthErrorEnum;
9 | import com.z.gateway.common.exception.OpenApiException;
10 | import com.z.gateway.common.util.CommonCodeConstants;
11 | import com.z.gateway.core.AbstractOpenApiHandler;
12 | import com.z.gateway.core.OpenApiHttpClientService;
13 | import com.z.gateway.protocol.OpenApiContext;
14 | import com.z.gateway.protocol.OpenApiHttpSessionBean;
15 | import com.z.gateway.service.ApiInterfaceService;
16 | import com.z.gateway.util.UrlUtil;
17 |
18 | public class OpenApiReqHandler extends AbstractOpenApiHandler {
19 |
20 | private final int maxReqDataLth = 500;
21 |
22 | private ApiInterfaceService apiInterfaceService;
23 |
24 | private OpenApiHttpClientService apiHttpClientService;
25 |
26 | public void setApiInterfaceService(ApiInterfaceService apiInterfaceService) {
27 | this.apiInterfaceService = apiInterfaceService;
28 | }
29 |
30 | public void setApiHttpClientService(OpenApiHttpClientService apiHttpClientService) {
31 | this.apiHttpClientService = apiHttpClientService;
32 | }
33 |
34 |
35 |
36 | // step2
37 | @Override
38 | protected boolean doExcuteBiz(Context context) {
39 | OpenApiContext openApiContext = (OpenApiContext) context;
40 | OpenApiHttpSessionBean httpSessionBean = (OpenApiHttpSessionBean) openApiContext.getOpenApiHttpSessionBean();
41 | OpenApiHttpRequestBean request = httpSessionBean.getRequest();
42 | long currentTime = System.currentTimeMillis();
43 | logger.debug("begin run doExecuteBiz,currentTime={},httpSessonBean={}", currentTime, httpSessionBean);
44 | /*
45 | * String routeBeanKey = request.getRouteBeanKey(); OpenApiRouteBean
46 | * routeBean = (OpenApiRouteBean) cacheService.get(routeBeanKey);
47 | *
48 | * routeBean.setServiceRsp(doInvokeBackService(routeBean)); // 返回值
49 | */
50 | request.setPrintStr(doInvokeBackService(request));
51 |
52 | logger.debug("end run doExecuteBiz,currentTime={},elapase_time={} milseconds,httpSessonBean={}",
53 | System.currentTimeMillis(), (System.currentTimeMillis() - currentTime), httpSessionBean);
54 |
55 | return true;
56 | }
57 |
58 | /**
59 | * 根据routeBean信息,通过httpclient调用后端信息,然后将返回值构建成string
60 | *
61 | * @param bean
62 | * @return
63 | */
64 | protected String doInvokeBackService(OpenApiHttpRequestBean bean) {
65 |
66 | String serviceRspData = null; // 后端服务返回值
67 | String operationType = bean.getOperationType();
68 | String requestMethod = bean.getRequestMethod();
69 |
70 | if (operationType.equals(CommonCodeConstants.API_SYSERVICE_KEY)) {
71 | /*
72 | * Map map = new TreeMap();
73 | * map.put("code", "200"); map.put("message",
74 | * "The request has been accepted, the processing number is :" +
75 | * bean.getDataId()); serviceRspData = JSON.toJSONString(map);
76 | */
77 | } else if (CommonCodeConstants.API_GETDATA_KEY.equals(operationType)) {
78 | /*
79 | * ListOperations lop = null; lop =
80 | * redisTemplate.opsForList(); while
81 | * (StringUtil.isNotEmpty(serviceRspData =
82 | * lop.rightPop(bean.getDataId()))) {
83 | *
84 | * return JSON.parseObject(serviceRspData,
85 | * OpenApiRouteBeanVO.class).getServiceReqData(); }
86 | */
87 | } else if (CommonCodeConstants.API_SERVICE_KEY.equals(operationType)) {
88 | logger.info("serviceId:{} ,version:{} ", bean.getApiId(), bean.getVersion());
89 | ApiInterface apiInfo = apiInterfaceService.findOne(bean.getApiId(), bean.getVersion());
90 | if (apiInfo == null) {
91 | return String.format("this apiId=%s,version=%s has off line,please use another one", bean.getApiId(),
92 | bean.getVersion());
93 | }
94 | if (CommonCodeConstants.REQUEST_METHOD.GET.name().equalsIgnoreCase(requestMethod)) { // get请求
95 | String url = apiInfo.getUrl();
96 | url = UrlUtil.dealUrl(url, bean.getThdApiUrlParams());
97 | /*
98 | * if (StringUtils.isNotBlank(bean.getQueryString())) { url +=
99 | * "?" + bean.getQueryString(); // 串好url 地址 }
100 | */
101 | logger.info("service url={}", url);
102 | // String contentType =
103 | // bean.getReqHeader().get(CONTENT_TYPE_KEY);
104 | if (url.startsWith("https")) {
105 | if (bean.getServiceGetReqData() == null) {
106 | serviceRspData = apiHttpClientService.doHttpsGet(url, bean.getReqHeader());
107 | } else {
108 | serviceRspData = apiHttpClientService.doHttpsGet(url, bean.getServiceGetReqData(),
109 | bean.getReqHeader());
110 | }
111 | } else {
112 | if (bean.getServiceGetReqData() == null) {
113 | serviceRspData = apiHttpClientService.doGet(url, bean.getReqHeader());
114 | } else {
115 | serviceRspData = apiHttpClientService.doGet(url, bean.getServiceGetReqData(),
116 | bean.getReqHeader());
117 | }
118 | }
119 |
120 | } else if (CommonCodeConstants.REQUEST_METHOD.POST.name().equalsIgnoreCase(requestMethod)) {// post请求
121 | String url = apiInfo.getUrl();
122 | logger.info("service url={}", url);
123 | String reqData = bean.getServiceReqData(); // 请求的json格式数据参数
124 | if (StringUtils.isNotBlank(reqData) && reqData.length() > this.maxReqDataLth) {
125 | reqData = reqData.substring(0, this.maxReqDataLth - 1);
126 | }
127 | logger.info("{serviceId={} ,reqData:{}", bean.getApiId(), reqData);
128 |
129 | // String contentType =
130 | // bean.getReqHeader().get(CONTENT_TYPE_KEY);
131 | if (url.startsWith("https://")) {
132 | serviceRspData = apiHttpClientService.doHttpsPost(url, bean.getServiceReqData(),
133 | bean.getReqHeader());
134 | } else {
135 | serviceRspData = apiHttpClientService.doPost(url, bean.getServiceReqData(), bean.getReqHeader());
136 | }
137 | if ("timeout".equals(serviceRspData)) {
138 | logger.error("invoke service: response is null!");
139 | throw new OpenApiException(OauthErrorEnum.ERROR.getErrCode(), OauthErrorEnum.ERROR.getErrMsg());
140 | }
141 | }
142 | } else {
143 | /*
144 | * String reqData = bean.getServiceReqData(); // 请求的json格式数据参数 if
145 | * (StringUtils.isNotBlank(reqData) && reqData.length() >
146 | * this.maxReqDataLth) { reqData = reqData.substring(0,
147 | * this.maxReqDataLth - 1); } log.info(String.format(
148 | * "{serviceId:%s ,reqData:%s }", bean.getApiId(), reqData));
149 | *
150 | * ApiInterface apiInfo =
151 | * apiInterfaceService.findOne(bean.getApiId(), bean.getVersion());
152 | * String contentType = bean.getReqHeader().get(CONTENT_TYPE_KEY);
153 | *
154 | * try { String url = apiInfo.getTargetUrl(); log.info(
155 | * "{service url: " + url); if (url.startsWith("https://")) {
156 | * serviceRspData = apiHttpClientService.doHttpsPost(url,
157 | * bean.getServiceReqData(), contentType); } else { if
158 | * (bean.getApiId().equals("bl.kd100.tms.backstatus") ||
159 | * bean.getApiId().equals("bl.order.dc.tmsexpress")) {
160 | *
161 | * url = this.generatePassUrl(apiInfo.getTargetUrl(),
162 | * user.getSalt(), bean.getAccessToken(), bean.getTimeStamp());
163 | * String params = this.getParams(user.getSalt(),
164 | * bean.getAccessToken(), bean.getTimeStamp(),
165 | * bean.getThdApiUrlParams()); serviceRspData =
166 | * mutiHttpClientUtil.doPost(url, bean.getServiceReqData(),
167 | * contentType, params);
168 | *
169 | * } else { serviceRspData = apiHttpClientService.doPost(url,
170 | * bean.getServiceReqData(), contentType); } } if
171 | * ("timeout".equals(serviceRspData)) { log.error(
172 | * "invoke service: response is null!"); throw new
173 | * OpenApiException(OauthErrorEnum.ERROR.getErrCode(),
174 | * OauthErrorEnum.ERROR.getErrMsg()); } } catch (Exception e) {
175 | * log.error("invoke service: " + e.getMessage()); throw new
176 | * OpenApiException(OauthErrorEnum.ERROR.getErrCode(),
177 | * OauthErrorEnum.ERROR.getErrMsg()); }
178 | */
179 | }
180 | return serviceRspData;
181 | }
182 | }
183 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/core/support/OpenApiHttpClientServiceImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.core.support;
5 |
6 | import java.io.IOException;
7 | import java.util.ArrayList;
8 | import java.util.Collections;
9 | import java.util.List;
10 | import java.util.Map;
11 | import java.util.concurrent.TimeUnit;
12 |
13 | import org.apache.http.HttpEntity;
14 | import org.apache.http.HttpStatus;
15 | import org.apache.http.client.ClientProtocolException;
16 | import org.apache.http.client.config.RequestConfig;
17 | import org.apache.http.client.methods.CloseableHttpResponse;
18 | import org.apache.http.config.Registry;
19 | import org.apache.http.config.RegistryBuilder;
20 | import org.apache.http.config.SocketConfig;
21 | import org.apache.http.conn.DnsResolver;
22 | import org.apache.http.conn.HttpConnectionFactory;
23 | import org.apache.http.conn.ManagedHttpClientConnection;
24 | import org.apache.http.conn.routing.HttpRoute;
25 | import org.apache.http.conn.socket.ConnectionSocketFactory;
26 | import org.apache.http.conn.socket.PlainConnectionSocketFactory;
27 | import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
28 | import org.apache.http.entity.StringEntity;
29 | import org.apache.http.impl.DefaultConnectionReuseStrategy;
30 | import org.apache.http.impl.client.CloseableHttpClient;
31 | import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
32 | import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
33 | import org.apache.http.impl.client.HttpClients;
34 | import org.apache.http.impl.conn.DefaultHttpResponseParserFactory;
35 | import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory;
36 | import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
37 | import org.apache.http.impl.conn.SystemDefaultDnsResolver;
38 | import org.apache.http.impl.io.DefaultHttpRequestWriterFactory;
39 | import org.apache.http.util.EntityUtils;
40 | import org.slf4j.Logger;
41 | import org.slf4j.LoggerFactory;
42 |
43 | import com.z.gateway.core.OpenApiHttpClientService;
44 |
45 | /**
46 | * @author sunff
47 | *
48 | */
49 | public class OpenApiHttpClientServiceImpl implements OpenApiHttpClientService {
50 |
51 | private static Logger logger = LoggerFactory.getLogger(OpenApiHttpClientServiceImpl.class);
52 | private static PoolingHttpClientConnectionManager manager = null;
53 | private static CloseableHttpClient httpClient = null;
54 |
55 | private Boolean usingHead;
56 |
57 | public void setUsingHead(Boolean usingHead) {
58 | this.usingHead = usingHead;
59 | }
60 |
61 | public void init() {
62 | initHttpClient();
63 | }
64 |
65 | private void initHttpClient() {
66 | // 注册访问协议相关的socket工厂
67 | Registry socketFactoryRegistry = RegistryBuilder. create()
68 | .register("http", PlainConnectionSocketFactory.INSTANCE)
69 | .register("https", SSLConnectionSocketFactory.getSystemSocketFactory()).build();
70 | // httpclient 工厂
71 | HttpConnectionFactory connFactory = new ManagedHttpClientConnectionFactory(
72 | DefaultHttpRequestWriterFactory.INSTANCE, DefaultHttpResponseParserFactory.INSTANCE);
73 | // dns解析器
74 | DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE;
75 | // 创建池化连接管理器
76 | manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connFactory, dnsResolver);
77 | // 默认socket配置
78 | SocketConfig defaultSocketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
79 | manager.setDefaultSocketConfig(defaultSocketConfig);
80 |
81 | manager.setMaxTotal(this.maxTotal);// 设置整个连接池的最大连接数
82 | manager.setDefaultMaxPerRoute(this.defaultMaxPerRoute);// 每个路由最大连接数
83 | manager.setValidateAfterInactivity(this.validateAfterInactivity);
84 |
85 | RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(this.connectionTimeout)
86 | // 2s
87 | .setSocketTimeout(this.socketTimeout)
88 | // 5s
89 | .setConnectionRequestTimeout(this.connectionRequestTimeout).build();
90 | httpClient = HttpClients.custom().setConnectionManager(manager).setConnectionManagerShared(false)
91 | .evictIdleConnections(60, TimeUnit.SECONDS).evictExpiredConnections()
92 | .setConnectionTimeToLive(60, TimeUnit.SECONDS).setDefaultRequestConfig(defaultRequestConfig)
93 | .setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE)
94 | .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
95 | .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).build();
96 |
97 | Runtime.getRuntime().addShutdownHook(new Thread() {
98 | @Override
99 | public void run() {
100 | try {
101 | httpClient.close();
102 | } catch (Exception e) {
103 | e.printStackTrace();
104 | }
105 | }
106 |
107 | });
108 | }
109 |
110 | private CloseableHttpClient getHttpClient() {
111 | return httpClient;
112 |
113 | }
114 |
115 | private int maxTotal = 300;
116 | private int defaultMaxPerRoute = 200;
117 | private int validateAfterInactivity = 5000;
118 | private int connectionTimeout = 2000;// 2s
119 | private int socketTimeout = 5000;// 5s
120 | private int connectionRequestTimeout = 2000;
121 |
122 | public void setConnectionTimeout(int connectionTimeout) {
123 | this.connectionTimeout = connectionTimeout;
124 | }
125 |
126 | public void setSocketTimeout(int socketTimeout) {
127 | this.socketTimeout = socketTimeout;
128 | }
129 |
130 | public void setConnectionRequestTimeout(int connectionRequestTimeout) {
131 | this.connectionRequestTimeout = connectionRequestTimeout;
132 | }
133 |
134 | public void setMaxTotal(int maxTotal) {
135 | this.maxTotal = maxTotal;
136 | }
137 |
138 | public void setDefaultMaxPerRoute(int defaultMaxPerRoute) {
139 | this.defaultMaxPerRoute = defaultMaxPerRoute;
140 | }
141 |
142 | public void setValidateAfterInactivity(int validateAfterInactivity) {
143 | this.validateAfterInactivity = validateAfterInactivity;
144 | }
145 |
146 | @Override
147 | public String doHttpsPost(String url, String reqData, Map requestHeader) {
148 | return doPost(url, reqData, requestHeader);
149 | }
150 |
151 | @Override
152 | public String doPost(String url, String reqData, Map requestHeader) {
153 | String body = "";
154 | org.apache.http.client.methods.HttpPost httpPost = new org.apache.http.client.methods.HttpPost(url);
155 | // 将所有的header都传过去
156 | if (requestHeader != null && usingHead) {
157 |
158 | for(Map.Entry kv:requestHeader.entrySet()){
159 | if(kv.getKey().equalsIgnoreCase("Content-Length")){
160 | continue;
161 | }
162 | httpPost.addHeader(kv.getKey(), kv.getValue());
163 | }
164 |
165 | }
166 |
167 | httpPost.setEntity(new StringEntity(reqData, "utf-8"));
168 | try {
169 | // 执行请求操作,并拿到结果(同步阻塞)
170 | CloseableHttpResponse response = getHttpClient().execute(httpPost);
171 | int statusCode = response.getStatusLine().getStatusCode();
172 | if (statusCode == HttpStatus.SC_OK) {
173 | // 获取结果实体
174 | HttpEntity entity = response.getEntity();
175 | if (entity != null) {
176 | // 按指定编码转换结果实体为String类型
177 | body = EntityUtils.toString(entity, "utf-8");
178 | }
179 | EntityUtils.consume(entity);
180 | }
181 |
182 | // 释放链接
183 | response.close();
184 | } catch (IOException e) {
185 | logger.error("url={}调用失败", e);
186 | e.printStackTrace();
187 | }
188 | return body;
189 | }
190 |
191 | @Override
192 | public String doGet(String webUrl, Map requestHeader) {
193 | logger.info(String.format("run doGet method,weburl=%s", webUrl));
194 | String body = "";
195 | org.apache.http.client.methods.HttpGet httpGet = new org.apache.http.client.methods.HttpGet(webUrl);
196 | // 将所有的header都传过去
197 | if (requestHeader != null && usingHead) {
198 |
199 | for(Map.Entry kv:requestHeader.entrySet()){
200 | if(kv.getKey().equalsIgnoreCase("Content-Length")){
201 | continue;
202 | }
203 | httpGet.addHeader(kv.getKey(), kv.getValue());
204 | }
205 | }
206 | try {
207 | CloseableHttpResponse response = getHttpClient().execute(httpGet);
208 | HttpEntity entity = response.getEntity();
209 | int statusCode = response.getStatusLine().getStatusCode();
210 | if (statusCode == HttpStatus.SC_OK) {
211 | if (entity != null) {
212 | body = EntityUtils.toString(entity, "utf-8");
213 | }
214 | EntityUtils.consume(entity);
215 | }
216 | response.close();
217 | } catch (ClientProtocolException e) {
218 | e.printStackTrace();
219 | } catch (IOException e) {
220 | e.printStackTrace();
221 | }
222 |
223 | return body;
224 | }
225 |
226 | @Override
227 | public String doGet(String webUrl, Map paramMap, Map requestHeader) {
228 | logger.info(String.format("run doGet method,weburl=%s", webUrl));
229 | String url = webUrl;
230 | // 设置编码格式
231 | String queryString = createLinkString(paramMap);
232 | url = url + "?" + queryString;
233 | return doGet(url, requestHeader);
234 | }
235 |
236 | /**
237 | * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
238 | *
239 | * @param params
240 | * 需要排序并参与字符拼接的参数组
241 | * @return 拼接后字符串
242 | */
243 | private String createLinkString(Map params) {
244 | List keys = new ArrayList(params.keySet());
245 | Collections.sort(keys);
246 | String prestr = "";
247 | for (int i = 0; i < keys.size(); i++) {
248 | String key = keys.get(i);
249 | String value = params.get(key);
250 |
251 | if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
252 | prestr = prestr + key + "=" + value;
253 | } else {
254 | prestr = prestr + key + "=" + value + "&";
255 | }
256 | }
257 |
258 | return prestr;
259 | }
260 |
261 | @Override
262 | public String doHttpsGet(String webUrl, Map requestHeader) { // https
263 | // 协议
264 | return doGet(webUrl, requestHeader);
265 | }
266 |
267 | @Override
268 | public String doHttpsGet(String webUrl, Map paramMap, Map requestHeader) {
269 |
270 | return doGet(webUrl, paramMap, requestHeader);
271 | }
272 |
273 | }
274 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/interceptor/OpenApiServiceParamValidateInterceptor.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.interceptor;
5 |
6 | import java.io.IOException;
7 | import java.io.UnsupportedEncodingException;
8 | import java.util.Enumeration;
9 | import java.util.HashMap;
10 | import java.util.Iterator;
11 | import java.util.Map;
12 |
13 | import javax.servlet.ServletInputStream;
14 | import javax.servlet.http.HttpServletRequest;
15 |
16 | import org.slf4j.Logger;
17 | import org.slf4j.LoggerFactory;
18 |
19 | import com.alibaba.fastjson.JSONObject;
20 | import com.z.gateway.common.OpenApiHttpRequestBean;
21 | import com.z.gateway.common.util.CommonCodeConstants;
22 | import com.z.gateway.common.util.NetworkUtil;
23 |
24 | /**
25 | * @author Administrator
26 | *
27 | */
28 | public class OpenApiServiceParamValidateInterceptor extends AbstractOpenApiValidateInterceptor {
29 |
30 | private static final Logger log = LoggerFactory.getLogger(OpenApiServiceParamValidateInterceptor.class);
31 |
32 | /**
33 | * 根据请求的协议进行解析
34 | */
35 | @Override
36 | protected OpenApiHttpRequestBean iniOpenApiHttpRequestBean(HttpServletRequest request) {
37 | String requestMethod = request.getMethod();
38 |
39 | OpenApiHttpRequestBean bean = new OpenApiHttpRequestBean();
40 | if (requestMethod.equalsIgnoreCase(CommonCodeConstants.REQUEST_METHOD.POST.name())) {
41 | try {
42 | parsePostMethod(request, bean);
43 | } catch (IOException e) {
44 | log.error("这个请求格式不是application/json的,我处理不了...");
45 | e.printStackTrace();
46 | throw new RuntimeException(e);
47 | }
48 | } else if (requestMethod.equalsIgnoreCase(CommonCodeConstants.REQUEST_METHOD.GET.name())) {
49 | parseGetMethod(request, bean);
50 | bean.setQueryString(request.getQueryString());
51 | }
52 | bean.setThdApiUrlParams(extractThdUrlParams(request));
53 | bean.setLocalAddr(request.getLocalAddr());
54 | bean.setLocalPort(request.getLocalPort());
55 | bean.setClientAddr(NetworkUtil.getClientIpAddr(request));
56 | bean.setReqHeader(getHeadersInfo(request)); // 获取请求头
57 | if (request.getContentType() != null)
58 | bean.getReqHeader().put("content-type", request.getContentType());
59 | bean.setOperationType(CommonCodeConstants.API_SERVICE_KEY);
60 | bean.setRequestMethod(requestMethod);
61 | if (bean.getSignMethod() == null)
62 | bean.setSignMethod("MD5");
63 | if (bean.getFormat() == null)
64 | bean.setFormat("json");
65 | return bean;
66 | }
67 |
68 | private void parseGetMethod(HttpServletRequest request, OpenApiHttpRequestBean bean) {
69 |
70 | Enumeration enums = request.getParameterNames();
71 | while (enums.hasMoreElements()) {
72 | String mapJson = enums.nextElement();
73 | String value = (String) request.getParameter(mapJson);
74 | // 公共参数
75 | // app_id
76 | if (mapJson.equals(CommonCodeConstants.app_id)) {
77 | bean.setAppId(value);
78 | } else if (mapJson.equals(CommonCodeConstants.api_id)) {
79 | bean.setApiId(value); // api_id
80 | } else if (mapJson.equals(CommonCodeConstants.version)) {
81 | bean.setVersion(value);// version
82 |
83 | } else if (mapJson.equals(CommonCodeConstants.app_token)) {
84 | bean.setAppToken(value); // app_token
85 | } else if (mapJson.equals(CommonCodeConstants.time_stamp)) {
86 | bean.setTimeStamp(value); // time_stamp
87 | } else if (mapJson.equals(CommonCodeConstants.sign_method)) {
88 | bean.setSignMethod(value); // sign_method
89 | }
90 | /*
91 | * else{ bean.setSignMethod("MD5"); //sign_method默认值 }
92 | */
93 |
94 | else if (mapJson.equals(CommonCodeConstants.sign)) {
95 | bean.setSign(value); // sign
96 |
97 | } else if (mapJson.equals(CommonCodeConstants.device_token)) {
98 | bean.setDeviceToken(value); // device_token
99 |
100 | } else if (mapJson.equals(CommonCodeConstants.user_token)) {
101 | bean.setUserToken(value);
102 | } // user_token
103 |
104 | else if (mapJson.equals(CommonCodeConstants.format)) {
105 | bean.setFormat(value);
106 | }
107 | /*
108 | * else{ bean.setFormat("json"); //业务请求参数默认是json格式 }
109 | */
110 | else {
111 | bean.addServiceGetReqData(mapJson, value);
112 | }
113 | }
114 | }
115 |
116 | private void parsePostMethod(HttpServletRequest request, OpenApiHttpRequestBean bean) throws IOException {
117 |
118 | String contentType = request.getContentType();
119 | if (CommonCodeConstants.content_type.equalsIgnoreCase(contentType)) { // 是json格式的,我们能够处理
120 |
121 | int len = request.getContentLength();
122 | ServletInputStream iii = request.getInputStream();
123 | byte[] buffer = new byte[len];
124 | iii.read(buffer, 0, len);
125 | String bodyContent = new String(buffer, "UTF-8"); // 将请求流读出来,利用 json
126 | // 框架解析出来
127 |
128 | JSONObject jsonObject = JSONObject.parseObject(bodyContent);
129 | if (jsonObject.containsKey(CommonCodeConstants.pub_attrs)) {
130 | JSONObject jsonObject2 = jsonObject.getJSONObject(CommonCodeConstants.pub_attrs);
131 | Map mapJson = (Map) jsonObject2;
132 | // 公共参数
133 | // app_id
134 | if (mapJson.get(CommonCodeConstants.app_id) != null) {
135 | bean.setAppId(mapJson.get(CommonCodeConstants.app_id).toString());
136 | }
137 | if (mapJson.get(CommonCodeConstants.api_id) != null)
138 | bean.setApiId(mapJson.get(CommonCodeConstants.api_id).toString()); // api_id
139 | if (mapJson.get(CommonCodeConstants.version) != null)
140 | bean.setVersion(mapJson.get(CommonCodeConstants.version).toString());// version
141 |
142 | if (mapJson.get(CommonCodeConstants.app_token) != null)
143 | bean.setAppToken(mapJson.get(CommonCodeConstants.app_token).toString()); // app_token
144 | if (mapJson.get(CommonCodeConstants.time_stamp) != null)
145 | bean.setTimeStamp(mapJson.get(CommonCodeConstants.time_stamp).toString()); // time_stamp
146 | if (mapJson.get(CommonCodeConstants.sign_method) != null) {
147 | bean.setSignMethod(mapJson.get(CommonCodeConstants.sign_method).toString()); // sign_method
148 | } else {
149 | bean.setSignMethod("MD5"); // sign_method默认值
150 | }
151 |
152 | if (mapJson.get(CommonCodeConstants.sign) != null)
153 | bean.setSign(mapJson.get(CommonCodeConstants.sign).toString()); // sign
154 |
155 | if (mapJson.get(CommonCodeConstants.device_token) != null)
156 | bean.setDeviceToken(mapJson.get(CommonCodeConstants.device_token).toString()); // device_token
157 |
158 | if (mapJson.get(CommonCodeConstants.user_token) != null) {
159 | bean.setUserToken(mapJson.get(CommonCodeConstants.user_token).toString());
160 | } // user_token
161 |
162 | if (mapJson.get(CommonCodeConstants.format) != null) {
163 | bean.setFormat(mapJson.get(CommonCodeConstants.format).toString());
164 | } else {
165 | bean.setFormat("json"); // 业务请求参数默认是json格式
166 | }
167 | String reqData = jsonObject.getJSONObject(CommonCodeConstants.busi_attrs).toJSONString();
168 | bean.setServiceReqData(reqData); // 请求体
169 | }
170 |
171 | }
172 |
173 | }
174 |
175 | private Map extractThdUrlParams(HttpServletRequest request) {
176 | Map urlParams = new HashMap();
177 | Map orignalUrlParams = request.getParameterMap();
178 | String key = null;
179 | String[] values = null;
180 | if (null != orignalUrlParams) {
181 | Iterator entries = orignalUrlParams.entrySet().iterator();
182 | while (entries.hasNext()) {
183 | Map.Entry entry = (Map.Entry) entries.next();
184 | key = (String) entry.getKey();
185 | values = (String[]) entry.getValue();
186 | if (key.equals(CommonCodeConstants.app_id) || key.equals(CommonCodeConstants.api_id)
187 | || key.equals(CommonCodeConstants.version) || key.equals(CommonCodeConstants.app_token)
188 | || key.equals(CommonCodeConstants.time_stamp) || key.equals(CommonCodeConstants.sign_method)
189 | || key.equals(CommonCodeConstants.sign) || key.equals(CommonCodeConstants.device_token)
190 | || key.equals(CommonCodeConstants.user_token) || key.equals(CommonCodeConstants.format)) {
191 | continue;
192 | }
193 | String val = values[0];
194 | try {
195 | val = java.net.URLEncoder.encode(val, "utf-8");
196 | } catch (UnsupportedEncodingException e) {
197 | log.error("exception on prceeding chinese char: " + val + " with " + e.getMessage());
198 | }
199 |
200 | urlParams.put(key, null != values ? val : "");
201 | }
202 | }
203 | return urlParams;
204 | }
205 |
206 | private Map getHeadersInfo(HttpServletRequest request) {
207 | Map map = new HashMap();
208 | Enumeration headerNames = request.getHeaderNames();
209 | while (headerNames.hasMoreElements()) {
210 | String key = (String) headerNames.nextElement();
211 | String value = request.getHeader(key);
212 | map.put(key, value);
213 | }
214 |
215 | return map;
216 | }
217 |
218 | /*
219 | * private String getHttpRequestBodyString(HttpServletRequest request) { if
220 | * ("POST".equalsIgnoreCase(request.getMethod())) { Scanner s = null; try {
221 | * s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A"); }
222 | * catch (IOException e) { log.error(e.getMessage()); } return s.hasNext() ?
223 | * s.next() : ""; } return ""; }
224 | */
225 | }
226 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/util/ApiHttpUtil.java:
--------------------------------------------------------------------------------
1 | package com.z.gateway.util;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.List;
6 | import java.util.Map;
7 |
8 | /*import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
9 | import org.apache.commons.httpclient.HttpClient;
10 | import org.apache.commons.httpclient.HttpException;
11 | import org.apache.commons.httpclient.HttpStatus;
12 | import org.apache.commons.httpclient.NameValuePair;
13 | import org.apache.commons.httpclient.URI;
14 | import org.apache.commons.httpclient.methods.GetMethod;
15 | import org.apache.commons.httpclient.methods.PostMethod;
16 | import org.apache.commons.httpclient.params.HttpClientParams;
17 | import org.apache.commons.httpclient.params.HttpConnectionParams;
18 | import org.apache.commons.httpclient.params.HttpMethodParams;*/
19 |
20 | /**
21 | *
22 | * @author Administrator
23 | *
24 | */
25 | @Deprecated
26 | public class ApiHttpUtil {
27 | private static final int TIME_OUT_MILL_SEC = 15000;
28 |
29 | /**
30 | * 发送post请求工具方法
31 | *
32 | * @Methods Name HttpPost
33 | * @Create In 2014年10月28日 By wangfei
34 | * @param url
35 | * @param method
36 | * @param paramMap
37 | * @return String
38 | */
39 | /*
40 | * @SuppressWarnings("rawtypes") public static String HttpPost(String url,
41 | * String method, Map paramMap) { return HttpPost(url + '/' + method,
42 | * paramMap); }
43 | */
44 |
45 | /*
46 | * public static String HttpPost(String webUrl, Map paramMap) { String
47 | * encoding = "UTF-8"; if (encoding == null || "".equals(encoding)) encoding
48 | * = "UTF-8"; StringBuffer sBuffer = new StringBuffer(); // 构造HttpClient的实例
49 | * HttpClient httpClient = new HttpClient(); // httpClient.set // 创建POS方法的实例
50 | * NameValuePair[] pairs = null; PostMethod postMethod = new
51 | * PostMethod(webUrl); if (paramMap != null) { pairs = new
52 | * NameValuePair[paramMap.size()]; Set set = paramMap.keySet(); Iterator it
53 | * = set.iterator(); int i = 0; while (it.hasNext()) { Object key =
54 | * it.next(); Object value = paramMap.get(key); if
55 | * (!ApiHttpUtil.checkNull(value)) { pairs[i] = new
56 | * NameValuePair(key.toString(), value.toString()); } i++; }
57 | * postMethod.setRequestBody(pairs); }
58 | * postMethod.getParams().setParameter(HttpMethodParams
59 | * .HTTP_CONTENT_CHARSET, encoding);
60 | * httpClient.getHttpConnectionManager().getParams
61 | * ().setConnectionTimeout(TIME_OUT_MILL_SEC);
62 | * httpClient.getHttpConnectionManager
63 | * ().getParams().setSoTimeout(TIME_OUT_MILL_SEC); HttpClientParams
64 | * httpClientParams = new HttpClientParams();
65 | * httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new
66 | * DefaultHttpMethodRetryHandler(0, false));
67 | * httpClientParams.setBooleanParameter
68 | * (HttpConnectionParams.STALE_CONNECTION_CHECK, true);
69 | * httpClient.setParams(httpClientParams); try { // 执行getMethod int
70 | * statusCode = httpClient.executeMethod(postMethod); if (statusCode !=
71 | * HttpStatus.SC_OK) { System.err.println("Method failed: " +
72 | * postMethod.getStatusLine()); sBuffer = new StringBuffer(); } else {
73 | * sBuffer = new StringBuffer(postMethod.getResponseBodyAsString() + ""); }
74 | * } catch (HttpException e) { // 发生致命的异常,可能是协议不对或者返回的内容有问题
75 | * System.out.println("Please check your provided http address!");
76 | * e.printStackTrace(); } catch (IOException e) { // 发生网络异常
77 | * e.printStackTrace(); } finally { // 释放连接 postMethod.releaseConnection();
78 | * } return sBuffer.toString(); }
79 | */
80 |
81 | /*
82 | * @SuppressWarnings({ "rawtypes", "unchecked" }) public static String
83 | * HttpGet(String webUrl, Map paramMap) {
84 | *
85 | * // 设置编码格式 String encoding = "GBK"; if (encoding == null ||
86 | * "".equals(encoding)) encoding = "GBK"; String queryString =
87 | * createLinkString(paramMap); webUrl = webUrl + "?" + queryString;
88 | * StringBuffer sBuffer = new StringBuffer(); // 构造HttpClient的实例 HttpClient
89 | * httpClient = new HttpClient(); GetMethod gettMethod = null; //
90 | * httpClient.set try { URI uri = new URI(webUrl, false, encoding);
91 | *
92 | * gettMethod = new GetMethod(uri.toString());
93 | *
94 | * gettMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
95 | * encoding);
96 | * httpClient.getHttpConnectionManager().getParams().setConnectionTimeout
97 | * (5000); // 连接5秒超时
98 | * httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);//
99 | * 读取30秒超时
100 | *
101 | * // 执行getMethod int statusCode = httpClient.executeMethod(gettMethod); if
102 | * (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " +
103 | * gettMethod.getStatusLine()); sBuffer = new StringBuffer(); } else {
104 | * sBuffer = new StringBuffer(gettMethod.getResponseBodyAsString() + ""); }
105 | * } catch (HttpException e) { // 发生致命的异常,可能是协议不对或者返回的内容有问题
106 | * System.out.println("Please check your provided http address!");
107 | * e.printStackTrace(); } catch (IOException e) { // 发生网络异常
108 | * e.printStackTrace(); } finally { // 释放连接 // Rewriter // Rewrite
109 | * Date:2015-12-22 By ZouYongle Case gettMethod MayBe is // NULL Start1: //
110 | * gettMethod.releaseConnection(); // End1: // Added by // Add
111 | * date:2015-12-22 Start2: if (gettMethod != null) {
112 | * gettMethod.releaseConnection(); } // End2: } return sBuffer.toString(); }
113 | */
114 |
115 | /**
116 | * 发送Get请求工具方法
117 | *
118 | * @Methods Name HttpGet
119 | * @Create In Dec 30, 2014 By lihongfei
120 | * @param url
121 | * @param method
122 | * @param paramMap
123 | * @return String
124 | */
125 | /*
126 | * @SuppressWarnings({ "rawtypes", "unchecked" }) public static String
127 | * HttpGet(String url, String method, Map paramMap) {
128 | *
129 | * String webUrl = url + "/" + method;
130 | *
131 | * return HttpGet(webUrl, paramMap); }
132 | */
133 |
134 | /**
135 | * 发送Get请求工具方法,处理参数有中文字符
136 | *
137 | * @Methods Name HttpGet
138 | * @Create In Dec 30, 2014 By songw
139 | * @param url
140 | * @param method
141 | * @param paramMap
142 | * @return String
143 | */
144 | /*
145 | * @SuppressWarnings({ "rawtypes", "unchecked" }) public static String
146 | * HttpGetByUtf(String url, String method, Map paramMap) { // 设置编码格式 String
147 | * encoding = "UTF-8"; String webUrl = url + "/" + method; if (encoding ==
148 | * null || "".equals(encoding)) encoding = "UTF-8"; String queryString =
149 | * createLinkString(paramMap); webUrl = webUrl + "?" + queryString;
150 | * StringBuffer sBuffer = new StringBuffer(); // 构造HttpClient的实例 HttpClient
151 | * httpClient = new HttpClient(); GetMethod gettMethod = null; //
152 | * httpClient.set try { URI uri = new URI(webUrl, false, encoding);
153 | *
154 | * gettMethod = new GetMethod(uri.toString());
155 | * gettMethod.setRequestHeader("Content-type", "application/json");
156 | * gettMethod
157 | * .getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
158 | * encoding);
159 | * httpClient.getHttpConnectionManager().getParams().setConnectionTimeout
160 | * (5000); // 连接5秒超时
161 | * httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);//
162 | * 读取30秒超时
163 | *
164 | * // 执行getMethod int statusCode = httpClient.executeMethod(gettMethod); if
165 | * (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " +
166 | * gettMethod.getStatusLine()); sBuffer = new StringBuffer(); } else {
167 | * sBuffer = new StringBuffer(gettMethod.getResponseBodyAsString() + ""); }
168 | * } catch (HttpException e) { // 发生致命的异常,可能是协议不对或者返回的内容有问题
169 | * System.out.println("Please check your provided http address!");
170 | * e.printStackTrace(); } catch (IOException e) { // 发生网络异常
171 | * e.printStackTrace(); } finally { // 释放连接 // Rewriter // Rewrite
172 | * Date:2015-12-22 By ZouYongle Case gettMethod MayBe is // NULL Start1: //
173 | * gettMethod.releaseConnection(); // End1: // Added by // Add
174 | * date:2015-12-22 Start2: if (gettMethod != null) {
175 | * gettMethod.releaseConnection(); } // End2: } return sBuffer.toString(); }
176 | */
177 |
178 | /**
179 | * 执行一个HTTP POST请求,返回请求响应的HTML
180 | *
181 | * @param url
182 | * 请求的URL地址
183 | * @param params
184 | * 请求的查询参数,可以为null
185 | * @return 返回请求响应的HTML
186 | */
187 | /*
188 | * @SuppressWarnings("deprecation") public static String doPost(String url,
189 | * String reqData, String contentType) { String response = null; HttpClient
190 | * client = new HttpClient();
191 | * client.getHttpConnectionManager().getParams().setConnectionTimeout
192 | * (TIME_OUT_MILL_SEC);
193 | * client.getHttpConnectionManager().getParams().setSoTimeout
194 | * (TIME_OUT_MILL_SEC); HttpClientParams httpClientParams = new
195 | * HttpClientParams();
196 | * httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new
197 | * DefaultHttpMethodRetryHandler(0, false));
198 | * httpClientParams.setBooleanParameter
199 | * (HttpConnectionParams.STALE_CONNECTION_CHECK, true);
200 | * client.setParams(httpClientParams); PostMethod method = new
201 | * PostMethod(url);
202 | * method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
203 | * "UTF-8"); // 设置Http Post数据 try { method.setRequestBody(reqData);
204 | * method.setRequestHeader("Content-type", contentType);
205 | * client.executeMethod(method); // if (method.getStatusCode() ==
206 | * HttpStatus.SC_OK) { response = method.getResponseBodyAsString(); // } }
207 | * catch (IOException e) { e.printStackTrace();
208 | * response="errorMessage:"+e.getMessage(); } finally {
209 | * method.releaseConnection(); } return response; }
210 | */
211 | /**
212 | * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
213 | *
214 | * @param params
215 | * 需要排序并参与字符拼接的参数组
216 | * @return 拼接后字符串
217 | */
218 | public static String createLinkString(Map params) {
219 |
220 | List keys = new ArrayList(params.keySet());
221 | Collections.sort(keys);
222 |
223 | String prestr = "";
224 |
225 | for (int i = 0; i < keys.size(); i++) {
226 | String key = keys.get(i);
227 | String value = params.get(key);
228 |
229 | if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
230 | prestr = prestr + key + "=" + value;
231 | } else {
232 | prestr = prestr + key + "=" + value + "&";
233 | }
234 | }
235 |
236 | return prestr;
237 | }
238 |
239 | public static boolean checkNull(Object target) {
240 | if (target == null || "".equals(target.toString().trim()) || "null".equalsIgnoreCase(target.toString().trim())) {
241 | return true;
242 | }
243 | return false;
244 | }
245 | }
246 |
--------------------------------------------------------------------------------
/gateway-core/src/main/java/com/z/gateway/core/support/OpenApiHttpAsynClientServiceImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package com.z.gateway.core.support;
5 |
6 | import java.io.IOException;
7 | import java.net.InetAddress;
8 | import java.net.UnknownHostException;
9 | import java.nio.charset.CodingErrorAction;
10 | import java.security.KeyManagementException;
11 | import java.security.NoSuchAlgorithmException;
12 | import java.security.cert.CertificateException;
13 | import java.util.Arrays;
14 | import java.util.Map;
15 | import java.util.concurrent.CountDownLatch;
16 | import java.util.concurrent.ExecutionException;
17 | import java.util.concurrent.Future;
18 |
19 | import javax.net.ssl.HostnameVerifier;
20 | import javax.net.ssl.SSLContext;
21 | import javax.net.ssl.TrustManager;
22 | import javax.net.ssl.X509TrustManager;
23 |
24 | import org.apache.http.Consts;
25 | import org.apache.http.Header;
26 | import org.apache.http.HttpEntity;
27 | import org.apache.http.HttpRequest;
28 | import org.apache.http.HttpResponse;
29 | import org.apache.http.HttpStatus;
30 | import org.apache.http.ParseException;
31 | import org.apache.http.client.CookieStore;
32 | import org.apache.http.client.config.AuthSchemes;
33 | import org.apache.http.client.config.CookieSpecs;
34 | import org.apache.http.client.config.RequestConfig;
35 | import org.apache.http.client.methods.HttpGet;
36 | import org.apache.http.concurrent.FutureCallback;
37 | import org.apache.http.config.ConnectionConfig;
38 | import org.apache.http.config.MessageConstraints;
39 | import org.apache.http.config.Registry;
40 | import org.apache.http.config.RegistryBuilder;
41 | import org.apache.http.conn.DnsResolver;
42 | import org.apache.http.conn.ssl.DefaultHostnameVerifier;
43 | import org.apache.http.impl.DefaultHttpResponseFactory;
44 | import org.apache.http.impl.client.BasicCookieStore;
45 | import org.apache.http.impl.conn.SystemDefaultDnsResolver;
46 | import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
47 | import org.apache.http.impl.nio.client.HttpAsyncClients;
48 | import org.apache.http.impl.nio.codecs.DefaultHttpRequestWriterFactory;
49 | import org.apache.http.impl.nio.codecs.DefaultHttpResponseParser;
50 | import org.apache.http.impl.nio.codecs.DefaultHttpResponseParserFactory;
51 | import org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionFactory;
52 | import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
53 | import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
54 | import org.apache.http.impl.nio.reactor.IOReactorConfig;
55 | import org.apache.http.message.BasicHeader;
56 | import org.apache.http.message.BasicLineParser;
57 | import org.apache.http.message.LineParser;
58 | import org.apache.http.nio.NHttpMessageParser;
59 | import org.apache.http.nio.NHttpMessageParserFactory;
60 | import org.apache.http.nio.NHttpMessageWriterFactory;
61 | import org.apache.http.nio.conn.ManagedNHttpClientConnection;
62 | import org.apache.http.nio.conn.NHttpConnectionFactory;
63 | import org.apache.http.nio.conn.NoopIOSessionStrategy;
64 | import org.apache.http.nio.conn.SchemeIOSessionStrategy;
65 | import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
66 | import org.apache.http.nio.reactor.ConnectingIOReactor;
67 | import org.apache.http.nio.reactor.IOReactorException;
68 | import org.apache.http.nio.reactor.SessionInputBuffer;
69 | import org.apache.http.nio.util.HeapByteBufferAllocator;
70 | import org.apache.http.util.CharArrayBuffer;
71 | import org.apache.http.util.EntityUtils;
72 |
73 | import com.z.gateway.core.OpenApiHttpClientService;
74 |
75 | /**
76 | * @author sunff
77 | *
78 | */
79 | @Deprecated
80 | public class OpenApiHttpAsynClientServiceImpl implements OpenApiHttpClientService {
81 |
82 | /* public static void main(String args[]) {
83 | OpenApiHttpAsynClientServiceImpl p = new OpenApiHttpAsynClientServiceImpl();
84 |
85 | try {
86 | p.test();
87 | } catch (Exception e1) {
88 | // TODO Auto-generated catch
89 | e1.printStackTrace();
90 | }
91 | try {
92 | System.in.read();
93 | } catch (IOException e) { // TODO Auto-generated catch block
94 | e.printStackTrace();
95 | }
96 |
97 | // p.init();
98 | // System.out.println(p.doGet("https://www.baidu.com/", "1000"));
99 | }*/
100 |
101 | // private CountDownLatch latch;
102 |
103 | /* public void test() throws IOException, InterruptedException {
104 | try {
105 | init();
106 | HttpGet httpGet = new HttpGet("https://www.baidu.com/");
107 | String body = "";
108 | httpAsyncClient.start();
109 | latch = new CountDownLatch(1);
110 | httpAsyncClient.execute(httpGet, new FutureCallbackImpl(body, latch));
111 |
112 | * try { System.in.read(); httpAsyncClient.close(); } catch
113 | * (IOException e) { // TODO Auto-generated catch block
114 | * e.printStackTrace(); }
115 |
116 | latch.await();
117 | } finally {
118 | httpAsyncClient.close();
119 | }
120 | }
121 | */
122 | public void init() {
123 | try {
124 | initHttpAsynClient();
125 | } catch (IOReactorException e) {
126 | // TODO Auto-generated catch block
127 | e.printStackTrace();
128 | }
129 | }
130 |
131 | private CloseableHttpAsyncClient httpAsyncClient;
132 |
133 |
134 | /**
135 | * 绕过验证
136 | *
137 | * @return
138 | * @throws NoSuchAlgorithmException
139 | * @throws KeyManagementException
140 | */
141 | private SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
142 | SSLContext sc = SSLContext.getInstance("SSLv3");
143 |
144 | // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
145 | X509TrustManager trustManager = new X509TrustManager() {
146 | @Override
147 | public void checkClientTrusted(
148 | java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
149 | String paramString) throws CertificateException {
150 | }
151 |
152 | @Override
153 | public void checkServerTrusted(
154 | java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
155 | String paramString) throws CertificateException {
156 | }
157 |
158 | @Override
159 | public java.security.cert.X509Certificate[] getAcceptedIssuers() {
160 | return null;
161 | }
162 | };
163 | sc.init(null, new TrustManager[] { trustManager }, null);
164 | return sc;
165 | }
166 | private void initHttpAsynClient() throws IOReactorException {
167 | // Use custom message parser / writer to customize the way HTTP
168 | // messages are parsed from and written out to the data stream.
169 | NHttpMessageParserFactory responseParserFactory = new DefaultHttpResponseParserFactory() {
170 |
171 | @Override
172 | public NHttpMessageParser create(final SessionInputBuffer buffer,
173 | final MessageConstraints constraints) {
174 | LineParser lineParser = new BasicLineParser() {
175 |
176 | @Override
177 | public Header parseHeader(final CharArrayBuffer buffer) {
178 | try {
179 | return super.parseHeader(buffer);
180 | } catch (ParseException ex) {
181 | return new BasicHeader(buffer.toString(), null);
182 | }
183 | }
184 |
185 | };
186 | return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE,
187 | constraints);
188 | }
189 |
190 | };
191 | NHttpMessageWriterFactory requestWriterFactory = new DefaultHttpRequestWriterFactory();
192 |
193 | // Use a custom connection factory to customize the process of
194 | // initialization of outgoing HTTP connections. Beside standard
195 | // connection
196 | // configuration parameters HTTP connection factory can define message
197 | // parser / writer routines to be employed by individual connections.
198 | NHttpConnectionFactory connFactory = new ManagedNHttpClientConnectionFactory(
199 | requestWriterFactory, responseParserFactory, HeapByteBufferAllocator.INSTANCE);
200 |
201 | // Client HTTP connection objects when fully initialized can be bound to
202 | // an arbitrary network socket. The process of network socket
203 | // initialization,
204 | // its connection to a remote address and binding to a local one is
205 | // controlled
206 | // by a connection socket factory.
207 |
208 | // SSL context for secure connections can be created either based on
209 | // system or application specific properties.
210 | // SSLContext sslcontext = org.apache.http.ssl.SSLContexts.createSystemDefault();
211 | // SSLContext sslcontext = org.apache.http.ssl.SSLContexts.createDefault();
212 | SSLContext sslcontext=null;
213 | try {
214 | sslcontext = this.createIgnoreVerifySSL();
215 | } catch (KeyManagementException | NoSuchAlgorithmException e) {
216 | // TODO Auto-generated catch block
217 | e.printStackTrace();
218 | }
219 | // Use custom hostname verifier to customize SSL hostname verification.
220 | HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
221 |
222 | // Create a registry of custom connection session strategies for
223 | // supported
224 | // protocol schemes.
225 | Registry sessionStrategyRegistry = RegistryBuilder. create()
226 | .register("http", NoopIOSessionStrategy.INSTANCE)
227 | // .register("https", new SSLIOSessionStrategy(sslcontext, hostnameVerifier)).build();
228 | .register("https", new SSLIOSessionStrategy(sslcontext)).build();
229 | // .register("https", SSLConnectionSocketFactory.getSystemSocketFactory()).build();
230 | // Use custom DNS resolver to override the system DNS resolution.
231 | DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
232 |
233 | @Override
234 | public InetAddress[] resolve(final String host) throws UnknownHostException {
235 | if (host.equalsIgnoreCase("myhost")) {
236 | return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
237 | } else {
238 | return super.resolve(host);
239 | }
240 | }
241 |
242 | };
243 |
244 | // Create I/O reactor configuration
245 | IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
246 | .setIoThreadCount(Runtime.getRuntime().availableProcessors()).setConnectTimeout(30000)
247 | .setSoTimeout(30000).build();
248 |
249 | // Create a custom I/O reactort
250 | ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
251 |
252 | // Create a connection manager with custom configuration.
253 | PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor,
254 | connFactory, sessionStrategyRegistry, dnsResolver);
255 |
256 | // Create message constraints
257 | MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
258 | .setMaxLineLength(2000).build();
259 | // Create connection configuration
260 | ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE)
261 | .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
262 | .setMessageConstraints(messageConstraints).build();
263 | // Configure the connection manager to use connection configuration
264 | // either
265 | // by default or for a specific host.
266 | connManager.setDefaultConnectionConfig(connectionConfig);
267 | // connManager.setConnectionConfig(new HttpHost("somehost", 80),
268 | // ConnectionConfig.DEFAULT);
269 |
270 | // Configure total max or per route limits for persistent connections
271 | // that can be kept in the pool or leased by the connection manager.
272 | connManager.setMaxTotal(100);
273 | connManager.setDefaultMaxPerRoute(10);
274 | // connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost",
275 | // 80)), 20);
276 |
277 | // Use custom cookie store if necessary.
278 | CookieStore cookieStore = new BasicCookieStore();
279 | // Use custom credentials provider if necessary.
280 | // CredentialsProvider credentialsProvider = new
281 | // BasicCredentialsProvider();
282 | // credentialsProvider.setCredentials(new AuthScope("localhost", 8889),
283 | // new UsernamePasswordCredentials("squid", "nopassword"));
284 | // Create global request configuration
285 | RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
286 | .setExpectContinueEnabled(true)
287 | .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
288 | .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
289 |
290 | // Create an HttpClient with the given custom dependencies and
291 | // configuration.
292 | // CloseableHttpAsyncClient
293 | httpAsyncClient = HttpAsyncClients.custom().setConnectionManager(connManager)
294 | // .setDefaultCookieStore(cookieStore)
295 | // .setDefaultCredentialsProvider(credentialsProvider)
296 | // .setProxy(new HttpHost("localhost", 8889))
297 | // .setDefaultRequestConfig(defaultRequestConfig)
298 | .build();
299 | }
300 |
301 | private static class FutureCallbackImpl implements FutureCallback {
302 |
303 | private String body;
304 | private CountDownLatch latch;
305 |
306 | public FutureCallbackImpl(String body, CountDownLatch latch) {
307 | this.body = body;
308 | this.latch = latch;
309 | }
310 |
311 | public void completed(final HttpResponse response) {
312 | // System.out.println(httpget.getRequestLine() + "->" +
313 | // response.getStatusLine())
314 | try {
315 | HttpEntity entity = response.getEntity();
316 | int statusCode = response.getStatusLine().getStatusCode();
317 | if (statusCode == HttpStatus.SC_OK) {
318 | if (entity != null) {
319 | body = EntityUtils.toString(entity, "utf-8");
320 | System.out.println("body======" + body);
321 | }
322 | EntityUtils.consume(entity);
323 | }
324 | } catch (ParseException e) {
325 | // TODO Auto-generated catch block
326 | e.printStackTrace();
327 | } catch (IOException e) {
328 | // TODO Auto-generated catch block
329 | e.printStackTrace();
330 | }
331 | latch.countDown();
332 | }
333 |
334 | public void failed(final Exception ex) {
335 |
336 | System.out.println("failed.....");
337 | latch.countDown();
338 | }
339 |
340 | public void cancelled() {
341 | System.out.println(" cancelled....");
342 | latch.countDown();
343 | }
344 |
345 | }
346 |
347 | @Override
348 | public String doGet(String webUrl, Map requestHeader) {
349 |
350 | final HttpGet httpget = new HttpGet(webUrl);
351 | if(requestHeader!=null){
352 | requestHeader.forEach((k,v)->{
353 | httpget.setHeader(k,v);
354 | });
355 | }
356 |
357 |
358 | String body = "";
359 | try {
360 | httpAsyncClient.start();
361 | Future r = httpAsyncClient.execute(httpget, null);
362 | try {
363 | HttpResponse response = r.get();
364 | try {
365 | HttpEntity entity = response.getEntity();
366 | int statusCode = response.getStatusLine().getStatusCode();
367 | if (statusCode == HttpStatus.SC_OK) {
368 | if (entity != null) {
369 | body = EntityUtils.toString(entity, "utf-8");
370 | // System.out.println("body======" + body);
371 | }
372 | EntityUtils.consume(entity);
373 | }
374 | } catch (ParseException e) {
375 | // TODO Auto-generated catch block
376 | e.printStackTrace();
377 | } catch (IOException e) {
378 | // TODO Auto-generated catch block
379 | e.printStackTrace();
380 | }
381 | } catch (InterruptedException | ExecutionException e) {
382 | // TODO Auto-generated catch block
383 | e.printStackTrace();
384 | }
385 | } finally {
386 | /*
387 | * try { this.httpAsyncClient.close(); } catch (IOException e) { //
388 | * TODO Auto-generated catch block e.printStackTrace(); }
389 | */
390 | }
391 | return body;
392 |
393 | }
394 |
395 | @Override
396 | public String doGet(String webUrl, Map paramMap, Map requestHeader) {
397 | // TODO Auto-generated method stub
398 | return null;
399 | }
400 |
401 | @Override
402 | public String doHttpsGet(String webUrl, Map requestHeader) {
403 | // TODO Auto-generated method stub
404 | return doGet(webUrl, requestHeader);
405 | }
406 |
407 | @Override
408 | public String doHttpsGet(String webUrl, Map paramMap,Map requestHeader) {
409 | // TODO Auto-generated method stub
410 | return null;
411 | }
412 |
413 | @Override
414 | public String doHttpsPost(String url, String content, Map requestHeader) {
415 | // TODO Auto-generated method stub
416 | return null;
417 | }
418 |
419 | @Override
420 | public String doPost(String url, String reqData,Map requestHeader) {
421 | // TODO Auto-generated method stub
422 | return null;
423 | }
424 | }
425 |
--------------------------------------------------------------------------------
/gateway-common/src/main/java/com/z/gateway/common/util/StringUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * 创建日期 2009-4-2
3 | *
4 | * TODO 要更改此生成的文件的模板,请转至
5 | * 窗口 - 首选项 - Java - 代码样式 - 代码模板
6 | */
7 | package com.z.gateway.common.util;
8 |
9 | import java.io.UnsupportedEncodingException;
10 | import java.net.URLDecoder;
11 | import java.sql.Timestamp;
12 | import java.text.DateFormat;
13 | import java.text.DecimalFormat;
14 | import java.text.ParseException;
15 | import java.text.SimpleDateFormat;
16 | import java.util.ArrayList;
17 | import java.util.Calendar;
18 | import java.util.Date;
19 | import java.util.Enumeration;
20 | import java.util.HashMap;
21 | import java.util.List;
22 | import java.util.Random;
23 | import java.util.StringTokenizer;
24 | import java.util.Vector;
25 | import java.util.regex.Matcher;
26 | import java.util.regex.Pattern;
27 |
28 | import org.apache.commons.lang3.StringUtils;
29 | import org.slf4j.Logger;
30 | import org.slf4j.LoggerFactory;
31 |
32 | /**
33 | * 要更改此生成的类型注释的模板,请转至 窗口 - 首选项 - Java - 代码样式 - 代码模板
34 | *
35 | * @author Administrator
36 | *
37 | */
38 | public class StringUtil {
39 |
40 | private static Logger log = LoggerFactory.getLogger(StringUtil.class);
41 |
42 | public static String gbkToAscii(String s) {
43 | if (s == null)
44 | return "";
45 | try {
46 | s = new String(s.getBytes("GBK"), "iso8859-1");
47 | } catch (Exception e) {
48 | log.error("gbkToAscii fail," + e.getMessage(), e);
49 | }
50 | return s;
51 | }
52 |
53 | public static String asciiToGbk(String s) {
54 | if (s == null)
55 | return null;
56 | try {
57 | s = new String(s.getBytes("iso8859-1"), "GBK");
58 | } catch (Exception e) {
59 | log.error("asciiToGbk fail," + e.getMessage(), e);
60 | return null;
61 | }
62 | return s;
63 | }
64 |
65 | public static String[] parseStringToArray(String s, String delim) {
66 | StringTokenizer st = new StringTokenizer(s, delim);
67 | List v = new ArrayList();
68 | while (st.hasMoreElements()) {
69 | String tmp = st.nextToken();
70 | v.add(tmp);
71 | }
72 | return (String[]) v.toArray(new String[v.size()]);
73 | }
74 |
75 | public static String[] parseStringToArray2(String s, String delim) {
76 |
77 | List v = new ArrayList();
78 |
79 | String tmp = s;
80 | int startIdx = 0;
81 | while (s != null && s.indexOf(delim) != -1) {
82 | int idx = s.indexOf(delim);
83 | v.add(s.substring(0, idx).trim());
84 | startIdx += idx + delim.length();
85 | s = s.substring(startIdx);
86 | startIdx = 0;
87 | }
88 | v.add((s != null) ? s.trim() : "");
89 | return (String[]) v.toArray(new String[v.size()]);
90 |
91 | }
92 |
93 | public static String replaceNonDigiCharToZero(String s) {
94 | if (s == null || s.equals("")) {
95 | return "0";
96 | }
97 | for (int ii = 0; ii < s.length(); ii++) {
98 | if (!Character.isDigit(s.charAt(ii))) {
99 | s = s.replace(s.charAt(ii), '0');
100 | }
101 | }
102 | return s;
103 | }
104 |
105 | /**
106 | * replace all the targets with patterns
107 | *
108 | * @param s
109 | * @param target
110 | * @param pattern
111 | * @return
112 | */
113 | public static String replace(String s, String target, String pattern) {
114 | while (s.indexOf(target) != -1) {
115 | int i = s.indexOf(target);
116 | s = s.substring(0, i) + pattern + s.substring(i + target.length());
117 | }
118 | return s;
119 | }
120 |
121 | public String isNull(Object obj) {
122 | return obj == null ? "" : obj.toString();
123 | }
124 |
125 | /**
126 | *
127 | * @param obj
128 | */
129 | public static boolean isNotEmpty(String obj) {
130 | return obj != null && obj.trim().length() > 0;
131 | }
132 |
133 | /**
134 | *
135 | * @param obj
136 | * @return
137 | */
138 | public static boolean isEmpty(String obj) {
139 | return !isNotEmpty(obj);
140 | }
141 |
142 | private static final char zeroArray[] = "0000000000000000000000000000000000000000000000000000000000000000"
143 | .toCharArray();
144 |
145 | public static String[] splitStr(String sStr, String sSplitter) {
146 | if (sStr == null || sStr.length() <= 0 || sSplitter == null || sSplitter.length() <= 0)
147 | return null;
148 | String[] saRet = null;
149 | int iLen = sSplitter.length();
150 | int[] iIndex = new int[sStr.length()];
151 | iIndex[0] = sStr.indexOf(sSplitter, 0);
152 | if (iIndex[0] == -1) {
153 | saRet = new String[1];
154 | saRet[0] = sStr;
155 | return saRet;
156 | }
157 | int iIndexNum = 1;
158 | while (true) {
159 | iIndex[iIndexNum] = sStr.indexOf(sSplitter, iIndex[iIndexNum - 1] + iLen);
160 | if (iIndex[iIndexNum] == -1)
161 | break;
162 | iIndexNum++;
163 | }
164 | Vector vStore = new Vector();
165 | int i = 0;
166 | String sub = null;
167 | for (i = 0; i < iIndexNum + 1; i++) {
168 | if (i == 0)
169 | sub = sStr.substring(0, iIndex[0]);
170 | else if (i == iIndexNum)
171 | sub = sStr.substring(iIndex[i - 1] + iLen, sStr.length());
172 | else
173 | sub = sStr.substring(iIndex[i - 1] + iLen, iIndex[i]);
174 | if (sub != null && sub.length() > 0)
175 | vStore.add(sub);
176 | }
177 | if (vStore.size() <= 0)
178 | return null;
179 | saRet = new String[vStore.size()];
180 | Enumeration e = vStore.elements();
181 | for (i = 0; e.hasMoreElements(); i++)
182 | saRet[i] = (String) e.nextElement();
183 | return saRet;
184 | }
185 |
186 | public static boolean isNum(String str) {
187 | if (str == null || str.length() <= 0)
188 | return false;
189 | char[] ch = str.toCharArray();
190 | for (int i = 0; i < str.length(); i++)
191 | if (!Character.isDigit(ch[i]))
192 | return false;
193 | return true;
194 | }
195 |
196 | public static String symbol(String value) {
197 | String val = "";
198 | if (value != null) {
199 | val = value;
200 | }
201 | val = replaceStrEx(val, "'", "’");
202 | val = replaceStrEx(val, ",", ",");
203 | val = replaceStrEx(val, "\"", "“");
204 | // val = replaceStrEx(val,"\"","“");
205 | return val;
206 | }
207 |
208 | public static String replaceStrEx(String sReplace, String sOld, String sNew) {
209 | if (sReplace == null || sOld == null || sNew == null)
210 | return null;
211 | int iLen = sReplace.length();
212 | int iLenOldStr = sOld.length();
213 | int iLenNewStr = sNew.length();
214 | if (iLen <= 0 || iLenOldStr <= 0 || iLenNewStr < 0)
215 | return sReplace;
216 | int[] iIndex = new int[iLen];
217 | iIndex[0] = sReplace.indexOf(sOld, 0);
218 | if (iIndex[0] == -1)
219 | return sReplace;
220 | int iIndexNum = 1;
221 | while (true) {
222 | iIndex[iIndexNum] = sReplace.indexOf(sOld, iIndex[iIndexNum - 1] + 1);
223 | if (iIndex[iIndexNum] == -1)
224 | break;
225 | iIndexNum++;
226 | }
227 | Vector vStore = new Vector();
228 | String sub = sReplace.substring(0, iIndex[0]);
229 | if (sub != null)
230 | vStore.add(sub);
231 | int i = 1;
232 | for (i = 1; i < iIndexNum; i++) {
233 | vStore.add(sReplace.substring(iIndex[i - 1] + iLenOldStr, iIndex[i]));
234 | }
235 | vStore.add(sReplace.substring(iIndex[i - 1] + iLenOldStr, iLen));
236 | StringBuffer sbReplaced = new StringBuffer("");
237 | for (i = 0; i < iIndexNum; i++) {
238 | sbReplaced.append(vStore.get(i) + sNew);
239 | }
240 | sbReplaced.append(vStore.get(i));
241 | return sbReplaced.toString();
242 | }
243 |
244 | public static String replaceStr(String sReplace, String sOld, String sNew) {
245 | if (sReplace == null || sOld == null || sNew == null)
246 | return null;
247 | int iLen = sReplace.length();
248 | int iLenOldStr = sOld.length();
249 | int iLenNewStr = sNew.length();
250 | if (iLen <= 0 || iLenOldStr <= 0 || iLenNewStr < 0)
251 | return sReplace;
252 | int iIndex = -1;
253 | iIndex = sReplace.indexOf(sOld, 0);
254 | if (iIndex == -1)
255 | return sReplace;
256 | String sub = sReplace.substring(0, iIndex);
257 | StringBuffer sbReplaced = new StringBuffer("");
258 | sbReplaced.append(sub + sNew);
259 | sbReplaced.append(sReplace.substring(iIndex + iLenOldStr, iLen));
260 | return sbReplaced.toString();
261 | }
262 |
263 | public static String cvtTOgbk(String encoding, String string) {
264 | if (string == null) {
265 | return "";
266 | }
267 | try {
268 | return new String(string.getBytes(encoding), "GBK");
269 | } catch (UnsupportedEncodingException e) {
270 | log.error("cvtTOgbk fail," + e.getMessage(), e);
271 | return string;
272 | }
273 | }
274 |
275 | public static String cvtTOgbk(String str) {
276 | if (str == null)
277 | return "";
278 | try {
279 | return new String(str.getBytes("iso-8859-1"), "GBK");
280 | } catch (java.io.UnsupportedEncodingException un) {
281 | log.error("cvtTOgbk fail," + un.getMessage(), un);
282 | return str;
283 | }
284 | }
285 |
286 | public static String cvtTOiso(String str) {
287 | if (str == null)
288 | return "";
289 | try {
290 | return new String(str.getBytes("GBK"), "iso-8859-1");
291 | } catch (java.io.UnsupportedEncodingException un) {
292 | log.error("cvtTOiso fail," + un.getMessage(), un);
293 | return str;
294 | }
295 | }
296 |
297 | public static String cvtToUTF8(String str) {
298 | if (str == null)
299 | return "";
300 | try {
301 | return new String(str.getBytes("iso-8859-1"), "GBK");
302 | } catch (java.io.UnsupportedEncodingException un) {
303 | log.error("cvtToUTF8 fail," + un.getMessage(), un);
304 | return str;
305 | }
306 | }
307 |
308 | public static int toInteger(String integer) {
309 | return toInteger(integer, 0);
310 | }
311 |
312 | public static int toInteger(String integer, int def) {
313 | int ret = 0;
314 | try {
315 | ret = Integer.parseInt(integer);
316 | } catch (NumberFormatException nfx) {
317 | ret = def;
318 | }
319 | return ret;
320 | }
321 |
322 | public static long toLong(String longStr) {
323 | return toLong(longStr, 0);
324 | }
325 |
326 | public static long toLong(String longStr, long def) {
327 | long ret = 0;
328 | try {
329 | ret = Long.parseLong(longStr);
330 | } catch (NumberFormatException nfx) {
331 | ret = def;
332 | }
333 | return ret;
334 | }
335 |
336 | public static double toDouble(String doubleStr) {
337 | return toDouble(doubleStr, 0.0);
338 | }
339 |
340 | public static double toDouble(String doubleStr, double def) {
341 | double ret = 0.0;
342 | try {
343 | ret = Double.parseDouble(doubleStr);
344 | } catch (NumberFormatException nfx) {
345 | ret = def;
346 | }
347 | return ret;
348 | }
349 |
350 | public static String contactStr(String[] saStr, String sContacter) {
351 | if (saStr == null || saStr.length <= 0 || sContacter == null || sContacter.length() <= 0)
352 | return null;
353 | StringBuffer sRet = new StringBuffer("");
354 | for (int i = 0; i < saStr.length; i++) {
355 | if (i == saStr.length - 1)
356 | sRet.append(saStr[i]);
357 | else
358 | sRet.append(saStr[i] + sContacter);
359 | }
360 | return sRet.toString();
361 | }
362 |
363 | public static String contactStr(String[] saStr, String sContacter, String str) {
364 | if (saStr == null || saStr.length <= 0 || sContacter == null || sContacter.length() <= 0)
365 | return null;
366 | StringBuffer sRet = new StringBuffer("");
367 | for (int i = 0; i < saStr.length; i++) {
368 | if (i == saStr.length - 1)
369 | sRet.append(str + saStr[i] + str);
370 | else
371 | sRet.append(str + saStr[i] + str + sContacter);
372 | }
373 | return sRet.toString();
374 | }
375 |
376 | public static boolean validHomepage(String homepage) {
377 | if (homepage == null)
378 | return false;
379 | if (homepage.length() == 0)
380 | return false;
381 | if (homepage.length() > 7) {
382 | if (homepage.toLowerCase().indexOf("http://") == 0 && homepage.indexOf(".") > 0)
383 | return false;
384 | else
385 | return true;
386 | } else {
387 | if (homepage.length() == 7 && homepage.toLowerCase().indexOf("http://") == 0)
388 | return false;
389 | else
390 | return true;
391 | }
392 | }
393 |
394 | public static boolean isEmailUrl(String str) {
395 | if ((str == null) || (str.length() == 0))
396 | return false;
397 | if ((str.indexOf('@') > 0) && (str.indexOf('@') == str.lastIndexOf('@'))) {
398 | if ((str.indexOf('.') > 0) && (str.lastIndexOf('.') > str.indexOf('@'))) {
399 | return true;
400 | }
401 | }
402 | return false;
403 | }
404 |
405 | public static boolean isValidEmail(String str) {
406 | return Pattern.compile("^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$").matcher(str).matches();
407 | }
408 |
409 | public static String cvtTOgb2312(String str) {
410 | if (str == null)
411 | return "";
412 | try {
413 | return new String(str.getBytes("iso-8859-1"), "gb2312");
414 | } catch (java.io.UnsupportedEncodingException un) {
415 | log.error("cvtTOgb2312 fail," + un.getMessage(), un);
416 | return str;
417 | }
418 | }
419 |
420 | public static String chkNull(String str) {
421 | if (str == null)
422 | return "未知";
423 | else
424 | return str;
425 | }
426 |
427 | public static String chkNullBlank(String str) {
428 | if (str == null)
429 | return "";
430 | else if (str.trim().equals("null"))
431 | return "";
432 | else
433 | return str.trim();
434 | }
435 |
436 | public static String chkNullDate(Date date) {
437 | if (date == null)
438 | return "";
439 | else {
440 | DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
441 | return df.format(date);
442 | }
443 | }
444 |
445 | public static String getDateToString(Date date) {
446 | if (date == null)
447 | return "";
448 | else {
449 | DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
450 | return df.format(date);
451 | }
452 | }
453 |
454 | public static String chkNullDateHH(Date date) {
455 | if (date == null)
456 | return "";
457 | else {
458 | DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
459 | return df.format(date);
460 | }
461 | }
462 |
463 | public static String checkNullDateHH(Timestamp timestamp) {
464 | if (timestamp == null)
465 | return "";
466 | else {
467 | DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
468 | return df.format(timestamp);
469 | }
470 | }
471 |
472 | public static String chkNullBlank(Object object) {
473 | if (object != null)
474 | return chkNullBlank(object.toString());
475 | else
476 | return "";
477 | }
478 |
479 | public static String[] checkBox(String[] source, String[] pos) {
480 | if (source == null || pos == null || source.length < pos.length)
481 | return null;
482 | String[] res = new String[pos.length];
483 | for (int i = 0; i < pos.length; i++) {
484 | res[i] = source[Integer.parseInt(pos[i])];
485 | }
486 | return res;
487 | }
488 |
489 | public static String randomString(int len) {
490 | String asctbl = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
491 | String str = "";
492 | for (int i = 0; i < len; i++) {
493 | int offset = (int) Math.round(Math.random() * (asctbl.length() - 1));
494 | str += asctbl.substring(offset, offset + 1);
495 | }
496 | return str;
497 | }
498 |
499 | public static String ParseMsg(String strMsg, String strValue, int intLen) {
500 | if (strMsg == null)
501 | strMsg = strValue;
502 | long lMsgLength = strMsg.getBytes().length;
503 | if (lMsgLength < intLen) {
504 | while (lMsgLength < intLen) {
505 | strMsg = strMsg + strValue;
506 | lMsgLength = strMsg.getBytes().length;
507 | }
508 | }
509 | return strMsg;
510 | }
511 |
512 | public static String getValue(Object str) {
513 | if (str == null || str.equals("null"))
514 | return "";
515 | else
516 | return str.toString();
517 | }
518 |
519 | public static Date formateDate(String dateString, String hourStr, String minStr) {
520 | Date result = null;
521 | Calendar calendar = Calendar.getInstance();
522 | int year = Integer.parseInt(dateString.substring(0, 4));
523 | int month = Integer.parseInt(dateString.substring(5, 7));
524 | int day = Integer.parseInt(dateString.substring(8, 10));
525 | int hour = Integer.parseInt(hourStr);
526 | int min = Integer.parseInt(minStr);
527 | calendar.set(year, month - 1, day, hour, min, 0);
528 | return calendar.getTime();
529 | }
530 |
531 | public static String TimestampDateFormat(Timestamp timestamp) {
532 | if (timestamp == null) {
533 | return null;
534 | }
535 | String timestampStr = null;
536 | timestampStr = "to_timestamp('" + timestamp.toString() + "','YYYY-MM-DD HH24:MI:SSXFF')";
537 | return timestampStr;
538 | }
539 |
540 | /**
541 | * 给出"YYYY-MM-DD","HH","MI"三个字符串,返回一个oracle的时间格式
542 | *
543 | * @author Ltao 2004-12-12
544 | * @param dateString
545 | * @param hourStr
546 | * @param minStr
547 | * @return oracle的时间格式 形如"to_date(..." , 如果三个参数中缺少其中任意一个,则返回null;
548 | */
549 | public static String oracleDateFormat(String dateString, String hourStr, String minStr, String secStr) {
550 | if (dateString == null || hourStr == null || minStr == null || secStr == null || dateString.equals("")
551 | || hourStr.equals("") || minStr.equals("") || secStr.equals("")) {
552 | return null;
553 | }
554 | String oracleDateStr = null;
555 | String tempStr = dateString + " " + hourStr + ":" + minStr + ":" + secStr;
556 | // oracleDateStr = "to_date('" + tempStr + "','YYYY-MM-DD HH24:MI:SS')";
557 | oracleDateStr = "str_to_date('" + tempStr + "','%Y-%m-%d %H:%i:%s')";
558 | return oracleDateStr;
559 | }
560 |
561 | /**
562 | * 取timestamp的形如"YYYY-MM-DD"的日期字符串,
563 | *
564 | * @author Ltao 2004-12-12
565 | * @param time
566 | * 时间
567 | * @return 形如"YYYY-MM-DD"的日期字符串, 如果time为null,则返回null;
568 | */
569 | public static String getDateStr(Date time) {
570 | if (time == null) {
571 | return "";
572 | }
573 | String result = null;
574 | DateFormat df = new SimpleDateFormat("yyyy-MM-dd ");
575 | result = df.format(time);
576 | return result;
577 | }
578 |
579 | /**
580 | * 取timestamp的形如"HH24:MI:SS"的时间字符串,
581 | *
582 | * @author Ltao 2004-12-12
583 | * @param time
584 | * 时间
585 | * @return 形如"HH24:MI:SS"的时间字符串, 如果time为null,则返回null;
586 | */
587 | public static String getHourMinuteSecondStr(Timestamp time) {
588 | if (time == null) {
589 | return "";
590 | }
591 | String result = null;
592 | DateFormat df = new SimpleDateFormat("hh:mm:ss");
593 | result = df.format(time);
594 | return result;
595 | }
596 |
597 | public static String getHourMinuteSecondStr(Date time) {
598 | if (time == null) {
599 | return "";
600 | }
601 | String result = null;
602 | DateFormat df = new SimpleDateFormat("hh:mm:ss");
603 | result = df.format(time);
604 | return result;
605 | }
606 |
607 | /**
608 | * 取timestamp的形如"HH24:MI"的时间字符串,
609 | *
610 | * @author Ltao 2004-12-12
611 | * @param time
612 | * 时间
613 | * @return 形如"HH24:MI"的时间字符串, 如果time为null,则返回null;
614 | */
615 | public static String getHourMinuteStr(Timestamp time) {
616 | if (time == null) {
617 | return "";
618 | }
619 | String result = null;
620 | DateFormat df = new SimpleDateFormat("hh:mm");
621 | result = df.format(time);
622 | return result;
623 | }
624 |
625 | public static String log2String(HashMap hashMap) {
626 | String result = "";
627 | Object[] keyList = hashMap.keySet().toArray();
628 | for (int i = 0; i < keyList.length; i++) {
629 | String keyName = keyList[i] == null ? "" : keyList[i].toString();
630 | String keyValue = hashMap.get(keyName) == null ? "" : hashMap.get(keyName).toString();
631 | result += keyName + ":" + hashMap.get(keyList[i].toString()) + "\n";
632 | }
633 | return result;
634 | }
635 |
636 | public static String log2ContentName(HashMap hashMap) {
637 | String result = "";
638 | if (hashMap.get("Content Name") != null) {
639 | result = (String) hashMap.get("Content Name");
640 | }
641 | return result;
642 | }
643 |
644 | public static String removeQueryString(String queryStr, String paramName) {
645 | int i = queryStr.indexOf(paramName);
646 | if (i >= 0) {
647 | int j = queryStr.indexOf("&", i);
648 | if (j > 0)
649 | queryStr = queryStr.substring(0, i) + queryStr.substring(j + 1);
650 | else if (i == 0)
651 | queryStr = "";
652 | else
653 | queryStr = queryStr.substring(0, i - 1);
654 | }
655 | return queryStr;
656 | }
657 |
658 | /**
659 | * 把时间类型传换成String,空的话换成""
660 | *
661 | * @return
662 | */
663 | public static String getDateWeb(Date newDate) {
664 | return newDate == null ? "" : newDate.toString();
665 | }
666 |
667 | /**
668 | * 把时间类型传换成String,空的话换成""
669 | *
670 | * @return
671 | */
672 | public static String getStrWeb(String str) {
673 | return str == null ? "" : str.toString();
674 | }
675 |
676 | /**
677 | * 把时间类型传换成String,空的话换成""
678 | *
679 | * @return
680 | */
681 | public static String getLongWeb(Long newLong) {
682 | return newLong == null ? "" : newLong.toString();
683 | }
684 |
685 | /**
686 | * 分割以指定符号的字符串
687 | *
688 | * @param splitStr
689 | * @return
690 | */
691 | public static String[] getSplitString(String splitStr, String splitType) {
692 | StringTokenizer str = new StringTokenizer(splitStr, splitType);
693 | int strNum = str.countTokens();
694 | String strTemp[] = new String[strNum];
695 | int i = 0;
696 | while (str.hasMoreElements()) {
697 | strTemp[i] = (String) str.nextElement();
698 | i++;
699 | }
700 | return strTemp;
701 | }
702 |
703 | public static String percentage(double d) {
704 | // System.out.println("d:"+d);
705 | Double double1 = new Double(d);
706 | int i = double1.intValue();
707 | return i + "%";
708 | }
709 |
710 | // 把字符串中大写的字母都变成小写
711 | public static String changeSmall(String str) {
712 | String smallStr = "";
713 | char indexChar;
714 | for (int i = 0; str != null && i < str.length(); i++) {
715 | indexChar = str.charAt(i);
716 | if (indexChar == 'A') {
717 | indexChar = 'a';
718 | } else if (indexChar == 'B') {
719 | indexChar = 'b';
720 | } else if (indexChar == 'C') {
721 | indexChar = 'c';
722 | } else if (indexChar == 'D') {
723 | indexChar = 'd';
724 | } else if (indexChar == 'E') {
725 | indexChar = 'e';
726 | } else if (indexChar == 'F') {
727 | indexChar = 'f';
728 | } else if (indexChar == 'G') {
729 | indexChar = 'g';
730 | } else if (indexChar == 'H') {
731 | indexChar = 'h';
732 | } else if (indexChar == 'I') {
733 | indexChar = 'i';
734 | } else if (indexChar == 'J') {
735 | indexChar = 'j';
736 | } else if (indexChar == 'K') {
737 | indexChar = 'k';
738 | } else if (indexChar == 'L') {
739 | indexChar = 'l';
740 | } else if (indexChar == 'M') {
741 | indexChar = 'm';
742 | } else if (indexChar == 'N') {
743 | indexChar = 'n';
744 | } else if (indexChar == 'O') {
745 | indexChar = 'o';
746 | } else if (indexChar == 'P') {
747 | indexChar = 'p';
748 | } else if (indexChar == 'Q') {
749 | indexChar = 'q';
750 | } else if (indexChar == 'R') {
751 | indexChar = 'r';
752 | } else if (indexChar == 'S') {
753 | indexChar = 's';
754 | } else if (indexChar == 'T') {
755 | indexChar = 't';
756 | } else if (indexChar == 'U') {
757 | indexChar = 'u';
758 | } else if (indexChar == 'V') {
759 | indexChar = 'v';
760 | } else if (indexChar == 'W') {
761 | indexChar = 'w';
762 | } else if (indexChar == 'X') {
763 | indexChar = 'x';
764 | } else if (indexChar == 'Y') {
765 | indexChar = 'y';
766 | } else if (indexChar == 'Z') {
767 | indexChar = 'z';
768 | }
769 | smallStr += indexChar;
770 | }
771 |
772 | return smallStr;
773 | }
774 |
775 | public static String percentage(String s1, String s2) {
776 | return percentage(toInteger(s1) * 100 / toInteger(s2));
777 | }
778 |
779 | /**
780 | * change window type path to unix
781 | *
782 | * @param originalPath
783 | * @return String
784 | */
785 | public static String makeAbsolutePath(String originalPath) {
786 | originalPath = originalPath.replace('\\', '/');
787 |
788 | if ('/' == originalPath.charAt(0)) {
789 | return originalPath;
790 | }
791 |
792 | /* Check for a drive specification for windows-type path */
793 | if (originalPath.substring(1, 2).equals(":")) {
794 | return originalPath;
795 | }
796 |
797 | /* and put the two together */
798 | return originalPath;
799 | }
800 |
801 | public static String str2booleanValue(String value) {
802 | if (value != null && value.trim().equals("1"))
803 | return "1";
804 | else
805 | return "0";
806 | }
807 |
808 | public static String concateFormArray(List values) {
809 | return concateFormArray(values, ",");
810 | }
811 |
812 | public static String concateFormArray(List values, String delimiter) {
813 | if (values == null || values.size() == 0)
814 | return "";
815 | String temp[] = new String[values.size()];
816 | values.toArray(temp);
817 | return contactStr(temp, delimiter);
818 | // // StringBuffer sb=new StringBuffer();
819 | // // for (int i=0;i length) {
828 | return string;
829 | } else {
830 | StringBuffer buf = new StringBuffer(length);
831 | buf.append(zeroArray, 0, length - string.length()).append(string);
832 | return buf.toString();
833 | }
834 | }
835 |
836 | public static final String moneyFormat(String param) {
837 | String ret = "";
838 | try {
839 |
840 | int index = param.indexOf(".");
841 | if (index > 0) {
842 | param = param + "00";
843 | } else {
844 | param = param + ".00";
845 | }
846 | index = param.indexOf(".");
847 |
848 | ret = param.substring(0, index + 3);
849 |
850 | } catch (Exception e) {
851 | ret = "0.00";
852 | }
853 | return ret;
854 | }
855 |
856 | public static final String achivFormat(String param) {
857 | String ret = "";
858 | try {
859 | double parValue = Double.parseDouble(param);
860 | ret = new DecimalFormat("0").format(parValue);
861 | } catch (Exception e) {
862 | ret = "0";
863 | }
864 | return ret;
865 | }
866 |
867 | /**
868 | * transform null to ""
869 | *
870 | * @param param
871 | * @return String
872 | */
873 | public static final String tranNull(String param) {
874 | String strPra = "";
875 | if (null == param) {
876 | strPra = "";
877 | } else {
878 | strPra = param;
879 | }
880 | return strPra;
881 | }
882 |
883 | /**
884 | * yyyyMMdd To yyyy-MM-dd
885 | */
886 | public static final String dateFormat(String param) {
887 | String strPra = "";
888 | if (null == param) {
889 | strPra = "";
890 | } else if (param.length() == 8) {
891 | strPra = param.substring(0, 4) + "-" + param.substring(4, 6) + "-" + param.substring(6, 8);
892 | } else if (param.length() >= 10) {
893 | strPra = param.substring(0, 10);
894 | } else {
895 | strPra = "";
896 | }
897 | return strPra;
898 | }
899 |
900 | /**
901 | * To yyyy-MM-dd hh:mm:ss
902 | */
903 | public static final String timeFormat(String param) {
904 | String strPra = "";
905 | if (null == param) {
906 | strPra = "";
907 | } else if (param.length() >= 19) {
908 | strPra = param.substring(0, 19);
909 | } else {
910 | strPra = "";
911 | }
912 | return strPra;
913 | }
914 |
915 | /**
916 | * 按字节截取字符串前n个字节,不分开全角字符
917 | */
918 | public static String strSplit(String s, int n) {
919 | int d = n;
920 | int i = 0;
921 | while (i < s.length() && (d > 1 || (d == 1 && s.charAt(i) < 256))) {
922 | if (s.charAt(i) < 256) {
923 | d--;
924 | } else {
925 | d -= 2;
926 | }
927 | ++i;
928 | }
929 | return s.substring(0, i);
930 | }
931 |
932 | /**
933 | *
934 | * @param paraString
935 | * @param paraParmsList
936 | * @return
937 | */
938 | private String GetFullConstants(String paraString, String[] paraParmsList) {
939 | String result = paraString;
940 |
941 | for (int i = 0; i < paraParmsList.length; i++) {
942 | result = result.replaceAll("{" + i + "}", paraParmsList[i]);
943 | }
944 |
945 | return result;
946 | }
947 |
948 | /**
949 | * convert IP addr (such as 192.168.10.21) to long (192168010021) Some time,
950 | * CDN return IP as [202.23.45.134,211.45.23.101], which the first is cust's
951 | * IP and the second is CDN's supplier's proxy server. Then in case, we
952 | * parse the first one only.
953 | */
954 | public static long convertIP2Long(String ipAddr) {
955 |
956 | if (ipAddr == null || ipAddr.length() < 7)
957 | return -1;
958 |
959 | StringBuffer result = new StringBuffer();
960 |
961 | if (ipAddr.indexOf(",") > 6)
962 | ipAddr = ipAddr.substring(0, ipAddr.indexOf(","));
963 |
964 | StringTokenizer st = new StringTokenizer(ipAddr.trim(), ".");
965 | while (st.hasMoreElements()) {
966 | String pt = (String) st.nextElement();
967 | if (pt.length() == 1)
968 | result.append("00" + pt);
969 | else if (pt.length() == 2)
970 | result.append("0" + pt);
971 | else
972 | result.append(pt);
973 | }
974 | return Long.parseLong(result.toString());
975 | }
976 |
977 | /**
978 | * 对给定字符串以默认"UTF-8"编码方式解码一次
979 | *
980 | * @param input
981 | * 待解码字符串
982 | * @return 如果给定字符串input不为空,则返回以"UTF-8"方式解码一次后的字符串;否则原样返回
983 | * @author 11082829
984 | */
985 | public static String decodeString(String input) {
986 | return decodeString(input, "UTF-8");
987 | }
988 |
989 | /**
990 | * 对给定字符串以指定编码方式解码一次
991 | */
992 | public static String decodeString(String input, String encode) {
993 | String result = input;
994 | if (isNotEmpty(input)) {
995 | if (isEmpty(encode)) {
996 | encode = "UTF-8";
997 | }
998 | try {
999 | result = URLDecoder.decode(input, encode);
1000 | } catch (UnsupportedEncodingException e) {
1001 | result = input;
1002 | }
1003 | }
1004 | return result;
1005 | }
1006 |
1007 | /**
1008 | * 对给定字符串以指定编码方式、指定次数解码
1009 | */
1010 | public static String decodeString(String input, String encode, int times) {
1011 | if (times < 0) {
1012 | times = 1;
1013 | }
1014 |
1015 | String result = input;
1016 | if (isNotEmpty(input)) {
1017 | while (times-- > 0) {
1018 | result = decodeString(input, encode);
1019 | }
1020 | }
1021 |
1022 | return result;
1023 | }
1024 |
1025 | /**
1026 | * 获取两个时间相隔的天数
1027 | *
1028 | * @author 12060945
1029 | * @param start
1030 | * 开始的天数
1031 | * @param end
1032 | * 结束的天
1033 | * @return 返回的天数
1034 | */
1035 | public static long getDay(String start, String end) {
1036 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
1037 | // 得到毫秒数
1038 | long timeStart;
1039 | long timeEnd;
1040 | long dayCount = 0;
1041 | try {
1042 | timeStart = sdf.parse(start).getTime();
1043 | timeEnd = sdf.parse(end).getTime();
1044 | // 两个日期想减得到天数
1045 | dayCount = (timeEnd - timeStart) / (24 * 3600 * 1000);
1046 | } catch (ParseException e) {
1047 | log.error("getDay fail," + e.getMessage(), e);
1048 | }
1049 | return dayCount;
1050 | }
1051 |
1052 | /**
1053 | * 判断两个日期的大小
1054 | *
1055 | * @author 12060945
1056 | * @param DATE1
1057 | * @param DATE2
1058 | * @return
1059 | */
1060 | public static int compareDate(String DATE1, String DATE2) {
1061 |
1062 | DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
1063 | try {
1064 | Date dt1 = df.parse(DATE1);
1065 | Date dt2 = df.parse(DATE2);
1066 | if (dt1.getTime() > dt2.getTime()) {
1067 | return 1;
1068 | } else if (dt1.getTime() < dt2.getTime()) {
1069 | return -1;
1070 | } else {
1071 | return 0;
1072 | }
1073 | } catch (Exception exception) {
1074 | log.error("compareDate fail," + exception.getMessage(), exception);
1075 | }
1076 | return 0;
1077 | }
1078 |
1079 | /**
1080 | * get main domain by ServerName
1081 | *
1082 | * @param serverName
1083 | * @return
1084 | */
1085 | public static String getServerMainDomain(String serverName) {
1086 | String svrMainDomain = serverName;
1087 | String domainParts[] = svrMainDomain.split("\\.");
1088 | int svrPartCount = domainParts.length;
1089 | // if the is 3 parts in the server name, will need to compare the
1090 | // 2nd,3rd part only, for others, will compare all
1091 | if (svrPartCount >= 3) {
1092 | svrMainDomain = domainParts[svrPartCount - 2] + "." + domainParts[svrPartCount - 1];
1093 | }
1094 | return svrMainDomain;
1095 | }
1096 |
1097 | /**
1098 | * get the domain as String with url
1099 | *
1100 | * @param url
1101 | * @return
1102 | */
1103 | public static String getURLMainDomain(String url) {
1104 | String svr = url;
1105 | boolean isFullURL = false;
1106 | String METHODNAME = "getMainDomainString";
1107 | try {
1108 | // decode url, if the url is encoded
1109 | svr = URLDecoder.decode(url, "UTF-8");
1110 | } catch (UnsupportedEncodingException e) {
1111 | svr = url;
1112 | log.error("getURLMainDomain fail," + e.getMessage(), e);
1113 | }
1114 | // remove the protocal part, http,https, etc
1115 | // modify by caifa 2012-11-21 begin
1116 | if (svr.contains("http://") && svr.contains(".com")) {
1117 | svr = svr.substring(svr.indexOf("http://"), svr.indexOf(".com") + 4);
1118 | isFullURL = true;
1119 | } else if (svr.contains("http://") && svr.contains(".cn")) {
1120 | svr = svr.substring(svr.indexOf("http://"), svr.indexOf(".cn") + 3);
1121 | isFullURL = true;
1122 | } else if (svr.contains("https://") && svr.contains(".com")) {
1123 | svr = svr.substring(svr.indexOf("https://"), svr.indexOf(".com") + 4);
1124 | isFullURL = true;
1125 | } else if (svr.contains("https://") && svr.contains(".cn")) {
1126 | svr = svr.substring(svr.indexOf("https://"), svr.indexOf(".cn") + 3);
1127 | isFullURL = true;
1128 | }
1129 | // modify by caifa 2012-11-21 end
1130 |
1131 | svr = StringUtils.stripStart(svr, "https://");
1132 | svr = StringUtils.stripStart(svr, "http://");
1133 | // get the first part as server name
1134 | svr = svr.split("/")[0];
1135 | String svrMainDomain = svr;
1136 | // if is full url then start getting main domain, otherwise, return
1137 | // empty
1138 | // if all the svr name removes. is numbers, then the server is using IP,
1139 | // otherwise, only need to compare the last 2 part
1140 | if (isFullURL) {
1141 | if (!StringUtils.isNumeric(svr.replace(".", ""))) {
1142 | String domainParts[] = svr.split("\\.");
1143 | int svrPartCount = domainParts.length;
1144 | // if the is 3 parts in the server name, will need to compare
1145 | // the 2nd,3rd part only, for others, will compare all
1146 | if (svrPartCount >= 3) {
1147 | svrMainDomain = domainParts[svrPartCount - 2] + "." + domainParts[svrPartCount - 1];
1148 | }
1149 | }
1150 | } else {
1151 | svrMainDomain = "";
1152 | }
1153 |
1154 | return svrMainDomain;
1155 | }
1156 |
1157 | /**
1158 | * if url is allowed
1159 | *
1160 | * @param urlString
1161 | * @param allowDomain
1162 | * (*.suning.com,*.cnsuning.com)
1163 | * @return
1164 | */
1165 | public static boolean urlAccessAllowed(String domainString, String[] allowDomains) {
1166 | boolean allow = false;
1167 | for (int i = 0; i < allowDomains.length; i++) {
1168 | String s = allowDomains[i];
1169 | // generate regex
1170 | s = s.replace('.', '#');
1171 | s = s.replaceAll("#", "\\.");
1172 | s = s.replace('*', '#');
1173 | s = s.replaceAll("#", ".*");
1174 | s = s.replace('?', '#');
1175 | s = s.replaceAll("#", ".?");
1176 | s = "^" + s + "$";
1177 | ;
1178 | Pattern p = Pattern.compile(s);
1179 | Matcher m = p.matcher(domainString);
1180 | boolean b = m.matches();
1181 | if (b) {
1182 | allow = true;
1183 | break;
1184 | }
1185 | }
1186 |
1187 | return allow;
1188 |
1189 | }
1190 |
1191 | /**
1192 | *
1193 | * @param obj
1194 | */
1195 | public static boolean isNotEmptyWithoutNull(String obj) {
1196 | return obj != null && obj.trim().length() > 0 && !obj.contains("null");
1197 | }
1198 |
1199 | /**
1200 | *
1201 | * @param obj
1202 | * @return
1203 | */
1204 | public static boolean isEmptyWithoutNull(String obj) {
1205 | return !isNotEmptyWithoutNull(obj);
1206 | }
1207 |
1208 | /**
1209 | * timestamp 类型转换成date
1210 | *
1211 | * @param timestamp
1212 | * @return
1213 | */
1214 | public static Date convertTimeStampToDate(Timestamp timestamp) {
1215 | String methodName = "convertStringToTimeStamp";
1216 | if (timestamp == null) {
1217 | return null;
1218 | }
1219 |
1220 | SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1221 | String times = df.format(timestamp);
1222 | Date date = null;
1223 | try {
1224 | date = df.parse(times);
1225 | } catch (ParseException e) {
1226 | }
1227 | return date;
1228 |
1229 | }
1230 |
1231 | public static String getPhoneVerification(int limit) {
1232 | Random random = new Random();
1233 | StringBuilder sb = new StringBuilder();
1234 | for (int i = 0; i < limit; i++) {
1235 | sb.append(random.nextInt(10));
1236 | }
1237 | return sb.toString();
1238 | }
1239 |
1240 | /**
1241 | * 重要个人信息(手机号码、身份证号码、邮箱)以星号代替
1242 | *
1243 | * @param num
1244 | * @return
1245 | */
1246 | public static String secreteSensitiveNum(String num) {
1247 | if (isEmpty(num)) {
1248 | return num;
1249 | }
1250 |
1251 | if (num.contains("@")) { // 邮箱email
1252 | int iAt = num.indexOf("@");
1253 | int oriLen = 3;
1254 | if (iAt <= 3) {
1255 | oriLen = 1;
1256 | }
1257 | int starArrayLen = num.substring(0, iAt - oriLen).length();
1258 | char[] starArray = new char[starArrayLen];
1259 | for (int i = 0; i < starArray.length; i++) {
1260 | starArray[i] = '*';
1261 | }
1262 | String starStr = String.valueOf(starArray);
1263 | StringBuilder sb = new StringBuilder();
1264 | sb.append(starStr).append(num.substring(iAt - oriLen, iAt)).append(num.substring(iAt));
1265 |
1266 | return sb.toString();
1267 | } else if (num.length() == 11) { // 手机号码
1268 | StringBuilder sb = new StringBuilder();
1269 | sb.append(num.substring(0, 3)).append("****").append(num.substring(7));
1270 |
1271 | return sb.toString();
1272 | } else if (num.length() == 15 || num.length() == 18) { // 身份证号码
1273 | StringBuilder sb = new StringBuilder();
1274 | sb.append(num.substring(0, 3)).append(num.length() == 15 ? "********" : "***********")
1275 | .append(num.substring(num.length() - 4));
1276 |
1277 | return sb.toString();
1278 | }
1279 |
1280 | return num;
1281 | }
1282 |
1283 | }
--------------------------------------------------------------------------------