> entry : paramMap.entrySet()) {
48 | params.add(entry.getKey(), entry.getValue());
49 | }
50 | }
51 | return params;
52 | } catch (Exception e) {
53 | return new CaseInsensitiveHeaders();
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/common/ParamCheckUtil.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.common;
2 |
3 | import io.vertx.core.json.EncodeException;
4 | import io.vertx.core.json.Json;
5 |
6 | /**
7 | * 参数检查工具
8 | *
9 | * @author Mirren
10 | *
11 | */
12 | public class ParamCheckUtil {
13 | /**
14 | * 检查是否为int类型的数据,
15 | *
16 | * @param obj
17 | * @return
18 | */
19 | public static boolean isInt(String obj) {
20 | try {
21 | Integer.valueOf(obj);
22 | return true;
23 | } catch (NumberFormatException e) {
24 | return false;
25 | }
26 | }
27 |
28 | /**
29 | * 检查是否为int类型的数据,
30 | *
31 | * @param obj
32 | * @return
33 | */
34 | public static boolean isInt(Object obj) {
35 | try {
36 | Integer.valueOf(obj.toString());
37 | return true;
38 | } catch (NumberFormatException e) {
39 | return false;
40 | }
41 | }
42 |
43 | /**
44 | * 检查是否为Long类型的数据,
45 | *
46 | * @param obj
47 | * @return
48 | */
49 | public static boolean isLong(String obj) {
50 | try {
51 | Long.valueOf(obj);
52 | return true;
53 | } catch (NumberFormatException e) {
54 | return false;
55 | }
56 | }
57 |
58 | /**
59 | * 检查否为Long类型的数据,
60 | *
61 | * @param obj
62 | * @return
63 | */
64 | public static boolean isLong(Object obj) {
65 | try {
66 | Long.valueOf(obj.toString());
67 | return true;
68 | } catch (NumberFormatException e) {
69 | return false;
70 | }
71 | }
72 |
73 | /**
74 | * 检查是否为Float类型的数据,
75 | *
76 | * @param obj
77 | * @return
78 | */
79 | public static boolean isFloat(String obj) {
80 | try {
81 | Float.valueOf(obj);
82 | return true;
83 | } catch (NumberFormatException e) {
84 | return false;
85 | }
86 | }
87 |
88 | /**
89 | * 检查是否为Float类型的数据,
90 | *
91 | * @param obj
92 | * @return
93 | */
94 | public static boolean isFloat(Object obj) {
95 | try {
96 | Float.valueOf(obj.toString());
97 | return true;
98 | } catch (NumberFormatException e) {
99 | return false;
100 | }
101 | }
102 |
103 | /**
104 | * 检查是否为Double类型的数据,
105 | *
106 | * @param obj
107 | * @return
108 | */
109 | public static boolean isDouble(String obj) {
110 | try {
111 | Double.valueOf(obj);
112 | return true;
113 | } catch (NumberFormatException e) {
114 | return false;
115 | }
116 | }
117 |
118 | /**
119 | * 检查是否为Double类型的数据,
120 | *
121 | * @param obj
122 | * @return
123 | */
124 | public static boolean isDouble(Object obj) {
125 | try {
126 | Double.valueOf(obj.toString());
127 | return true;
128 | } catch (NumberFormatException e) {
129 | return false;
130 | }
131 | }
132 |
133 | /**
134 | * 检查是否为Boolean数据
135 | *
136 | * @param obj
137 | * @return
138 | */
139 | public static boolean isBoolean(String obj) {
140 | return (obj != null && (obj.equals("true") || obj.equals("false")));
141 | }
142 |
143 | /**
144 | * 检查字符串是否为Boolean数据
145 | *
146 | * @param obj
147 | * @return
148 | */
149 | public static boolean isBoolean(Object obj) {
150 | return (obj != null && (obj.equals("true") || obj.equals("false")));
151 | }
152 |
153 | /**
154 | * 检查是否为json格式
155 | *
156 | * @param obj
157 | * @return
158 | */
159 | public static boolean isJosn(Object obj) {
160 | try {
161 | Json.encode(obj);
162 | return true;
163 | } catch (EncodeException e) {
164 | return false;
165 | }
166 | }
167 | }
168 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/common/PathUtil.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.common;
2 |
3 | import java.io.File;
4 | import java.io.InputStream;
5 | import java.net.URL;
6 | import java.nio.file.Path;
7 |
8 | /**
9 | * 获取相应路径的工具
10 | *
11 | * @author Mirren
12 | *
13 | */
14 | public class PathUtil {
15 | /**
16 | * 判断是否在jar环境中运行
17 | *
18 | * @return 是返回true
19 | */
20 | public static boolean isJarEnv() {
21 | return PathUtil.class.getResource("").getPath().contains(".jar!");
22 | }
23 |
24 | /**
25 | * 判断是否在jar环境中运行
26 | *
27 | * @return 是返回true
28 | */
29 | public static boolean isJarEnv(String fileName) {
30 | return Thread.currentThread().getContextClassLoader().getResource(fileName).getPath().contains(".jar!");
31 | }
32 |
33 | /**
34 | * 获得根目录如果在jar中运行获得相对路径,反则返回当前线程运行的根目录
35 | *
36 | * @param name
37 | * @return
38 | */
39 | public static String getPathString(String fileName) {
40 | if (fileName == null) {
41 | throw new NullPointerException("文件名字不能为空");
42 | }
43 | URL path = Thread.currentThread().getContextClassLoader().getResource(fileName);
44 | if (path != null && path.getPath().contains(".jar!")) {
45 | return fileName;
46 | } else {
47 | String result = path == null ? "" : path.getPath();
48 | return result;
49 | }
50 | }
51 |
52 | /**
53 | * 通过名字获得项目的Path文件
54 | *
55 | * @param fileName
56 | * @return
57 | */
58 | public static Path getPath(String fileName) {
59 | File file = new File(PathUtil.getPathString(fileName));
60 | return file.toPath();
61 | }
62 |
63 | /**
64 | * 获得资源的流
65 | *
66 | * @param fileName
67 | * @return
68 | */
69 | public static InputStream getStream(String fileName) {
70 | if (fileName == null) {
71 | throw new NullPointerException("文件名字不能为空");
72 | }
73 | return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
74 | }
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/common/ResultFormat.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.common;
2 |
3 | import com.szmirren.vxApi.core.enums.HTTPStatusCodeMsgEnum;
4 |
5 | import io.vertx.core.json.JsonArray;
6 | import io.vertx.core.json.JsonObject;
7 |
8 | /**
9 | * 将StatusCodeMsg转换为返回json
10 | * 返回结果
11 | * status : 状态码
12 | * msg : 信息
13 | * data : 数据
14 | *
15 | * @author Mirren
16 | *
17 | */
18 | public class ResultFormat {
19 | /**
20 | * 格式化返回结果,code为状态码枚举类,data为数据
21 | *
22 | * @param code
23 | * @param data
24 | * @return
25 | */
26 | public static String format(HTTPStatusCodeMsgEnum code, Object data) {
27 | ResultFormatObj result = new ResultFormatObj(code.getCode(), code.getMsg(), data);
28 | return result.toJsonStr();
29 | }
30 |
31 | /**
32 | * 格式化返回结果,code为状态码枚举类,data为数据
33 | *
34 | * @param code
35 | * @param data
36 | * @return
37 | */
38 | public static String format(HTTPStatusCodeMsgEnum code, JsonArray data) {
39 | JsonObject result = new JsonObject();
40 | result.put("status", code.getCode());
41 | result.put("msg", code.getMsg());
42 | if (data == null) {
43 | data = new JsonArray();
44 | }
45 | result.put("data", data);
46 | return result.toString();
47 | }
48 |
49 | /**
50 | * 格式化返回结果,code为状态码枚举类,data为数据
51 | *
52 | * @param code
53 | * @param data
54 | * @return
55 | */
56 | public static String format(HTTPStatusCodeMsgEnum code, JsonObject data) {
57 | JsonObject result = new JsonObject();
58 | result.put("status", code.getCode());
59 | result.put("msg", code.getMsg());
60 | if (data == null) {
61 | data = new JsonObject();
62 | }
63 | result.put("data", data);
64 | return result.toString();
65 | }
66 |
67 | /**
68 | * 格式化返回结果其中data为null,code为状态码枚举类
69 | *
70 | * @param code
71 | * @return
72 | */
73 | public static String formatAsNull(HTTPStatusCodeMsgEnum code) {
74 | JsonObject result = new JsonObject();
75 | result.put("status", code.getCode());
76 | result.put("msg", code.getMsg());
77 | result.putNull("data");
78 | return result.toString();
79 | }
80 |
81 | /**
82 | * 格式化返回结果其中data为{},code为状态码枚举类
83 | *
84 | * @param code
85 | * @return
86 | */
87 | public static String formatAsNewJson(HTTPStatusCodeMsgEnum code) {
88 | JsonObject result = new JsonObject();
89 | result.put("status", code.getCode());
90 | result.put("msg", code.getMsg());
91 | result.put("data", new JsonObject());
92 | return result.toString();
93 | }
94 |
95 | /**
96 | * 格式化返回结果其中data为[],code为状态码枚举类
97 | *
98 | * @param code
99 | * @return
100 | */
101 | public static String formatAsNewArray(HTTPStatusCodeMsgEnum code) {
102 | JsonObject result = new JsonObject();
103 | result.put("status", code.getCode());
104 | result.put("msg", code.getMsg());
105 | result.put("data", new JsonArray());
106 | return result.toString();
107 | }
108 |
109 | /**
110 | * 格式化返回结果其中data为0,code为状态码枚举类
111 | *
112 | * @param code
113 | * @return
114 | */
115 | public static String formatAsZero(HTTPStatusCodeMsgEnum code) {
116 | JsonObject result = new JsonObject();
117 | result.put("status", code.getCode());
118 | result.put("msg", code.getMsg());
119 | result.put("data", 0);
120 | return result.toString();
121 | }
122 |
123 | /**
124 | * 格式化返回结果其中data为1,code为状态码枚举类
125 | *
126 | * @param code
127 | * @return
128 | */
129 | public static String formatAsOne(HTTPStatusCodeMsgEnum code) {
130 | JsonObject result = new JsonObject();
131 | result.put("status", code.getCode());
132 | result.put("msg", code.getMsg());
133 | result.put("data", 1);
134 | return result.toString();
135 | }
136 |
137 | /**
138 | * 自定义返回结果
139 | *
140 | * @param formatObj
141 | * @return
142 | */
143 | public static String formatCustom(ResultFormatObj formatObj) {
144 | return formatObj.toJsonStr();
145 | }
146 |
147 | }
148 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/common/ResultFormatObj.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.common;
2 |
3 | import io.vertx.core.json.Json;
4 |
5 | /**
6 | *
7 | * @author Mirren
8 | *
9 | */
10 | public class ResultFormatObj {
11 | private int status;// 状态码
12 | private String msg;// 信息
13 | private Object data;// 数据
14 |
15 | public String getMsg() {
16 | return msg;
17 | }
18 |
19 | public void setMsg(String msg) {
20 | this.msg = msg;
21 | }
22 |
23 | public int getStatus() {
24 | return status;
25 | }
26 |
27 | public void setStatus(int status) {
28 | this.status = status;
29 | }
30 |
31 | public Object getData() {
32 | return data;
33 | }
34 |
35 | public void setData(Object data) {
36 | this.data = data;
37 | }
38 |
39 | public String toJsonStr() {
40 | return Json.encode(this);
41 | }
42 |
43 | public ResultFormatObj() {
44 | super();
45 | }
46 |
47 | public ResultFormatObj(int status, String msg, Object data) {
48 | super();
49 | this.msg = msg;
50 | this.status = status;
51 | this.data = data;
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/common/VxApiApplicationConverter.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.common;
2 |
3 | import com.szmirren.vxApi.core.options.VxApiApplicationOptions;
4 | import com.szmirren.vxApi.core.options.VxApiCorsOptions;
5 | import com.szmirren.vxApi.core.options.VxApiServerOptions;
6 |
7 | import io.vertx.core.json.Json;
8 | import io.vertx.core.json.JsonObject;
9 |
10 | /**
11 | * 该类主要用于处理VxAPIApplication的json装换
12 | *
13 | * @author Mirren
14 | *
15 | */
16 | public class VxApiApplicationConverter {
17 |
18 | public static void fromJson(JsonObject json, VxApiApplicationOptions obj) {
19 | if (json.getValue("appName") instanceof String) {
20 | obj.setAppName((String) json.getValue("appName"));
21 | }
22 | if (json.getValue("describe") instanceof String) {
23 | obj.setDescribe((String) json.getValue("describe"));
24 | }
25 | if (json.getValue("contentLength") instanceof Number) {
26 | obj.setContentLength(((Number) json.getValue("contentLength")).longValue());
27 | }
28 | if (json.getValue("scope") instanceof Number) {
29 | obj.setScope(((Number) json.getValue("scope")).intValue());
30 | }
31 | if (json.getValue("sessionTimeOut") instanceof Number) {
32 | obj.setSessionTimeOut(((Number) json.getValue("sessionTimeOut")).longValue());
33 | }
34 | if (json.getValue("sessionCookieName") instanceof String) {
35 | obj.setSessionCookieName((String) json.getValue("sessionCookieName"));
36 | }
37 | if (json.getValue("portOptions") instanceof JsonObject) {
38 | obj.setServerOptions(
39 | Json.decodeValue(json.getJsonObject("portOptions").toString(), VxApiServerOptions.class));
40 | }
41 | if (json.getValue("corsOptions") instanceof JsonObject) {
42 | obj.setCorsOptions(Json.decodeValue(json.getJsonObject("corsOptions").toString(), VxApiCorsOptions.class));
43 | }
44 | }
45 |
46 | public static void toJson(VxApiApplicationOptions obj, JsonObject json) {
47 | json.put("scope", obj.getScope());
48 | json.put("sessionTimeOut", obj.getSessionTimeOut());
49 | json.put("sessionCookieName", obj.getSessionCookieName());
50 | json.put("portOptions", Json.encode(obj.getServerOptions()));
51 | json.put("contentLength", obj.getContentLength());
52 | if (obj.getAppName() != null) {
53 | json.put("appName", obj.getAppName());
54 | }
55 | if (obj.getDescribe() != null) {
56 | json.put("describe", obj.getDescribe());
57 | }
58 | if (obj.getCorsOptions() != null) {
59 | json.put("corsOptions", Json.encode(obj.getCorsOptions()));
60 | }
61 |
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/common/VxApiDATAStoreConstant.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.common;
2 |
3 | /**
4 | * 该类主要用于存放应用网关与API数据存储于传输的关键字,主要用于方便自己存储网关数据到自己的数据库中
5 | *
6 | * 应用网关存储的表结构:
7 | *
8 | * - 表名 = APPLICATION_TABLE_NAME 存放网关应用的表名
9 | * - 主键列 = APPLICATION_ID_COLUMN 字符串用于存放应用网关的名字
10 | * - 内容列 = APPLICATION_ID_COLUMN json字符串用于存放应用网关的名字
11 | *
12 | *
13 | * 应用网关属性在传输中的名字:
14 | *
15 | * - 主键 = APPLICATION_ID_NAME 主键在json中的名字
16 | * - 内容 = APPLICATION_CONTENT_COLUMN 内容在json中的名字
17 | *
18 | *
19 | * API存储的表结构:
20 | *
21 | * - 表名 = API_TABLE_NAME 存放API的表名
22 | * - 主键列 = API_ID_COLUMN 字符串用于存放API的名字
23 | * - 应用网关主键列 = API_APP_ID_COLUMN 字符串用于存放API的名字
24 | * - 内容列 = API_CONTENT_COLUMN json字符串用于存放API的名字
25 | *
26 | *
27 | * API属性在传输中的名字:
28 | *
29 | * - 主键 = API_ID_NAME 主键在json中的名字
30 | * - 主键 = API_APP_ID_NAME 应用网关主键在json中的名字
31 | * - 内容 = API_CONTENT_NAME 内容在json中的名字
32 | *
33 | *
34 | * 黑名单列表的表结构:(系统默认取黑名单列表第一行数据,)
35 | *
36 | * - 表名 = BLACKLIST_TABLE_NAME 存放网关应用的黑名单的表名
37 | * - 主键列 = BLACKLIST_ID_COLUMN 字符串用于存放应用网关黑名单主键的名字
38 | * - 内容列 = BLACKLIST_ID_COLUMN json数组字符串用于存放应用网关黑名单内容的名字
39 | *
40 | *
41 | * 黑名单列表在传输中的名字:
42 | *
43 | * - 主键 = BLACKLIST_ID_NAME 黑名单主键在json中的名字
44 | * - 内容 = BLACKLIST_CONTENT_COLUMN 黑名单内容在json中的名字
45 | *
46 | *
47 | *
48 | * @author Mirren
49 | *
50 | */
51 | public interface VxApiDATAStoreConstant {
52 | // ==============================================
53 | // ==================应用网关表结构=================
54 | // ==============================================
55 | /**
56 | * 网关应用的表名
57 | */
58 | static final String APPLICATION_TABLE_NAME = "vx_api_application";
59 | /**
60 | * 网关应用的主键列
61 | */
62 | static final String APPLICATION_ID_COLUMN = "name";
63 | /**
64 | * 网关应用json字符串内容的列名
65 | */
66 | static final String APPLICATION_CONTENT_COLUMN = "content";
67 |
68 | // ==================应用网关传输中获取内容的名字=================
69 | /**
70 | * 网关应用通讯传输中获取json中存放主键的属性名
71 | */
72 | static final String APPLICATION_ID_NAME = "name";
73 | /**
74 | * 网关应用通讯传输中获取json中存放json字符串对象的属性名
75 | */
76 | static final String APPLICATION_CONTENT_NAME = "content";
77 |
78 | // ==============================================
79 | // ==================API表结构====================
80 | // ==============================================
81 |
82 | /**
83 | * 存放API的表名
84 | */
85 | static final String API_TABLE_NAME = "vx_api_apis";
86 | /**
87 | * 存放API的主键列
88 | */
89 | static final String API_ID_COLUMN = "name";
90 | /**
91 | * 存放API表中网关应用主键的列
92 | */
93 | static final String API_APP_ID_COLUMN = "app_name";
94 | /**
95 | * 存放API,json字符串内容的列名
96 | */
97 | static final String API_CONTENT_COLUMN = "content";
98 |
99 | // ==================API传输中获取内容的名字=================
100 |
101 | /**
102 | * API通讯传输中获取json中存放主键的属性名
103 | */
104 | static final String API_ID_NAME = "name";
105 | /**
106 | * API通讯传输中获取json中存放应用网关主键的属性名
107 | */
108 | static final String API_APP_ID_NAME = "appName";
109 | /**
110 | * API通讯传输中获取json中存放json字符串对象的属性名
111 | */
112 | static final String API_CONTENT_NAME = "content";
113 |
114 | // ==============================================
115 | // ==================黑名单列表表结构================
116 | // ==============================================
117 | /**
118 | * 黑名单列表的表名
119 | */
120 | static final String BLACKLIST_TABLE_NAME = "vx_api_blacklist";
121 | /**
122 | * 黑名单列表的主键列
123 | */
124 | static final String BLACKLIST_ID_COLUMN = "name";
125 | /**
126 | * 黑名单列表jsonArray字符串内容的列名
127 | */
128 | static final String BLACKLIST_CONTENT_COLUMN = "content";
129 |
130 | // ==================应用网关传输中获取内容的名字=================
131 | /**
132 | * 黑名单列表通讯传输中获取json中存放主键的属性名
133 | */
134 | static final String BLACKLIST_ID_NAME = "blacklist";
135 | /**
136 | * 黑名单列表通讯传输中获取json中存放json字符串对象的属性名
137 | */
138 | static final String BLACKLIST_CONTENT_NAME = "content";
139 |
140 | }
141 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/common/VxApiGatewayAttribute.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.common;
2 |
3 | /**
4 | * 存储VxApiGateway常用的属性
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public interface VxApiGatewayAttribute {
10 | /**
11 | * 网关的名字
12 | */
13 | static final String NAME = "VX-API";
14 | /**
15 | * 网关的全名
16 | */
17 | static final String FULL_NAME = "VX-API-Gateway";
18 | /**
19 | * VxApiGateway版本号
20 | */
21 | static final String VERSION = "1.0.3";
22 | /**
23 | * session默认的cookie名字
24 | */
25 | static final String SESSION_COOKIE_NAME = "VX-API.session";
26 | /**
27 | * 网关userAgent默认名字
28 | */
29 | static final String VX_API_USER_AGENT = "VX-API-Gateway/" + VERSION;
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/common/VxApiRequestBodyHandler.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.common;
2 |
3 | import com.szmirren.vxApi.core.entity.VxApiContentType;
4 |
5 | import io.vertx.core.Handler;
6 | import io.vertx.core.MultiMap;
7 | import io.vertx.core.buffer.Buffer;
8 | import io.vertx.core.http.CaseInsensitiveHeaders;
9 | import io.vertx.core.json.JsonObject;
10 | /**
11 | * 用户请求的body主体解析工具
12 | * 当前只解析Content-type=Null或者Urlencoded
13 | *
14 | * @author Mirren
15 | *
16 | */
17 | public class VxApiRequestBodyHandler implements Handler {
18 | /** 用户请求的body参数 */
19 | private MultiMap body = new CaseInsensitiveHeaders();
20 | /** 用户请求的body长度 */
21 | private long bodyLength;
22 | /** 用户请求的contentType */
23 | private VxApiContentType contentType;
24 | /** 请求体的最大限制长度小于=0代表无限 */
25 | private long maxContentLength;
26 | /** 用户请求的数据Buffer */
27 | private Buffer bodyBuffer = Buffer.buffer();
28 | /**
29 | * 实例化一个用户请求bodyhandler
30 | *
31 | * @param contentType
32 | * @param maxContentLength
33 | */
34 | public VxApiRequestBodyHandler(VxApiContentType contentType, long maxContentLength) {
35 | super();
36 | this.contentType = contentType;
37 | this.maxContentLength = maxContentLength;
38 | }
39 |
40 | @Override
41 | public void handle(Buffer buffer) {
42 | // 如果buffer为null或者不是支持解析的类型则返回
43 | if (buffer == null || !contentType.isDecodedSupport()) {
44 | return;
45 | }
46 | bodyLength += buffer.length();
47 | if (maxContentLength > 0 && bodyLength > maxContentLength) {
48 | return;
49 | }
50 | bodyBuffer.appendBuffer(buffer);
51 | }
52 | /**
53 | * 获得body的参数
54 | *
55 | * @return 返回一个不为null的MultiMap
56 | */
57 | public MultiMap getBody() {
58 | if (contentType.isApplicationJson()) {
59 | try {
60 | JsonObject object = new JsonObject(bodyBuffer);
61 | if (object.getMap() != null) {
62 | object.getMap().forEach((k, v) -> {
63 | body.add(k, v.toString());
64 | });
65 | }
66 | } catch (Exception e) {
67 | }
68 | } else if (contentType.isUrlencoded()) {
69 | MultiMap decoderUriParams = HttpUtils.decoderUriParams(bodyBuffer.toString(), contentType.getCharset());
70 | if (decoderUriParams != null) {
71 | body.addAll(decoderUriParams);
72 | }
73 | }
74 | return body;
75 | }
76 |
77 | /**
78 | * 获得body的长度
79 | *
80 | * @return
81 | */
82 | public long getBodyLength() {
83 | return bodyLength;
84 | }
85 | /**
86 | * 获得是否超过最大Content-Length限定
87 | *
88 | * @return 超过返回true , 不超过返回false
89 | */
90 | public boolean isExceededMaxLen() {
91 | return maxContentLength > 0 && bodyLength > maxContentLength;
92 | }
93 |
94 | @Override
95 | public String toString() {
96 | return "VxApiRequestBodyHandler [body=" + body + ", bodyLength=" + bodyLength + ", contentType=" + contentType + ", maxContentLength="
97 | + maxContentLength + "]";
98 | }
99 |
100 | }
101 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/entity/VxApiAPILimit.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.entity;
2 |
3 | import java.time.Instant;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | /**
8 | * 流量监控
9 | *
10 | * @author Mirren
11 | *
12 | */
13 | public class VxApiAPILimit {
14 | private Instant timePoints = Instant.now();// 统计时间
15 | private Map userIpCurPoints = new HashMap<>();// 用户ip统计
16 | private long ipTop = -1;// ip限制的数量
17 | private long apiTop = -1;// api的限制数量
18 | private long curPoint;// 当前的数量
19 |
20 | /**
21 | * 创建一个流量限制
22 | *
23 | * @param ipTop
24 | * IP最大数
25 | * @param apiTop
26 | * api最大数
27 | */
28 | public VxApiAPILimit(long ipTop, long apiTop) {
29 | super();
30 | this.ipTop = ipTop;
31 | this.apiTop = apiTop;
32 | }
33 |
34 | /**
35 | * 得到统计的时间
36 | *
37 | * @return
38 | */
39 | public Instant getTimePoints() {
40 | return timePoints;
41 | }
42 |
43 | /**
44 | * 设置统计时间
45 | *
46 | * @param timePoints
47 | */
48 | public void setTimePoints(Instant timePoints) {
49 | this.timePoints = timePoints;
50 | }
51 |
52 | /**
53 | * 获得当前连接的用户
54 | *
55 | * @return
56 | */
57 | public Map getUserIpCurPoints() {
58 | return userIpCurPoints;
59 | }
60 |
61 | /**
62 | * 设置当前连接的用户
63 | *
64 | * @param userIpCurPoints
65 | */
66 | public void setUserIpCurPoints(Map userIpCurPoints) {
67 | this.userIpCurPoints = userIpCurPoints;
68 | }
69 |
70 | /**
71 | * 给当前连接用户连接数添加一个新用户,如果存在该用户将用户数据重置
72 | *
73 | * @param ip
74 | * @param points
75 | */
76 | public void addUserIpCurPotints(String ip, long points) {
77 | this.userIpCurPoints.put(ip, points);
78 | }
79 |
80 | /**
81 | * 得到IP的最大限制数
82 | *
83 | * @return
84 | */
85 | public long getIpTop() {
86 | return ipTop;
87 | }
88 |
89 | /**
90 | * 设置IP的最大限制数,-1表示无限
91 | *
92 | * @param ipTop
93 | */
94 | public void setIpTop(long ipTop) {
95 | this.ipTop = ipTop;
96 | }
97 |
98 | /**
99 | * 得到API的最大限制数
100 | *
101 | * @return
102 | */
103 | public long getApiTop() {
104 | return apiTop;
105 | }
106 |
107 | /**
108 | * 设置API的最大限制数,-1表示无限
109 | *
110 | * @param apiTop
111 | */
112 | public void setApiTop(long apiTop) {
113 | this.apiTop = apiTop;
114 | }
115 |
116 | /**
117 | * 得到当前连接的人数
118 | *
119 | * @return
120 | */
121 | public long getCurPoint() {
122 | return curPoint;
123 | }
124 |
125 | /**
126 | * 设置当前连接的人数
127 | *
128 | * @param curPoint
129 | */
130 | public void setCurPoint(long curPoint) {
131 | this.curPoint = curPoint;
132 | }
133 |
134 | @Override
135 | public String toString() {
136 | return "VxApiAPILimit [timePoints=" + timePoints + ", userIpCurPoints=" + userIpCurPoints + ", ipTop=" + ipTop
137 | + ", apiTop=" + apiTop + ", curPoint=" + curPoint + "]";
138 | }
139 |
140 | }
141 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/entity/VxApiApiEntrance.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.entity;
2 |
3 | import java.util.List;
4 |
5 | import com.szmirren.vxApi.core.enums.HttpMethodEnum;
6 |
7 | /**
8 | * VxApi的入口
9 | *
10 | * @author Mirren
11 | *
12 | */
13 | public class VxApiApiEntrance {
14 | private String path;// 请求路径
15 | private List methods;// 请求的方法
16 | private List paramOptions;// 参数的配置
17 |
18 | public VxApiApiEntrance() {
19 | super();
20 | }
21 |
22 | public VxApiApiEntrance(String path, List methods, List paramOptions) {
23 | super();
24 | this.path = path;
25 | this.methods = methods;
26 | this.paramOptions = paramOptions;
27 | }
28 |
29 | public String getPath() {
30 | return path;
31 | }
32 |
33 | public void setPath(String path) {
34 | this.path = path;
35 | }
36 |
37 | public List getMethods() {
38 | return methods;
39 | }
40 |
41 | public void setMethods(List methods) {
42 | this.methods = methods;
43 | }
44 |
45 | public List getParamOptions() {
46 | return paramOptions;
47 | }
48 |
49 | public void setParamOptions(List paramOptions) {
50 | this.paramOptions = paramOptions;
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/entity/VxApiContentType.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.entity;
2 |
3 | import java.nio.charset.Charset;
4 |
5 | public class VxApiContentType {
6 |
7 | private String contentType;
8 | private String boundary;
9 | private Charset charset;
10 |
11 | /**
12 | * 通过Content-Type字符串初始一个ContentType对象
13 | *
14 | * @param contentType
15 | */
16 | public VxApiContentType(String contentType) {
17 | super();
18 | if (contentType != null) {
19 | init(contentType);
20 | }
21 | }
22 |
23 | /**
24 | * 初始化
25 | *
26 | * @param contentType
27 | */
28 | public void init(String contentType) {
29 | String[] item = contentType.split(";");
30 | this.contentType = item[0];
31 | if (item.length > 1) {
32 | if (item[1].indexOf("=") != -1) {
33 | String[] split = item[1].split("=");
34 | initVar(split[0].trim(), split[1].trim());
35 | }
36 | }
37 | if (item.length > 2) {
38 | if (item[2].indexOf("=") != -1) {
39 | String[] split = item[1].split("=");
40 | initVar(split[0].trim(), split[1].trim());
41 | }
42 | }
43 | }
44 |
45 | /**
46 | * 根据类型进行初始化数据
47 | *
48 | * @param type
49 | * @param value
50 | */
51 | public void initVar(String type, String value) {
52 | if ("charset".equalsIgnoreCase(type)) {
53 | try {
54 | this.charset = Charset.forName(value);
55 | } catch (Exception e) {
56 | e.printStackTrace();
57 | }
58 | } else if ("boundary".equalsIgnoreCase(type)) {
59 | this.boundary = value;
60 | }
61 | }
62 |
63 | /**
64 | * 判断Content-Type类型是否支持解析
65 | *
66 | * @return
67 | */
68 | public boolean isDecodedSupport() {
69 | return (isUrlencoded() || isApplicationJson());
70 | }
71 |
72 | /**
73 | * Content-Type是否为:null或者application/x-www-form-urlencoded
74 | *
75 | * @return
76 | */
77 | public boolean isNullOrUrlencoded() {
78 | return contentType == null || "application/x-www-form-urlencoded".equalsIgnoreCase(contentType);
79 | }
80 |
81 | /**
82 | * Content-Type是否为:application/x-www-form-urlencoded
83 | *
84 | * @return
85 | */
86 | public boolean isUrlencoded() {
87 | return "application/x-www-form-urlencoded".equalsIgnoreCase(contentType);
88 | }
89 |
90 | /**
91 | * Content-Type是否为:multipart/form-data
92 | *
93 | * @return
94 | */
95 | public boolean isFormData() {
96 | return "multipart/form-data".equalsIgnoreCase(contentType);
97 | }
98 |
99 | /**
100 | * Content-Type是否为:application/json
101 | *
102 | * @return
103 | */
104 | public boolean isApplicationJson() {
105 | return "application/json".equalsIgnoreCase(contentType);
106 | }
107 |
108 | /**
109 | * 获得content类型
110 | *
111 | * @return
112 | */
113 | public String getContentType() {
114 | return contentType;
115 | }
116 |
117 | /**
118 | * 获得Boundary
119 | *
120 | * @return
121 | */
122 | public String getBoundary() {
123 | return boundary;
124 | }
125 |
126 | /**
127 | * 获得字符编码
128 | *
129 | * @return
130 | */
131 | public Charset getCharset() {
132 | return charset;
133 | }
134 |
135 | /**
136 | * 设置content类型
137 | *
138 | * @param contentType
139 | */
140 | public void setContentType(String contentType) {
141 | this.contentType = contentType;
142 | }
143 | /**
144 | * 设置Boundary
145 | *
146 | * @param boundary
147 | */
148 | public void setBoundary(String boundary) {
149 | this.boundary = boundary;
150 | }
151 | /**
152 | * 设置字符编码
153 | *
154 | * @param charset
155 | */
156 | public void setCharset(Charset charset) {
157 | this.charset = charset;
158 | }
159 |
160 | @Override
161 | public String toString() {
162 | return "VxApiContentType [contentType=" + contentType + ", boundary=" + boundary + ", charset=" + charset + "]";
163 | }
164 |
165 | }
166 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/entity/VxApiDeployInfos.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.entity;
2 |
3 | import com.szmirren.vxApi.core.options.VxApiServerOptions;
4 |
5 | /**
6 | * 存储已经部署的应用信息
7 | *
8 | * @author Mirren
9 | *
10 | */
11 | public class VxApiDeployInfos {
12 | private String appName;// 应用的名称
13 | private String deployId;// 应用的部署id
14 | private Integer httpPort;// HTTP服务器的端口号
15 | private Integer httpsPort;// HTTPS服务器的端口号
16 | private Integer webSocketPort;// WebSocket服务器的端口号
17 | /**
18 | * 实例化一个没有属性的部署信息
19 | */
20 | public VxApiDeployInfos() {
21 | super();
22 | }
23 | /**
24 | * 实例化一个部署信息
25 | *
26 | * @param appName
27 | * 应用的名字
28 | * @param deployId
29 | * 部署的id
30 | * @param options
31 | * 服务器配置信息
32 | */
33 | public VxApiDeployInfos(String appName, String deployId, VxApiServerOptions options) {
34 | super();
35 | this.appName = appName;
36 | this.deployId = deployId;
37 | if (options != null) {
38 | if (options.isCreateHttp()) {
39 | this.httpPort = options.getHttpPort();
40 | }
41 | if (options.isCreateHttps()) {
42 | this.httpsPort = options.getHttpsPort();
43 | }
44 | if (options.isCreatewebSocket()) {
45 | this.webSocketPort = options.getWebSocketPort();
46 | }
47 | }
48 | }
49 | /**
50 | * 实例化一个部署信息
51 | *
52 | * @param appName
53 | * 应用的名字
54 | * @param deployId
55 | * 部署的id
56 | * @param httpPort
57 | * http服务器端口号
58 | * @param httpsPort
59 | * https服务器端口号
60 | * @param webSocketPort
61 | * webSocket端口号
62 | */
63 | public VxApiDeployInfos(String appName, String deployId, Integer httpPort, Integer httpsPort, Integer webSocketPort) {
64 | super();
65 | this.appName = appName;
66 | this.deployId = deployId;
67 | this.httpPort = httpPort;
68 | this.httpsPort = httpsPort;
69 | this.webSocketPort = webSocketPort;
70 | }
71 | public String getAppName() {
72 | return appName;
73 | }
74 | public void setAppName(String appName) {
75 | this.appName = appName;
76 | }
77 | public String getDeployId() {
78 | return deployId;
79 | }
80 | public void setDeployId(String deployId) {
81 | this.deployId = deployId;
82 | }
83 | public Integer getHttpPort() {
84 | return httpPort;
85 | }
86 | public void setHttpPort(Integer httpPort) {
87 | this.httpPort = httpPort;
88 | }
89 | public Integer getHttpsPort() {
90 | return httpsPort;
91 | }
92 | public void setHttpsPort(Integer httpsPort) {
93 | this.httpsPort = httpsPort;
94 | }
95 | public Integer getWebSocketPort() {
96 | return webSocketPort;
97 | }
98 | public void setWebSocketPort(Integer webSocketPort) {
99 | this.webSocketPort = webSocketPort;
100 | }
101 | @Override
102 | public String toString() {
103 | return "VxApiDeployInfos [appName=" + appName + ", deployId=" + deployId + ", httpPort=" + httpPort + ", httpsPort=" + httpsPort
104 | + ", webSocketPort=" + webSocketPort + "]";
105 | }
106 |
107 | }
108 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/entity/VxApiEntranceParam.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.entity;
2 |
3 | import com.szmirren.vxApi.core.enums.ParamPositionEnum;
4 | import com.szmirren.vxApi.core.enums.ParamTypeEnum;
5 | import com.szmirren.vxApi.core.options.VxApiParamCheckOptions;
6 |
7 | import io.vertx.core.json.JsonObject;
8 |
9 | /**
10 | * 网关的入口参数
11 | *
12 | * @author Mirren
13 | *
14 | */
15 | public class VxApiEntranceParam {
16 | private String paramName;// 参数的名字
17 | private String describe;// 描述
18 | private ParamPositionEnum position;// 参数的位置
19 | private ParamTypeEnum paramType;// 参数类型
20 | private boolean isNotNull;// 是否可以为空
21 | private Object def;// 默认值
22 | private VxApiParamCheckOptions checkOptions;// 参数的配置
23 |
24 | /**
25 | * 将对象装换为JsonObject
26 | *
27 | * @return
28 | */
29 | public JsonObject toJson() {
30 | JsonObject json = new JsonObject();
31 | json.put("paramName", this.paramName);
32 | json.put("position", this.position);
33 | json.put("paramType", this.paramType);
34 | json.put("isNotNull", this.isNotNull);
35 | if (def != null) {
36 | json.put("def", this.def);
37 | }
38 | if (describe != null) {
39 | json.put("describe", this.describe);
40 | }
41 | if (checkOptions != null) {
42 | json.put("checkOptions", checkOptions.toJson());
43 | }
44 | return json;
45 | }
46 |
47 | /**
48 | * 通过JsonObject实例化一个对象
49 | *
50 | * @param obj
51 | * @return
52 | */
53 | public static VxApiEntranceParam fromJson(JsonObject obj) {
54 | if (obj == null) {
55 | return null;
56 | }
57 | VxApiEntranceParam option = new VxApiEntranceParam();
58 | if (obj.getValue("paramName") instanceof String) {
59 | option.setParamName(obj.getString("paramName"));
60 | }
61 | if (obj.getValue("describe") instanceof String) {
62 | option.setDescribe(obj.getString("describe"));
63 | }
64 | if (obj.getValue("isNotNull") instanceof Boolean) {
65 | option.setNotNull(obj.getBoolean("isNotNull"));
66 | }
67 | if (obj.getValue("position") instanceof String) {
68 | option.setPosition(ParamPositionEnum.valueOf(obj.getString("position")));
69 | }
70 | if (obj.getValue("paramType") instanceof String) {
71 | option.setParamType(ParamTypeEnum.valueOf(obj.getString("paramType")));
72 | }
73 | if (obj.getValue("def") != null) {
74 | option.setDef(obj.getValue("def"));
75 | }
76 | if (obj.getValue("checkOptions") instanceof JsonObject) {
77 | option.setCheckOptions(VxApiParamCheckOptions.fromJson(obj.getJsonObject("checkOptions")));
78 | } else if (obj.getValue("checkOptions") instanceof String) {
79 | option.setCheckOptions(VxApiParamCheckOptions.fromJson(new JsonObject(obj.getString("checkOptions"))));
80 | }
81 | return option;
82 | }
83 |
84 | public VxApiEntranceParam() {
85 | super();
86 | }
87 |
88 | public String getParamName() {
89 | return paramName;
90 | }
91 |
92 | public void setParamName(String paramName) {
93 | this.paramName = paramName;
94 | }
95 |
96 | public ParamPositionEnum getPosition() {
97 | return position;
98 | }
99 |
100 | public void setPosition(ParamPositionEnum position) {
101 | this.position = position;
102 | }
103 |
104 | public ParamTypeEnum getParamType() {
105 | return paramType;
106 | }
107 |
108 | public void setParamType(ParamTypeEnum paramType) {
109 | this.paramType = paramType;
110 | }
111 |
112 | public boolean isNotNull() {
113 | return isNotNull;
114 | }
115 |
116 | public void setNotNull(boolean isNotNull) {
117 | this.isNotNull = isNotNull;
118 | }
119 |
120 | public Object getDef() {
121 | return def;
122 | }
123 |
124 | public void setDef(Object def) {
125 | this.def = def;
126 | }
127 |
128 | public String getDescribe() {
129 | return describe;
130 | }
131 |
132 | public void setDescribe(String describe) {
133 | this.describe = describe;
134 | }
135 |
136 | public VxApiParamCheckOptions getCheckOptions() {
137 | return checkOptions;
138 | }
139 |
140 | public void setCheckOptions(VxApiParamCheckOptions checkOptions) {
141 | this.checkOptions = checkOptions;
142 | }
143 |
144 | @Override
145 | public String toString() {
146 | return "VxApiEntranceParam [paramName=" + paramName + ", describe=" + describe + ", position=" + position
147 | + ", paramType=" + paramType + ", isNotNull=" + isNotNull + ", def=" + def + ", checkOptions="
148 | + checkOptions + "]";
149 | }
150 |
151 | }
152 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/entity/VxApiResultStatus.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.entity;
2 |
3 | import io.vertx.core.json.JsonObject;
4 |
5 | /**
6 | * API返回结果状态码
7 | *
8 | * @author Mirren
9 | *
10 | */
11 | public class VxApiResultStatus {
12 | private String code;// 状态码
13 | private String msg;// 错误信息
14 | private String describe;// 描述
15 |
16 | /**
17 | * 将对象装换为JsonObject
18 | *
19 | * @return
20 | */
21 | public JsonObject toJson() {
22 | JsonObject json = new JsonObject();
23 | if (code != null) {
24 | json.put("code", this.code);
25 | }
26 | if (msg != null) {
27 | json.put("msg", this.msg);
28 | }
29 | if (describe != null) {
30 | json.put("describe", this.describe);
31 | }
32 | return json;
33 | }
34 |
35 | /**
36 | * 通过JsonObject实例化一个对象
37 | *
38 | * @param obj
39 | * @return
40 | */
41 | public static VxApiResultStatus fromJson(JsonObject obj) {
42 | if (obj == null) {
43 | return null;
44 | }
45 | VxApiResultStatus option = new VxApiResultStatus();
46 | if (obj.getValue("code") instanceof String) {
47 | option.setCode(obj.getString("code"));
48 | }
49 | if (obj.getValue("msg") instanceof String) {
50 | option.setMsg(obj.getString("msg"));
51 | }
52 | if (obj.getValue("describe") instanceof String) {
53 | option.setDescribe(obj.getString("describe"));
54 | }
55 | return option;
56 | }
57 |
58 | public VxApiResultStatus() {
59 | super();
60 | }
61 |
62 | public VxApiResultStatus(String code, String msg, String describe) {
63 | super();
64 | this.code = code;
65 | this.msg = msg;
66 | this.describe = describe;
67 | }
68 |
69 | public String getCode() {
70 | return code;
71 | }
72 |
73 | public void setCode(String code) {
74 | this.code = code;
75 | }
76 |
77 | public String getMsg() {
78 | return msg;
79 | }
80 |
81 | public void setMsg(String msg) {
82 | this.msg = msg;
83 | }
84 |
85 | public String getDescribe() {
86 | return describe;
87 | }
88 |
89 | public void setDescribe(String describe) {
90 | this.describe = describe;
91 | }
92 |
93 | @Override
94 | public String toString() {
95 | return "VxApiResultStatus [code=" + code + ", msg=" + msg + ", describe=" + describe + "]";
96 | }
97 |
98 | }
99 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/entity/VxApiSecurityPolicies.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.entity;
2 |
3 | import com.szmirren.vxApi.core.enums.TimeUnitEnum;
4 |
5 | import io.vertx.core.json.JsonObject;
6 |
7 | /**
8 | * 安全策略
9 | *
10 | * @author Mirren
11 | *
12 | */
13 | public class VxApiSecurityPolicies {
14 | private String policyName;// 安全策略的名字
15 | private String policyDescribe;// 安全策略的描述
16 | private TimeUnitEnum timeUnit;// 安全策略的限制单位
17 | private long apiLimit;// api的总限制访问数,0等于无限制,默认=0
18 | private long ipLimit;// ip的限制访问数,必须小于apiLimint,默认与apiLimit一致
19 |
20 | /**
21 | * 将对象装换为json
22 | *
23 | * @return
24 | */
25 | public JsonObject toJson() {
26 | JsonObject json = new JsonObject();
27 | json.put("policyName", this.policyName);
28 | json.put("policyDescribe", this.policyDescribe);
29 | json.put("timeUnit", this.timeUnit);
30 | json.put("apiLimit", this.apiLimit);
31 | json.put("ipLimit", this.ipLimit);
32 | return json;
33 | }
34 |
35 | /**
36 | * 通过json实例化一个对象
37 | *
38 | * @param json
39 | * @return
40 | */
41 | public static VxApiSecurityPolicies fromJson(JsonObject json) {
42 | if (json == null) {
43 | return null;
44 | }
45 | VxApiSecurityPolicies option = new VxApiSecurityPolicies();
46 | if (json.getValue("policyName") instanceof String) {
47 | option.setPolicyName(json.getString("policyName"));
48 | }
49 | if (json.getValue("policyDescribe") instanceof String) {
50 | option.setPolicyDescribe(json.getString("policyDescribe"));
51 | }
52 | if (json.getValue("timeUnit") instanceof String) {
53 | option.setTimeUnit(TimeUnitEnum.valueOf(json.getString("timeUnit")));
54 | }
55 | if (json.getValue("apiLimit") instanceof Number) {
56 | option.setApiLimit(((Number) json.getValue("apiLimit")).longValue());
57 | }
58 | if (json.getValue("ipLimit") instanceof Number) {
59 | option.setApiLimit(((Number) json.getValue("ipLimit")).longValue());
60 | }
61 | return option;
62 | }
63 |
64 | public VxApiSecurityPolicies() {
65 | super();
66 | }
67 |
68 | public VxApiSecurityPolicies(String policyName, String policyDescribe, TimeUnitEnum timeUnit, long apiLimit,
69 | long ipLimit) {
70 | super();
71 | this.policyName = policyName;
72 | this.policyDescribe = policyDescribe;
73 | this.timeUnit = timeUnit;
74 | this.apiLimit = apiLimit;
75 | this.ipLimit = ipLimit;
76 | }
77 |
78 | /**
79 | * 获得安全策略的名字
80 | *
81 | * @return
82 | */
83 | public String getPolicyName() {
84 | return policyName;
85 | }
86 |
87 | /**
88 | * 设置安全策略的名字
89 | *
90 | * @param policyName
91 | */
92 | public void setPolicyName(String policyName) {
93 | this.policyName = policyName;
94 | }
95 |
96 | /**
97 | * 获得安全策略的描述
98 | *
99 | * @return
100 | */
101 | public String getPolicyDescribe() {
102 | return policyDescribe;
103 | }
104 |
105 | /**
106 | * 安全策略的描述
107 | *
108 | * @param policyDescribe
109 | */
110 | public void setPolicyDescribe(String policyDescribe) {
111 | this.policyDescribe = policyDescribe;
112 | }
113 |
114 | /**
115 | * 获得安全策略的限制单位
116 | *
117 | * @return
118 | */
119 | public TimeUnitEnum getTimeUnit() {
120 | return timeUnit;
121 | }
122 |
123 | /**
124 | * 设置安全策略的限制单位
125 | *
126 | * @param timeUnit
127 | */
128 | public void setTimeUnit(TimeUnitEnum timeUnit) {
129 | this.timeUnit = timeUnit;
130 | }
131 |
132 | /**
133 | * 获得api的总限制访问数
134 | *
135 | * @return
136 | */
137 | public long getApiLimit() {
138 | return apiLimit;
139 | }
140 |
141 | /**
142 | * 设置api的总限制访问数,0等于无限制,默认=0
143 | *
144 | * @param apiLimit
145 | */
146 | public void setApiLimit(long apiLimit) {
147 | this.apiLimit = apiLimit;
148 | }
149 |
150 | /**
151 | * 获得ip的限制访问数
152 | *
153 | * @return
154 | */
155 | public long getIpLimit() {
156 | return ipLimit;
157 | }
158 |
159 | /**
160 | * 设置ip的限制访问数,必须小于apiLimint,默认与apiLimit一致
161 | *
162 | * @param ipLimit
163 | */
164 | public void setIpLimit(long ipLimit) {
165 | this.ipLimit = ipLimit;
166 | }
167 |
168 | @Override
169 | public String toString() {
170 | return "VxSecurityPolicies [policyName=" + policyName + ", policyDescribe=" + policyDescribe + ", timeUnit="
171 | + timeUnit + ", apiLimit=" + apiLimit + ", ipLimit=" + ipLimit + "]";
172 | }
173 |
174 | }
175 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/entity/VxApiServerEntrance.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.entity;
2 |
3 | import com.szmirren.vxApi.core.enums.ApiServerTypeEnum;
4 |
5 | import io.vertx.core.json.JsonObject;
6 |
7 | /**
8 | * Api服务端入口
9 | *
10 | * @author Mirren
11 | *
12 | */
13 | public class VxApiServerEntrance {
14 |
15 | private ApiServerTypeEnum serverType;// api的服务类型
16 | private JsonObject body;// 存储后端服务的json,根据serverType而实例化相应的服务操作对象
17 |
18 | /**
19 | * 将对象转换为JsonObject
20 | *
21 | * @return
22 | */
23 | public JsonObject toJson() {
24 | JsonObject json = new JsonObject();
25 | json.put("serverType", this.serverType);
26 | json.put("body", this.body);
27 | return json;
28 | }
29 |
30 | /**
31 | * 通过一个JsonObject获得一个实例
32 | *
33 | * @param obj
34 | * @return
35 | */
36 | public static VxApiServerEntrance fromJson(JsonObject obj) {
37 | if (obj == null) {
38 | return null;
39 | }
40 | VxApiServerEntrance option = new VxApiServerEntrance();
41 | if (obj.getValue("serverType") instanceof String) {
42 | option.setServerType(ApiServerTypeEnum.valueOf(obj.getString("serverType")));
43 | }
44 | if (obj.getValue("body") instanceof JsonObject) {
45 | option.setBody(obj.getJsonObject("body"));
46 | }
47 | return option;
48 | }
49 |
50 | public ApiServerTypeEnum getServerType() {
51 | return serverType;
52 | }
53 |
54 | public void setServerType(ApiServerTypeEnum serverType) {
55 | this.serverType = serverType;
56 | }
57 |
58 | public JsonObject getBody() {
59 | return body;
60 | }
61 |
62 | public void setBody(JsonObject body) {
63 | this.body = body;
64 | }
65 |
66 | @Override
67 | public String toString() {
68 | return "VxApiServerEntrance [serverType=" + serverType + ", body=" + body + "]";
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/entity/VxApiServerURL.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.entity;
2 |
3 | import io.vertx.core.json.JsonObject;
4 |
5 | /**
6 | * 服务器地址与权重
7 | *
8 | * @author Mirren
9 | *
10 | */
11 | public class VxApiServerURL {
12 | private String url;// 路径
13 | private int weight = 0;// 访问权重
14 |
15 | /**
16 | * 将当前对象装换为JsonObject
17 | *
18 | * @return
19 | */
20 | public JsonObject toJson() {
21 | JsonObject json = new JsonObject();
22 | json.put("url", url);
23 | json.put("weight", weight);
24 | return json;
25 | }
26 |
27 | /**
28 | * 通过Json配置文件得到一个服务地址对象,如果配置文件为空或者,key:url非String类型报错NullPointerException
29 | *
30 | * @param obj
31 | * @return
32 | */
33 | public static VxApiServerURL fromJson(JsonObject obj) {
34 | if (obj == null) {
35 | throw new NullPointerException("服务地址的JSON配置文件不能是null");
36 | }
37 | VxApiServerURL option = new VxApiServerURL();
38 | if (obj.getValue("url") instanceof String) {
39 | option.setUrl(obj.getString("url"));
40 | } else {
41 | throw new NullPointerException("url必须为字符串类型");
42 | }
43 | if (obj.getValue("weight") instanceof Number) {
44 | option.setWeight(((Number) obj.getValue("weight")).intValue());
45 | }
46 | return option;
47 | }
48 |
49 | private VxApiServerURL() {
50 | super();
51 | }
52 |
53 | public VxApiServerURL(String url) {
54 | super();
55 | this.url = url;
56 | this.weight = 0;
57 | }
58 |
59 | public VxApiServerURL(String url, int weight) {
60 | super();
61 | this.url = url;
62 | this.weight = weight;
63 | }
64 |
65 | public String getUrl() {
66 | return url;
67 | }
68 |
69 | public void setUrl(String url) {
70 | this.url = url;
71 | }
72 |
73 | public int getWeight() {
74 | return weight;
75 | }
76 |
77 | public void setWeight(int weight) {
78 | this.weight = weight;
79 | }
80 |
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/entity/VxApiServerURLInfo.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.entity;
2 |
3 | /**
4 | * 服务地址的信息,getUrl得到服务地址,getIndex得到这个地址对应的下标,下标用于报告地址可用或地址不可用
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public class VxApiServerURLInfo {
10 | private String url;// 路径
11 | private int index;// 路径的下标
12 |
13 | public VxApiServerURLInfo(String url, int index) {
14 | super();
15 | this.url = url;
16 | this.index = index;
17 | }
18 |
19 | public String getUrl() {
20 | return url;
21 | }
22 |
23 | public void setUrl(String url) {
24 | this.url = url;
25 | }
26 |
27 | public int getIndex() {
28 | return index;
29 | }
30 |
31 | public void setIndex(int index) {
32 | this.index = index;
33 | }
34 |
35 | @Override
36 | public String toString() {
37 | return "ServerUrlInfo [url=" + url + ", index=" + index + "]";
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/entity/VxApiServerURLPollingPolicy.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.entity;
2 |
3 | import java.net.MalformedURLException;
4 | import java.net.URL;
5 | import java.util.ArrayList;
6 | import java.util.HashMap;
7 | import java.util.List;
8 | import java.util.Map;
9 |
10 | /**
11 | * 服务地址的轮询策略
12 | * tips:在非线程安全的环境下需要注意线程安全的问题
13 | *
14 | * @author Mirren
15 | *
16 | */
17 | public class VxApiServerURLPollingPolicy {
18 | /**
19 | * 一共有多少个服务对象
20 | */
21 | private int size = 1;
22 | /**
23 | * 当前服务对象坐标
24 | */
25 | private int curIndex = 0;
26 | /**
27 | * 当前权重下标
28 | */
29 | private int weightIndex = 0;
30 | /**
31 | * 服务的地址
32 | */
33 | private String[] urls;
34 | /**
35 | * 服务地址权重
36 | */
37 | private int[] weight;
38 | /**
39 | * 是否存有可用服务
40 | */
41 | private boolean haveService = true;
42 | /**
43 | * 是否存在坏的连接
44 | */
45 | private boolean haveBadService = false;
46 | /**
47 | * 是否正在重试检查坏的服务连接
48 | */
49 | private boolean checkWaiting = false;
50 | /**
51 | * 存储用户的IP地址对应的下标
52 | */
53 | private Map ipMap = new HashMap<>();
54 | /**
55 | * 用于存储当前下标的服务地址是否可用
56 | */
57 | private Map availableMap = new HashMap<>();
58 | /**
59 | * 失败的次数
60 | */
61 | private Map failureCountMap = new HashMap<>();
62 |
63 | /**
64 | * 创建轮询策略
65 | *
66 | * @param urls
67 | * 服务连接的URL集,不能为空,size大于1,正确的URL地址
68 | * @throws NullPointerException
69 | * 服务连接集合空是抛出
70 | * @throws MalformedURLException
71 | * 不是正确的URL是抛出
72 | */
73 | public VxApiServerURLPollingPolicy(List urls) throws NullPointerException, MalformedURLException {
74 | super();
75 | if (urls == null || urls.size() == 0) {
76 | throw new NullPointerException("服务URL集不能为空");
77 | }
78 | for (VxApiServerURL absoluteURI : urls) {
79 | new URL(absoluteURI.getUrl());
80 | }
81 | size = urls.size();
82 | this.urls = new String[size];
83 | weight = new int[size];
84 | for (int i = 0; i < urls.size(); i++) {
85 | // 初始化URL与权重
86 | this.urls[i] = urls.get(i).getUrl();
87 | weight[i] = urls.get(i).getWeight();
88 | // 默认设置所有连接可用
89 | availableMap.put(i, true);
90 | }
91 | }
92 |
93 | /**
94 | * 以轮询权重的方式得到服务URL
95 | *
96 | * @return
97 | */
98 | public VxApiServerURLInfo getUrl() {
99 | String url = urls[curIndex];
100 | int index = curIndex;
101 | if (size > 1) {
102 | weightIndex++;
103 | if (weightIndex >= weight[curIndex]) {
104 | weightIndex = 0;
105 | moveCurIndex();// 下标移动
106 | }
107 | }
108 | VxApiServerURLInfo urlInfo = new VxApiServerURLInfo(url, index);
109 | return urlInfo;
110 | }
111 |
112 | /**
113 | * 通过用户的IP地址获得用户对应的服务连接
114 | *
115 | * @param ip
116 | * 用户的IP
117 | * @return
118 | */
119 | public VxApiServerURLInfo getUrl(String ip) {
120 | VxApiServerURLInfo urlInfo = null;
121 | if (haveService) {
122 | Integer index = ipMap.get(ip);
123 | if (index == null || availableMap.get(index) == false) {
124 | urlInfo = getUrl();
125 | ipMap.put(ip, urlInfo.getIndex());
126 | } else {
127 | urlInfo = new VxApiServerURLInfo(urls[index], index);
128 | }
129 | } else {
130 | urlInfo = new VxApiServerURLInfo(urls[0], 0);
131 | }
132 | return urlInfo;
133 | }
134 |
135 | /**
136 | * 移动当前下标
137 | */
138 | private void moveCurIndex() {
139 | if (!haveService) {
140 | curIndex = 0;
141 | } else if (haveBadService) {
142 | updateCurIndex();
143 | } else {
144 | if ((curIndex + 1) > size - 1) {
145 | curIndex = 0;
146 | } else {
147 | curIndex++;
148 | }
149 | }
150 | }
151 |
152 | /**
153 | * 改变当前下标
154 | */
155 | private void updateCurIndex() {
156 | if (!haveService) {
157 | curIndex = 0;
158 | } else {
159 | if (availableMap.get(curIndex + 1) != null && availableMap.get(curIndex + 1) == true) {
160 | curIndex++;
161 | return;
162 | }
163 | boolean flag = true;// 标记当前坐标到结束是否有可用的地址
164 | for (int i = curIndex + 1; i < size; i++) {
165 | if (availableMap.get(i) == true) {
166 | curIndex = i;
167 | flag = false;
168 | break;
169 | }
170 | }
171 | if (flag) {
172 | boolean bad = false;
173 | for (int i = 0; i < size; i++) {
174 | if (availableMap.get(i) == true) {
175 | curIndex = i;
176 | break;
177 | }
178 | if (i == size - 1) {
179 | bad = true;
180 | }
181 | }
182 | if (bad) {
183 | haveService = false;
184 | }
185 | }
186 | }
187 | }
188 |
189 | /**
190 | * 提交连接失败的连接下标
191 | *
192 | * @param index
193 | */
194 | public void reportBadService(int index) {
195 | if (index >= size || index < 0) {
196 | return;
197 | }
198 | if (failureCountMap.get(index) != null) {
199 | availableMap.put(index, false);
200 | haveBadService = true;
201 | if (index == curIndex) {
202 | updateCurIndex();
203 | }
204 | } else {
205 | failureCountMap.put(index, 1);
206 | }
207 | }
208 |
209 | /**
210 | * 提交下标可以使用
211 | *
212 | * @param index
213 | */
214 | public void reportGreatService(int index) {
215 | if (index >= size || index < 0) {
216 | return;
217 | }
218 | failureCountMap.remove(index);
219 | availableMap.put(index, true);
220 | haveService = true;
221 | if (failureCountMap.size() == 0) {
222 | haveBadService = false;
223 | }
224 | }
225 |
226 | /**
227 | * 获得坏的连接
228 | *
229 | * @return 返回一个不为null的List
230 | */
231 | public List getBadService() {
232 | List result = new ArrayList<>();
233 | failureCountMap.forEach((k, v) -> result.add(new VxApiServerURLInfo(urls[k], k)));
234 | return result;
235 | }
236 |
237 | /**
238 | * 查看是否有可用服务连接
239 | *
240 | * @return 有可用服务连接返回true,没有可用服务连接返回false
241 | */
242 | public boolean isHaveService() {
243 | return haveService;
244 | }
245 |
246 | /**
247 | * 查看是否有坏的服务连接
248 | *
249 | * @return 存在坏的服务连接放回true,不存在返回false
250 | */
251 | public boolean isHaveBadService() {
252 | return haveBadService;
253 | }
254 |
255 | /**
256 | * 查看是否正在重试坏的服务连接是否可用,正在检查返回true,不在检查返回false
257 | *
258 | * @return
259 | */
260 | public boolean isCheckWaiting() {
261 | return checkWaiting;
262 | }
263 |
264 | /**
265 | * 设置是否正在重试坏的服务连接,true=正在检查,false=不在检查
266 | *
267 | * @param checkWaiting
268 | */
269 | public void setCheckWaiting(boolean checkWaiting) {
270 | this.checkWaiting = checkWaiting;
271 | }
272 |
273 | }
274 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/enums/ApiServerTypeEnum.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.enums;
2 |
3 | /**
4 | * 服务的类型
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public enum ApiServerTypeEnum {
10 | HTTP_HTTPS, // http或https类型
11 | REDIRECT, // 页面跳转
12 | CUSTOM;// 自定义服务类型
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/enums/ConnectProtocolEnum.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.enums;
2 |
3 | /**
4 | * 请求协议的类型
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public enum ConnectProtocolEnum {
10 | HTTP, HTTPS, WEB_SOCKET, TCP;
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/enums/ContentTypeEnum.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.enums;
2 |
3 | /**
4 | * 返回的ContentType类型
5 | *
6 | * @author Mirren
7 | */
8 | public enum ContentTypeEnum {
9 | /** 内容: application/json */
10 | JSON("application/json"),
11 | /** 内容: application/xml */
12 | XML("application/xml"),
13 | /** 内容: text/html */
14 | HTML("text/html"),
15 | /** 内容: text/plain */
16 | TEXT("text/plain"),
17 | /** 内容: application/x-www-form-urlencoded */
18 | FORM("application/x-www-form-urlencoded"),
19 | /** 内容: application/x-www-form-urlencoded */
20 | APPLICATION_X_WWW_FORM_URLENCODED("application/x-www-form-urlencoded"),
21 | /** 内容: multipart/form-data */
22 | MULTIPART_FORM_DATA("multipart/form-data"),
23 | /** 内容: application/octet-stream */
24 | BINARY("application/octet-stream"),
25 | /** 内容: application/json;charset=UTF-8 */
26 | JSON_UTF8("application/json;charset=UTF-8"),
27 | /** 内容: application/xml;charset=UTF-8 */
28 | XML_UTF8("application/xml;charset=UTF-8"),
29 | /** 内容: text/html;charset=UTF-8 */
30 | HTML_UTF8("text/html;charset=UTF-8"),
31 | /** 内容: text/plain;charset=UTF-8 */
32 | TEXT_UTF8("text/plain;charset=UTF-8"),
33 | /** 内容: application/x-www-form-urlencoded;charset=UTF-8 */
34 | FORM_UTF8("application/x-www-form-urlencoded;charset=UTF-8"),
35 | /** 内容: application/octet-stream;charset=UTF-8 */
36 | BINARY_UTF8("application/octet-stream;charset=UTF-8");
37 |
38 | private String type;
39 |
40 | private ContentTypeEnum(String type) {
41 | this.type = type;
42 | }
43 |
44 | public String val() {
45 | return type;
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/enums/EnterParamMapTypeEnum.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.enums;
2 |
3 | /**
4 | * API的入口参数映射类型
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public enum EnterParamMapTypeEnum {
10 | /**
11 | * 参数透传
12 | */
13 | PASS,
14 | /**
15 | * 参数映射
16 | */
17 | MAPING;
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/enums/HTTPStatusCodeMsgEnum.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.enums;
2 |
3 | /**
4 | * HTTP状态码与状态信息的枚举类
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public enum HTTPStatusCodeMsgEnum {
10 | /**
11 | * ok
12 | */
13 | C200(200, "ok"),
14 | /**
15 | * Bad Request
16 | */
17 | C400(400, "Bad Request"),
18 | /**
19 | * Unauthorized
20 | */
21 | C401(401, "Unauthorized"),
22 | /**
23 | * Forbidden
24 | */
25 | C403(403, "Forbidden"),
26 | /**
27 | * Not Found
28 | */
29 | C404(404, "Not Found"),
30 | /**
31 | * Internal Server Error
32 | */
33 | C500(500, "Internal Server Error"),
34 | /**
35 | * Server Unavailable
36 | */
37 | C503(503, "Server Unavailable"),
38 | /**
39 | * 空指针异常
40 | */
41 | C1000(1000, "NullPointerException"),
42 | /**
43 | * 文件中缺少比用参数或者参数不正确
44 | */
45 | C1400(1400, "Lack of request parameters or parameters is invalid"),
46 | /**
47 | * 没有找到指定文件
48 | */
49 | C1404(1404, "No file in path can be found"),
50 | /**
51 | * 错误的json格式文件
52 | */
53 | C1405(1405, "The specified JSON file is wrong"),
54 | /**
55 | * 文件已经存在或者数据已经存在
56 | */
57 | C1444(1444, "The data has already existed"),
58 |
59 | /**
60 | * 当前端口被占用
61 | */
62 | C1111(1111, "Address already in use: bind"),
63 | /**
64 | * 未知错误
65 | */
66 | C1999(1999, "Unknown error"),;
67 | // 状态码
68 | private int code;
69 | private String msg;
70 |
71 | HTTPStatusCodeMsgEnum(int code, String msg) {
72 | this.msg = msg;
73 | this.code = code;
74 | }
75 |
76 | /**
77 | * 得到状态码
78 | *
79 | * @return
80 | */
81 | public int getCode() {
82 | return code;
83 | }
84 |
85 | /**
86 | * 获得状态码相应的信息
87 | *
88 | * @return
89 | */
90 | public String getMsg() {
91 | return msg;
92 | }
93 |
94 | }
95 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/enums/HttpMethodEnum.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.enums;
2 |
3 | /**
4 | * http的请求方式
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public enum HttpMethodEnum {
10 | ALL("ALL"), OPTIONS("OPTIONS"), GET("GET"), HEAD("HEAD"), POST("POST"),
11 | PUT("PUT"), DELETE("DELETE"), TRACE("TRACE"), CONNECT("CONNECT"), PATCH("PATCH"), OTHER("OTHER");
12 | private String val;
13 | private HttpMethodEnum(String val) {
14 | this.val = val;
15 | }
16 | public String getVal() {
17 | return val;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/enums/LoadBalanceEnum.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.enums;
2 |
3 | /**
4 | * 负载均衡类型
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public enum LoadBalanceEnum {
10 | /**
11 | * 轮询可用
12 | */
13 | POLLING_AVAILABLE,
14 | /**
15 | * ip哈希化
16 | */
17 | IP_HASH,
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/enums/ParamPositionEnum.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.enums;
2 |
3 | /**
4 | * 参数的作用域
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public enum ParamPositionEnum {
10 | PATH, QUERY, BODY, HEADER;
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/enums/ParamSystemVarTypeEnum.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.enums;
2 |
3 | /**
4 | * API请求后台时的产量常量
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public enum ParamSystemVarTypeEnum {
10 | /**
11 | * 请求客服端的ip地址
12 | */
13 | CLIENT_HOST,
14 | /**
15 | * 请求客户端的端口
16 | */
17 | CLIENT_PORT,
18 | /**
19 | * 请求客户端的PATH
20 | */
21 | CLIENT_PATH,
22 | /**
23 | * 请求客户端的sessionId
24 | */
25 | CLIENT_SESSION_ID,
26 |
27 | /**
28 | * 用户请求的完整路径
29 | */
30 | CLIENT_ABSOLUTE_URI,
31 | /**
32 | * 用户请求的模式
33 | */
34 | CLIENT_REQUEST_SCHEMA,
35 | /**
36 | * 获得api的名字
37 | */
38 | SERVER_API_NAME,
39 | /**
40 | * 获得API服务器的unix时间戳
41 | */
42 | SERVER_UNIX_TIME,
43 | /**
44 | * 获得网关USER_AGENT
45 | */
46 | SERVER_USER_AGENT;
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/enums/ParamTypeEnum.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.enums;
2 |
3 | /**
4 | * 参数类型
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public enum ParamTypeEnum {
10 | String, Integer, Long, Float, Double, Boolean, JsonObject,JsonArray;
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/enums/TimeUnitEnum.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.enums;
2 |
3 | /**
4 | * 时间单位类
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public enum TimeUnitEnum {
10 | DAYS(86400), HOURS(3600), MINUTES(60);
11 | private long val;
12 |
13 | private TimeUnitEnum(long val) {
14 | this.val = val;
15 | }
16 |
17 | public long getVal() {
18 | return val;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/handler/FreeMarkerTemplateHander.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Red Hat, Inc.
3 | *
4 | * All rights reserved. This program and the accompanying materials
5 | * are made available under the terms of the Eclipse Public License v1.0
6 | * and Apache License v2.0 which accompanies this distribution.
7 | *
8 | * The Eclipse Public License is available at
9 | * http://www.eclipse.org/legal/epl-v10.html
10 | *
11 | * The Apache License v2.0 is available at
12 | * http://www.opensource.org/licenses/apache2.0.php
13 | *
14 | * You may elect to redistribute this code under either of these licenses.
15 | */
16 |
17 | package com.szmirren.vxApi.core.handler;
18 |
19 | import java.io.ByteArrayOutputStream;
20 | import java.io.File;
21 | import java.io.IOException;
22 | import java.io.OutputStreamWriter;
23 | import java.util.Map;
24 |
25 | import org.apache.logging.log4j.LogManager;
26 | import org.apache.logging.log4j.Logger;
27 |
28 | import freemarker.cache.NullCacheStorage;
29 | import freemarker.template.Configuration;
30 | import freemarker.template.Template;
31 | import io.vertx.core.AsyncResult;
32 | import io.vertx.core.Future;
33 | import io.vertx.core.Handler;
34 | import io.vertx.core.Vertx;
35 | import io.vertx.core.buffer.Buffer;
36 | import io.vertx.core.file.FileSystemException;
37 | import io.vertx.core.http.HttpHeaders;
38 | import io.vertx.core.json.JsonObject;
39 | import io.vertx.ext.web.RoutingContext;
40 | import io.vertx.ext.web.common.template.CachingTemplateEngine;
41 | import io.vertx.ext.web.handler.TemplateHandler;
42 | import io.vertx.ext.web.impl.Utils;
43 | import io.vertx.ext.web.templ.freemarker.FreeMarkerTemplateEngine;
44 | import io.vertx.ext.web.templ.freemarker.impl.VertxWebObjectWrapper;
45 |
46 | /**
47 | * @author Paulo Lopes
48 | */
49 | public class FreeMarkerTemplateHander extends CachingTemplateEngine implements FreeMarkerTemplateEngine, TemplateHandler {
50 | private static final Logger LOG = LogManager.getLogger(FreeMarkerTemplateHander.class);
51 |
52 | private final Configuration config;
53 | private String contentType;
54 |
55 | public FreeMarkerTemplateHander(Vertx vertx, String templateDirectory, String contentType) {
56 | super(DEFAULT_TEMPLATE_EXTENSION, DEFAULT_MAX_CACHE_SIZE);
57 | this.contentType = contentType;
58 | config = new Configuration(Configuration.VERSION_2_3_28);
59 | try {
60 | config.setDirectoryForTemplateLoading(new File(templateDirectory));
61 | } catch (IOException e) {
62 | throw new FileSystemException("not found template directory:" + templateDirectory);
63 | }
64 | config.setObjectWrapper(new VertxWebObjectWrapper(config.getIncompatibleImprovements()));
65 | config.setCacheStorage(new NullCacheStorage());
66 | }
67 |
68 | @Override
69 | public FreeMarkerTemplateEngine setExtension(String extension) {
70 | doSetExtension(extension);
71 | return this;
72 | }
73 |
74 | @Override
75 | public FreeMarkerTemplateEngine setMaxCacheSize(int maxCacheSize) {
76 | this.cache.setMaxSize(maxCacheSize);
77 | return this;
78 | }
79 |
80 | @Override
81 | public void render(Map context, String templateFile, Handler> handler) {
82 | try {
83 | Template template = isCachingEnabled() ? cache.get(templateFile) : null;
84 | if (template == null) {
85 | synchronized (this) {
86 | template = config.getTemplate(adjustLocation(templateFile));
87 | }
88 | if (isCachingEnabled()) {
89 | cache.put(templateFile, template);
90 | }
91 | }
92 | try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
93 | template.process(context, new OutputStreamWriter(baos));
94 | handler.handle(Future.succeededFuture(Buffer.buffer(baos.toByteArray())));
95 | }
96 | } catch (Exception ex) {
97 | handler.handle(Future.failedFuture(ex));
98 | }
99 | }
100 |
101 | @Override
102 | public void handle(RoutingContext context) {
103 | String file = Utils.pathOffset(context.normalisedPath(), context);
104 | if (file != null && file.startsWith("/")) {
105 | file = file.substring(1);
106 | }
107 | render(new JsonObject(context.data()), file, res -> {
108 | if (res.succeeded()) {
109 | context.response().putHeader(HttpHeaders.CONTENT_TYPE, contentType).end(res.result());
110 | } else {
111 | context.fail(res.cause());
112 | }
113 | });
114 |
115 | }
116 |
117 | @Override
118 | public TemplateHandler setIndexTemplate(String indexTemplate) {
119 | return this;
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/handler/route/VxApiRouteConstant.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.handler.route;
2 |
3 | /**
4 | * VxApiRoute需要用到的常量
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public interface VxApiRouteConstant {
10 | /** 返回类型 Content-Type */
11 | public final static String CONTENT_TYPE = "Content-Type";
12 | /** 返回类型小写 content-type */
13 | public final static String CONTENT_TYPE_LOWER_CASE = "content-type";
14 | /** 时间 Content-Length */
15 | public final static String CONTENT_LENGTH = "Content-Length";
16 | /** 时间 content-length */
17 | public final static String CONTENT_LENGTH_LOWER_CASE = "content-length";
18 | /** 服务器类型 Server */
19 | public final static String SERVER = "Server";
20 | /** 服务器类型 User-Agent */
21 | public final static String USER_AGENT = "User-Agent";
22 | /** 时间 Date */
23 | public final static String DATE = "Date";
24 | /** 从RoutingContext获取用户请求长度的key */
25 | public final static String BODY_KEY_CONTENT_LENGTH = "VxApiBodyContentLength";
26 | /** 从RoutingContext获取用户请求PATH参数的key */
27 | public final static String BODY_KEY_PATH_TYPE_MultiMap = "VxApiBodyPathParams";
28 | /** 从RoutingContext获取用户请求HEADER参数的key */
29 | public final static String BODY_KEY_HEADER_TYPE_MultiMap = "VxApiBodyHeaderParams";
30 | /** 从RoutingContext获取用户请求QUERY参数的key */
31 | public final static String BODY_KEY_QUERY_TYPE_QueryStringEncoder = "VxApiBodyQueryPathParams";
32 | /** 从RoutingContext获取用户请求BODY参数的key */
33 | public final static String BODY_KEY_BODY_TYPE_QueryStringEncoder = "VxApiBodyBodyPathParams";
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/handler/route/VxApiRouteHandlerApiLimit.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.handler.route;
2 |
3 | import com.szmirren.vxApi.core.entity.VxApis;
4 | import com.szmirren.vxApi.core.handler.route.impl.VxApiRouteApiLimitImpl;
5 |
6 | import io.vertx.core.Handler;
7 | import io.vertx.ext.web.RoutingContext;
8 |
9 | /**
10 | * VxApiRoute访问限制处理器
11 | *
12 | * @author Mirren
13 | *
14 | */
15 | public interface VxApiRouteHandlerApiLimit extends Handler {
16 | /**
17 | * 得到一个默认的访问限制实现
18 | *
19 | * @param api
20 | * @return
21 | */
22 | static VxApiRouteHandlerApiLimit create(VxApis api) {
23 | return new VxApiRouteApiLimitImpl(api);
24 | };
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/handler/route/VxApiRouteHandlerHttpService.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.handler.route;
2 |
3 | import java.net.MalformedURLException;
4 |
5 | import com.szmirren.vxApi.core.entity.VxApis;
6 | import com.szmirren.vxApi.core.handler.route.impl.VxApiRouteHandlerHttpServiceImpl;
7 |
8 | import io.vertx.core.Handler;
9 | import io.vertx.core.http.HttpClient;
10 | import io.vertx.ext.web.RoutingContext;
11 | /**
12 | * VxApiRoute HTTP/HTTPS服务类型的处理器
13 | *
14 | * @author Mirren
15 | *
16 | */
17 | public interface VxApiRouteHandlerHttpService extends Handler {
18 | /**
19 | * 得到一个HTTP/HTTPS服务类型的处理器
20 | *
21 | * @param appName
22 | * 应用程序的名字
23 | * @param isNext
24 | * 是否有下一个处理器
25 | * @param api
26 | * API配置文件
27 | * @param httpClient
28 | * 与后台连接的客户端
29 | * @return
30 | * @throws NullPointerException
31 | * @throws MalformedURLException
32 | */
33 | static VxApiRouteHandlerHttpService create(String appName, boolean isNext, VxApis api, HttpClient httpClient)
34 | throws NullPointerException, MalformedURLException {
35 | return new VxApiRouteHandlerHttpServiceImpl(appName, isNext, api, httpClient);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/handler/route/VxApiRouteHandlerParamCheck.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.handler.route;
2 |
3 | import com.szmirren.vxApi.core.entity.VxApis;
4 | import com.szmirren.vxApi.core.handler.route.impl.VxApiRouteHandlerParamCheckImpl;
5 |
6 | import io.vertx.core.Handler;
7 | import io.vertx.ext.web.RoutingContext;
8 |
9 | /**
10 | * VxApiRoute参数检查处理器
11 | *
12 | * @author Mirren
13 | *
14 | */
15 | public interface VxApiRouteHandlerParamCheck extends Handler {
16 | /**
17 | * 得到一个默认的参数检查处理器实现
18 | *
19 | * @param api
20 | * API配置文件
21 | * @param maxContentLength
22 | * 请求体的长度限制参数的长度
23 | * @return
24 | */
25 | static VxApiRouteHandlerParamCheck create(VxApis api, long maxContentLength) {
26 | return new VxApiRouteHandlerParamCheckImpl(api, maxContentLength);
27 | };
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/handler/route/VxApiRouteHandlerRedirectType.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.handler.route;
2 |
3 | import com.szmirren.vxApi.core.entity.VxApis;
4 | import com.szmirren.vxApi.core.handler.route.impl.VxApiRouteHandlerRedirectTypeImpl;
5 |
6 | import io.vertx.core.Handler;
7 | import io.vertx.ext.web.RoutingContext;
8 |
9 | /**
10 | * VxApiRoute页面跳转处理器
11 | *
12 | * @author Mirren
13 | *
14 | */
15 | public interface VxApiRouteHandlerRedirectType extends Handler {
16 | /**
17 | * 得到一个默认的页面跳转处理器实现
18 | *
19 | * @param api
20 | * @return
21 | */
22 | static VxApiRouteHandlerRedirectType create(boolean isNext,VxApis api) {
23 | return new VxApiRouteHandlerRedirectTypeImpl(isNext,api);
24 | };
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/handler/route/impl/VxApiRouteApiLimitImpl.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.handler.route.impl;
2 |
3 | import java.time.Duration;
4 | import java.time.Instant;
5 | import java.util.Map;
6 |
7 | import com.szmirren.vxApi.core.common.VxApiGatewayAttribute;
8 | import com.szmirren.vxApi.core.entity.VxApiAPILimit;
9 | import com.szmirren.vxApi.core.entity.VxApis;
10 | import com.szmirren.vxApi.core.handler.route.VxApiRouteConstant;
11 | import com.szmirren.vxApi.core.handler.route.VxApiRouteHandlerApiLimit;
12 |
13 | import io.vertx.ext.web.RoutingContext;
14 |
15 | /**
16 | * VxApi的访问限制的实现
17 | *
18 | * @author Mirren
19 | *
20 | */
21 | public class VxApiRouteApiLimitImpl implements VxApiRouteHandlerApiLimit {
22 | // API的相关配置
23 | private VxApis api;
24 | // 流量限制
25 | private VxApiAPILimit limit;
26 |
27 | public VxApiRouteApiLimitImpl(VxApis api) {
28 | super();
29 | this.api = api;
30 | if (api.getLimitUnit() != null) {
31 | if (api.getApiLimit() <= -1 && api.getIpLimit() <= -1) {
32 | api.setLimitUnit(null);
33 | }
34 | }
35 | }
36 |
37 | @Override
38 | public void handle(RoutingContext rct) {
39 | if (api.getLimitUnit() == null) {
40 | rct.next();
41 | } else {
42 | if (limit != null) {
43 | if (limit.getIpTop() > -1) {
44 | Map ipPoints = limit.getUserIpCurPoints();
45 | String host = rct.request().remoteAddress().host();
46 | if (ipPoints.get(host) == null) {
47 | ipPoints.put(host, 1L);
48 | }
49 | if (ipPoints.get(host) >= limit.getIpTop()) {
50 | Instant oldTime = limit.getTimePoints().plusSeconds(api.getLimitUnit().getVal());
51 | Duration between = Duration.between(Instant.now(), oldTime);
52 | if (between.getSeconds() > 0) {
53 | if (!rct.response().ended()) {
54 | rct.response().putHeader(VxApiRouteConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
55 | .putHeader(VxApiRouteConstant.CONTENT_TYPE, api.getContentType()).setStatusCode(api.getResult().getLimitStatus())
56 | .end(api.getResult().getLimitExample());
57 | }
58 | return;
59 | } else {
60 | VxApiAPILimit newLimit = new VxApiAPILimit(api.getIpLimit(), api.getApiLimit());
61 | newLimit.setCurPoint(1);
62 | newLimit.addUserIpCurPotints(host, 1L);
63 | limit = newLimit;
64 | rct.next();
65 | return;
66 | }
67 | } else {
68 | ipPoints.put(host, ipPoints.get(host) + 1);
69 | limit.setCurPoint(limit.getCurPoint() + 1);
70 | rct.next();
71 | return;
72 | }
73 | }
74 | if (limit.getApiTop() > -1) {
75 | if (limit.getCurPoint() >= limit.getApiTop()) {
76 | Instant oldTime = limit.getTimePoints().plusSeconds(api.getLimitUnit().getVal());
77 | Duration between = Duration.between(Instant.now(), oldTime);
78 | if (between.getSeconds() > 0) {
79 | if (!rct.response().ended()) {
80 | rct.response().putHeader(VxApiRouteConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
81 | .putHeader(VxApiRouteConstant.CONTENT_TYPE, api.getContentType()).setStatusCode(api.getResult().getLimitStatus())
82 | .end(api.getResult().getLimitExample());
83 | }
84 | return;
85 | } else {
86 | VxApiAPILimit newLimit = new VxApiAPILimit(api.getIpLimit(), api.getApiLimit());
87 | newLimit.setCurPoint(1);
88 | if (api.getIpLimit() != -1) {
89 | String host = rct.request().remoteAddress().host();
90 | newLimit.addUserIpCurPotints(host, 1L);
91 | }
92 | limit = newLimit;
93 | rct.next();
94 | return;
95 | }
96 | } else {
97 | limit.setCurPoint(limit.getCurPoint() + 1);
98 | rct.next();
99 | return;
100 | }
101 | }
102 | rct.next();
103 | } else {
104 | VxApiAPILimit newLimit = new VxApiAPILimit(api.getIpLimit(), api.getApiLimit());
105 | newLimit.setCurPoint(1);
106 | if (api.getIpLimit() != -1) {
107 | String host = rct.request().remoteAddress().host();
108 | newLimit.addUserIpCurPotints(host, 1L);
109 | }
110 | limit = newLimit;
111 | rct.next();
112 | }
113 | }
114 | }
115 |
116 | }
117 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/handler/route/impl/VxApiRouteHandlerRedirectTypeImpl.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.handler.route.impl;
2 |
3 | import com.szmirren.vxApi.core.entity.VxApis;
4 | import com.szmirren.vxApi.core.handler.route.VxApiRouteHandlerRedirectType;
5 | import com.szmirren.vxApi.core.options.VxApiServerEntranceRedirectOptions;
6 | import com.szmirren.vxApi.spi.handler.VxApiAfterHandler;
7 |
8 | import io.vertx.core.Future;
9 | import io.vertx.core.json.JsonObject;
10 | import io.vertx.ext.web.RoutingContext;
11 |
12 | /**
13 | * VxApiRoute页面跳转处理器实现类
14 | *
15 | * @author Mirren
16 | *
17 | */
18 | public class VxApiRouteHandlerRedirectTypeImpl implements VxApiRouteHandlerRedirectType {
19 |
20 | private boolean isNext;
21 | private VxApiServerEntranceRedirectOptions redirectOptions;
22 |
23 | public VxApiRouteHandlerRedirectTypeImpl(boolean isNext, VxApis api) {
24 | super();
25 | this.isNext = isNext;
26 | JsonObject body = api.getServerEntrance().getBody();
27 | redirectOptions = VxApiServerEntranceRedirectOptions.fromJson(body);
28 | if (redirectOptions == null) {
29 | throw new NullPointerException("页面跳转服务类型的配置文件无法装换为服务类");
30 | }
31 | }
32 |
33 | @Override
34 | public void handle(RoutingContext rct) {
35 | rct.response().putHeader("Location", redirectOptions.getUrl()).setStatusCode(302);
36 | if (isNext) {
37 | rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.succeededFuture(true));// 告诉后置处理器当前操作成功执行
38 | rct.next();
39 | } else {
40 | if (!rct.response().ended()) {
41 | rct.response().end();
42 | }
43 | }
44 |
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/options/VxApiCertOptions.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.options;
2 |
3 | import io.vertx.core.json.JsonObject;
4 |
5 | /**
6 | * 证书类
7 | *
8 | * @author Mirren
9 | *
10 | */
11 | public class VxApiCertOptions {
12 | private String certType;// 证书的类型支持pem与pfx
13 | private String certKey;// 证书的key,pem模式为证书key的路径,pfx模式证书的密码
14 | private String certPath;// 证书的路径
15 |
16 | /**
17 | * 将对象转换为json
18 | *
19 | * @return
20 | */
21 | public JsonObject toJson() {
22 | JsonObject json = new JsonObject();
23 | json.put("certType", this.certType);
24 | json.put("certKey", this.certKey);
25 | json.put("certPath", this.certPath);
26 | return json;
27 | }
28 |
29 | /**
30 | * 将一个json对象装换为VxApiCertOptions,如果JsonObject为null或者或者JsonObject没有数据返回null
31 | *
32 | * @param obj
33 | * @return
34 | */
35 | public static VxApiCertOptions fromJson(JsonObject obj) {
36 | if (obj == null) {
37 | return null;
38 | } else {
39 | VxApiCertOptions options = new VxApiCertOptions();
40 | boolean isEmpty = true;
41 | if (obj.getValue("certType") instanceof String) {
42 | isEmpty = false;
43 | options.setCertType(obj.getString("certType"));
44 | }
45 | if (obj.getValue("certKey") instanceof String) {
46 | isEmpty = false;
47 | options.setCertKey(obj.getString("certKey"));
48 | }
49 | if (obj.getValue("certPath") instanceof String) {
50 | isEmpty = false;
51 | options.setCertPath(obj.getString("certPath"));
52 | }
53 | if (!isEmpty) {
54 | return options;
55 | }
56 | return null;
57 |
58 | }
59 | }
60 |
61 | /**
62 | * 获得证书的类型
63 | *
64 | * @return
65 | */
66 | public String getCertType() {
67 | return certType;
68 | }
69 |
70 | /**
71 | * 设置证书的类型支持pem与pfx
72 | *
73 | * @param certType
74 | */
75 | public void setCertType(String certType) {
76 | this.certType = certType;
77 | }
78 |
79 | /**
80 | * 获得证书key的路径或者密码
81 | *
82 | * @return
83 | */
84 | public String getCertKey() {
85 | return certKey;
86 | }
87 |
88 | /**
89 | * 设置证书的key,pem模式为证书key的路径,pfx模式证书的密码
90 | *
91 | * @param certKey
92 | */
93 | public void setCertKey(String certKey) {
94 | this.certKey = certKey;
95 | }
96 |
97 | /**
98 | * 获得证书的路径
99 | *
100 | * @return
101 | */
102 | public String getCertPath() {
103 | return certPath;
104 | }
105 |
106 | /**
107 | * 设置证书的路径
108 | *
109 | * @param certPath
110 | */
111 | public void setCertPath(String certPath) {
112 | this.certPath = certPath;
113 | }
114 |
115 | }
116 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/options/VxApiCorsOptions.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.options;
2 |
3 | import java.util.ArrayList;
4 | import java.util.LinkedHashSet;
5 | import java.util.Set;
6 |
7 | import io.vertx.core.http.HttpMethod;
8 | import io.vertx.core.json.JsonArray;
9 | import io.vertx.core.json.JsonObject;
10 |
11 | /**
12 | * 应用网关跨域设置
13 | *
14 | * @author Mirren
15 | *
16 | */
17 | public class VxApiCorsOptions {
18 |
19 | private String allowedOrigin;
20 | private boolean allowCredentials;
21 | private int maxAgeSeconds;
22 | private Set allowedMethods;// HttpMethod依赖io.vertx.core.http.HttpMethod
23 | private Set allowedHeaders;
24 | private Set exposedHeaders;
25 |
26 | private VxApiCorsOptions() {
27 | super();
28 | }
29 |
30 | public VxApiCorsOptions(String allowedOrigin) {
31 | super();
32 | }
33 |
34 | /**
35 | * 将对象装换为JsonString
36 | *
37 | * @return
38 | */
39 | public JsonObject toJson() {
40 | JsonObject json = new JsonObject();
41 | json.put("allowedOrigin", this.allowedOrigin);
42 | json.put("allowCredentials", this.allowCredentials);
43 | json.put("maxAgeSeconds", this.maxAgeSeconds);
44 | if (allowedMethods != null) {
45 | JsonArray ar = new JsonArray();
46 | this.allowedMethods.forEach(va -> {
47 | ar.add(va.toString());
48 | });
49 | json.put("allowedMethods", ar);
50 | }
51 | if (allowedHeaders != null) {
52 | json.put("allowedHeaders", new ArrayList<>(this.allowedHeaders));
53 | }
54 | if (exposedHeaders != null) {
55 | json.put("exposedHeaders", new ArrayList<>(this.exposedHeaders));
56 | }
57 | return json;
58 | }
59 |
60 | /**
61 | * 通过Json得到一个对象,如果Json对象为空或者是错误的格式放回一个null对象
62 | *
63 | * @param obj
64 | * @return
65 | */
66 | public static VxApiCorsOptions fromJson(JsonObject obj) {
67 | if (obj != null && obj.getValue("allowedOrigin") instanceof String) {
68 | VxApiCorsOptions options = new VxApiCorsOptions();
69 | options.setAllowedOrigin(obj.getString("allowedOrigin"));
70 | if (obj.getValue("allowCredentials") instanceof Boolean) {
71 | options.setAllowCredentials(obj.getBoolean("allowCredentials"));
72 | } else if (obj.getValue("allowCredentials") instanceof String) {
73 | if ("true".equals(obj.getString("allowCredentials"))
74 | || "false".equals(obj.getString("allowCredentials"))) {
75 | options.setAllowCredentials(Boolean.valueOf(obj.getString("allowCredentials")));
76 | }
77 | }
78 | if (obj.getValue("maxAgeSeconds") instanceof Number) {
79 | options.setMaxAgeSeconds(((Number) obj.getValue("maxAgeSeconds")).intValue());
80 | }
81 | if (obj.getValue("allowedHeaders") instanceof JsonArray) {
82 | Set linkedHashSet = new LinkedHashSet<>();
83 | obj.getJsonArray("allowedHeaders").forEach(item -> {
84 | if (item instanceof String) {
85 | linkedHashSet.add(item.toString());
86 | }
87 | });
88 | options.setAllowedHeaders(linkedHashSet);
89 | }
90 | if (obj.getValue("exposedHeaders") instanceof JsonArray) {
91 | Set linkedHashSet = new LinkedHashSet<>();
92 | obj.getJsonArray("exposedHeaders").forEach(item -> {
93 | if (item instanceof String) {
94 | linkedHashSet.add(item.toString());
95 | }
96 | });
97 | options.setExposedHeaders(linkedHashSet);
98 | }
99 | if (obj.getValue("allowedMethods") instanceof JsonArray) {
100 | Set linkedHashSet = new LinkedHashSet<>();
101 | obj.getJsonArray("allowedMethods").forEach(item -> {
102 | if (item instanceof String) {
103 | linkedHashSet.add(HttpMethod.valueOf(item.toString()));
104 | }
105 | });
106 | options.setAllowedMethods(linkedHashSet);
107 | }
108 | return options;
109 | } else {
110 | return null;
111 | }
112 | }
113 |
114 | public String getAllowedOrigin() {
115 | return allowedOrigin;
116 | }
117 |
118 | public void setAllowedOrigin(String allowedOrigin) {
119 | this.allowedOrigin = allowedOrigin;
120 | }
121 |
122 | public boolean isAllowCredentials() {
123 | return allowCredentials;
124 | }
125 |
126 | public void setAllowCredentials(boolean allowCredentials) {
127 | this.allowCredentials = allowCredentials;
128 | }
129 |
130 | public int getMaxAgeSeconds() {
131 | return maxAgeSeconds;
132 | }
133 |
134 | public void setMaxAgeSeconds(int maxAgeSeconds) {
135 | this.maxAgeSeconds = maxAgeSeconds;
136 | }
137 |
138 | public Set getAllowedMethods() {
139 | return allowedMethods;
140 | }
141 |
142 | public void setAllowedMethods(Set allowedMethods) {
143 | this.allowedMethods = allowedMethods;
144 | }
145 |
146 | public Set getAllowedHeaders() {
147 | return allowedHeaders;
148 | }
149 |
150 | public void setAllowedHeaders(Set allowedHeaders) {
151 | this.allowedHeaders = allowedHeaders;
152 | }
153 |
154 | public Set getExposedHeaders() {
155 | return exposedHeaders;
156 | }
157 |
158 | public void setExposedHeaders(Set exposedHeaders) {
159 | this.exposedHeaders = exposedHeaders;
160 | }
161 |
162 | @Override
163 | public String toString() {
164 | return "VxApiCorsOptions [allowedOrigin=" + allowedOrigin + ", allowCredentials=" + allowCredentials
165 | + ", maxAgeSeconds=" + maxAgeSeconds + ", allowedMethods=" + allowedMethods + ", allowedHeaders="
166 | + allowedHeaders + ", exposedHeaders=" + exposedHeaders + "]";
167 | }
168 |
169 | }
170 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/options/VxApiParamCheckOptions.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.options;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import io.vertx.core.json.JsonArray;
7 | import io.vertx.core.json.JsonObject;
8 |
9 | /**
10 | * 参数检查的配置
11 | *
12 | * @author Mirren
13 | *
14 | */
15 | public class VxApiParamCheckOptions {
16 | private Long maxLength;// 字符串的最大长度
17 | private Number minValue;// 数值的最小值
18 | private Number maxValue;// 数值的最大值
19 | private String regex;// 正则表达式
20 | private List enums;// 枚举类
21 |
22 | /**
23 | * 将对象转换为json
24 | *
25 | * @return
26 | */
27 | public JsonObject toJson() {
28 | JsonObject json = new JsonObject();
29 | if (maxLength != null) {
30 | json.put("maxLength", this.maxLength);
31 | }
32 | if (minValue != null) {
33 | json.put("minValue", this.minValue);
34 | }
35 | if (maxValue != null) {
36 | json.put("maxValue", this.maxValue);
37 | }
38 | if (regex != null) {
39 | json.put("regex", this.regex);
40 | }
41 | if (enums != null) {
42 | json.put("enums", enums);
43 | }
44 | return json;
45 | }
46 |
47 | /**
48 | * 通过json实例化一个对象
49 | *
50 | * @param obj
51 | * @return
52 | */
53 | public static VxApiParamCheckOptions fromJson(JsonObject obj) {
54 | if (obj == null) {
55 | return null;
56 | }
57 | VxApiParamCheckOptions option = new VxApiParamCheckOptions();
58 | if (obj.getValue("maxLength") instanceof Number) {
59 | option.setMaxLength(((Number) obj.getValue("maxLength")).longValue());
60 | }
61 | if (obj.getValue("minValue") instanceof Number) {
62 | option.setMinValue((Number) obj.getValue("minValue"));
63 | }
64 | if (obj.getValue("maxValue") instanceof Number) {
65 | option.setMaxValue((Number) obj.getValue("maxValue"));
66 | }
67 | if (obj.getValue("regex") instanceof String) {
68 | option.setRegex(obj.getString("regex"));
69 | }
70 | if (obj.getValue("enums") instanceof JsonArray) {
71 | List list = new ArrayList<>();
72 | obj.getJsonArray("enums").forEach(va -> {
73 | if (va instanceof String) {
74 | list.add(va.toString());
75 | }
76 | });
77 | option.setEnums(list);
78 | }
79 | return option;
80 | }
81 |
82 | public VxApiParamCheckOptions() {
83 | super();
84 | }
85 |
86 | public VxApiParamCheckOptions(Long maxLength, Number minValue, Number maxValue, String regex, List enums) {
87 | super();
88 | this.maxLength = maxLength;
89 | this.minValue = minValue;
90 | this.maxValue = maxValue;
91 | this.regex = regex;
92 | this.enums = enums;
93 | }
94 |
95 | public Long getMaxLength() {
96 | return maxLength;
97 | }
98 |
99 | public void setMaxLength(Long maxLength) {
100 | this.maxLength = maxLength;
101 | }
102 |
103 | public Number getMinValue() {
104 | return minValue;
105 | }
106 |
107 | public void setMinValue(Number minValue) {
108 | this.minValue = minValue;
109 | }
110 |
111 | public Number getMaxValue() {
112 | return maxValue;
113 | }
114 |
115 | public void setMaxValue(Number maxValue) {
116 | this.maxValue = maxValue;
117 | }
118 |
119 | public String getRegex() {
120 | return regex;
121 | }
122 |
123 | public void setRegex(String regex) {
124 | this.regex = regex;
125 | }
126 |
127 | public List getEnums() {
128 | return enums;
129 | }
130 |
131 | public void setEnums(List enums) {
132 | this.enums = enums;
133 | }
134 |
135 | @Override
136 | public String toString() {
137 | return "VxApiParamCheckOptions [maxLength=" + maxLength + ", minValue=" + minValue + ", maxValue=" + maxValue
138 | + ", regex=" + regex + ", enums=" + enums + "]";
139 | }
140 |
141 | }
142 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/options/VxApiParamOptions.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.options;
2 |
3 | import com.szmirren.vxApi.core.enums.ParamPositionEnum;
4 | import com.szmirren.vxApi.core.enums.ParamSystemVarTypeEnum;
5 | import com.szmirren.vxApi.core.enums.ParamTypeEnum;
6 |
7 | import io.vertx.core.json.JsonObject;
8 |
9 | /**
10 | * 用于映射前后端对应的参数值
11 | *
12 | * @author Mirren
13 | *
14 | */
15 | public class VxApiParamOptions {
16 | private String apiParamName;// 网关参数的名字
17 | private ParamPositionEnum apiParamPosition;// 网关参数的位置
18 | private String serParamName;// 服务端参数的名字
19 | private ParamPositionEnum serParamPosition;// 服务端参数的位置
20 | private ParamTypeEnum paramType;// 前后端映射的参数类型
21 | private ParamSystemVarTypeEnum sysParamType;// 系统参数类型
22 | private Object paramValue;// 参数值
23 | private String describe;// 参数描述
24 | private int type = 0;// 参数的类型0=前端映射参数,1=系统参数,2=透传参数,9=自定义参数
25 |
26 | /**
27 | * 将对象装换为JsonObject
28 | *
29 | * @return
30 | */
31 | public JsonObject toJson() {
32 | JsonObject json = new JsonObject();
33 | if (this.apiParamName != null) {
34 | json.put("apiParamName", this.apiParamName);
35 | }
36 | if (this.apiParamPosition != null) {
37 | json.put("apiParamPosition", this.apiParamPosition);
38 | }
39 | json.put("serParamName", this.serParamName);
40 | json.put("serParamPosition", this.serParamPosition);
41 | json.put("paramType", this.paramType);
42 | if (this.paramValue != null) {
43 | json.put("paramValue", this.paramValue);
44 | }
45 | if (this.describe != null) {
46 | json.put("describe", this.describe);
47 | }
48 | if (this.sysParamType != null) {
49 | json.put("sysParamType", this.sysParamType);
50 | }
51 | json.put("type", this.type);
52 | return json;
53 | }
54 |
55 | /**
56 | * 通过JsonObject实例化一个对象
57 | *
58 | * @param obj
59 | * @return
60 | */
61 | public static VxApiParamOptions fromJson(JsonObject obj) {
62 | if (obj == null) {
63 | return null;
64 | }
65 | VxApiParamOptions option = new VxApiParamOptions();
66 | if (obj.getValue("apiParamName") instanceof String) {
67 | option.setApiParamName(obj.getString("apiParamName"));
68 | }
69 | if (obj.getValue("serParamName") instanceof String) {
70 | option.setSerParamName(obj.getString("serParamName"));
71 | }
72 | if (obj.getValue("apiParamPosition") instanceof String) {
73 | option.setApiParamPosition(ParamPositionEnum.valueOf(obj.getString("apiParamPosition")));
74 | }
75 | if (obj.getValue("serParamPosition") instanceof String) {
76 | option.setSerParamPosition(ParamPositionEnum.valueOf(obj.getString("serParamPosition")));
77 | }
78 | if (obj.getValue("paramType") instanceof String) {
79 | option.setParamType(ParamTypeEnum.valueOf(obj.getString("paramType")));
80 | }
81 | if (obj.getValue("describe") instanceof String) {
82 | option.setDescribe(obj.getString("describe"));
83 | }
84 | if (obj.getValue("sysParamType") instanceof String) {
85 | option.setSysParamType(ParamSystemVarTypeEnum.valueOf(obj.getString("sysParamType")));
86 | }
87 | if (obj.getValue("paramValue") != null) {
88 | option.setParamValue(obj.getValue("paramValue"));
89 | }
90 | if (obj.getValue("type") instanceof Number) {
91 | option.setType(((Number) obj.getValue("type")).intValue());
92 | }
93 | return option;
94 | }
95 |
96 | public VxApiParamOptions() {
97 | super();
98 | }
99 |
100 | public String getApiParamName() {
101 | return apiParamName;
102 | }
103 |
104 | public void setApiParamName(String apiParamName) {
105 | this.apiParamName = apiParamName;
106 | }
107 |
108 | public ParamPositionEnum getApiParamPosition() {
109 | return apiParamPosition;
110 | }
111 |
112 | public void setApiParamPosition(ParamPositionEnum apiParamPosition) {
113 | this.apiParamPosition = apiParamPosition;
114 | }
115 |
116 | public String getSerParamName() {
117 | return serParamName;
118 | }
119 |
120 | public void setSerParamName(String serParamName) {
121 | this.serParamName = serParamName;
122 | }
123 |
124 | public ParamPositionEnum getSerParamPosition() {
125 | return serParamPosition;
126 | }
127 |
128 | public void setSerParamPosition(ParamPositionEnum serParamPosition) {
129 | this.serParamPosition = serParamPosition;
130 | }
131 |
132 | public ParamTypeEnum getParamType() {
133 | return paramType;
134 | }
135 |
136 | public void setParamType(ParamTypeEnum paramType) {
137 | this.paramType = paramType;
138 | }
139 |
140 | public Object getParamValue() {
141 | return paramValue;
142 | }
143 |
144 | public void setParamValue(Object paramValue) {
145 | this.paramValue = paramValue;
146 | }
147 |
148 | public ParamSystemVarTypeEnum getSysParamType() {
149 | return sysParamType;
150 | }
151 |
152 | public void setSysParamType(ParamSystemVarTypeEnum sysParamType) {
153 | this.sysParamType = sysParamType;
154 | }
155 |
156 | public String getDescribe() {
157 | return describe;
158 | }
159 |
160 | public void setDescribe(String describe) {
161 | this.describe = describe;
162 | }
163 |
164 | /**
165 | * 参数的类型0=前端映射参数,1=系统参数,2=透传参数,9=自定义参数
166 | *
167 | * @return
168 | */
169 | public int getType() {
170 | return type;
171 | }
172 |
173 | public void setType(int type) {
174 | this.type = type;
175 | }
176 |
177 | }
178 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/options/VxApiServerEntranceHttpOptions.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.options;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import com.szmirren.vxApi.core.entity.VxApiServerURL;
7 | import com.szmirren.vxApi.core.enums.LoadBalanceEnum;
8 |
9 | import io.vertx.core.http.HttpMethod;
10 | import io.vertx.core.json.JsonArray;
11 | import io.vertx.core.json.JsonObject;
12 |
13 | /**
14 | * Api服务端处理类型为HTTP或者HTTPS
15 | *
16 | * @author Mirren
17 | *
18 | */
19 | public class VxApiServerEntranceHttpOptions {
20 | /** 默认的请求超时时间 */
21 | private final long DEFAULT_TIME_OUT = 6000L;
22 | /** 默认的请求超时时间 */
23 | private final long DEFAULT_RETRY_TIME = 30000L;
24 | /** 负载均衡类型 */
25 | private LoadBalanceEnum balanceType;
26 | /** 服务器的服务路径 */
27 | private List serverUrls;
28 | /** 请求的方式 */
29 | private HttpMethod method;
30 | /** 连接超时时间默认6000ms */
31 | private long timeOut = DEFAULT_TIME_OUT;
32 | /** 当服务连接不可用时,重试连接服务的间隔时间,默认30000ms */
33 | private long retryTime = DEFAULT_RETRY_TIME;
34 | /** 参数集 */
35 | private List params;
36 |
37 | /**
38 | * 将对象转换为JsonObject
39 | *
40 | * @return
41 | */
42 | public JsonObject toJson() {
43 | JsonObject json = new JsonObject();
44 | if (balanceType != null) {
45 | json.put("balanceType", this.balanceType);
46 | }
47 | if (this.serverUrls != null) {
48 | JsonArray array = new JsonArray();
49 | this.serverUrls.forEach(va -> {
50 | array.add(va.toJson());
51 | });
52 | json.put("serverUrls", array);
53 | }
54 | if (method != null) {
55 | json.put("method", this.method);
56 | }
57 | json.put("timeOut", this.timeOut);
58 | json.put("retryTime", this.retryTime);
59 | if (params != null) {
60 | JsonArray array = new JsonArray();
61 | params.forEach(va -> {
62 | array.add(va.toJson());
63 | });
64 | json.put("params", array);
65 | }
66 | return json;
67 | }
68 |
69 | /**
70 | * 通过一个JsonObject获得一个实例
71 | *
72 | * @param obj
73 | * @return
74 | */
75 | public static VxApiServerEntranceHttpOptions fromJson(JsonObject obj) {
76 | if (obj == null) {
77 | return null;
78 | }
79 | VxApiServerEntranceHttpOptions option = new VxApiServerEntranceHttpOptions();
80 | if (obj.getValue("balanceType") instanceof String) {
81 | option.setBalanceType(LoadBalanceEnum.valueOf(obj.getString("balanceType")));
82 | }
83 | if (obj.getValue("serverUrls") instanceof JsonArray) {
84 | List list = new ArrayList<>();
85 | obj.getJsonArray("serverUrls").forEach(va -> {
86 | if (va instanceof JsonObject) {
87 | list.add(VxApiServerURL.fromJson((JsonObject) va));
88 | } else if (va instanceof String) {
89 | list.add(VxApiServerURL.fromJson(new JsonObject(va.toString())));
90 | }
91 | });
92 | option.setServerUrls(list);
93 | }
94 | if (obj.getValue("method") instanceof String) {
95 | option.setMethod(HttpMethod.valueOf(obj.getString("method")));
96 | }
97 | if (obj.getValue("timeOut") instanceof Number) {
98 | option.setTimeOut(((Number) obj.getValue("timeOut")).longValue());
99 | }
100 | if (obj.getValue("retryTime") instanceof Number) {
101 | option.setRetryTime(((Number) obj.getValue("retryTime")).longValue());
102 | }
103 | if (obj.getValue("params") instanceof JsonArray) {
104 | List params = new ArrayList<>();
105 | obj.getJsonArray("params").forEach(va -> {
106 | params.add(VxApiParamOptions.fromJson((JsonObject) va));
107 | });
108 | option.setParams(params);
109 | }
110 |
111 | return option;
112 | }
113 |
114 | private VxApiServerEntranceHttpOptions() {
115 | super();
116 | }
117 |
118 | /**
119 | * 获得负责均衡类型
120 | *
121 | * @return
122 | */
123 | public LoadBalanceEnum getBalanceType() {
124 | return balanceType;
125 | }
126 |
127 | /**
128 | * 设置负载均衡类型
129 | *
130 | * @param balanceType
131 | */
132 | public void setBalanceType(LoadBalanceEnum balanceType) {
133 | this.balanceType = balanceType;
134 | }
135 |
136 | /**
137 | * 获得服务器的服务路径
138 | *
139 | * @return
140 | */
141 | public List getServerUrls() {
142 | return serverUrls;
143 | }
144 |
145 | /**
146 | * 设置服务器的服务路径
147 | *
148 | * @param serverUrls
149 | */
150 | public void setServerUrls(List serverUrls) {
151 | this.serverUrls = serverUrls;
152 | }
153 |
154 | /**
155 | * 获得请求方式
156 | *
157 | * @return
158 | */
159 | public HttpMethod getMethod() {
160 | return method;
161 | }
162 |
163 | /**
164 | * 设置请求方式
165 | *
166 | * @param method
167 | */
168 | public void setMethod(HttpMethod method) {
169 | this.method = method;
170 | }
171 |
172 | /**
173 | * 获取请求超时时间
174 | *
175 | * @return
176 | */
177 | public long getTimeOut() {
178 | return timeOut;
179 | }
180 |
181 | /**
182 | * 设置请求超时时间(ms),如果时间小于0则使用默认时间,默认6000ms
183 | *
184 | * @param timeOut
185 | */
186 | public void setTimeOut(long timeOut) {
187 | if (timeOut < 0) {
188 | this.timeOut = DEFAULT_TIME_OUT;
189 | } else {
190 | this.timeOut = timeOut;
191 | }
192 | }
193 |
194 | /**
195 | * 获得重试连接失效服务的时间
196 | *
197 | * @return
198 | */
199 | public long getRetryTime() {
200 | return retryTime;
201 | }
202 |
203 | /**
204 | * 设置重试连接失效服务的时间(ms),如果时间小于0则使用默认时间,默认30000ms
205 | *
206 | * @param retryTime
207 | */
208 | public void setRetryTime(long retryTime) {
209 | if (retryTime < 0) {
210 | this.retryTime = DEFAULT_RETRY_TIME;
211 | } else {
212 | this.retryTime = retryTime;
213 | }
214 | }
215 |
216 | /**
217 | * 获得参数集
218 | *
219 | * @return
220 | */
221 | public List getParams() {
222 | return params;
223 | }
224 |
225 | /**
226 | * 设置参数集
227 | *
228 | * @param params
229 | */
230 | public void setParams(List params) {
231 | this.params = params;
232 | }
233 |
234 | @Override
235 | public String toString() {
236 | return "VxApiServerEntranceHttpOptions [DEFAULT_TIME_OUT=" + DEFAULT_TIME_OUT + ", DEFAULT_RETRY_TIME=" + DEFAULT_RETRY_TIME
237 | + ", balanceType=" + balanceType + ", serverUrls=" + serverUrls + ", method=" + method + ", timeOut=" + timeOut + ", retryTime="
238 | + retryTime + ", params=" + params + "]";
239 | }
240 |
241 | }
242 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/options/VxApiServerEntranceRedirectOptions.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.options;
2 |
3 | import io.vertx.core.json.JsonObject;
4 |
5 | /**
6 | * Api服务端处理类型为Redirect
7 | *
8 | * @author Mirren
9 | *
10 | */
11 | public class VxApiServerEntranceRedirectOptions {
12 |
13 | private String url;// 将要跳转的URL路径
14 |
15 | /**
16 | * 将对象装换为JsonObject
17 | *
18 | * @return
19 | */
20 | public JsonObject toJson() {
21 | JsonObject json = new JsonObject();
22 | json.put("url", this.url);
23 | return json;
24 | }
25 |
26 | /**
27 | * 通过配置文件创建一个对象
28 | *
29 | * @param obj
30 | * @return
31 | */
32 | public static VxApiServerEntranceRedirectOptions fromJson(JsonObject obj) {
33 | if (obj == null || obj.getString("url") == null) {
34 | return null;
35 | }
36 | VxApiServerEntranceRedirectOptions options = new VxApiServerEntranceRedirectOptions();
37 | options.setUrl(obj.getString("url"));
38 | return options;
39 | }
40 |
41 | private VxApiServerEntranceRedirectOptions() {
42 | super();
43 | }
44 |
45 | public String getUrl() {
46 | return url;
47 | }
48 |
49 | public void setUrl(String url) {
50 | this.url = url;
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/options/VxApiServerOptions.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.options;
2 |
3 | import io.vertx.core.http.HttpServerOptions;
4 | import io.vertx.core.json.JsonObject;
5 |
6 | /**
7 | * 应用程序的端口号配置默认http=8330,https=8430,websocket=8530,
8 | *
9 | * @author Mirren
10 | *
11 | */
12 | public class VxApiServerOptions extends HttpServerOptions {
13 | /**
14 | * 默认HTTP端口号
15 | */
16 | public final static int HTTP_DEFAULT_PORT = 8330;
17 | /**
18 | * 默认的HTTPS端口号
19 | */
20 | public final static int HTTPS_DEFAULT_PORT = 8430;
21 | /**
22 | * 默认的webSocket端口号
23 | */
24 | public final static int WEB_SOCKET_DEFAULT_PORT = 8530;
25 | private boolean createHttp = true;// 是否开启http服务
26 | private boolean createHttps = false;// 是否开启https服务
27 | private boolean createwebSocket = false;// 是否开启WebSocket服务
28 | private int httpPort = HTTP_DEFAULT_PORT;// HTTP服务器的端口号
29 | private int httpsPort = HTTPS_DEFAULT_PORT;// HTTPS服务器的端口号
30 | private int webSocketPort = WEB_SOCKET_DEFAULT_PORT;// WebSocket服务器的端口号
31 | private VxApiCertOptions certOptions;// 服务器证书
32 | private String custom;// 拓展配置
33 |
34 | /**
35 | * 创建一个默认端口号的端口配置
36 | */
37 | public VxApiServerOptions() {
38 | super();
39 | }
40 |
41 | /**
42 | * 通过json实例化一个对象
43 | *
44 | * @param json
45 | */
46 | private VxApiServerOptions(JsonObject json) {
47 | super(json);
48 | }
49 |
50 | /**
51 | * 将对象转换为json
52 | *
53 | * @return
54 | */
55 | public JsonObject toJson() {
56 | JsonObject json = new JsonObject();
57 | json.put("createHttp", this.createHttp);
58 | json.put("createHttps", this.createHttps);
59 | json.put("createwebSocket", this.createwebSocket);
60 | json.put("httpPort", this.httpPort);
61 | json.put("httpsPort", this.httpsPort);
62 | json.put("webSocketPort", this.webSocketPort);
63 | if (certOptions != null) {
64 | if (!certOptions.toJson().isEmpty()) {
65 | json.put("certOptions", certOptions.toJson());
66 | }
67 | }
68 | if (custom != null) {
69 | json.put("custom", this.custom);
70 | }
71 | return json;
72 | }
73 |
74 | /**
75 | * 将一个json对象装换为VxApiCertOptions,如果JsonObject为null或者或者JsonObject没有数据返回null
76 | *
77 | * @param obj
78 | * @return
79 | */
80 | public static VxApiServerOptions fromJson(JsonObject obj) {
81 | VxApiServerOptions options;
82 | if (obj.getValue("custom") instanceof String) {
83 | try {
84 | options = new VxApiServerOptions(new JsonObject(obj.getString("custom")));
85 | } catch (Exception e) {
86 | options = new VxApiServerOptions();
87 | }
88 | options.setCustom(obj.getString("custom"));
89 | } else {
90 | options = new VxApiServerOptions();
91 | }
92 | if (obj.getValue("httpPort") instanceof Number) {
93 | options.setHttpPort(((Number) obj.getValue("httpPort")).intValue());
94 | }
95 | if (obj.getValue("httpsPort") instanceof Number) {
96 | options.setHttpsPort(((Number) obj.getValue("httpsPort")).intValue());
97 | }
98 | if (obj.getValue("webSocketPort") instanceof Number) {
99 | options.setWebSocketPort(((Number) obj.getValue("webSocketPort")).intValue());
100 | }
101 | if (obj.getValue("createHttp") instanceof Boolean) {
102 | options.setCreateHttp((Boolean) obj.getValue("createHttp"));
103 | }
104 | if (obj.getValue("createHttps") instanceof Boolean) {
105 | options.setCreateHttps((Boolean) obj.getValue("createHttps"));
106 | }
107 | if (obj.getValue("createwebSocket") instanceof Boolean) {
108 | options.setCreatewebSocket((Boolean) obj.getValue("createwebSocket"));
109 | }
110 | if (obj.getValue("certOptions") instanceof JsonObject) {
111 | options.setCertOptions(VxApiCertOptions.fromJson(obj.getJsonObject("certOptions")));
112 | }
113 | return options;
114 | }
115 |
116 | /**
117 | * 获得是否开启http服务器
118 | *
119 | * @return
120 | */
121 | public boolean isCreateHttp() {
122 | return createHttp;
123 | }
124 |
125 | /**
126 | * 设置是否开启http服务器
127 | *
128 | * @param createHttp
129 | */
130 | public void setCreateHttp(boolean createHttp) {
131 | this.createHttp = createHttp;
132 | }
133 |
134 | /**
135 | * 获得是否开启http服务器
136 | *
137 | * @return
138 | */
139 | public boolean isCreateHttps() {
140 | return createHttps;
141 | }
142 |
143 | /**
144 | * 设置是否开启https服务器
145 | *
146 | * @param createHttps
147 | */
148 | public void setCreateHttps(boolean createHttps) {
149 | this.createHttps = createHttps;
150 | }
151 |
152 | /**
153 | * 获得是否开启webSocket服务器
154 | *
155 | * @return
156 | */
157 | public boolean isCreatewebSocket() {
158 | return createwebSocket;
159 | }
160 |
161 | /**
162 | * 设置是否开启webSocket服务器
163 | *
164 | * @param createwebSocket
165 | */
166 | public void setCreatewebSocket(boolean createwebSocket) {
167 | this.createwebSocket = createwebSocket;
168 | }
169 |
170 | public int getHttpPort() {
171 | return httpPort;
172 | }
173 |
174 | public VxApiServerOptions setHttpPort(int httpPort) {
175 | this.httpPort = httpPort;
176 | return this;
177 | }
178 |
179 | public int getHttpsPort() {
180 | return httpsPort;
181 | }
182 |
183 | public VxApiServerOptions setHttpsPort(int httpsPort) {
184 | this.httpsPort = httpsPort;
185 | return this;
186 | }
187 |
188 | public int getWebSocketPort() {
189 | return webSocketPort;
190 | }
191 |
192 | public VxApiServerOptions setWebSocketPort(int webSocketPort) {
193 | this.webSocketPort = webSocketPort;
194 | return this;
195 | }
196 |
197 | /**
198 | * 获得服务器证书
199 | *
200 | * @return
201 | */
202 | public VxApiCertOptions getCertOptions() {
203 | return certOptions;
204 | }
205 |
206 | /**
207 | * 设置服务器证书
208 | *
209 | * @param certOptions
210 | */
211 | public void setCertOptions(VxApiCertOptions certOptions) {
212 | this.certOptions = certOptions;
213 | }
214 |
215 | /**
216 | * 获得拓展配置信息
217 | *
218 | * @return
219 | */
220 | public String getCustom() {
221 | return custom;
222 | }
223 |
224 | /**
225 | * 设置拓展配置信息
226 | *
227 | * @param custom
228 | */
229 | public void setCustom(String custom) {
230 | this.custom = custom;
231 | }
232 |
233 | @Override
234 | public String toString() {
235 | return "VxApiServerOptions [createHttp=" + createHttp + ", createHttps=" + createHttps + ", createwebSocket=" + createwebSocket
236 | + ", httpPort=" + httpPort + ", httpsPort=" + httpsPort + ", webSocketPort=" + webSocketPort + ", certOptions=" + certOptions
237 | + ", custom=" + custom + "]";
238 | }
239 |
240 | }
241 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/core/verticle/CURLClientVerticle.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.core.verticle;
2 |
3 | import java.text.MessageFormat;
4 |
5 | import org.apache.logging.log4j.LogManager;
6 | import org.apache.logging.log4j.Logger;
7 |
8 | import com.szmirren.vxApi.core.auth.VxApiClientJsonAuth;
9 | import com.szmirren.vxApi.core.auth.VxApiRolesConstant;
10 | import com.szmirren.vxApi.core.common.ResultFormat;
11 | import com.szmirren.vxApi.core.common.StrUtil;
12 | import com.szmirren.vxApi.core.common.VxApiEventBusAddressConstant;
13 | import com.szmirren.vxApi.core.enums.ContentTypeEnum;
14 | import com.szmirren.vxApi.core.enums.HTTPStatusCodeMsgEnum;
15 |
16 | import io.vertx.core.AbstractVerticle;
17 | import io.vertx.core.AsyncResult;
18 | import io.vertx.core.Future;
19 | import io.vertx.core.Handler;
20 | import io.vertx.core.json.JsonArray;
21 | import io.vertx.core.json.JsonObject;
22 | import io.vertx.ext.web.Router;
23 | import io.vertx.ext.web.RoutingContext;
24 | import io.vertx.ext.web.handler.BodyHandler;
25 | import io.vertx.ext.web.handler.ResponseContentTypeHandler;
26 |
27 | /**
28 | * VX-API的CURL客户端Verticle,
29 | *
30 | * @author Mirren
31 | *
32 | */
33 | public class CURLClientVerticle extends AbstractVerticle {
34 | private static final Logger LOG = LogManager.getLogger(CURLClientVerticle.class);
35 |
36 | /**
37 | * 返回的CONTENT_TYPE值JSON
38 | */
39 | private final String CONTENT_VALUE_JSON_UTF8 = ContentTypeEnum.JSON_UTF8.val();
40 | /**
41 | * 当前Vertx的唯一标识
42 | */
43 | private String thisVertxName;
44 |
45 | @Override
46 | public void start(Future fut) throws Exception {
47 | thisVertxName = System.getProperty("thisVertxName", "VX-API");
48 | Router router = Router.router(vertx);
49 | router.route().handler(BodyHandler.create());
50 | router.route().handler(ResponseContentTypeHandler.create());
51 | // 通过curl的方式创建网关应用
52 | router.route("/curl/findAPP").produces(CONTENT_VALUE_JSON_UTF8).handler(this::findAPPbyCURL);
53 | vertx.createHttpServer().requestHandler(router::accept).listen(5053, res -> {
54 | if (res.succeeded()) {
55 | System.out.println("The VX-API console running on port 5053");
56 | fut.complete();
57 | } else {
58 | fut.fail(res.cause());
59 | }
60 | });
61 | }
62 |
63 | /**
64 | * 查看所有应用网关,通过curl的方式
65 | *
66 | * @param rct
67 | */
68 | public void findAPPbyCURL(RoutingContext rct) {
69 | String user = rct.request().getParam("user");
70 | String pwd = rct.request().getParam("pwd");
71 | LOG.info(MessageFormat.format("[ip: {0},user: {1}] 访问curl模式->查看所有应用网关", rct.request().remoteAddress(), user));
72 | if (StrUtil.isNullOrEmpty(user, pwd)) {
73 | JsonObject authInfo = new JsonObject();
74 | authInfo.put(VxApiRolesConstant.USER_NAME_KEY, user);
75 | authInfo.put(VxApiRolesConstant.USER_PWD_KEY, pwd);
76 | authInfo.put(VxApiRolesConstant.USER_ROLE_KEY, VxApiRolesConstant.READ);
77 | Future.future(auth -> {
78 | // 进行用户权限认证
79 | VxApiClientJsonAuth.auth(authInfo, vertx, auth);
80 | }).compose((auth) -> Future.future(findApp -> {
81 | LOG.info("[user: " + user + "] 访问curl模式->查看所有应用网关-->鉴权结果: " + auth);
82 | // 检查用户权限并查询所有应用网关
83 | if (auth) {
84 | vertx.eventBus().send(thisVertxName + VxApiEventBusAddressConstant.FIND_APP, null, reply -> {
85 | if (reply.succeeded()) {
86 | findApp.complete(reply.result().body());
87 | } else {
88 | findApp.fail(reply.cause());
89 | }
90 | });
91 | } else {
92 | rct.response().end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401));
93 | findApp.fail("VX-API Manual response");
94 | }
95 | })).setHandler(res -> {
96 | LOG.info("[user:" + user + "] 访问curl模式->查看所有应用网关-->执行结果: " + res.succeeded());
97 | // 统一失败处理与创建文件是否成功!
98 | if (res.succeeded()) {
99 | JsonArray result = res.result();
100 | rct.response().end(ResultFormat.format(HTTPStatusCodeMsgEnum.C200, result));
101 | } else {
102 | if (res.cause() != null && !(res.cause().getMessage().contains("VX-API Manual response"))) {
103 | LOG.error("[user:" + user + "] 访问curl模式->查看所有应用网关-->异常:" + res.cause());
104 | }
105 | if (res.cause() == null) {
106 | rct.response().end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C1000));
107 | } else if (res.cause().getMessage().contains("VX-API Manual response")) {
108 | } else {
109 | rct.response().end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, res.cause().toString()));
110 | }
111 | }
112 | });
113 | } else {
114 | rct.response().end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C1400));
115 | }
116 | }
117 |
118 | /**
119 | * 读取文件JsonObject文件并返回
120 | *
121 | * @param path
122 | * @param handler
123 | */
124 | public void readFile(String path, Handler> handler) {
125 | vertx.fileSystem().readFile(path, fileRes -> {
126 | try {
127 | JsonObject result = fileRes.result().toJsonObject();
128 | handler.handle(Future.succeededFuture(result));
129 | } catch (Exception e) {
130 | handler.handle(Future.failedFuture(e));
131 | }
132 | });
133 | }
134 |
135 | }
136 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/auth/VxApiAuth.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.auth;
2 |
3 | import io.vertx.core.Handler;
4 | import io.vertx.ext.web.RoutingContext;
5 |
6 | /**
7 | * 通用认证接口
8 | *
9 | * @author Mirren
10 | *
11 | */
12 | public interface VxApiAuth extends Handler {
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/auth/VxApiAuthFactory.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.auth;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import com.szmirren.vxApi.core.common.StrUtil;
7 | import com.szmirren.vxApi.core.entity.VxApis;
8 | import com.szmirren.vxApi.spi.auth.impl.VxApiAuthJwtTokenImpl;
9 | import com.szmirren.vxApi.spi.auth.impl.VxApiAuthSessionTokenImpl;
10 |
11 | import io.vertx.core.http.HttpClient;
12 | import io.vertx.core.json.JsonObject;
13 |
14 | /**
15 | * VxApiAuth 实现工厂
16 | *
17 | * @author Mirren
18 | *
19 | */
20 | public class VxApiAuthFactory {
21 | /**
22 | * sessionToken的实现类名称
23 | */
24 | public final static String SESSION_TOKEN_AUTH = "sessionTokenAuth";
25 |
26 | public final static String JWT_TOKEN_AUTH = "jwtTokenAuth";
27 |
28 | /**
29 | * 获得所有实现类的名字
30 | *
31 | * @return
32 | */
33 | public static List getImplNames() {
34 | List result = new ArrayList<>();
35 | result.add(SESSION_TOKEN_AUTH);
36 | return result;
37 | }
38 |
39 | /**
40 | * 通过名字获得相应的权限实现类,可采用本类自带的静态字符串,如果配置信息类为空则采用默认的实现类
41 | *
42 | * @param name
43 | * 实现类的在工厂中的名字,可以使用本类静态属性
44 | * @param options
45 | * 配置信息
46 | * @return
47 | * @throws ClassNotFoundException
48 | */
49 | public static VxApiAuth getVxApiAuth(String name, JsonObject options, VxApis api, HttpClient httpClient)
50 | throws NullPointerException, ClassNotFoundException {
51 | if (StrUtil.isNullOrEmpty(name)) {
52 | throw new NullPointerException("获取API权限验证实现-->失败:工厂名字不能为空");
53 | }
54 | if (SESSION_TOKEN_AUTH.equalsIgnoreCase(name)) {
55 | return new VxApiAuthSessionTokenImpl(options);
56 | }
57 | if (JWT_TOKEN_AUTH.equalsIgnoreCase(name)) {
58 | return new VxApiAuthJwtTokenImpl(options);
59 | }
60 | throw new ClassNotFoundException("没有找到名字为 : " + name + " 的API权限验证实现类");
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/auth/VxApiAuthOptions.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.auth;
2 |
3 | import io.vertx.core.json.JsonObject;
4 |
5 | /**
6 | * 权限认证的配置信息
7 | *
8 | * @author Mirren
9 | *
10 | */
11 | public class VxApiAuthOptions {
12 | private String inFactoryName;// 实现类的名字
13 | private JsonObject option;// 配置信息
14 |
15 | /**
16 | * 将对象转为JsonObject
17 | *
18 | * @return
19 | */
20 | public JsonObject toJson() {
21 | JsonObject json = new JsonObject();
22 | json.put("inFactoryName", this.inFactoryName);
23 | json.put("option", this.option);
24 | return json;
25 | }
26 |
27 | /**
28 | * 通过Json对象获得一个实例
29 | *
30 | * @param obj
31 | * @return
32 | */
33 | public static VxApiAuthOptions fromJson(JsonObject obj) {
34 | if (obj == null) {
35 | return null;
36 | }
37 | VxApiAuthOptions option = new VxApiAuthOptions();
38 | if (obj.getValue("inFactoryName") instanceof String) {
39 | option.setInFactoryName(obj.getString("inFactoryName"));
40 | }
41 |
42 | if (obj.getValue("option") instanceof JsonObject) {
43 | option.setOption(obj.getJsonObject("option"));
44 | }
45 | return option;
46 | }
47 |
48 | private VxApiAuthOptions() {
49 | super();
50 | }
51 |
52 | public VxApiAuthOptions(String inFactoryName, JsonObject option) {
53 | super();
54 | this.inFactoryName = inFactoryName;
55 | this.option = option;
56 | }
57 |
58 | public String getInFactoryName() {
59 | return inFactoryName;
60 | }
61 |
62 | public void setInFactoryName(String inFactoryName) {
63 | this.inFactoryName = inFactoryName;
64 | }
65 |
66 | public JsonObject getOption() {
67 | return option;
68 | }
69 |
70 | public void setOption(JsonObject option) {
71 | this.option = option;
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/auth/impl/VxApiAuthJwtTokenImpl.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.auth.impl;
2 |
3 | import org.apache.logging.log4j.LogManager;
4 | import org.apache.logging.log4j.Logger;
5 |
6 | import com.auth0.jwt.JWT;
7 | import com.auth0.jwt.JWTVerifier;
8 | import com.auth0.jwt.algorithms.Algorithm;
9 | import com.auth0.jwt.interfaces.DecodedJWT;
10 | import com.szmirren.vxApi.core.common.ResultFormat;
11 | import com.szmirren.vxApi.core.common.VxApiGatewayAttribute;
12 | import com.szmirren.vxApi.core.enums.ContentTypeEnum;
13 | import com.szmirren.vxApi.core.enums.HTTPStatusCodeMsgEnum;
14 | import com.szmirren.vxApi.core.enums.ParamPositionEnum;
15 | import com.szmirren.vxApi.spi.auth.VxApiAuth;
16 | import com.szmirren.vxApi.spi.common.HttpHeaderConstant;
17 |
18 | import io.vertx.core.json.JsonArray;
19 | import io.vertx.core.json.JsonObject;
20 | import io.vertx.ext.web.RoutingContext;
21 |
22 | /**
23 | * JWTToken权限认证实现类
24 | *
25 | * @author onemy
26 | *
27 | */
28 | public class VxApiAuthJwtTokenImpl implements VxApiAuth {
29 | private static final Logger LOG = LogManager.getLogger(VxApiAuthJwtTokenImpl.class);
30 | /**
31 | * 存放Session中token值key的名字
32 | */
33 | private final static String VX_API_JWT_TOKEN_NAME = "apiToken";
34 | /**
35 | * 存放请求参数中token值key的名字
36 | */
37 | private final static String VX_API_USER_TOKEN_NAME = "apiName";
38 |
39 | private String apiTokenName;// 存在API网关token值的key名字
40 | private String userTokenName;// 用户请求token值的key名字
41 | private ParamPositionEnum userTokenScope = ParamPositionEnum.HEADER;// 用户请求token存放的位置,默认为header
42 | private ContentTypeEnum authFailContentType = ContentTypeEnum.JSON_UTF8;// 认证失败返回结果的contentType,默认json-utf8
43 | private String authFailResult;// 认证失败返回结果
44 |
45 | private JsonArray userKeys;
46 |
47 | @Override
48 | public void handle(RoutingContext event) {
49 | String token=event.request().getHeader(apiTokenName);
50 | String username=event.request().getHeader(userTokenName);
51 | String userKey=null;
52 |
53 | if(username==null||username.equals("")){
54 | event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
55 | .putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
56 | }
57 |
58 | for(Object object: userKeys){
59 | if(object instanceof JsonObject){
60 | if(((JsonObject) object).getString(username) instanceof String){
61 | userKey=((JsonObject) object).getString(username);
62 | }
63 | }
64 | }
65 |
66 | LOG.info("userKey:"+userKey);
67 |
68 | if(userKey==null||userKey.equals("")){
69 | event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
70 | .putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
71 | }
72 |
73 | JWTVerifier verifier=JWT.require(Algorithm.HMAC256(userKey)).build();
74 | DecodedJWT jwt=null;
75 |
76 | try{
77 | jwt=verifier.verify(token);
78 | event.next();
79 | }catch(Exception e){
80 | event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
81 | .putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
82 |
83 | //throw new RuntimeException("凭证无效或己过期!");
84 | }
85 |
86 | /*
87 | Session session = event.session();
88 | if (session == null) {
89 | event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
90 | .putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
91 | } else {
92 | // session中的token
93 | String apiToken = session.get(apiTokenName) == null ? null : session.get(apiTokenName).toString();
94 | // 用户request中的token
95 | String userTokoen = null;
96 | if (userTokenScope == ParamPositionEnum.HEADER) {
97 | userTokoen = event.request().getHeader(userTokenName);
98 | } else {
99 | userTokoen = event.request().getParam(userTokenName);
100 | }
101 | // 检验请求是否正确如果正确放行反则不通过
102 | if (!StrUtil.isNullOrEmpty(apiToken) && apiToken.equals(userTokoen)) {
103 | event.next();
104 | } else {
105 | event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
106 | .putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
107 | }
108 | }
109 | */
110 | }
111 |
112 | /**
113 | * @param obj
114 | * 通过一个JsonObject实例化一个对象
115 | * obj.apiTokenName = API中token的名字
116 | * obj.userTokenName = 用户token在请求中的名字
117 | * obj.userTokenScope =
118 | * 用户token在请求中的名字所在的位置枚举类型{@link ParamPositionEnum} 默认在HEADER中
119 | * obj.authFailContentType =
120 | * 验证不通过时返回的Content-Type枚举类型{@link ContentTypeEnum} 默认为JSON_UTF8
121 | * obj.authFailResult = 验证不通过时的返回结果 默认为
122 | * {@link ResultFormat}.formatAsNull({@link HTTPStatusCodeMsgEnum}.C401)
123 | */
124 | public VxApiAuthJwtTokenImpl(JsonObject obj) {
125 | if (obj == null) {
126 | throw new NullPointerException("JwtToken认证方式的配置文件不能为空!");
127 | }
128 | if (obj.getValue("apiTokenName") instanceof String) {
129 | this.apiTokenName = obj.getString("apiTokenName");
130 | } else {
131 | this.apiTokenName = VX_API_JWT_TOKEN_NAME;
132 | }
133 | if (obj.getValue("userTokenName") instanceof String) {
134 | this.userTokenName = obj.getString("userTokenName");
135 | } else {
136 | this.userTokenName = VX_API_USER_TOKEN_NAME;
137 | }
138 |
139 | if(obj.getJsonArray("secretKeys") instanceof JsonArray){
140 | this.userKeys=obj.getJsonArray("secretKeys");
141 |
142 | }
143 |
144 | if (obj.getValue("userTokenScope") instanceof String) {
145 | this.userTokenScope = ParamPositionEnum.valueOf(obj.getString("userTokenScope"));
146 | } else {
147 | this.userTokenScope = ParamPositionEnum.HEADER;
148 | }
149 | if (obj.getValue("authFailContentType") instanceof String) {
150 | this.authFailContentType = ContentTypeEnum.valueOf(obj.getString("authFailContentType"));
151 | } else {
152 | this.authFailContentType = ContentTypeEnum.JSON_UTF8;
153 | }
154 | if (obj.getValue("authFailResult") instanceof String) {
155 | this.authFailResult = obj.getString("authFailResult");
156 | } else {
157 | this.authFailResult = ResultFormat.formatAsNull(HTTPStatusCodeMsgEnum.C401);
158 | }
159 | }
160 | }
161 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/auth/impl/VxApiAuthSessionTokenImpl.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.auth.impl;
2 |
3 | import com.szmirren.vxApi.core.common.ResultFormat;
4 | import com.szmirren.vxApi.core.common.StrUtil;
5 | import com.szmirren.vxApi.core.common.VxApiGatewayAttribute;
6 | import com.szmirren.vxApi.core.enums.ContentTypeEnum;
7 | import com.szmirren.vxApi.core.enums.HTTPStatusCodeMsgEnum;
8 | import com.szmirren.vxApi.core.enums.ParamPositionEnum;
9 | import com.szmirren.vxApi.spi.auth.VxApiAuth;
10 | import com.szmirren.vxApi.spi.common.HttpHeaderConstant;
11 |
12 | import io.vertx.core.json.JsonObject;
13 | import io.vertx.ext.web.RoutingContext;
14 | import io.vertx.ext.web.Session;
15 |
16 | /**
17 | * SessionToken权限认证实现类
18 | *
19 | * @author Mirren
20 | *
21 | */
22 | public class VxApiAuthSessionTokenImpl implements VxApiAuth {
23 | /**
24 | * 存放Session中token值key的名字
25 | */
26 | private final static String VX_API_SESSION_TOKEN_NAME = "vxApiSessionToken";
27 | /**
28 | * 存放请求参数中token值key的名字
29 | */
30 | private final static String VX_API_USER_TOKEN_NAME = "vxApiUserToken";
31 |
32 | private String apiTokenName;// 存在API网关token值的key名字
33 | private String userTokenName;// 用户请求token值的key名字
34 | private ParamPositionEnum userTokenScope = ParamPositionEnum.HEADER;// 用户请求token存放的位置,默认为header
35 | private ContentTypeEnum authFailContentType = ContentTypeEnum.JSON_UTF8;// 认证失败返回结果的contentType,默认json-utf8
36 | private String authFailResult;// 认证失败返回结果
37 |
38 | @Override
39 | public void handle(RoutingContext event) {
40 | Session session = event.session();
41 | if (session == null) {
42 | if (!event.response().ended()) {
43 | event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
44 | .putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
45 | }
46 | } else {
47 | // session中的token
48 | String apiToken = session.get(apiTokenName) == null ? null : session.get(apiTokenName).toString();
49 | // 用户request中的token
50 | String userTokoen = null;
51 | if (userTokenScope == ParamPositionEnum.HEADER) {
52 | userTokoen = event.request().getHeader(userTokenName);
53 | } else {
54 | userTokoen = event.request().getParam(userTokenName);
55 | }
56 | // 检验请求是否正确如果正确放行反则不通过
57 | if (!StrUtil.isNullOrEmpty(apiToken) && apiToken.equals(userTokoen)) {
58 | event.next();
59 | } else {
60 | if (!event.response().ended()) {
61 | event.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
62 | .putHeader(HttpHeaderConstant.CONTENT_TYPE, authFailContentType.val()).end(authFailResult);
63 | }
64 | }
65 | }
66 | }
67 |
68 | /**
69 | * @param obj
70 | * 通过一个JsonObject实例化一个对象
71 | * obj.apiTokenName = API中token的名字
72 | * obj.userTokenName = 用户token在请求中的名字
73 | * obj.userTokenScope =
74 | * 用户token在请求中的名字所在的位置枚举类型{@link ParamPositionEnum} 默认在HEADER中
75 | * obj.authFailContentType =
76 | * 验证不通过时返回的Content-Type枚举类型{@link ContentTypeEnum} 默认为JSON_UTF8
77 | * obj.authFailResult = 验证不通过时的返回结果 默认为
78 | * {@link ResultFormat}.formatAsNull({@link HTTPStatusCodeMsgEnum}.C401)
79 | */
80 | public VxApiAuthSessionTokenImpl(JsonObject obj) {
81 | if (obj == null) {
82 | throw new NullPointerException("SessionToken认证方式的配置文件不能为空!");
83 | }
84 | if (obj.getValue("apiTokenName") instanceof String) {
85 | this.apiTokenName = obj.getString("apiTokenName");
86 | } else {
87 | this.apiTokenName = VX_API_SESSION_TOKEN_NAME;
88 | }
89 | if (obj.getValue("userTokenName") instanceof String) {
90 | this.userTokenName = obj.getString("userTokenName");
91 | } else {
92 | this.userTokenName = VX_API_USER_TOKEN_NAME;
93 | }
94 | if (obj.getValue("userTokenScope") instanceof String) {
95 | this.userTokenScope = ParamPositionEnum.valueOf(obj.getString("userTokenScope"));
96 | } else {
97 | this.userTokenScope = ParamPositionEnum.HEADER;
98 | }
99 | if (obj.getValue("authFailContentType") instanceof String) {
100 | this.authFailContentType = ContentTypeEnum.valueOf(obj.getString("authFailContentType"));
101 | } else {
102 | this.authFailContentType = ContentTypeEnum.JSON_UTF8;
103 | }
104 | if (obj.getValue("authFailResult") instanceof String) {
105 | this.authFailResult = obj.getString("authFailResult");
106 | } else {
107 | this.authFailResult = ResultFormat.formatAsNull(HTTPStatusCodeMsgEnum.C401);
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/common/HttpHeaderConstant.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.common;
2 |
3 | /**
4 | * 返回类型常用常量
5 | *
6 | * @author Mirren
7 | *
8 | */
9 | public interface HttpHeaderConstant {
10 | /**
11 | * Content-type
12 | */
13 | static String CONTENT_TYPE = "Content-Type";
14 | /**
15 | * server
16 | */
17 | static String SERVER = "Server";
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/customHandler/VxApiCustomHandler.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.customHandler;
2 |
3 | import io.vertx.core.Handler;
4 | import io.vertx.ext.web.RoutingContext;
5 |
6 | /**
7 | * 拓展处理器,用于做某些自定义的业务
8 | *
9 | * @author Mirren
10 | *
11 | */
12 | public interface VxApiCustomHandler extends Handler {
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/customHandler/VxApiCustomHandlerFactory.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.customHandler;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import com.szmirren.vxApi.core.common.StrUtil;
7 | import com.szmirren.vxApi.core.entity.VxApis;
8 | import com.szmirren.vxApi.spi.customHandler.impl.GetConstantValueHandler;
9 | import com.szmirren.vxApi.spi.customHandler.impl.GetServerUnixTimestampHandler;
10 | import com.szmirren.vxApi.spi.customHandler.impl.SessionTokenGrantAuthHandler;
11 |
12 | import io.vertx.core.http.HttpClient;
13 | import io.vertx.core.json.JsonObject;
14 |
15 | /**
16 | * 自定义处理器工厂
17 | *
18 | * @author Mirren
19 | *
20 | */
21 | public class VxApiCustomHandlerFactory {
22 | /**
23 | * 获得VxApi当前服务的unix时间戳
24 | */
25 | public static String GET_SERVER_UNIX_TIMESTAMP = "GET_SERVER_UNIX_TIMESTAMP";
26 | /**
27 | * 获得自定义常量
28 | */
29 | public static String GET_CONSTANT_VALUE = "GET_CONSTANT_VALUE";
30 | /**
31 | * session_token权限认证的授权
32 | */
33 | public static String SESSION_TOKEN_GRANT_AUTH = "SESSION_TOKEN_GRANT_AUTH";
34 |
35 | /**
36 | * 获得所有实现类名字
37 | *
38 | * @return
39 | */
40 | public static List getImplNames() {
41 | List result = new ArrayList<>();
42 | result.add(GET_SERVER_UNIX_TIMESTAMP);
43 | result.add(GET_CONSTANT_VALUE);
44 | result.add(SESSION_TOKEN_GRANT_AUTH);
45 | return result;
46 | }
47 |
48 | /**
49 | * 自定义处理器
50 | *
51 | * @param name
52 | * 处理器在工厂中的名字
53 | * @param options
54 | * 处理器配置文件
55 | *
56 | * @param api
57 | * API 相关配置文件
58 | * @param httpClient
59 | * http的客户端
60 | * @return
61 | * @throws NullPointerException
62 | * @throws ClassNotFoundException
63 | * @throws Exception
64 | */
65 | public static VxApiCustomHandler getCustomHandler(String name, JsonObject options, VxApis api, HttpClient httpClient)
66 | throws NullPointerException, ClassNotFoundException, Exception {
67 | if (StrUtil.isNullOrEmpty(name)) {
68 | throw new NullPointerException("获取自定义处理器-->失败:工厂名字不能为空");
69 | }
70 | if (SESSION_TOKEN_GRANT_AUTH.equalsIgnoreCase(name)) {
71 | return new SessionTokenGrantAuthHandler(options, api, httpClient);
72 | }
73 | if (GET_SERVER_UNIX_TIMESTAMP.equalsIgnoreCase(name)) {
74 | return new GetServerUnixTimestampHandler(options);
75 | }
76 | if (GET_CONSTANT_VALUE.equalsIgnoreCase(name)) {
77 | return new GetConstantValueHandler(options);
78 | }
79 | throw new ClassNotFoundException("没有找到名字为 : " + name + " 的实现类");
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/customHandler/VxApiCustomHandlerOptions.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.customHandler;
2 |
3 | import io.vertx.core.json.JsonObject;
4 |
5 | /**
6 | * 自定义处理器配置信息
7 | *
8 | * @author Mirren
9 | *
10 | */
11 | public class VxApiCustomHandlerOptions {
12 | private String inFactoryName;// 实现类的名字
13 | private boolean isNext = false;// 是否有后置处理器,用于判断是响应请求还是将请求传送到下一个处理器
14 | private JsonObject option;// 配置信息
15 |
16 | /**
17 | * 将对象转为JsonObject
18 | *
19 | * @return
20 | */
21 | public JsonObject toJson() {
22 | JsonObject json = new JsonObject();
23 | json.put("inFactoryName", this.inFactoryName);
24 | json.put("isNext", this.isNext);
25 | json.put("option", this.option);
26 | return json;
27 | }
28 |
29 | /**
30 | * 通过Json对象获得一个实例
31 | *
32 | * @param obj
33 | * @return
34 | */
35 | public static VxApiCustomHandlerOptions fromJson(JsonObject obj) {
36 | if (obj == null) {
37 | return null;
38 | }
39 | VxApiCustomHandlerOptions option = new VxApiCustomHandlerOptions();
40 | if (obj.getValue("inFactoryName") instanceof String) {
41 | option.setInFactoryName(obj.getString("inFactoryName"));
42 | }
43 | if (obj.getValue("isNext") instanceof Boolean) {
44 | option.setNext(obj.getBoolean("isNext"));
45 | }
46 | if (obj.getValue("option") instanceof JsonObject) {
47 | option.setOption(obj.getJsonObject("option"));
48 | }
49 | return option;
50 | }
51 |
52 | public VxApiCustomHandlerOptions() {
53 | super();
54 | }
55 |
56 | public VxApiCustomHandlerOptions(String inFactoryName, JsonObject option) {
57 | super();
58 | this.inFactoryName = inFactoryName;
59 | this.option = option;
60 | }
61 |
62 | public String getInFactoryName() {
63 | return inFactoryName;
64 | }
65 |
66 | public void setInFactoryName(String inFactoryName) {
67 | this.inFactoryName = inFactoryName;
68 | }
69 |
70 | public JsonObject getOption() {
71 | return option;
72 | }
73 |
74 | public void setOption(JsonObject option) {
75 | this.option = option;
76 | }
77 |
78 | public boolean isNext() {
79 | return isNext;
80 | }
81 |
82 | public void setNext(boolean isNext) {
83 | this.isNext = isNext;
84 | }
85 |
86 | @Override
87 | public String toString() {
88 | return "VxApiCustomHandlerOptions [inFactoryName=" + inFactoryName + ", isNext=" + isNext + ", option=" + option + "]";
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/customHandler/impl/GetConstantValueHandler.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.customHandler.impl;
2 |
3 | import com.szmirren.vxApi.core.common.VxApiGatewayAttribute;
4 | import com.szmirren.vxApi.core.enums.ContentTypeEnum;
5 | import com.szmirren.vxApi.spi.common.HttpHeaderConstant;
6 | import com.szmirren.vxApi.spi.customHandler.VxApiCustomHandler;
7 | import com.szmirren.vxApi.spi.handler.VxApiAfterHandler;
8 |
9 | import io.vertx.core.Future;
10 | import io.vertx.core.json.JsonObject;
11 | import io.vertx.ext.web.RoutingContext;
12 |
13 | /**
14 | * 返回常量值处理器
15 | *
16 | * @author Mirren
17 | *
18 | */
19 | public class GetConstantValueHandler implements VxApiCustomHandler {
20 | /**
21 | * 返回值默认等于null
22 | */
23 | private Object value = "null";
24 |
25 | /**
26 | * 返回结果定义,默认占位符为$(val)
27 | */
28 | private String resultFormat = "$(val)";
29 | /**
30 | * 路由器要结束了还是讲任务传到下一个处理器,默认为结束
31 | */
32 | private boolean isNext = false;
33 | /**
34 | * 默认的返回类型为json_utf8
35 | */
36 | private String contentType = ContentTypeEnum.JSON_UTF8.val();
37 |
38 | @Override
39 | public void handle(RoutingContext rct) {
40 | String result = resultFormat.replace("$(val)", value.toString());
41 | if (isNext) {
42 | rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.succeededFuture(true));// 告诉后置处理器当前操作成功执行
43 | rct.next();
44 | } else {
45 | if (!rct.response().ended()) {
46 | rct.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
47 | .putHeader(HttpHeaderConstant.CONTENT_TYPE, contentType).end(result);
48 | }
49 | }
50 |
51 | }
52 |
53 | /**
54 | * 初始化一个常量返回值处理器
55 | * option.value 要返回的值,默认值字符串null返回时以该值的toString方法,所以特殊返回值需要实现toString方法
56 | * option.resultFormat 格式化返回值,$(val)为值占位,默认值$(val)
57 | * option.isNext 是否还有后置处理器,默认false, true处理请求后next,false响应请求
58 | * option.contentType 返回的content-type 类型 <@ ContentTypeEnum.JSON_UTF8>
59 | *
60 | * @param option
61 | */
62 | public GetConstantValueHandler(JsonObject option) {
63 | if (option.getValue("value") != null) {
64 | this.value = option.getValue("value");
65 | }
66 | if (option.getValue("resultFormat") instanceof String) {
67 | this.resultFormat = option.getString("resultFormat");
68 | }
69 | if (option.getValue("isNext") instanceof Boolean) {
70 | this.isNext = option.getBoolean("isNext");
71 | }
72 | if (option.getValue("contentType") instanceof String) {
73 | this.contentType = option.getString("contentType");
74 | }
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/customHandler/impl/GetServerUnixTimestampHandler.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.customHandler.impl;
2 |
3 | import com.szmirren.vxApi.core.common.VxApiGatewayAttribute;
4 | import com.szmirren.vxApi.core.enums.ContentTypeEnum;
5 | import com.szmirren.vxApi.spi.common.HttpHeaderConstant;
6 | import com.szmirren.vxApi.spi.customHandler.VxApiCustomHandler;
7 | import com.szmirren.vxApi.spi.handler.VxApiAfterHandler;
8 |
9 | import io.vertx.core.Future;
10 | import io.vertx.core.json.JsonObject;
11 | import io.vertx.ext.web.RoutingContext;
12 |
13 | /**
14 | * 获得服务器时间戳
15 | *
16 | * @author Mirren
17 | *
18 | */
19 | public class GetServerUnixTimestampHandler implements VxApiCustomHandler {
20 | /**
21 | * 返回结果定义,默认占位符为$(val)
22 | */
23 | private String resultFormat = "$(val)";
24 | /**
25 | * 路由器要结束了还是讲任务传到下一个处理器,默认为结束
26 | */
27 | private boolean isNext = false;
28 | /**
29 | * 默认的返回类型为json_utf8
30 | */
31 | private String contentType = ContentTypeEnum.JSON_UTF8.val();
32 |
33 | @Override
34 | public void handle(RoutingContext rct) {
35 | String result = resultFormat.replace("$(val)", Long.toString(System.currentTimeMillis()));
36 | if (isNext) {
37 | rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.succeededFuture(true));// 告诉后置处理器当前操作成功执行
38 | rct.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(HttpHeaderConstant.CONTENT_TYPE,
39 | contentType);
40 | rct.next();
41 | } else {
42 | if (!rct.response().ended()) {
43 | rct.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
44 | .putHeader(HttpHeaderConstant.CONTENT_TYPE, contentType).end(result);
45 | }
46 | }
47 | }
48 |
49 | /**
50 | * 实例化一个返回服务器时间戳处理器
51 | * option.resultFormat 格式化返回值,$(val)为值占位,默认值$(val)
52 | * option.isNext 是否还有后置处理器,默认false, true处理请求后next,false响应请求
53 | * option.contentType 返回的content-type 类型 <@ ContentTypeEnum.JSON_UTF8>
54 | *
55 | * @param obj
56 | */
57 | public GetServerUnixTimestampHandler(JsonObject option) {
58 | if (option.getValue("resultFormat") instanceof String) {
59 | this.resultFormat = option.getString("resultFormat");
60 | }
61 | if (option.getValue("isNext") instanceof Boolean) {
62 | this.isNext = option.getBoolean("isNext");
63 | }
64 | if (option.getValue("contentType") instanceof String) {
65 | this.contentType = option.getString("contentType");
66 | }
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/handler/VxApiAfterHandler.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.handler;
2 |
3 | import io.vertx.core.Handler;
4 | import io.vertx.ext.web.RoutingContext;
5 |
6 | /**
7 | * API后置处理器,既API逻辑执行后完毕后做什么事情,
8 | * 逻辑处理做完后会在RoutingContext中put一个名为prev_is_success类型为{@AsyncResult}结果
9 | * 可以通过RoutingContext.get得到,key值为当前接口的PREV_IS_SUCCESS_KEY值
10 | * 做完后需要进行响应,比如router.next()或者end()
11 | *
12 | * @author Mirren
13 | *
14 | */
15 | public interface VxApiAfterHandler extends Handler {
16 | /**
17 | * 逻辑处理器操作结果的key值,用于通过该key值在route上下文中获取逻辑处理器的操作结果
18 | */
19 | static String PREV_IS_SUCCESS_KEY = "prev_is_success";
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/handler/VxApiAfterHandlerFactory.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.handler;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import com.szmirren.vxApi.core.common.StrUtil;
7 | import com.szmirren.vxApi.core.entity.VxApis;
8 |
9 | import io.vertx.core.http.HttpClient;
10 | import io.vertx.core.json.JsonObject;
11 |
12 | /**
13 | *
14 | * @author Mirren
15 | *
16 | */
17 | public class VxApiAfterHandlerFactory {
18 |
19 | /**
20 | * 获得所有实现类名字
21 | *
22 | * @return
23 | */
24 | public static List getImplNames() {
25 | List result = new ArrayList<>();
26 | // result.add(TEST_SIMPLE);
27 | return result;
28 | }
29 |
30 | /**
31 | * 获得后置处理器
32 | *
33 | * @param name
34 | * @param options
35 | * @return
36 | * @throws NullPointerException
37 | * @throws ClassNotFoundException
38 | */
39 | public static VxApiAfterHandler getAfterHandler(String name, JsonObject options, VxApis api, HttpClient httpClient)
40 | throws NullPointerException, ClassNotFoundException {
41 | if (StrUtil.isNullOrEmpty(name)) {
42 | throw new NullPointerException("获取后置处理器实现-->失败:工厂名字不能为空");
43 | }
44 | // if (TEST_SIMPLE.equalsIgnoreCase(name)) {
45 | // return new TestAfterHandlerSimple(api);
46 | // }
47 | throw new ClassNotFoundException("没有找到名字为 : " + name + " 的后置处理器实现类");
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/handler/VxApiAfterHandlerOptions.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.handler;
2 |
3 | import io.vertx.core.json.JsonObject;
4 |
5 | /**
6 | * API后置处理器共产,通过该名字获得相应的实现类
7 | *
8 | * @author Mirren
9 | *
10 | */
11 | public class VxApiAfterHandlerOptions {
12 | private String inFactoryName;// 实现类的名字
13 | private JsonObject option;// 配置信息
14 |
15 | /**
16 | * 将对象转为JsonObject
17 | *
18 | * @return
19 | */
20 | public JsonObject toJson() {
21 | JsonObject json = new JsonObject();
22 | json.put("inFactoryName", this.inFactoryName);
23 | json.put("option", this.option);
24 | return json;
25 | }
26 |
27 | /**
28 | * 通过Json对象获得一个实例
29 | *
30 | * @param obj
31 | * @return
32 | */
33 | public static VxApiAfterHandlerOptions fromJson(JsonObject obj) {
34 | if (obj == null) {
35 | return null;
36 | }
37 | VxApiAfterHandlerOptions option = new VxApiAfterHandlerOptions();
38 | if (obj.getValue("inFactoryName") instanceof String) {
39 | option.setInFactoryName(obj.getString("inFactoryName"));
40 | }
41 |
42 | if (obj.getValue("option") instanceof JsonObject) {
43 | option.setOption(obj.getJsonObject("option"));
44 | }
45 | return option;
46 | }
47 |
48 | public VxApiAfterHandlerOptions() {
49 | super();
50 | }
51 |
52 | public VxApiAfterHandlerOptions(String inFactoryName, JsonObject option) {
53 | super();
54 | this.inFactoryName = inFactoryName;
55 | this.option = option;
56 | }
57 |
58 | public String getInFactoryName() {
59 | return inFactoryName;
60 | }
61 |
62 | public void setInFactoryName(String inFactoryName) {
63 | this.inFactoryName = inFactoryName;
64 | }
65 |
66 | public JsonObject getOption() {
67 | return option;
68 | }
69 |
70 | public void setOption(JsonObject option) {
71 | this.option = option;
72 | }
73 |
74 | @Override
75 | public String toString() {
76 | return "BeforeHandlerOptions [inFactoryName=" + inFactoryName + ", option=" + option + "]";
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/handler/VxApiBeforeHandler.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.handler;
2 |
3 | import io.vertx.core.Handler;
4 | import io.vertx.ext.web.RoutingContext;
5 |
6 | /**
7 | * API前置处理器,既API执行前做什么事情
8 | *
9 | * @author Mirren
10 | *
11 | */
12 | public interface VxApiBeforeHandler extends Handler {
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/handler/VxApiBeforeHandlerFactory.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.handler;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import com.szmirren.vxApi.core.common.StrUtil;
7 | import com.szmirren.vxApi.core.entity.VxApis;
8 |
9 | import io.vertx.core.http.HttpClient;
10 | import io.vertx.core.json.JsonObject;
11 |
12 | /**
13 | * API前置置处理器共产,通过该名字获得相应的实现类
14 | *
15 | * @author Mirren
16 | *
17 | */
18 | public class VxApiBeforeHandlerFactory {
19 |
20 | /**
21 | * 获得实现类名字
22 | *
23 | * @return
24 | */
25 | public static List getImplNames() {
26 | List result = new ArrayList<>();
27 | // result.add(TEST_SIMPLE);
28 | return result;
29 | }
30 |
31 | /**
32 | * 获得前置处理器
33 | *
34 | * @param name
35 | * @param options
36 | * @return
37 | * @throws NullPointerException
38 | * @throws ClassNotFoundException
39 | */
40 | public static VxApiBeforeHandler getBeforeHandler(String name, JsonObject options, VxApis api, HttpClient httpClient)
41 | throws NullPointerException, ClassNotFoundException {
42 | if (StrUtil.isNullOrEmpty(name)) {
43 | throw new NullPointerException("获取前置处理器实现-->失败:工厂名字不能为空");
44 | }
45 | // if (TEST_SIMPLE.equalsIgnoreCase(name)) {
46 | // return new TestBeforeHandlerSimple(api);
47 | // }
48 | throw new ClassNotFoundException("没有找到名字为 : " + name + " 的前置处理器实现类");
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/handler/VxApiBeforeHandlerOptions.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.handler;
2 |
3 | import io.vertx.core.json.JsonObject;
4 |
5 | /**
6 | * API前置处理器配置信息,通过该名字获得相应的实现类
7 | *
8 | * @author Mirren
9 | *
10 | */
11 | public class VxApiBeforeHandlerOptions {
12 | private String inFactoryName;// 实现类的名字
13 | private JsonObject option;// 配置信息
14 |
15 | /**
16 | * 将对象转为JsonObject
17 | *
18 | * @return
19 | */
20 | public JsonObject toJson() {
21 | JsonObject json = new JsonObject();
22 | json.put("inFactoryName", this.inFactoryName);
23 | json.put("option", this.option);
24 | return json;
25 | }
26 |
27 | /**
28 | * 通过Json对象获得一个实例
29 | *
30 | * @param obj
31 | * @return
32 | */
33 | public static VxApiBeforeHandlerOptions fromJson(JsonObject obj) {
34 | if (obj == null) {
35 | return null;
36 | }
37 | VxApiBeforeHandlerOptions option = new VxApiBeforeHandlerOptions();
38 | if (obj.getValue("inFactoryName") instanceof String) {
39 | option.setInFactoryName(obj.getString("inFactoryName"));
40 | }
41 |
42 | if (obj.getValue("option") instanceof JsonObject) {
43 | option.setOption(obj.getJsonObject("option"));
44 | }
45 | return option;
46 | }
47 |
48 | public VxApiBeforeHandlerOptions() {
49 | super();
50 | }
51 |
52 | public VxApiBeforeHandlerOptions(String inFactoryName, JsonObject option) {
53 | super();
54 | this.inFactoryName = inFactoryName;
55 | this.option = option;
56 | }
57 |
58 | public String getInFactoryName() {
59 | return inFactoryName;
60 | }
61 |
62 | public void setInFactoryName(String inFactoryName) {
63 | this.inFactoryName = inFactoryName;
64 | }
65 |
66 | public JsonObject getOption() {
67 | return option;
68 | }
69 |
70 | public void setOption(JsonObject option) {
71 | this.option = option;
72 | }
73 |
74 | @Override
75 | public String toString() {
76 | return "BeforeHandlerOptions [inFactoryName=" + inFactoryName + ", option=" + option + "]";
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/handler/impl/TestAfterHandlerSimple.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.handler.impl;
2 |
3 | import com.szmirren.vxApi.core.entity.VxApis;
4 | import com.szmirren.vxApi.spi.handler.VxApiAfterHandler;
5 |
6 | import io.vertx.core.AsyncResult;
7 | import io.vertx.ext.web.RoutingContext;
8 |
9 | /**
10 | * 后置处理器处理示例
11 | *
12 | * @author Mirren
13 | *
14 | */
15 | public class TestAfterHandlerSimple implements VxApiAfterHandler {
16 | private VxApis apis;
17 |
18 | @Override
19 | public void handle(RoutingContext event) {
20 | // 这里得到主处理器的执行结果后可以做一些相应的处理,处理完毕后响应请求
21 | AsyncResult result = event.>get(PREV_IS_SUCCESS_KEY);
22 | if (result.succeeded()) {
23 | System.out.println("AfterHandler : " + apis);
24 | } else {
25 | System.out.println("AfterHandler error : " + result.cause());
26 | }
27 | event.response().end();
28 | }
29 |
30 | public TestAfterHandlerSimple(VxApis api) {
31 | super();
32 | this.apis = api;
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/szmirren/vxApi/spi/handler/impl/TestBeforeHandlerSimple.java:
--------------------------------------------------------------------------------
1 | package com.szmirren.vxApi.spi.handler.impl;
2 |
3 | import com.szmirren.vxApi.core.entity.VxApis;
4 | import com.szmirren.vxApi.spi.handler.VxApiBeforeHandler;
5 |
6 | import io.vertx.ext.web.RoutingContext;
7 |
8 | /**
9 | * 前置处理器处理示例
10 | *
11 | * @author Mirren
12 | *
13 | */
14 | public class TestBeforeHandlerSimple implements VxApiBeforeHandler {
15 | private VxApis apis;
16 |
17 | @Override
18 | public void handle(RoutingContext event) {
19 | // 这里做些什么事情后将请求放行到下一个处理器,或者在这里响应请求
20 | System.out.println("beforeHandler : " + apis);
21 | event.next();
22 | }
23 |
24 | public TestBeforeHandlerSimple(VxApis api) {
25 | super();
26 | this.apis = api;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/resources/cert/目录说明.txt:
--------------------------------------------------------------------------------
1 | 该目录用户放置SSL等所需要的证书
--------------------------------------------------------------------------------
/src/main/resources/conf.json:
--------------------------------------------------------------------------------
1 | {
2 | "cliConfig": {
3 | "startEverything": true
4 | },
5 | "cluster": {
6 | "clusterType": "NONE",
7 | "getVxApiConfFromCluster": false,
8 | "clusterConf": {
9 | "zookeeperHosts": "127.0.0.1",
10 | "sessionTimeout": 20000,
11 | "connectTimeout": 3000,
12 | "rootPath": "io.vertx",
13 | "vxApiConfPath": "/io.vertx/vx.api.gateway/conf",
14 | "retry": {
15 | "initialSleepTime": 100,
16 | "intervalTimes": 10000,
17 | "maxTimes": 5
18 | }
19 | }
20 | },
21 | "dataConfig": {
22 | "provider_class": "com.szmirren.vxApi.core.common.DataSourceProviderOfDruid",
23 | "url": "jdbc:sqlite:configDB.db",
24 | "driver_class": "org.sqlite.JDBC"
25 | },
26 | "clientConfig": {
27 | "clientPort": 5256
28 | }
29 | }
--------------------------------------------------------------------------------
/src/main/resources/configDB.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EliMirren/VX-API-Gateway/fffd8bffa91d6dc6e79b304416179f797bf72e41/src/main/resources/configDB.db
--------------------------------------------------------------------------------
/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.rootLogger=INFO, Console,ERROR,warn
2 |
3 | #Console
4 | log4j.appender.Console=org.apache.log4j.ConsoleAppender
5 | log4j.appender.Console.layout=org.apache.log4j.PatternLayout
6 | log4j.appender.Console.layout.ConversionPattern=[%p] %-d{yyyy-MM-dd HH\:mm\:ss} --> %m --> %F:%L %n
7 |
8 |
9 | ### 保存异常信息到单独文件 ###
10 | log4j.appender.ERROR = org.apache.log4j.DailyRollingFileAppender
11 | ###设置DatePattern,当天日志保存到error.log文件,前一天的日志文件名将被修改为
12 | #error.log + _yyyy-MM-dd.log
13 | log4j.appender.ERROR.File =../logs/thrid/error.log
14 | log4j.appender.ERROR.DatePattern = '_'yyyy-MM-dd'.log'
15 | log4j.appender.ERROR.Append = true
16 | ## 只输出ERROR级别以上的日志!!!
17 | log4j.appender.ERROR.Threshold = ERROR
18 | log4j.appender.ERROR.layout = org.apache.log4j.PatternLayout
19 | log4j.appender.ERROR.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} %l ---> %l %m%n
20 |
21 | ### 保存警告信息到单独文件 ###
22 | log4j.appender.warn = org.apache.log4j.DailyRollingFileAppender
23 | ###设置DatePattern,当天日志保存到error.log文件,前一天的日志文件名将被修改为
24 | #error.log + _yyyy-MM-dd.log
25 | log4j.appender.warn.File =../logs/thrid/warn.log
26 | log4j.appender.warn.DatePattern = '_'yyyy-MM-dd'.log'
27 | log4j.appender.warn.Append = true
28 | ## 只输出info级别以上的日志!!!
29 | log4j.appender.warn.Threshold = WARN
30 | log4j.appender.warn.layout = org.apache.log4j.PatternLayout
31 | log4j.appender.warn.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} %l ---> %l %m%n
32 |
33 |
--------------------------------------------------------------------------------
/src/main/resources/log4j2-test.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | logs
6 |
7 | history
8 |
9 | debug
10 |
11 | debug
12 |
13 | com.szmirren.vxApi
14 |
15 |
16 |
17 |
18 |
20 |
21 |
23 |
24 |
27 |
28 |
29 |
31 |
33 |
34 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
46 |
47 |
49 |
51 |
52 |
54 |
55 |
56 |
57 |
58 |
59 |
62 |
64 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
85 |
86 |
87 |
88 |
89 |
90 |
92 |
93 |
94 |
95 |
96 |
97 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
--------------------------------------------------------------------------------
/src/main/resources/log4j2.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ../logs
6 |
7 | history
8 |
9 | info
10 |
11 | error
12 |
13 | com.szmirren.vxApi
14 |
15 |
16 |
17 |
18 |
20 |
21 |
23 |
24 |
27 |
28 |
29 |
31 |
33 |
34 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
46 |
47 |
49 |
51 |
52 |
54 |
55 |
56 |
57 |
58 |
59 |
62 |
64 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
79 |
80 |
81 |
82 |
83 |
84 |
86 |
87 |
88 |
89 |
90 |
91 |
93 |
94 |
95 |
96 |
97 |
98 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
--------------------------------------------------------------------------------
/src/main/resources/static/API.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | VX-API-APIs
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
25 |
26 |
27 |
28 | - 应用列表
29 | - API管理 (部分页面使用了js的go(-1),当看不到最新数据时可以使用CTRL+F5刷新得到最新数据)
30 |
31 |
32 |
33 |
新建API
34 |
35 |
36 |
37 |
38 | API名称 |
39 | 描述 |
40 | Path |
41 | 创建时间 |
42 | 运行环境 |
43 | 查看详情 |
44 |
45 |
46 |
47 |
48 |
49 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
141 |
142 |
143 |
--------------------------------------------------------------------------------
/src/main/resources/static/Application.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | VX-API-Gateway
8 |
10 |
11 |
13 |
14 |
15 |
16 |
17 |
26 |
27 |
31 |
32 |
33 |
34 |
35 |
36 |
新建应用
37 |
38 |
39 |
40 |
41 |
42 |
43 | 应用名称 |
44 | 应用描述 |
45 | 创建时间 |
46 | 应用环境 |
47 | 状态 |
48 | 操作 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
109 |
110 |
111 |
--------------------------------------------------------------------------------
/src/main/resources/static/css/page.css:
--------------------------------------------------------------------------------
1 |
2 | .page{
3 | list-style: none;
4 | }
5 | .page>li{
6 | float: left;
7 | padding: 5px 10px;
8 | cursor: pointer;
9 | }
10 | .page .pageItem{
11 | border: solid thin #DDDDDD;
12 | margin: 5px;
13 | }
14 | .page .pageItemActive{
15 | border: solid thin #337ab7;
16 | margin: 5px;
17 | background-color: #337ab7;
18 | color:white;
19 | }
20 | .page .pageItem:hover{
21 | border: solid thin #337ab7;
22 | background-color: #337ab7;
23 | color:white;
24 | }
25 | .page .pageItemDisable{
26 | border: solid thin #DDDDDD;
27 | margin: 5px;
28 | background-color: #DDDDDD;
29 | }
--------------------------------------------------------------------------------
/src/main/resources/static/js/APISelectChange.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by Mirren on 2018/2/13.
3 | */
4 | // 权限认证改变事件
5 | $("#auth-options-name").change(function () {
6 | if ($(this).val() == 'none') {
7 | $(".auth-hide-show").hide();
8 | } else if ($(this).val() == 'sessionTokenAuth') {
9 | $("#auth-options-config").val('{\n"apiTokenName":"vxApiSessionToken",\n"userTokenName":"vxApiUserToken",\n"userTokenScope":"HEADER",\n"authFailContentType":"HTML_UTF8",\n"authFailResult":"Unauthorized"\n}');
10 | $(".auth-hide-show").show();
11 | } else {
12 | $("#auth-options-config").val('');
13 | $("#auth-options-config").val('{\n"apiTokenName":"apiToken",\n"userTokenName":"apiName",\n"secretKeys":[{"admin":"secret"},{"test":"123456"}]}');
14 | $(".auth-hide-show").show();
15 | }
16 | });
17 | //访问限制改变事件
18 | $("#limitUnit").change(function () {
19 | if ($(this).val() == 'none') {
20 | $(".limit-hide-show").hide();
21 | } else {
22 | $(".limit-hide-show").show();
23 | }
24 | });
25 | $(function () {
26 | if ($("#auth-options-name").val() == 'none') {
27 | $(".auth-hide-show").hide();
28 | } else {
29 | $(".auth-hide-show").show();
30 | }
31 | if ($("#limitUnit").val() == 'none') {
32 | $(".limit-hide-show").hide();
33 | } else {
34 | $(".limit-hide-show").show();
35 | }
36 | });
37 | //前置处理器改变事件
38 | $("#beforeHandler").change(function () {
39 | if ($(this).val() == 'none') {
40 | $(".beforeHandler-hide-show").hide();
41 | } else {
42 | $(".beforeHandler-hide-show").show();
43 | }
44 | });
45 | //后置处理器改变事件
46 | $("#afterHandler").change(function () {
47 | if ($(this).val() == 'none') {
48 | $(".afterHandler-hide-show").hide();
49 | } else {
50 | $(".afterHandler-hide-show").show();
51 | }
52 | });
53 |
54 | //前置与后置处理器改变事件
55 | $(function () {
56 | if ($("#beforeHandler").val() == 'none') {
57 | $(".beforeHandler-hide-show").hide();
58 | } else {
59 | $(".beforeHandler-hide-show").show();
60 | }
61 | if ($("#afterHandler").val() == 'none') {
62 | $(".afterHandler-hide-show").hide();
63 | } else {
64 | $(".afterHandler-hide-show").show();
65 | }
66 | });
67 |
68 |
69 | //后端服务类型改变事件
70 | $("#custom_server_type").change(function () {
71 | if($(this).val() == 'GET_SERVER_UNIX_TIMESTAMP'){//获得服务器时间戳
72 | $(".custom_server_type_tips").text(" $(val) 为返回结果值的占位符,VX-API会将其替换为时间戳");
73 | $("#custom-option").val('{"resultFormat":"$(val)"}');
74 | }else if ($(this).val() == 'GET_CONSTANT_VALUE'){//获得常量值
75 | $(".custom_server_type_tips").text(" $(val) 为返回结果值的占位符,VX-API会将其替换为值");
76 | $("#custom-option").val('{"value":"null","resultFormat":"$(val)"}');
77 | }else if ($(this).val() == 'SESSION_TOKEN_GRANT_AUTH'){//获得基于Session-token的授权
78 | $(".custom_server_type_tips").text('');
79 | $("#custom-option").val('{"saveTokenName":"vxApiSessionToken","getTokenName":"vxApiUserToken","balanceType":"POLLING_AVAILABLE","method":"GET","timeOut":6000,"retryTime":30000,"serverUrls":[{"url":"http://127.0.0.1/test","weight":0}]}');
80 | }
81 | });
82 |
83 |
84 |
85 | //返回结果Conten-Type改变事件
86 | $("#content-type").change(function () {
87 | if ($(this).val() == 'custom') {
88 | $("#custom-content-type-hide-show").show();
89 | } else {
90 | $("#custom-content-type-hide-show").hide();
91 | }
92 | });
93 | $(function () {
94 | if ($("#content-type").val() == 'custom') {
95 | $("#custom-content-type-hide-show").show();
96 | } else {
97 | $("#custom-content-type-hide-show").hide();
98 | }
99 | });
100 |
--------------------------------------------------------------------------------
/src/main/resources/static/js/page.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by zxm on 2017/3/31.
3 | */
4 | $.fn.extend({
5 | "initPage":function(listCount,currentPage){
6 | var maxshowpageitem = $(this).attr("maxshowpageitem");
7 | if(maxshowpageitem!=null&&maxshowpageitem>0&&maxshowpageitem!=""){
8 | page.maxshowpageitem = maxshowpageitem;
9 | }
10 | var pagelistcount = $(this).attr("pagelistcount");
11 | if(pagelistcount!=null&&pagelistcount>0&&pagelistcount!=""){
12 | page.pagelistcount = pagelistcount;
13 | }
14 |
15 | var pageId = $(this).attr("id");
16 | page.pageId=pageId;
17 | if(listCount<0){
18 | listCount = 0;
19 | }
20 | if(currentPage<=0){
21 | currentPage=1;
22 | }
23 | page.setPageListCount(listCount,currentPage);
24 |
25 | }
26 | });
27 | var page = {
28 | "pageId":"",
29 | "maxshowpageitem":5,//最多显示的页码个数
30 | "pagelistcount":10,//每一页显示的内容条数
31 | /**
32 | * 初始化分页界面
33 | * @param listCount 列表总量
34 | */
35 | "initWithUl":function(listCount,currentPage){
36 | var pageCount = 1;
37 | if(listCount>=0){
38 | var pageCount = listCount%page.pagelistcount>0?parseInt(listCount/page.pagelistcount)+1:parseInt(listCount/page.pagelistcount);
39 | }
40 | var appendStr = page.getPageListModel(pageCount,currentPage);
41 | $("#"+page.pageId).html(appendStr);
42 | },
43 | /**
44 | * 设置列表总量和当前页码
45 | * @param listCount 列表总量
46 | * @param currentPage 当前页码
47 | */
48 | "setPageListCount":function(listCount,currentPage){
49 | listCount = parseInt(listCount);
50 | currentPage = parseInt(currentPage);
51 | page.initWithUl(listCount,currentPage);
52 | },
53 | "getPageListModel":function(pageCount,currentPage){
54 | var prePage = currentPage-1;
55 | var nextPage = currentPage+1;
56 | var prePageClass ="pageItem";
57 | var nextPageClass = "pageItem";
58 | if(prePage<=0){
59 | prePageClass="pageItemDisable";
60 | }
61 | if(nextPage>pageCount){
62 | nextPageClass="pageItemDisable";
63 | }
64 | var appendStr ="";
65 | if(prePage<=0){
66 | appendStr+="首页";
67 | appendStr+="<上一页";
68 | }else{
69 | appendStr+="首页";
70 | appendStr+="<上一页";
71 | }
72 | var miniPageNumber = 1;
73 | if(currentPage-parseInt(page.maxshowpageitem/2)>0&¤tPage+parseInt(page.maxshowpageitem/2)<=pageCount){
74 | miniPageNumber = currentPage-parseInt(page.maxshowpageitem/2);
75 | }else if(currentPage-parseInt(page.maxshowpageitem/2)>0&¤tPage+parseInt(page.maxshowpageitem/2)>pageCount){
76 | miniPageNumber = pageCount-page.maxshowpageitem+1;
77 | if(miniPageNumber<=0){
78 | miniPageNumber=1;
79 | }
80 | }
81 | var showPageNum = parseInt(page.maxshowpageitem);
82 | if(pageCount"+pageNumber+"";
93 | }
94 | if(nextPage>pageCount){
95 | appendStr+="下一页>";
96 | appendStr+="尾页";
97 | }else{
98 | appendStr+="下一页>";
99 | appendStr+="尾页";
100 | }
101 | return appendStr;
102 |
103 | }
104 | }
--------------------------------------------------------------------------------
/src/main/resources/static/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EliMirren/VX-API-Gateway/fffd8bffa91d6dc6e79b304416179f797bf72e41/src/main/resources/static/logo.png
--------------------------------------------------------------------------------
/src/main/resources/user.json:
--------------------------------------------------------------------------------
1 | {
2 | "VXAdmin": {
3 | "pwd": "hivx",
4 | "roles": [
5 | "write",
6 | "read"
7 | ]
8 | },
9 | "VXOps": {
10 | "pwd": "hivx",
11 | "roles": [
12 | "read"
13 | ]
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/resources/目录说明.txt:
--------------------------------------------------------------------------------
1 | conf --->配置文件
2 | ┃
3 | ┣━━━━cert/ --->该目录用户放置SSL等所需要的证书
4 | ┃
5 | ┣━━━━static/ --->存储前端静态页面
6 | ┃
7 | ┣━━━━templates/ --->存储前端模板
8 | ┃
9 | ┣━━━━配置文件说明.txt --->配置说明
10 | ┃
11 | ┣━━━━conf.json --->配置
12 | ┃
13 | ┣━━━━configDB.db --->存储网关应用的sqlite数据库
14 | ┃
15 | ┣━━━━log4j.properties --->一些框架需要使用到的日志配置文件
16 | ┃
17 | ┣━━━━log4j2-test.xml --->VX-API使用的测试环境日志配置文件
18 | ┃
19 | ┣━━━━log4j2.xml --->VX-API使用的正式环境日志配置文件
20 | ┃
21 | ┗━━━{*className*}.json -->运行访问的用户
22 |
--------------------------------------------------------------------------------
/src/main/resources/配置文件说明.txt:
--------------------------------------------------------------------------------
1 | ===================code format : UTF-8==================
2 | ========================================================
3 | ===================cliConfig: cli的配置==================
4 | ========================================================
5 | cli配置为json格式,start优先顺序startEverything > startAllAPP > startAPPEverything > startAPP
6 | startEverything = 是否启动所有网关应用跟网关应用的所有API 默认false
7 | startAllAPP = 是否启动所有网关应用(不启动API) true|false 默认false
8 | startAPPEverything = 启动指定的网关应用并启动其所有的API JsonArray["应用网关的名字",...]
9 | startAPP = 启动指定的网关应用(不启动API) JsonArray["应用网关的名字",...]
10 |
11 | ========================================================
12 | ==================vertx: vert.x的配置====================
13 | ========================================================
14 | vert.x配置为json格式
15 | eventLoopPoolSize = Vert.x实例中使用的Event Loop线程的数量,默认值为:2 * Runtime.getRuntime().availableProcessors()可用的处理器个数;
16 | workerPoolSize = Vert.x实例中支持的Worker线程的最大数量,默认值为20;
17 | internalBlockingPoolSize = 内部阻塞线程池最大线程数,这个参数主要被Vert.x的一些内部操作使用,默认值为20;
18 | blockedThreadCheckInterval = 阻塞线程检查的时间间隔,默认1000,单位ms,即1秒;
19 | maxEventLoopExecuteTime = Event Loop的最大执行时间,默认2 * 1000 * 1000000,单位ns,即2秒;
20 | maxWorkerExecuteTime = Worker线程的最大执行时间,默认60 * 1000 * 1000000,单位ns,即60秒;
21 | haEnabled = 是否支持HA架构,默认值false;
22 | quorumSize = 【HA模式有效】支持了HA模式过后,此方法设置冲裁节点的数量,默认值1;
23 | haGroup = 【HA模式有效】支持了HA模式过后,可根据不同的组名将Vert.x进行逻辑分组,此方法设置当前Vert.x的逻辑组名,默认DEFAULT;
24 | warningExceptionTime = 如果线程阻塞时间超过了这个阀值,那么就会打印警告的堆栈信息,默认为5 * 1000 * 1000000,单位ns,即5秒;
25 | preferNativeTransport = 在unix环境下是否使用epoll优化,默认值false
26 | 更多配置请参考VertxOptions 网址: http://vertx.io/docs/apidocs/io/vertx/core/VertxOptions.html
27 |
28 | =========================================================
29 | =================cluster: vert.x集群配置===================
30 | =========================================================
31 | clusterType = 使用集群的模式,默认NONE(不使用集群),只支持zookeeper如果需要别的集群方式可以在VxApiLauncher与VxApiMain中配置项修改
32 | getVxApiConfFromCluster = 是否从集群环境获取VX-API的配置信息,默认false
33 | clusterConf = 集群的配置文件JSON格式,默认:
34 | {
35 | "zookeeperHosts": "127.0.0.1",
36 | "sessionTimeout": 20000,
37 | "connectTimeout": 3000,
38 | "rootPath": "io.vertx",
39 | "vxApiConfPath":"/io.vertx/vx.api.gateway/conf", //集群时以json格式存储Verticle应用的配置,数据库配置,客户端配置的节点
40 | "retry": {
41 | "initialSleepTime": 100,
42 | "intervalTimes": 10000,
43 | "maxTimes": 5
44 | }
45 | }
46 | 更多zookeeper配置请参考: http://vertxchina.github.io/vertx-translation-chinese/clustering/ApacheZookeeper.html
47 |
48 | =========================================================
49 | ========verticleConfig: Verticle应用的配置=================
50 | =========================================================
51 | worker = 是否设置为worker verticle, 默认false
52 | multiThreaded = 是否设置为多线程worker verticle, 默认false
53 | isolationGroup = 设置隔离组
54 | workerPoolName = 设置worker线程池的名字
55 | workerPoolSize = 设置worker线程池的大小, 默认20
56 | ha = 设置是否启用高可用, 默认false
57 | instances = 设置应用的实例数量, 默认1
58 | maxWorkerExecuteTime = 设置worker的最大执行时间, 以ns为单位,默认60000000000
59 | extraClasspath = 额外的classPath, JsonArray格式
60 | isolatedClasses = 设置隔离组, JsonArray格式
61 |
62 | =============================================
63 | =============dataConfig: 数据库配置 ============
64 | =============================================
65 | url = 数据库 JDBC 连接地址
66 | driver_clas = JDBC 驱动
67 | user = 数据库用户名
68 | password = 数据库密码
69 | initial_pool_size = 连接池初始连接数, 默认3
70 | max_pool_size = 连接池最大连接数, 默认15
71 | min_pool_size = 连接池最小连接数
72 | max_statements = 预处理SQL语句最小缓存数, 默认 0
73 | max_statements_per_connection = 每个数据库连接的最大预处理SQL缓存数, 默认0
74 | max_idle_time = 空闲连接保留时间, 默认0 (代表一直保留)
75 | validation_query = druid的validationQuery语句,默认select 1
76 | =============================================
77 | =============clientConfig: 客户端配置 ==========
78 | =============================================
79 | clientPort = 网关的客户端服务端口,默认5256
80 |
81 |
--------------------------------------------------------------------------------
/src/test/.gitignore:
--------------------------------------------------------------------------------
1 | /java/
2 | /resources/
--------------------------------------------------------------------------------