合并分支 'fix-bug-202303' 到 'master'

Fix bug 202303

查看合并请求 JeroBoot/jero-boot!14
This commit is contained in:
李雪涛
2023-04-14 09:34:37 +08:00
1108 changed files with 149285 additions and 39961 deletions
+2 -2
View File
@@ -1553,7 +1553,6 @@ INSERT INTO `sys_permission` VALUES ('4356a1a67b564f0988a484f5531fd4d9', '2a470f
INSERT INTO `sys_permission` VALUES ('45c966826eeff4c99b8f8ebfe74511fc', 'd7d6e2e4e2934f2c9385a623fd98c6f3', '部门管理', '/isystem/depart', 'system/DepartList', null, null, '1', 'sys:depart:list', '1', '1.40', '0', null, '1', '0', '0', '0', null, 'admin', '2019-01-29 18:47:40', 'admin', '2019-12-25 09:36:47', '0', '0', '1', '0');
INSERT INTO `sys_permission` VALUES ('4875ebe289344e14844d8e3ea1edd73f', '2a470fc0c3954d9dbb61de6d80846549', '详情页', '/profile', 'layouts/RouteView', null, null, '1', null, null, '21.00', '0', 'profile', '1', '0', '0', '0', null, null, '2018-12-25 20:34:38', 'admin', '2021-03-16 22:23:07', '0', '0', null, '0');
INSERT INTO `sys_permission` VALUES ('4f66409ef3bbd69c1d80469d6e2a885e', '6e73eb3c26099c191bf03852ee1310a1', '账户绑定', '/account/settings/binding', 'account/settings/Binding', null, null, '1', 'BindingSettings', null, null, null, null, '1', '1', null, null, null, null, '2018-12-26 19:01:20', null, null, '0', '0', null, null);
INSERT INTO `sys_permission` VALUES ('4f84f9400e5e92c95f05b554724c2b58', '540a2936940846cb98114ffb0d145cb8', '角色列表', '/list/role-list', 'demo/list/RoleList', null, null, '1', null, null, '4.00', null, null, '1', '1', null, null, null, null, '2018-12-25 20:34:38', null, null, '0', '0', null, null);
INSERT INTO `sys_permission` VALUES ('53a9230444d33de28aa11cc108fb1dba', '5c8042bd6c601270b2bbd9b20bccc68b', '我的消息', '/isps/userAnnouncement', 'system/UserAnnouncementList', null, null, '1', null, null, '4.00', '0', null, '1', '1', '0', '0', null, 'admin', '2019-04-19 10:16:00', 'admin', '2021-03-16 18:01:26', '0', '0', null, '0');
INSERT INTO `sys_permission` VALUES ('540a2936940846cb98114ffb0d145cb8', '2a470fc0c3954d9dbb61de6d80846549', '列表页', '/list', 'layouts/PageView', null, '/list/query-list', '1', null, null, '24.00', '0', 'table', '1', '0', '0', '0', null, null, '2018-12-25 20:34:38', 'admin', '2021-03-16 22:23:31', '0', '0', null, '0');
INSERT INTO `sys_permission` VALUES ('54dd5457a3190740005c1bfec55b1c34', 'e41b69c57a941a3bbcce45032fe57605', '菜单管理', '/isystem/permission', 'system/PermissionList', null, null, '1', null, null, '7.00', '0', null, '1', '1', '0', '0', null, null, '2018-12-25 20:34:38', 'admin', '2021-03-16 22:32:38', '0', '0', null, '0');
@@ -1611,6 +1610,7 @@ INSERT INTO `sys_permission` VALUES ('fb07ca05a3e13674dbf6d3245956da2e', '540a29
INSERT INTO `sys_permission` VALUES ('fb367426764077dcf94640c843733985', '2a470fc0c3954d9dbb61de6d80846549', '一对多示例', '/demo/jeroOrderMainList', 'demo/JeroOrderMainList', null, null, '1', null, null, '2.00', '0', null, '1', '1', '0', '0', null, 'admin', '2019-02-15 16:24:11', 'admin', '2021-03-16 22:18:47', '0', '0', null, '0');
INSERT INTO `sys_permission` VALUES ('fedfbf4420536cacc0218557d263dfea', '6e73eb3c26099c191bf03852ee1310a1', '新消息通知', '/account/settings/notification', 'account/settings/Notification', null, null, '1', 'NotificationSettings', null, null, null, '', '1', '1', null, null, null, null, '2018-12-26 19:02:05', null, null, '0', '0', null, null);
INSERT INTO `sys_permission` VALUES ('1404684556047024130', '08e6b9dc3c04489c8e1ff2ce6f105aa4', '在线用户', '/isystem/online', 'system/SysUserOnlineList', null, null, '1', null, null, '5.00', '0', null, '1', '0', '0', '0', null, 'admin', '2019-04-02 11:34:34', 'admin', '2020-09-09 14:48:51', '0', '0', null, '0');
INSERT INTO `sys_permission` VALUES ('1636190218344304641', '540a2936940846cb98114ffb0d145cb8', 'JTable列表', '/list/j-table-list', 'demo/list/JTableList', NULL, NULL, 1, NULL, '1', 1.00, 0, NULL, 1, 1, 0, 0, NULL, 'admin', '2023-03-16 10:18:42', 'admin', '2023-03-16 10:25:49', 0, 0, '1', 0);
-- ----------------------------
-- Table structure for sys_permission_data_rule
@@ -1830,7 +1830,6 @@ INSERT INTO `sys_role_permission` VALUES ('b64c4ab9cd9a2ea8ac1e9db5fb7cf522', 'f
INSERT INTO `sys_role_permission` VALUES ('bbec16ad016efec9ea2def38f4d3d9dc', 'f6817f48af4fb3af11b9e8bf182f618b', '13212d3416eb690c2e1d5033166ff47a', null, null, null);
INSERT INTO `sys_role_permission` VALUES ('bea2986432079d89203da888d99b3f16', 'f6817f48af4fb3af11b9e8bf182f618b', '54dd5457a3190740005c1bfec55b1c34', null, null, null);
INSERT INTO `sys_role_permission` VALUES ('c56fb1658ee5f7476380786bf5905399', 'f6817f48af4fb3af11b9e8bf182f618b', 'de13e0f6328c069748de7399fcc1dbbd', null, null, null);
INSERT INTO `sys_role_permission` VALUES ('c6fee38d293b9d0596436a0cbd205070', 'f6817f48af4fb3af11b9e8bf182f618b', '4f84f9400e5e92c95f05b554724c2b58', null, null, null);
INSERT INTO `sys_role_permission` VALUES ('c90b0b01c7ca454d2a1cb7408563e696', 'f6817f48af4fb3af11b9e8bf182f618b', '882a73768cfd7f78f3a37584f7299656', null, null, null);
INSERT INTO `sys_role_permission` VALUES ('cf1feb1bf69eafc982295ad6c9c8d698', 'f6817f48af4fb3af11b9e8bf182f618b', 'a2b11669e98c5fe54a53c3e3c4f35d14', null, null, null);
INSERT INTO `sys_role_permission` VALUES ('cf2ef620217673e4042f695743294f01', 'f6817f48af4fb3af11b9e8bf182f618b', '717f6bee46f44a3897eca9abd6e2ec44', null, null, null);
@@ -1856,6 +1855,7 @@ INSERT INTO `sys_role_permission` VALUES ('f99f99cc3bc27220cdd4f5aced33b7d7', 'f
INSERT INTO `sys_role_permission` VALUES ('fafe73c4448b977fe42880a6750c3ee8', 'f6817f48af4fb3af11b9e8bf182f618b', '9cb91b8851db0cf7b19d7ecc2a8193dd', null, null, null);
INSERT INTO `sys_role_permission` VALUES ('fced905c7598973b970d42d833f73474', 'f6817f48af4fb3af11b9e8bf182f618b', '4875ebe289344e14844d8e3ea1edd73f', null, null, null);
INSERT INTO `sys_role_permission` VALUES ('fd97963dc5f144d3aecfc7045a883427', 'f6817f48af4fb3af11b9e8bf182f618b', '043780fa095ff1b2bec4dc406d76f023', null, null, null);
INSERT INTO `sys_role_permission` VALUES ('1637690312462643202', 'f6817f48af4fb3af11b9e8bf182f618b', '1636190218344304641', NULL, NULL, NULL);
-- ----------------------------
-- Table structure for sys_sms
+3 -2
View File
@@ -2023,7 +2023,6 @@ INSERT INTO "SYS_PERMISSION" VALUES ('4356a1a67b564f0988a484f5531fd4d9', '2a470f
INSERT INTO "SYS_PERMISSION" VALUES ('45c966826eeff4c99b8f8ebfe74511fc', 'd7d6e2e4e2934f2c9385a623fd98c6f3', '部门管理', '/isystem/depart', 'system/DepartList', null, null, '1', 'sys:depart:list', null, '1.40', '0', null, '1', '0', '0', '0', null, 'admin', TO_DATE('2019-01-29 18:47:40', 'YYYY-MM-DD HH24:MI:SS'), 'admin', TO_DATE('2019-12-25 09:36:47', 'YYYY-MM-DD HH24:MI:SS'), '0', '0', '1', '0');
INSERT INTO "SYS_PERMISSION" VALUES ('4875ebe289344e14844d8e3ea1edd73f', '2a470fc0c3954d9dbb61de6d80846549', '详情页', '/profile', 'layouts/RouteView', null, null, '1', null, null, '21', '0', 'profile', '1', '0', '0', '0', null, null, TO_DATE('2018-12-25 20:34:38', 'YYYY-MM-DD HH24:MI:SS'), 'admin', TO_DATE('2021-03-16 22:23:07', 'YYYY-MM-DD HH24:MI:SS'), '0', '0', null, '0');
INSERT INTO "SYS_PERMISSION" VALUES ('4f66409ef3bbd69c1d80469d6e2a885e', '6e73eb3c26099c191bf03852ee1310a1', '账户绑定', '/account/settings/binding', 'account/settings/Binding', null, null, '1', 'BindingSettings', null, null, null, null, '1', '1', null, null, null, null, TO_DATE('2018-12-26 19:01:20', 'YYYY-MM-DD HH24:MI:SS'), null, null, '0', '0', null, null);
INSERT INTO "SYS_PERMISSION" VALUES ('4f84f9400e5e92c95f05b554724c2b58', '540a2936940846cb98114ffb0d145cb8', '角色列表', '/list/role-list', 'demo/list/RoleList', null, null, '1', null, null, '4', null, null, '1', '1', null, null, null, null, TO_DATE('2018-12-25 20:34:38', 'YYYY-MM-DD HH24:MI:SS'), null, null, '0', '0', null, null);
INSERT INTO "SYS_PERMISSION" VALUES ('53a9230444d33de28aa11cc108fb1dba', '5c8042bd6c601270b2bbd9b20bccc68b', '我的消息', '/isps/userAnnouncement', 'system/UserAnnouncementList', null, null, '1', null, null, '4', '0', null, '1', '1', '0', '0', null, 'admin', TO_DATE('2019-04-19 10:16:00', 'YYYY-MM-DD HH24:MI:SS'), 'admin', TO_DATE('2021-03-16 18:01:26', 'YYYY-MM-DD HH24:MI:SS'), '0', '0', null, '0');
INSERT INTO "SYS_PERMISSION" VALUES ('540a2936940846cb98114ffb0d145cb8', '2a470fc0c3954d9dbb61de6d80846549', '列表页', '/list', 'layouts/PageView', null, '/list/query-list', '1', null, null, '24', '0', 'table', '1', '0', '0', '0', null, null, TO_DATE('2018-12-25 20:34:38', 'YYYY-MM-DD HH24:MI:SS'), 'admin', TO_DATE('2021-03-16 22:23:31', 'YYYY-MM-DD HH24:MI:SS'), '0', '0', null, '0');
INSERT INTO "SYS_PERMISSION" VALUES ('54dd5457a3190740005c1bfec55b1c34', 'e41b69c57a941a3bbcce45032fe57605', '菜单管理', '/isystem/permission', 'system/PermissionList', null, null, '1', null, null, '7', '0', null, '1', '1', '0', '0', null, null, TO_DATE('2018-12-25 20:34:38', 'YYYY-MM-DD HH24:MI:SS'), 'admin', TO_DATE('2021-03-16 22:32:38', 'YYYY-MM-DD HH24:MI:SS'), '0', '0', null, '0');
@@ -2117,6 +2116,8 @@ INSERT INTO "SYS_PERMISSION" VALUES ('1383956779212550146', '3f915b2769fc80648e9
INSERT INTO "SYS_PERMISSION" VALUES ('1260931366557696001', '3f915b2769fc80648e92d04e84ca059d', '表单性别可见', null, null, null, null, '2', 'user:sex', '1', '1', '0', null, '1', '1', '0', '0', null, 'admin', TO_DATE('2020-05-14 21:53:59', 'YYYY-MM-DD HH24:MI:SS'), 'admin', TO_DATE('2020-05-14 21:57:00', 'YYYY-MM-DD HH24:MI:SS'), '0', '0', '1', '0');
INSERT INTO "SYS_PERMISSION" VALUES ('1260933542969458689', '3f915b2769fc80648e92d04e84ca059d', '禁用生日字段', null, null, null, null, '2', 'user:form:birthday', '2', '1', '0', null, '1', '1', '0', '0', null, 'admin', TO_DATE('2020-05-14 22:02:38', 'YYYY-MM-DD HH24:MI:SS'), null, null, '0', '0', '1', '0');
INSERT INTO "SYS_PERMISSION" VALUES ('1404684556047024130', '08e6b9dc3c04489c8e1ff2ce6f105aa4', '在线用户', '/isystem/online', 'system/SysUserOnlineList', null, null, '1', null, null, '3', '0', null, '1', '0', '0', '0', null, 'admin', TO_DATE('2019-04-02 11:34:34', 'YYYY-MM-DD HH24:MI:SS'), 'admin', TO_DATE('2020-09-09 14:48:51', 'YYYY-MM-DD HH24:MI:SS'), '0', '0', null, '0');
INSERT INTO `SYS_PERMISSION` VALUES ('1636190218344304641', '540a2936940846cb98114ffb0d145cb8', 'JTable列表', '/list/j-table-list', 'demo/list/JTableList', NULL, NULL, 1, NULL, '1', 1.00, 0, NULL, 1, 1, 0, 0, NULL, 'admin', '2023-03-16 10:18:42', 'admin', '2023-03-16 10:25:49', 0, 0, '1', 0);
-- ----------------------------
-- Table structure for SYS_PERMISSION_DATA_RULE
@@ -2287,7 +2288,6 @@ INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('b64c4ab9cd9a2ea8ac1e9db5fb7cf522', 'f
INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('bbec16ad016efec9ea2def38f4d3d9dc', 'f6817f48af4fb3af11b9e8bf182f618b', '13212d3416eb690c2e1d5033166ff47a', NULL, NULL, NULL);
INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('bea2986432079d89203da888d99b3f16', 'f6817f48af4fb3af11b9e8bf182f618b', '54dd5457a3190740005c1bfec55b1c34', NULL, NULL, NULL);
INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('c56fb1658ee5f7476380786bf5905399', 'f6817f48af4fb3af11b9e8bf182f618b', 'de13e0f6328c069748de7399fcc1dbbd', NULL, NULL, NULL);
INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('c6fee38d293b9d0596436a0cbd205070', 'f6817f48af4fb3af11b9e8bf182f618b', '4f84f9400e5e92c95f05b554724c2b58', NULL, NULL, NULL);
INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('c90b0b01c7ca454d2a1cb7408563e696', 'f6817f48af4fb3af11b9e8bf182f618b', '882a73768cfd7f78f3a37584f7299656', NULL, NULL, NULL);
INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('cf1feb1bf69eafc982295ad6c9c8d698', 'f6817f48af4fb3af11b9e8bf182f618b', 'a2b11669e98c5fe54a53c3e3c4f35d14', NULL, NULL, NULL);
INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('cf2ef620217673e4042f695743294f01', 'f6817f48af4fb3af11b9e8bf182f618b', '717f6bee46f44a3897eca9abd6e2ec44', NULL, NULL, NULL);
@@ -2427,6 +2427,7 @@ INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('a5d25fdb3c62904a8474182706ce11a0', 'f
INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('acacce4417e5d7f96a9c3be2ded5b4be', 'f6817f48af4fb3af11b9e8bf182f618b', 'f9d3f4f27653a71c52faa9fb8070fbe7', NULL, NULL, NULL);
INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('ae1852fb349d8513eb3fdc173da3ee56', 'f6817f48af4fb3af11b9e8bf182f618b', '8d4683aacaa997ab86b966b464360338', NULL, NULL, NULL);
INSERT INTO "SYS_ROLE_PERMISSION" VALUES ('af60ac8fafd807ed6b6b354613b9ccbc', 'f6817f48af4fb3af11b9e8bf182f618b', '58857ff846e61794c69208e9d3a85466', NULL, NULL, NULL);
INSERT INTO `SYS_ROLE_PERMISSION` VALUES ('1637690312462643202', 'f6817f48af4fb3af11b9e8bf182f618b', '1636190218344304641', NULL, NULL, NULL);
-- ----------------------------
-- Table structure for SYS_SMS
+5 -6
View File
@@ -5492,9 +5492,6 @@ GO
INSERT INTO [dbo].[sys_permission] ([id], [parent_id], [name], [url], [component], [component_name], [redirect], [menu_type], [perms], [perms_type], [sort_no], [always_show], [icon], [is_route], [is_leaf], [keep_alive], [hidden], [description], [create_by], [create_time], [update_by], [update_time], [del_flag], [rule_flag], [status], [internal_or_external]) VALUES (N'4f66409ef3bbd69c1d80469d6e2a885e', N'6e73eb3c26099c191bf03852ee1310a1', N'账户绑定', N'/account/settings/binding', N'account/settings/Binding', NULL, NULL, N'1', N'BindingSettings', NULL, NULL, NULL, NULL, N'1', N'1', NULL, NULL, NULL, NULL, N'2018-12-26 19:01:20.0000000', NULL, NULL, N'0', N'0', NULL, NULL)
GO
INSERT INTO [dbo].[sys_permission] ([id], [parent_id], [name], [url], [component], [component_name], [redirect], [menu_type], [perms], [perms_type], [sort_no], [always_show], [icon], [is_route], [is_leaf], [keep_alive], [hidden], [description], [create_by], [create_time], [update_by], [update_time], [del_flag], [rule_flag], [status], [internal_or_external]) VALUES (N'4f84f9400e5e92c95f05b554724c2b58', N'540a2936940846cb98114ffb0d145cb8', N'角色列表', N'/list/role-list', N'demo/list/RoleList', NULL, NULL, N'1', NULL, NULL, N'4', NULL, NULL, N'1', N'1', NULL, NULL, NULL, NULL, N'2018-12-25 20:34:38.0000000', NULL, NULL, N'0', N'0', NULL, NULL)
GO
INSERT INTO [dbo].[sys_permission] ([id], [parent_id], [name], [url], [component], [component_name], [redirect], [menu_type], [perms], [perms_type], [sort_no], [always_show], [icon], [is_route], [is_leaf], [keep_alive], [hidden], [description], [create_by], [create_time], [update_by], [update_time], [del_flag], [rule_flag], [status], [internal_or_external]) VALUES (N'53a9230444d33de28aa11cc108fb1dba', N'5c8042bd6c601270b2bbd9b20bccc68b', N'我的消息', N'/isps/userAnnouncement', N'system/UserAnnouncementList', NULL, NULL, N'1', NULL, NULL, N'4', N'0', NULL, N'1', N'1', N'0', N'0', NULL, N'admin', N'2019-04-19 10:16:00.0000000', N'admin', N'2021-03-16 18:01:26.0000000', N'0', N'0', NULL, N'0')
GO
@@ -5720,6 +5717,9 @@ GO
INSERT INTO [dbo].[sys_permission] ([id], [parent_id], [name], [url], [component], [component_name], [redirect], [menu_type], [perms], [perms_type], [sort_no], [always_show], [icon], [is_route], [is_leaf], [keep_alive], [hidden], [description], [create_by], [create_time], [update_by], [update_time], [del_flag], [rule_flag], [status], [internal_or_external]) VALUES (N'1404684556047024130', N'08e6b9dc3c04489c8e1ff2ce6f105aa4', N'在线用户', N'/isystem/online', N'system/SysUserOnlineList',NULL, NULL, N'1', NULL, NULL, N'3', N'0', NULL, N'1', N'0', N'0', N'0', NULL, N'admin', N'2019-04-02 11:34:34.0000000', N'admin', N'2020-09-09 14:48:51.0000000', N'0', N'0', NULL, N'0');
GO
INSERT INTO [dbo].[sys_permission] ([id], [parent_id], [name], [url], [component], [component_name], [redirect], [menu_type], [perms], [perms_type], [sort_no], [always_show], [icon], [is_route], [is_leaf], [keep_alive], [hidden], [description], [create_by], [create_time], [update_by], [update_time], [del_flag], [rule_flag], [status], [internal_or_external]) VALUES (N'1636190218344304641', N'540a2936940846cb98114ffb0d145cb8', N'JTable列表', N'/list/j-table-list', N'demo/list/JTableList',NULL, NULL, N'1', NULL, N'1', N'1.00', N'0', NULL, N'1', N'1', N'0', N'0', NULL, N'admin', N'2023-03-16 10:18:42.0000000', N'admin', N'2023-03-16 10:25:49.0000000', N'0', N'0', N'1', N'0');
GO
-- ----------------------------
-- Table structure for sys_permission_data_rule
-- ----------------------------
@@ -6446,9 +6446,6 @@ GO
INSERT INTO [dbo].[sys_role_permission] ([id], [role_id], [permission_id], [data_rule_ids], [operate_date], [operate_ip]) VALUES (N'c56fb1658ee5f7476380786bf5905399', N'f6817f48af4fb3af11b9e8bf182f618b', N'de13e0f6328c069748de7399fcc1dbbd', NULL, NULL, NULL)
GO
INSERT INTO [dbo].[sys_role_permission] ([id], [role_id], [permission_id], [data_rule_ids], [operate_date], [operate_ip]) VALUES (N'c6fee38d293b9d0596436a0cbd205070', N'f6817f48af4fb3af11b9e8bf182f618b', N'4f84f9400e5e92c95f05b554724c2b58', NULL, NULL, NULL)
GO
INSERT INTO [dbo].[sys_role_permission] ([id], [role_id], [permission_id], [data_rule_ids], [operate_date], [operate_ip]) VALUES (N'c90b0b01c7ca454d2a1cb7408563e696', N'f6817f48af4fb3af11b9e8bf182f618b', N'882a73768cfd7f78f3a37584f7299656', NULL, NULL, NULL)
GO
@@ -6524,6 +6521,8 @@ GO
INSERT INTO [dbo].[sys_role_permission] ([id], [role_id], [permission_id], [data_rule_ids], [operate_date], [operate_ip]) VALUES (N'fd97963dc5f144d3aecfc7045a883427', N'f6817f48af4fb3af11b9e8bf182f618b', N'043780fa095ff1b2bec4dc406d76f023', NULL, NULL, NULL)
GO
INSERT INTO [dbo].[sys_role_permission] ([id], [role_id], [permission_id], [data_rule_ids], [operate_date], [operate_ip]) VALUES (N'1637690312462643202', N'f6817f48af4fb3af11b9e8bf182f618b', N'1636190218344304641', NULL, NULL, NULL)
GO
-- ----------------------------
-- Table structure for sys_sms
@@ -165,25 +165,26 @@ public interface ISysBaseAPI extends CommonAPI {
* @param text
* @param code
* @param keyArray
* @deprecated 不建议使用
* @return
*/
@Deprecated
@GetMapping("/sys/api/queryTableDictByKeys")
public List<String> queryTableDictByKeys(@RequestParam("table") String table, @RequestParam("text") String text, @RequestParam("code") String code, @RequestParam("keyArray") String[] keyArray);
List<String> queryTableDictByKeys(@RequestParam("table") String table, @RequestParam("text") String text, @RequestParam("code") String code, @RequestParam("keyArray") String[] keyArray);
/**
* 18查询所有用户 返回ComboModel
* @return
*/
@GetMapping("/sys/api/queryAllUserBackCombo")
public List<ComboModel> queryAllUserBackCombo();
List<ComboModel> queryAllUserBackCombo();
/**
* 19分页查询用户 返回JSONObject
* @return
*/
@GetMapping("/sys/api/queryAllUser")
public JSONObject queryAllUser(@RequestParam(name = "userIds", required = false) String userIds, @RequestParam(name = "pageNo", required = false) Integer pageNo, @RequestParam(name = "pageSize", required = false) int pageSize);
JSONObject queryAllUser(@RequestParam(name = "userIds", required = false) String userIds, @RequestParam(name = "pageNo", required = false) Integer pageNo, @RequestParam(name = "pageSize", required = false) int pageSize);
/**
@@ -192,7 +193,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @return
*/
@GetMapping("/sys/api/queryAllRole")
public List<ComboModel> queryAllRole(@RequestParam(name = "roleIds", required = false) String[] roleIds);
List<ComboModel> queryAllRole(@RequestParam(name = "roleIds", required = false) String[] roleIds);
/**
* 21通过用户账号查询角色Id集合
@@ -200,7 +201,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @return
*/
@GetMapping("/sys/api/getRoleIdsByUsername")
public List<String> getRoleIdsByUsername(@RequestParam("username") String username);
List<String> getRoleIdsByUsername(@RequestParam("username") String username);
/**
* 22通过部门编号查询部门id
@@ -208,14 +209,14 @@ public interface ISysBaseAPI extends CommonAPI {
* @return
*/
@GetMapping("/sys/api/getDepartIdsByOrgCode")
public String getDepartIdsByOrgCode(@RequestParam("orgCode") String orgCode);
String getDepartIdsByOrgCode(@RequestParam("orgCode") String orgCode);
/**
* 23查询所有部门
* @return
*/
@GetMapping("/sys/api/getAllSysDepart")
public List<SysDepartModel> getAllSysDepart();
List<SysDepartModel> getAllSysDepart();
/**
* 24查找父级部门
@@ -231,7 +232,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @return
*/
@GetMapping("/sys/api/getDeptHeadByDepId")
public List<String> getDeptHeadByDepId(@RequestParam("deptId") String deptId);
List<String> getDeptHeadByDepId(@RequestParam("deptId") String deptId);
/**
* 26给指定用户发消息
@@ -239,7 +240,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @param cmd
*/
@GetMapping("/sys/api/sendWebSocketMsg")
public void sendWebSocketMsg(@RequestParam("userIds") String[] userIds, @RequestParam("cmd") String cmd);
void sendWebSocketMsg(@RequestParam("userIds") String[] userIds, @RequestParam("cmd") String cmd);
/**
* 27根据id获取所有参与用户
@@ -247,7 +248,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @return
*/
@GetMapping("/sys/api/queryAllUserByIds")
public List<LoginUser> queryAllUserByIds(@RequestParam("userIds") String[] userIds);
List<LoginUser> queryAllUserByIds(@RequestParam("userIds") String[] userIds);
/**
* 28将会议签到信息推动到预览
@@ -450,7 +451,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @param orgCode
*/
@GetMapping("/sys/api/getDeptUserByOrgCode")
List<Map> getDeptUserByOrgCode(@RequestParam("orgCode")String orgCode);
List<Map<String,Object>> getDeptUserByOrgCode(@RequestParam("orgCode")String orgCode);
/**
* 42 查询分类字典翻译
@@ -8,6 +8,7 @@ import com.jero.common.api.dto.message.*;
import com.jero.common.system.api.ISysBaseAPI;
import com.jero.common.system.vo.*;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -21,24 +22,26 @@ public class SysBaseAPIFallback implements ISysBaseAPI {
@Setter
private Throwable cause;
private static final String ERROR_MESSAGE = "发送消息失败 {}";
@Override
public void sendSysAnnouncement(MessageDTO message) {
log.error("发送消息失败 {}", cause);
log.error(ERROR_MESSAGE, cause);
}
@Override
public void sendBusAnnouncement(BusMessageDTO message) {
log.error("发送消息失败 {}", cause);
log.error(ERROR_MESSAGE, cause);
}
@Override
public void sendTemplateAnnouncement(TemplateMessageDTO message) {
log.error("发送消息失败 {}", cause);
log.error(ERROR_MESSAGE, cause);
}
@Override
public void sendBusTemplateAnnouncement(BusTemplateMessageDTO message) {
log.error("发送消息失败 {}", cause);
log.error(ERROR_MESSAGE, cause);
}
@Override
@@ -54,84 +57,84 @@ public class SysBaseAPIFallback implements ISysBaseAPI {
@Override
public List<String> getRolesByUsername(String username) {
return null;
return Collections.emptyList();
}
@Override
public List<String> getDepartIdsByUsername(String username) {
return null;
return Collections.emptyList();
}
@Override
public List<String> getDepartNamesByUsername(String username) {
return null;
return Collections.emptyList();
}
@Override
public List<DictModel> queryDictItemsByCode(String code) {
return null;
return Collections.emptyList();
}
@Override
public List<DictModel> queryEnableDictItemsByCode(String code) {
return null;
return Collections.emptyList();
}
@Override
public List<DictModel> queryAllDict() {
return null;
return Collections.emptyList();
}
@Override
public List<SysCategoryModel> queryAllDSysCategory() {
return null;
return Collections.emptyList();
}
@Override
public List<DictModel> queryTableDictItemsByCode(String table, String text, String code) {
return null;
return Collections.emptyList();
}
@Override
public List<DictModel> queryAllDepartBackDictModel() {
return null;
return Collections.emptyList();
}
@Override
public void updateSysAnnounReadFlag(String busType, String busId) {
// do other
}
@Override
public List<DictModel> queryFilterTableDictInfo(String table, String text, String code, String filterSql) {
return null;
return Collections.emptyList();
}
@Override
public List<String> queryTableDictByKeys(String table, String text, String code, String[] keyArray) {
log.error("queryTableDictByKeys查询失败 {}", cause);
return null;
return Collections.emptyList();
}
@Override
public List<ComboModel> queryAllUserBackCombo() {
return null;
return Collections.emptyList();
}
@Override
public JSONObject queryAllUser(String userIds, Integer pageNo, int pageSize) {
return null;
return new JSONObject();
}
@Override
public List<ComboModel> queryAllRole(String[] roleIds) {
log.error("获取角色信息失败 {}", cause);
return null;
return Collections.emptyList();
}
@Override
public List<String> getRoleIdsByUsername(String username) {
return null;
return Collections.emptyList();
}
@Override
@@ -141,7 +144,7 @@ public class SysBaseAPIFallback implements ISysBaseAPI {
@Override
public List<SysDepartModel> getAllSysDepart() {
return null;
return Collections.emptyList();
}
@Override
@@ -151,37 +154,37 @@ public class SysBaseAPIFallback implements ISysBaseAPI {
@Override
public List<String> getDeptHeadByDepId(String deptId) {
return null;
return Collections.emptyList();
}
@Override
public void sendWebSocketMsg(String[] userIds, String cmd) {
// do other
}
@Override
public List<LoginUser> queryAllUserByIds(String[] userIds) {
return null;
return Collections.emptyList();
}
@Override
public void meetingSignWebsocket(String userId) {
// do other
}
@Override
public List<LoginUser> queryUserByNames(String[] userNames) {
return null;
return Collections.emptyList();
}
@Override
public Set<String> getUserRoleSet(String username) {
return null;
return Collections.emptySet();
}
@Override
public Set<String> getUserPermissionSet(String username) {
return null;
return Collections.emptySet();
}
@Override
@@ -196,17 +199,17 @@ public class SysBaseAPIFallback implements ISysBaseAPI {
@Override
public List<String> queryDeptUsersByUserId(String userId) {
return null;
return Collections.emptyList();
}
@Override
public Set<String> queryUserRoles(String username) {
return null;
return Collections.emptySet();
}
@Override
public Set<String> queryUserAuths(String username) {
return null;
return Collections.emptySet();
}
@Override
@@ -237,7 +240,7 @@ public class SysBaseAPIFallback implements ISysBaseAPI {
@Override
public List<SysPermissionDataRuleModel> queryPermissionDataRule(String component, String requestPath, String username) {
return null;
return Collections.emptyList();
}
@Override
@@ -248,81 +251,81 @@ public class SysBaseAPIFallback implements ISysBaseAPI {
@Override
public List<JSONObject> queryUsersByUsernames(String usernames) {
return null;
return Collections.emptyList();
}
@Override
public List<JSONObject> queryUsersByIds(String ids) {
return null;
return Collections.emptyList();
}
@Override
public List<JSONObject> queryDepartsByOrgcodes(String orgCodes) {
return null;
return Collections.emptyList();
}
@Override
public List<JSONObject> queryDepartsByIds(String ids) {
return null;
return Collections.emptyList();
}
@Override
public Map<String, List<DictModel>> translateManyDict(String dictCodes, String keys) {
return null;
return Collections.emptyMap();
}
@Override
public List<DictModel> translateDictFromTableByKeys(String table, String text, String code, String keys) {
return null;
return Collections.emptyList();
}
@Override
public void sendEmailMsg(String email,String title,String content) {
// do other
}
@Override
public List<SysDepartTreeModel> listParentDepartsByDepId(String departId) {
return null;
return Collections.emptyList();
}
@Override
public List<SysDepartTreeModel> listSonDepartsByDepId(String departId) {
return null;
return Collections.emptyList();
}
@Override
public List<Map> getDeptUserByOrgCode(String orgCode) {
return null;
public List<Map<String,Object>> getDeptUserByOrgCode(String orgCode) {
return Collections.emptyList();
}
@Override
public List<JSONObject> queryDepartsByOrgIds(String ids) {
return null;
return Collections.emptyList();
}
@Override
public List<String> loadCategoryDictItem(String ids) {
return null;
return Collections.emptyList();
}
@Override
public List<String> loadDictItem(String dictCode, String keys) {
return null;
return Collections.emptyList();
}
@Override
public List<DictModel> getDictItems(String dictCode) {
return null;
return Collections.emptyList();
}
@Override
public Map<String, List<DictModel>> getManyDictItems(List<String> dictCodeList) {
return null;
return Collections.emptyMap();
}
@Override
public List<DictModel> loadDictItemByKeyword(String dictCode, String keyword, Integer pageSize) {
return null;
return Collections.emptyList();
}
}
@@ -1,20 +1,25 @@
package com.jero.config;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.alibaba.fastjson.support.springfox.SwaggerJsonSerializer;
import com.jero.common.config.mqtoken.UserTokenContext;
import com.jero.common.constant.CommonConstant;
import com.jero.common.util.DateUtils;
import com.jero.common.util.PathMatcherUtil;
import com.jero.common.config.mqtoken.UserTokenContext;
import com.jero.config.sign.interceptor.SignAuthConfiguration;
import com.jero.config.sign.util.HttpUtils;
import com.jero.config.sign.util.SignUtil;
import feign.Feign;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@@ -30,19 +35,12 @@ import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.alibaba.fastjson.support.springfox.SwaggerJsonSerializer;
import feign.Feign;
import feign.Logger;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;
@ConditionalOnClass(Feign.class)
@@ -56,40 +54,7 @@ public class FeignConfig {
return requestTemplate -> {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (null != attributes) {
HttpServletRequest request = attributes.getRequest();
log.debug("Feign request: {}", request.getRequestURI());
// 将token信息放入header中
String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
if(token==null || "".equals(token)){
token = request.getParameter("token");
}
log.debug("Feign request token: {}", token);
requestTemplate.header(CommonConstant.X_ACCESS_TOKEN, token);
//根据URL地址过滤请求 字典表参数签名验证
if (PathMatcherUtil.matches(Arrays.asList(SignAuthConfiguration.urlList),requestTemplate.path())) {
try {
log.info("============================ [begin] fegin api url ============================");
log.info(requestTemplate.path());
log.info(requestTemplate.method());
String queryLine = requestTemplate.queryLine();
if(queryLine!=null && queryLine.startsWith("?")){
queryLine = queryLine.substring(1);
}
log.info(queryLine);
if(requestTemplate.body()!=null){
log.info(new String(requestTemplate.body()));
}
SortedMap<String, String> allParams = HttpUtils.getAllParams(requestTemplate.path(),queryLine,requestTemplate.body(),requestTemplate.method());
String sign = SignUtil.getParamsSign(allParams);
log.info(" Feign request params sign: {}",sign);
log.info("============================ [end] fegin api url ============================");
requestTemplate.header(CommonConstant.X_SIGN, sign);
requestTemplate.header(CommonConstant.X_TIMESTAMP, DateUtils.getCurrentTimestamp().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
filterRequest(requestTemplate, attributes);
}else{
String token = UserTokenContext.getToken();
log.debug("Feign request token: {}", token);
@@ -98,6 +63,42 @@ public class FeignConfig {
};
}
private void filterRequest(RequestTemplate requestTemplate, ServletRequestAttributes attributes) {
HttpServletRequest request = attributes.getRequest();
log.debug("Feign request: {}", request.getRequestURI());
// 将token信息放入header中
String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
if(token==null || "".equals(token)){
token = request.getParameter("token");
}
log.debug("Feign request token: {}", token);
requestTemplate.header(CommonConstant.X_ACCESS_TOKEN, token);
//根据URL地址过滤请求 字典表参数签名验证
if (PathMatcherUtil.matches(Arrays.asList(SignAuthConfiguration.urlList),requestTemplate.path())) {
try {
log.info("============================ [begin] fegin api url ============================");
log.info(requestTemplate.path());
log.info(requestTemplate.method());
String queryLine = requestTemplate.queryLine();
if(queryLine.startsWith("?")){
queryLine = queryLine.substring(1);
}
log.info(queryLine);
if(requestTemplate.body()!=null){
log.info(new String(requestTemplate.body()));
}
SortedMap<String, String> allParams = HttpUtils.getAllParams(requestTemplate.path(),queryLine,requestTemplate.body(),requestTemplate.method());
String sign = SignUtil.getParamsSign(allParams);
log.info(" Feign request params sign: {}",sign);
log.info("============================ [end] fegin api url ============================");
requestTemplate.header(CommonConstant.X_SIGN, sign);
requestTemplate.header(CommonConstant.X_TIMESTAMP, DateUtils.getCurrentTimestamp().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
@@ -119,6 +119,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @param text
* @param code
* @param keyArray
* @deprecated 不建议使用
* @return
*/
@Deprecated
@@ -304,7 +305,7 @@ public interface ISysBaseAPI extends CommonAPI {
* 43 获取公司下级部门和公司下所有用户信息
* @param orgCode
*/
List<Map> getDeptUserByOrgCode(String orgCode);
List<Map<String,Object>> getDeptUserByOrgCode(String orgCode);
/**
@@ -17,7 +17,7 @@ public class FileDownDTO implements Serializable {
private String filePath;
private String uploadpath;
private String uploadType;
private HttpServletResponse response;
private transient HttpServletResponse response;
public FileDownDTO(){}
@@ -14,7 +14,7 @@ public class FileUploadDTO implements Serializable {
private static final long serialVersionUID = -4111953058578954386L;
private MultipartFile file;
private transient MultipartFile file;
private String bizPath;
@@ -23,7 +23,7 @@ public class LogDTO implements Serializable {
private Integer operateType;
/**登录用户 */
private LoginUser loginUser;
private transient LoginUser loginUser;
private String id;
private String createBy;
@@ -21,7 +21,7 @@ public class TemplateDTO implements Serializable {
/**
* 模板参数
*/
protected Map<String, String> templateParam;
protected transient Map<String, String> templateParam;
/**
* 构造器 通过设置模板参数和模板编码 作为参数获取消息内容
@@ -0,0 +1,25 @@
package com.jero.common.api.vo;
/**
* @author LQT
* @date 2023/3/9 9:11
*/
public class ResultConstant {
private ResultConstant(){
}
public static final String OP_OK = "操作成功!";
public static final String DEL_OK = "删除成功!";
public static final String DEL_ERR = "删除失败!";
public static final String BATCH_DEL_OK = "批量删除成功!";
public static final String EN_WAS_NOT_FOUND = "未找到对应实体!";
}
@@ -15,7 +15,7 @@ import lombok.Data;
*/
@Data
@ApiModel(value="接口返回对象", description="接口返回对象")
public class Result<T> implements Serializable {
public class Results<T> implements Serializable {
private static final long serialVersionUID = 1L;
@@ -36,49 +36,49 @@ public class Result<T> implements Serializable {
*/
@ApiModelProperty(value = "返回代码")
private Integer code = 200;
/**
* 返回数据对象 data
*/
@ApiModelProperty(value = "返回数据对象")
private T result;
private transient T result;
/**
* 时间戳
*/
@ApiModelProperty(value = "时间戳")
private long timestamp = System.currentTimeMillis();
public Result() {
public Results() {
// do other
}
public static<T> Result<T> OK() {
Result<T> r = new Result<T>();
public static<T> Results<T> OK() {
Results<T> r = new Results<>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setMessage("成功");
return r;
}
public static<T> Result<T> OK(String message) {
Result<T> r = new Result<T>();
public static<T> Results<T> OK(String message) {
Results<T> r = new Results<>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setMessage(message);
return r;
}
public static<T> Result<T> OK(T data) {
Result<T> r = new Result<T>();
public static<T> Results<T> OK(T data) {
Results<T> r = new Results<>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setResult(data);
return r;
}
public static<T> Result<T> OK(String msg, T data) {
Result<T> r = new Result<T>();
public static<T> Results<T> OK(String msg, T data) {
Results<T> r = new Results<>();
r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200);
r.setMessage(msg);
@@ -86,8 +86,8 @@ public class Result<T> implements Serializable {
return r;
}
public static<T> Result<T> error(String msg, T data) {
Result<T> r = new Result<T>();
public static<T> Results<T> error(String msg, T data) {
Results<T> r = new Results<>();
r.setSuccess(false);
r.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500);
r.setMessage(msg);
@@ -95,12 +95,12 @@ public class Result<T> implements Serializable {
return r;
}
public static<T> Result<T> error(String msg) {
public static<T> Results<T> error(String msg) {
return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, msg);
}
public static<T> Result<T> error(int code, String msg) {
Result<T> r = new Result<T>();
public static<T> Results<T> error(int code, String msg) {
Results<T> r = new Results<>();
r.setCode(code);
r.setMessage(msg);
r.setSuccess(false);
@@ -110,11 +110,11 @@ public class Result<T> implements Serializable {
/**
* 无权限访问返回结果
*/
public static Result<Object> noauth(String msg) {
public static Results<Object> noauth(String msg) {
return error(CommonConstant.SC_JERO_NO_AUTHZ, msg);
}
@JsonIgnore
private String onlTable;
}
}
@@ -1,7 +1,18 @@
package com.jero.common.aspect;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.jero.common.api.dto.LogDTO;
import com.jero.common.api.vo.Results;
import com.jero.common.aspect.annotation.AutoLog;
import com.jero.common.constant.CommonConstant;
import com.jero.common.constant.enums.ModuleType;
import com.jero.common.system.vo.LoginUser;
import com.jero.common.util.IPUtils;
import com.jero.common.util.SpringContextUtils;
import com.jero.common.util.oConvertUtils;
import com.jero.modules.base.service.BaseCommonService;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
@@ -9,26 +20,19 @@ import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import com.jero.common.api.dto.LogDTO;
import com.jero.common.api.vo.Result;
import com.jero.common.aspect.annotation.AutoLog;
import com.jero.common.constant.CommonConstant;
import com.jero.common.constant.enums.ModuleType;
import com.jero.modules.base.service.BaseCommonService;
import com.jero.common.system.vo.LoginUser;
import com.jero.common.util.IPUtils;
import com.jero.common.util.SpringContextUtils;
import com.jero.common.util.oConvertUtils;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
@@ -46,7 +50,7 @@ public class AutoLogAspect {
@Pointcut("@annotation(com.jero.common.aspect.annotation.AutoLog)")
public void logPointCut() {
// do other
}
@Around("logPointCut()")
@@ -88,6 +92,7 @@ public class AutoLogAspect {
//设置操作类型
if (dto.getLogType() == CommonConstant.LOG_TYPE_2) {
assert syslog != null;
dto.setOperateType(getOperateType(methodName, syslog.operateType()));
}
@@ -150,8 +155,9 @@ public class AutoLogAspect {
*/
private String getReqestParams(HttpServletRequest request, JoinPoint joinPoint) {
String httpMethod = request.getMethod();
String params = "";
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) {
StringBuilder params = new StringBuilder();
List<String> list = Arrays.asList("POST","PUT","PATCH");
if (list.contains(httpMethod)) {
Object[] paramsArray = joinPoint.getArgs();
// java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
// https://my.oschina.net/mengzhang6/blog/2395893
@@ -165,16 +171,8 @@ public class AutoLogAspect {
arguments[i] = paramsArray[i];
}
//update-begin-author:taoyan date:20200724 for:日志数据太长的直接过滤掉
PropertyFilter profilter = new PropertyFilter() {
@Override
public boolean apply(Object o, String name, Object value) {
if(value!=null && value.toString().length()>500){
return false;
}
return true;
}
};
params = JSONObject.toJSONString(arguments, profilter);
PropertyFilter profilter = (o, name, value) -> value == null || value.toString().length() <= 500;
params = new StringBuilder(JSON.toJSONString(arguments, profilter));
//update-end-author:taoyan date:20200724 for:日志数据太长的直接过滤掉
} else {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
@@ -186,11 +184,11 @@ public class AutoLogAspect {
String[] paramNames = u.getParameterNames(method);
if (args != null && paramNames != null) {
for (int i = 0; i < args.length; i++) {
params += " " + paramNames[i] + ": " + args[i];
params.append(" ").append(paramNames[i]).append(": ").append(args[i]);
}
}
}
return params;
return params.toString();
}
/**
@@ -200,8 +198,8 @@ public class AutoLogAspect {
* @return
*/
private String getOnlineLogContent(Object obj, String content){
if (Result.class.isInstance(obj)){
Result res = (Result)obj;
if (obj instanceof Results){
Results<T> res = (Results)obj;
String msg = res.getMessage();
String tableName = res.getOnlTable();
if(oConvertUtils.isNotEmpty(tableName)){
@@ -6,23 +6,22 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import com.jero.common.api.CommonAPI;
import com.jero.common.api.vo.Result;
import com.jero.common.api.vo.Results;
import com.jero.common.aspect.annotation.Dict;
import com.jero.common.constant.CommonConstant;
import com.jero.common.system.vo.DictModel;
import com.jero.common.util.oConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
@@ -44,11 +43,14 @@ public class DictAspect {
@Autowired
private CommonAPI commonAPI;
@Autowired
public RedisTemplate redisTemplate;
public RedisTemplate<String,Object> redisTemplate;
private static final String SYS_CACHE_DICT_S_S = "sys:cache:dict::%s:%s";
// 定义切点Pointcut
@Pointcut("execution(public * com.jero.modules..*.*Controller.*(..))")
public void excudeService() {
// do other
}
@Around("excudeService()")
@@ -87,99 +89,107 @@ public class DictAspect {
* @param result
*/
private void parseDictText(Object result) {
if (result instanceof Result) {
if (((Result) result).getResult() instanceof IPage) {
List<JSONObject> items = new ArrayList<>();
if (result instanceof Results && ((Results) result).getResult() instanceof IPage) {
List<JSONObject> items = new ArrayList<>();
//step.1 筛选出加了 Dict 注解的字段列表
List<Field> dictFieldList = new ArrayList<>();
// 字典数据列表 key = 字典codevalue=数据列表
Map<String, List<String>> dataListMap = new HashMap<>();
//step.1 筛选出加了 Dict 注解的字段列表
List<Field> dictFieldList = new ArrayList<>();
// 字典数据列表 key = 字典codevalue=数据列表
Map<String, List<String>> dataListMap = new HashMap<>();
for (Object record : ((IPage) ((Result) result).getResult()).getRecords()) {
ObjectMapper mapper = new ObjectMapper();
String json="{}";
try {
//解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
json = mapper.writeValueAsString(record);
} catch (JsonProcessingException e) {
log.error("json解析失败"+e.getMessage(),e);
}
JSONObject item = JSONObject.parseObject(json);
//update-begin--Author:scott -- Date:20190603 ----for解决继承实体字段无法翻译问题------
//for (Field field : record.getClass().getDeclaredFields()) {
// 遍历所有字段把字典Code取出来放到 map
for (Field field : oConvertUtils.getAllFields(record)) {
String value = item.getString(field.getName());
if (oConvertUtils.isEmpty(value)) {
continue;
}
//update-end--Author:scott -- Date:20190603 ----for解决继承实体字段无法翻译问题------
if (field.getAnnotation(Dict.class) != null) {
if (!dictFieldList.contains(field)) {
dictFieldList.add(field);
}
String code = field.getAnnotation(Dict.class).dicCode();
String text = field.getAnnotation(Dict.class).dicText();
String table = field.getAnnotation(Dict.class).dictTable();
addItems((Results) result, items, dictFieldList, dataListMap);
List<String> dataList;
String dictCode = code;
if (!StringUtils.isEmpty(table)) {
dictCode = String.format("%s,%s,%s", table, text, code);
}
dataList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(",")));
}
//date类型默认转换string格式化日期
if (field.getType().getName().equals("java.util.Date")&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
}
}
items.add(item);
//step.2 调用翻译方法一次性翻译
Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap);
//step.3 将翻译结果填充到返回结果里
putItems(items, dictFieldList, translText);
((IPage) ((Results) result).getResult()).setRecords(items);
}
}
private void putItems(List<JSONObject> items, List<Field> dictFieldList, Map<String, List<DictModel>> translText) {
for (JSONObject obj : items) {
for (Field field : dictFieldList) {
String code = field.getAnnotation(Dict.class).dicCode();
String text = field.getAnnotation(Dict.class).dicText();
String table = field.getAnnotation(Dict.class).dictTable();
String fieldDictCode = code;
if (!StringUtils.isEmpty(table)) {
fieldDictCode = String.format("%s,%s,%s", table, text, code);
}
//step.2 调用翻译方法一次性翻译
Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap);
//step.3 将翻译结果填充到返回结果里
for (JSONObject record : items) {
for (Field field : dictFieldList) {
String code = field.getAnnotation(Dict.class).dicCode();
String text = field.getAnnotation(Dict.class).dicText();
String table = field.getAnnotation(Dict.class).dictTable();
String fieldDictCode = code;
if (!StringUtils.isEmpty(table)) {
fieldDictCode = String.format("%s,%s,%s", table, text, code);
}
String value = record.getString(field.getName());
if (oConvertUtils.isNotEmpty(value)) {
List<DictModel> dictModels = translText.get(fieldDictCode);
if(dictModels==null || dictModels.size()==0){
continue;
}
String textValue = this.translDictText(dictModels, value);
log.debug(" 字典Val : " + textValue);
log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + " " + textValue);
// TODO-sun 测试输出待删
log.debug(" ---- dictCode: " + fieldDictCode);
log.debug(" ---- value: " + value);
log.debug(" ----- text: " + textValue);
log.debug(" ---- dictModels: " + JSON.toJSONString(dictModels));
record.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
}
String value = obj.getString(field.getName());
if (oConvertUtils.isNotEmpty(value)) {
List<DictModel> dictModels = translText.get(fieldDictCode);
if(dictModels==null || dictModels.isEmpty()){
continue;
}
}
((IPage) ((Result) result).getResult()).setRecords(items);
String textValue = this.translDictText(dictModels, value);
log.debug(" 字典Val : " + textValue);
log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + " " + textValue);
// TODO-sun 测试输出待删
log.debug(" ---- dictCode: " + fieldDictCode);
log.debug(" ---- value: " + value);
log.debug(" ----- text: " + textValue);
log.debug(" ---- dictModels: " + JSON.toJSONString(dictModels));
obj.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
}
}
}
}
private void addItems(Results<IPage<T>> result, List<JSONObject> items, List<Field> dictFieldList, Map<String, List<String>> dataListMap) {
for (Object obj : result.getResult().getRecords()) {
ObjectMapper mapper = new ObjectMapper();
String json="{}";
try {
//解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
json = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
log.error("json解析失败"+e.getMessage(),e);
}
JSONObject item = JSON.parseObject(json);
//update-begin--Author:scott -- Date:20190603 ----for解决继承实体字段无法翻译问题------
// 遍历所有字段把字典Code取出来放到 map
putItem(dictFieldList, dataListMap, obj, item);
items.add(item);
}
}
private void putItem(List<Field> dictFieldList, Map<String, List<String>> dataListMap, Object obj, JSONObject item) {
for (Field field : oConvertUtils.getAllFields(obj)) {
String value = item.getString(field.getName());
if (oConvertUtils.isEmpty(value)) {
continue;
}
//update-end--Author:scott -- Date:20190603 ----for解决继承实体字段无法翻译问题------
if (field.getAnnotation(Dict.class) != null) {
if (!dictFieldList.contains(field)) {
dictFieldList.add(field);
}
String code = field.getAnnotation(Dict.class).dicCode();
String text = field.getAnnotation(Dict.class).dicText();
String table = field.getAnnotation(Dict.class).dictTable();
List<String> dataList;
String dictCode = code;
if (!StringUtils.isEmpty(table)) {
dictCode = String.format("%s,%s,%s", table, text, code);
}
dataList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(",")));
}
//date类型默认转换string格式化日期
if (Date.class.isAssignableFrom(field.getType()) && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null){
SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
}
}
}
@@ -205,53 +215,21 @@ public class DictAspect {
// 需要翻译的数据有些可以从redis缓存中获取就不走数据库查询
List<String> needTranslData = new ArrayList<>();
//step.1 先通过redis中获取缓存字典数据
for (String dictCode : dataListMap.keySet()) {
List<String> dataList = dataListMap.get(dictCode);
if (dataList.size() == 0) {
for (Map.Entry<String, List<String>> entry : dataListMap.entrySet()) {
String dictCode = entry.getKey();
List<String> dataList = entry.getValue();
if (dataList.isEmpty()) {
continue;
}
// 表字典需要翻译的数据
List<String> needTranslDataTable = new ArrayList<>();
for (String s : dataList) {
String data = s.trim();
if (data.length() == 0) {
continue; //跳过循环
}
if (dictCode.contains(",")) {
String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, data);
if (redisTemplate.hasKey(keyString)) {
try {
String text = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
list.add(new DictModel(data, text));
} catch (Exception e) {
log.warn(e.getMessage());
}
} else if (!needTranslDataTable.contains(data)) {
// 去重添加
needTranslDataTable.add(data);
}
} else {
String keyString = String.format("sys:cache:dict::%s:%s", dictCode, data);
if (redisTemplate.hasKey(keyString)) {
try {
String text = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
list.add(new DictModel(data, text));
} catch (Exception e) {
log.warn(e.getMessage());
}
} else if (!needTranslData.contains(data)) {
// 去重添加
needTranslData.add(data);
}
}
}
addNeedTranslData(translText, needTranslData, dictCode, dataList, needTranslDataTable);
//step.2 调用数据库翻译表字典
if (needTranslDataTable.size() > 0) {
if (!needTranslDataTable.isEmpty()) {
String[] arr = dictCode.split(",");
String table = arr[0], text = arr[1], code = arr[2];
String table = arr[0];
String text = arr[1];
String code = arr[2];
String values = String.join(",", needTranslDataTable);
log.info("translateDictFromTableByKeys.dictCode:" + dictCode);
log.info("translateDictFromTableByKeys.values:" + values);
@@ -259,22 +237,13 @@ public class DictAspect {
log.info("translateDictFromTableByKeys.result:" + texts);
List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
list.addAll(texts);
setRedis(dictCode, texts);
// redis 缓存
for (DictModel dict : texts) {
String redisKey = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, dict.getValue());
try {
// 保留10分钟
redisTemplate.opsForValue().set(redisKey, dict.getText(), 600, TimeUnit.SECONDS);
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
}
}
}
//step.3 调用数据库进行翻译普通字典
if (needTranslData.size() > 0) {
if (!needTranslData.isEmpty()) {
List<String> dictCodeList = Arrays.asList(dataListMap.keySet().toArray(new String[]{}));
// 将不包含逗号的字典code筛选出来因为带逗号的是表字典而不是普通的数据字典
List<String> filterDictCodes = dictCodeList.stream().filter(key -> !key.contains(",")).collect(Collectors.toList());
@@ -284,14 +253,15 @@ public class DictAspect {
log.info("translateManyDict.values:" + values);
Map<String, List<DictModel>> manyDict = commonAPI.translateManyDict(dictCodes, values);
log.info("translateManyDict.result:" + manyDict);
for (String dictCode : manyDict.keySet()) {
for (Map.Entry<String, List<DictModel>> entry : manyDict.entrySet()) {
String dictCode = entry.getKey();
List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
List<DictModel> newList = manyDict.get(dictCode);
List<DictModel> newList = entry.getValue();
list.addAll(newList);
// redis 缓存
for (DictModel dict : newList) {
String redisKey = String.format("sys:cache:dict::%s:%s", dictCode, dict.getValue());
String redisKey = String.format(SYS_CACHE_DICT_S_S, dictCode, dict.getValue());
try {
redisTemplate.opsForValue().set(redisKey, dict.getText());
} catch (Exception e) {
@@ -303,6 +273,56 @@ public class DictAspect {
return translText;
}
private void setRedis(String dictCode, List<DictModel> texts) {
// redis 缓存
for (DictModel dict : texts) {
String redisKey = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, dict.getValue());
try {
// 保留10分钟
redisTemplate.opsForValue().set(redisKey, dict.getText(), 600, TimeUnit.SECONDS);
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
}
}
private void addNeedTranslData(Map<String, List<DictModel>> translText, List<String> needTranslData, String dictCode, List<String> dataList, List<String> needTranslDataTable) {
for (String s : dataList) {
String data = s.trim();
if (data.length() == 0) {
continue; //跳过循环
}
if (dictCode.contains(",")) {
String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, data);
if (Boolean.TRUE.equals(redisTemplate.hasKey(keyString))) {
addList(translText, dictCode, data, keyString);
} else if (!needTranslDataTable.contains(data)) {
// 去重添加
needTranslDataTable.add(data);
}
} else {
String keyString = String.format(SYS_CACHE_DICT_S_S, dictCode, data);
if (Boolean.TRUE.equals(redisTemplate.hasKey(keyString))) {
addList(translText, dictCode, data, keyString);
} else if (!needTranslData.contains(data)) {
// 去重添加
needTranslData.add(data);
}
}
}
}
private void addList(Map<String, List<DictModel>> translText, String dictCode, String data, String keyString) {
try {
String text = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
list.add(new DictModel(data, text));
} catch (Exception e) {
log.warn(e.getMessage());
}
}
/**
* 字典值替换文本
*
@@ -334,6 +354,7 @@ public class DictAspect {
* @param text
* @param table
* @param key
* @deprecated 不推荐
* @return
*/
@Deprecated
@@ -341,7 +362,7 @@ public class DictAspect {
if(oConvertUtils.isEmpty(key)) {
return null;
}
StringBuffer textValue=new StringBuffer();
StringBuilder textValue = new StringBuilder();
String[] keys = key.split(",");
for (String k : keys) {
String tmpValue = null;
@@ -350,30 +371,7 @@ public class DictAspect {
continue; //跳过循环
}
//update-begin--Author:scott -- Date:20210531 ----for !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题-----
if (!StringUtils.isEmpty(table)){
log.info("--DictAspect------dicTable="+ table+" ,dicText= "+text+" ,dicCode="+code);
String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s,%s,%s]",table,text,code,k.trim());
if (redisTemplate.hasKey(keyString)){
try {
tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
} catch (Exception e) {
log.warn(e.getMessage());
}
}else {
tmpValue= commonAPI.translateDictFromTable(table,text,code,k.trim());
}
}else {
String keyString = String.format("sys:cache:dict::%s:%s",code,k.trim());
if (redisTemplate.hasKey(keyString)){
try {
tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
} catch (Exception e) {
log.warn(e.getMessage());
}
}else {
tmpValue = commonAPI.translateDict(code, k.trim());
}
}
tmpValue = getTmpValue(code, text, table, k, tmpValue);
//update-end--Author:scott -- Date:20210531 ----for !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题-----
if (tmpValue != null) {
@@ -387,5 +385,33 @@ public class DictAspect {
return textValue.toString();
}
private String getTmpValue(String code, String text, String table, String k, String tmpValue) {
if (!StringUtils.isEmpty(table)){
log.info("--DictAspect------dicTable="+ table+" ,dicText= "+text+" ,dicCode="+code);
String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s,%s,%s]",table,text,code,k.trim());
if (Boolean.TRUE.equals(redisTemplate.hasKey(keyString))){
try {
tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
} catch (Exception e) {
log.warn(e.getMessage());
}
}else {
tmpValue= commonAPI.translateDictFromTable(table,text,code,k.trim());
}
}else {
String keyString = String.format(SYS_CACHE_DICT_S_S,code,k.trim());
if (Boolean.TRUE.equals(redisTemplate.hasKey(keyString))){
try {
tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
} catch (Exception e) {
log.warn(e.getMessage());
}
}else {
tmpValue = commonAPI.translateDict(code, k.trim());
}
}
return tmpValue;
}
}
@@ -1,11 +1,5 @@
package com.jero.common.aspect;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import com.jero.common.api.CommonAPI;
import com.jero.common.aspect.annotation.PermissionData;
import com.jero.common.system.util.JeroDataAutorUtils;
@@ -14,6 +8,12 @@ import com.jero.common.system.vo.SysPermissionDataRuleModel;
import com.jero.common.system.vo.SysUserCacheInfo;
import com.jero.common.util.SpringContextUtils;
import com.jero.common.util.oConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -37,7 +37,7 @@ public class PermissionDataAspect {
@Pointcut("@annotation(com.jero.common.aspect.annotation.PermissionData)")
public void pointCut() {
// do other
}
@Around("pointCut()")
@@ -54,12 +54,12 @@ public class PermissionDataAspect {
log.debug("拦截请求 >> "+requestPath+";请求类型 >> "+requestMethod);
String username = JwtUtil.getUserNameByToken(request);
//查询数据权限信息
//TODO 微服务情况下也得支持缓存机制
// TODO 微服务情况下也得支持缓存机制
List<SysPermissionDataRuleModel> dataRules = commonAPI.queryPermissionDataRule(component, requestPath, username);
if(dataRules!=null && dataRules.size()>0) {
if(dataRules!=null && !dataRules.isEmpty()) {
//临时存储
JeroDataAutorUtils.installDataSearchConditon(request, dataRules);
//TODO 微服务情况下也得支持缓存机制
// TODO 微服务情况下也得支持缓存机制
SysUserCacheInfo userinfo = commonAPI.getCacheUser(username);
JeroDataAutorUtils.installUserInfo(request, userinfo);
}
@@ -71,12 +71,9 @@ public class PermissionDataAspect {
if(oConvertUtils.isNotEmpty(requestPath)){
url = requestPath.replace("\\", "/");
url = url.replace("//", "/");
if(url.indexOf("//")>=0){
if(url.contains("//")){
url = filterUrl(url);
}
/*if(url.startsWith("/")){
url=url.substring(1);
}*/
}
return url;
}
@@ -85,7 +82,9 @@ public class PermissionDataAspect {
* 获取请求地址
* @param request
* @return
* @deprecated 未调用
*/
@Deprecated
private String getJgAuthRequsetPath(HttpServletRequest request) {
String queryString = request.getQueryString();
String requestPath = request.getRequestURI();
@@ -106,6 +105,11 @@ public class PermissionDataAspect {
return filterUrl(requestPath);
}
/**
*
* @deprecated 未调用
*/
@Deprecated
private boolean moHuContain(List<String> list,String key){
for(String str : list){
if(key.contains(str)){
@@ -115,5 +119,4 @@ public class PermissionDataAspect {
return false;
}
}
@@ -6,16 +6,17 @@ package com.jero.common.aspect;
* @Description: 请求URL与菜单路由URL转换规则方便于采用菜单路由URL来配置数据权限规则
*/
public enum UrlMatchEnum {
CGFORM_DATA("/online/cgform/api/getData/", "/online/cgformList/"),
CGFORM_EXCEL_DATA("/online/cgform/api/exportXls/", "/online/cgformList/"),
CGFORM_TREE_DATA("/online/cgform/api/getTreeData/", "/online/cgformList/"),
CGFORM_DATA("/online/cgform/api/getData/", UrlMatch.ONLINE_CGFORMLIST),
CGFORM_EXCEL_DATA("/online/cgform/api/exportXls/", UrlMatch.ONLINE_CGFORMLIST),
CGFORM_TREE_DATA("/online/cgform/api/getTreeData/", UrlMatch.ONLINE_CGFORMLIST),
CGREPORT_DATA("/online/cgreport/api/getColumnsAndData/", "/online/cgreport/"),
CGREPORT_EXCEL_DATA("/online/cgreport/api/exportXls/", "/online/cgreport/");
UrlMatchEnum(String url, String match_url) {
UrlMatchEnum(String url, String matchUrl) {
this.url = url;
this.match_url = match_url;
this.matchUrl = matchUrl;
}
/**
@@ -25,7 +26,7 @@ public enum UrlMatchEnum {
/**
* 菜单路由 URL前缀 (对应菜单路径)
*/
private String match_url;
private String matchUrl;
/**
* 根据req url 获取到菜单配置路径前端页面路由URL
@@ -41,18 +42,16 @@ public enum UrlMatchEnum {
//如果遍历获取的type和参数type一致
if (url.indexOf(lr.url) != -1) {
//返回type对象的desc
return url.replace(lr.url, lr.match_url);
return url.replace(lr.url, lr.matchUrl);
}
}
return null;
}
public class UrlMatch{
private UrlMatch(){
// public static void main(String[] args) {
// /**
// * 比如request真实请求URL: /online/cgform/api/getData/81fcf7d8922d45069b0d5ba983612d3a
// * 转换匹配路由URL后对应配置的菜单路径:/online/cgformList/81fcf7d8922d45069b0d5ba983612d3a
// */
// System.out.println(UrlMatchEnum.getMatchResultByUrl("/online/cgform/api/getData/81fcf7d8922d45069b0d5ba983612d3a"));
// }
}
}
public static final String ONLINE_CGFORMLIST = "/online/cgformList/";
}
}
@@ -1,6 +1,10 @@
package com.jero.common.constant;
public interface CommonConstant {
public class CommonConstant {
private CommonConstant(){
}
/**
* 正常状态
@@ -26,7 +30,7 @@ public interface CommonConstant {
* 系统日志类型 登录
*/
public static final int LOG_TYPE_1 = 1;
/**
* 系统日志类型 操作
*/
@@ -36,93 +40,93 @@ public interface CommonConstant {
* 操作日志类型 查询
*/
public static final int OPERATE_TYPE_1 = 1;
/**
* 操作日志类型 添加
*/
public static final int OPERATE_TYPE_2 = 2;
/**
* 操作日志类型 更新
*/
public static final int OPERATE_TYPE_3 = 3;
/**
* 操作日志类型 删除
*/
public static final int OPERATE_TYPE_4 = 4;
/**
* 操作日志类型 倒入
*/
public static final int OPERATE_TYPE_5 = 5;
/**
* 操作日志类型 导出
*/
public static final int OPERATE_TYPE_6 = 6;
/** {@code 500 Server Error} (HTTP/1.0 - RFC 1945) */
public static final Integer SC_INTERNAL_SERVER_ERROR_500 = 500;
/** {@code 200 OK} (HTTP/1.0 - RFC 1945) */
public static final Integer SC_OK_200 = 200;
/**访问权限认证未通过 510*/
public static final Integer SC_JERO_NO_AUTHZ=510;
/** 登录用户Shiro权限缓存KEY前缀 */
public static String PREFIX_USER_SHIRO_CACHE = "shiro:cache:com.jero.config.shiro.ShiroRealm.authorizationCache:";
public static final String PREFIX_USER_SHIRO_CACHE = "shiro:cache:com.jero.config.shiro.ShiroRealm.authorizationCache:";
/** 登录用户Token令牌缓存KEY前缀 */
public static final String PREFIX_USER_TOKEN = "prefix_user_token_";
/** Token缓存时间:3600秒即一小时 */
public static final int TOKEN_EXPIRE_TIME = 3600;
/**
* 0一级菜单
*/
public static final Integer MENU_TYPE_0 = 0;
/**
* 1子菜单
* 1子菜单
*/
public static final Integer MENU_TYPE_1 = 1;
/**
* 2按钮权限
*/
public static final Integer MENU_TYPE_2 = 2;
/**通告对象类型(USER:指定用户,ALL:全体用户)*/
public static final String MSG_TYPE_UESR = "USER";
public static final String MSG_TYPE_ALL = "ALL";
/**发布状态(0未发布,1已发布,2已撤销)*/
public static final String NO_SEND = "0";
public static final String HAS_SEND = "1";
public static final String HAS_CANCLE = "2";
/**阅读状态(0未读,1已读)*/
public static final String HAS_READ_FLAG = "1";
public static final String NO_READ_FLAG = "0";
/**优先级(L低,M中,H高)*/
public static final String PRIORITY_L = "L";
public static final String PRIORITY_M = "M";
public static final String PRIORITY_H = "H";
/**
* 短信模板方式 0 .登录模板1.注册模板2.忘记密码模板
*/
public static final String SMS_TPL_TYPE_0 = "0";
public static final String SMS_TPL_TYPE_1 = "1";
public static final String SMS_TPL_TYPE_2 = "2";
/**
* 状态(0无效1有效)
*/
public static final String STATUS_0 = "0";
public static final String STATUS_1 = "1";
/**
* 同步工作流引擎1同步0不同步
*/
@@ -134,7 +138,7 @@ public interface CommonConstant {
*/
public static final String MSG_CATEGORY_1 = "1";
public static final String MSG_CATEGORY_2 = "2";
/**
* 是否配置菜单的数据权限 1是0否
*/
@@ -146,7 +150,7 @@ public interface CommonConstant {
*/
public static final Integer USER_UNFREEZE = 1;
public static final Integer USER_FREEZE = 2;
/**字典翻译文本后缀*/
public static final String DICT_TEXT_SUFFIX = "_dictText";
@@ -291,28 +295,28 @@ public interface CommonConstant {
public static final String WPS_TYPE_2="2";
public final static String X_ACCESS_TOKEN = "X-Access-Token";
public final static String X_SIGN = "X-Sign";
public final static String X_TIMESTAMP = "X-TIMESTAMP";
public static final String X_ACCESS_TOKEN = "X-Access-Token";
public static final String X_SIGN = "X-Sign";
public static final String X_TIMESTAMP = "X-TIMESTAMP";
/**
* 多租户 请求头
*/
public final static String TENANT_ID = "tenant-id";
public static final String TENANT_ID = "tenant-id";
/**
* 微服务读取配置文件属性 服务地址
*/
public final static String CLOUD_SERVER_KEY = "spring.cloud.nacos.discovery.server-addr";
public static final String CLOUD_SERVER_KEY = "spring.cloud.nacos.discovery.server-addr";
/**
* 第三方登录 验证密码/创建用户 都需要设置一个操作码 防止被恶意调用
*/
public final static String THIRD_LOGIN_CODE = "third_login_code";
public static final String THIRD_LOGIN_CODE = "third_login_code";
public final static String ANNOUNCEMENT_SEND_STATUS_0 = "0";
public static final String ANNOUNCEMENT_SEND_STATUS_0 = "0";
/** 系统通告消息状态:1=已发布 */
public final static String ANNOUNCEMENT_SEND_STATUS_1 = "1";
public static final String ANNOUNCEMENT_SEND_STATUS_1 = "1";
/** 系统通告消息状态:2=已撤销 */
public final static String ANNOUNCEMENT_SEND_STATUS_2 = "2";
public static final String ANNOUNCEMENT_SEND_STATUS_2 = "2";
}
@@ -5,12 +5,15 @@ package com.jero.common.constant;
* @Author LeeShaoQing
*
*/
public interface CommonSendStatus {
public class CommonSendStatus {
private CommonSendStatus(){
}
public static final String UNPUBLISHED_STATUS_0 = "0"; //未发布
public static final String PUBLISHED_STATUS_1 = "1"; //已发布
public static final String REVOKE_STATUS_2 = "2"; //撤销
//app端推送会话标识后缀
@@ -2,7 +2,11 @@ package com.jero.common.constant;
/**
* 数据库上下文常量
*/
public interface DataBaseConstant {
public class DataBaseConstant {
private DataBaseConstant(){
}
//*********数据库类型****************************************
public static final String DB_TYPE_MYSQL = "MYSQL";
public static final String DB_TYPE_ORACLE = "ORACLE";
@@ -40,7 +44,7 @@ public interface DataBaseConstant {
* 数据-系统用户编码对应登录用户账号
*/
public static final String SYS_USER_CODE_TABLE = "sys_user_code";
/**
* 登录用户真实姓名
*/
@@ -66,8 +70,8 @@ public interface DataBaseConstant {
*/
public static final String SYS_TIME_TABLE = "sys_time";
//*********系统上下文变量****************************************
//*********系统建表标准字段****************************************
/**
* 创建者登录名称
@@ -101,7 +105,7 @@ public interface DataBaseConstant {
* 更新日期时间
*/
public static final String UPDATE_TIME_TABLE = "update_time";
/**
* 业务流程状态
*/
@@ -115,9 +119,9 @@ public interface DataBaseConstant {
/**
* 租户ID 实体字段名
*/
String TENANT_ID = "tenantId";
public static final String TENANT_ID = "tenantId";
/**
* 租户ID 数据库字段名
*/
String TENANT_ID_TABLE = "tenant_id";
public static final String TENANT_ID_TABLE = "tenant_id";
}
@@ -7,6 +7,10 @@ package com.jero.common.constant;
*/
public class FillRuleConstant {
private FillRuleConstant(){
}
/**
* 公文发文编码
*/
@@ -1,17 +1,15 @@
package com.jero.common.constant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jero.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Set;
import java.util.List;
import java.util.Scanner;
@Component("pca")
public class ProvinceCityArea {
@@ -19,8 +17,8 @@ public class ProvinceCityArea {
public String getText(String code){
this.initAreaList();
if(this.areaList!=null || this.areaList.size()>0){
List<String> ls = new ArrayList<String>();
if(!CollectionUtils.isEmpty(this.areaList)){
List<String> ls = new ArrayList<>();
getAreaByCode(code,ls);
return String.join("/",ls);
}
@@ -29,7 +27,7 @@ public class ProvinceCityArea {
public String getCode(String text){
this.initAreaList();
if(areaList!=null || areaList.size()>0){
if(!CollectionUtils.isEmpty(areaList)){
for(int i=areaList.size()-1;i>=0;i--){
if(text.indexOf(areaList.get(i).getText())>=0){
return areaList.get(i).getId();
@@ -50,32 +48,25 @@ public class ProvinceCityArea {
}
private void initAreaList(){
//System.out.println("=====================");
if(this.areaList==null || this.areaList.size()==0){
this.areaList = new ArrayList<Area>();
if(CollectionUtils.isEmpty(this.areaList)){
this.areaList = new ArrayList<>();
try {
String jsonData = oConvertUtils.readStatic("classpath:static/pca.json");
JSONObject baseJson = JSONObject.parseObject(jsonData);
JSONObject baseJson = JSON.parseObject(jsonData);
//第一层
JSONObject provinceJson = baseJson.getJSONObject("86");
for(String provinceKey: provinceJson.keySet()){
//System.out.println("===="+provinceKey);
Area province = new Area(provinceKey,provinceJson.getString(provinceKey),"86");
this.areaList.add(province);
//第二层
JSONObject cityJson = baseJson.getJSONObject(provinceKey);
for(String cityKey:cityJson.keySet()){
//System.out.println("-----"+cityKey);
Area city = new Area(cityKey,cityJson.getString(cityKey),provinceKey);
this.areaList.add(city);
//第三层
JSONObject areaJson = baseJson.getJSONObject(cityKey);
if(areaJson!=null){
for(String areaKey:areaJson.keySet()){
//System.out.println("········"+areaKey);
Area area = new Area(areaKey,areaJson.getString(areaKey),cityKey);
this.areaList.add(area);
}
addArea(cityKey, areaJson);
}
}
}
@@ -86,21 +77,26 @@ public class ProvinceCityArea {
}
private void addArea(String cityKey, JSONObject areaJson) {
for(String areaKey:areaJson.keySet()){
Area area = new Area(areaKey,areaJson.getString(areaKey),cityKey);
this.areaList.add(area);
}
}
/**
*
* @deprecated 未调用
*/
@Deprecated
private String jsonRead(File file){
Scanner scanner = null;
StringBuilder buffer = new StringBuilder();
try {
scanner = new Scanner(file, "utf-8");
try(Scanner scanner = new Scanner(file, "utf-8");) {
while (scanner.hasNextLine()) {
buffer.append(scanner.nextLine());
}
} catch (Exception e) {
} finally {
if (scanner != null) {
scanner.close();
}
e.printStackTrace();
}
return buffer.toString();
}
@@ -23,16 +23,20 @@ package com.jero.common.constant;
* @date 2019年05月18日
* 服务名称
*/
public interface ServiceNameConstants {
public class ServiceNameConstants {
private ServiceNameConstants(){
}
/**
* 系统管理 admin
*/
String SYSTEM_SERVICE = "jero-system";
public static final String SYSTEM_SERVICE = "jero-system";
/**
* gateway通过header传递根路径 basePath
*/
String X_GATEWAY_BASE_PATH = "X_GATEWAY_BASE_PATH";
public static final String X_GATEWAY_BASE_PATH = "X_GATEWAY_BASE_PATH";
}
@@ -5,6 +5,10 @@ package com.jero.common.constant;
*/
public class VXESocketConst {
private VXESocketConst(){
}
/**
* 消息类型
*/
@@ -7,6 +7,9 @@ package com.jero.common.constant;
*/
public class WebsocketConst {
private WebsocketConst(){
}
/**
* 消息json key:cmd
@@ -1,9 +1,6 @@
package com.jero.common.constant.enums;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
* online表单枚举 代码生成器用到
@@ -13,31 +10,31 @@ public enum CgformEnum {
/**
* 单表
*/
ONE(1, "one", "/jero/code-template-online", "default.one", "经典风格"),
ONE(1, "one", Cgform.CODE_TEMPLATE_ONLINE, "default.one", "经典风格"),
/**
* 多表
*/
MANY(2, "many", "/jero/code-template-online", "default.onetomany", "经典风格"),
MANY(2, "many", Cgform.CODE_TEMPLATE_ONLINE, "default.onetomany", "经典风格"),
/**
* 多表
*/
ERP(2, "erp", "/jero/code-template-online", "erp.onetomany", "ERP风格"),
ERP(2, "erp", Cgform.CODE_TEMPLATE_ONLINE, "erp.onetomany", "ERP风格"),
/**
* 多表jvxe风格
* */
JVXE_TABLE(2, "jvxe", "/jero/code-template-online", "jvxe.onetomany", "JVXE风格"),
JVXE_TABLE(2, "jvxe", Cgform.CODE_TEMPLATE_ONLINE, "jvxe.onetomany", "JVXE风格"),
/**
* 多表内嵌子表风格
*/
INNER_TABLE(2, "innerTable", "/jero/code-template-online", "inner-table.onetomany", "内嵌子表风格"),
INNER_TABLE(2, "innerTable", Cgform.CODE_TEMPLATE_ONLINE, "inner-table.onetomany", "内嵌子表风格"),
/**
* 多表tab风格
* */
TAB(2, "tab", "/jero/code-template-online", "tab.onetomany", "Tab风格"),
TAB(2, "tab", Cgform.CODE_TEMPLATE_ONLINE, "tab.onetomany", "Tab风格"),
/**
* 树形列表
*/
TREE(3, "tree", "/jero/code-template-online", "default.tree", "树形列表");
TREE(3, "tree", Cgform.CODE_TEMPLATE_ONLINE, "default.tree", "树形列表");
/**
* 类型 1/单表 2/一对多 3/
@@ -84,7 +81,7 @@ public enum CgformEnum {
* @return
*/
public static String getTemplatePathByConfig(String code) {
return getCgformEnumByConfig(code).templatePath;
return Objects.requireNonNull(getCgformEnumByConfig(code)).templatePath;
}
@@ -134,10 +131,10 @@ public enum CgformEnum {
* @return
*/
public static List<Map<String, Object>> getJspModelList(int type) {
List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();
List<Map<String, Object>> ls = new ArrayList<>();
for (CgformEnum e : CgformEnum.values()) {
if (e.type == type) {
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Object> map = new HashMap<>();
map.put("code", e.code);
map.put("note", e.note);
ls.add(map);
@@ -145,6 +142,11 @@ public enum CgformEnum {
}
return ls;
}
public class Cgform{
private Cgform(){
}
public static final String CODE_TEMPLATE_ONLINE = "/jero/code-template-online";
}
}
@@ -25,7 +25,7 @@ import java.util.*;
public class JeroElasticsearchTemplate {
/** es服务地址 */
private String baseUrl;
private final String FORMAT_JSON = "format=json";
private static final String FORMAT_JSON = "format=json";
/** Elasticsearch 的版本号 */
private String version = null;
@@ -144,7 +144,7 @@ public class JeroElasticsearchTemplate {
if (found) {
return result.getJSONObject("_source");
} else {
return null;
return new JSONObject();
}
}
@@ -156,13 +156,6 @@ public class JeroElasticsearchTemplate {
public boolean createIndex(String indexName) {
String url = this.getBaseUrl(indexName).toString();
/* 返回结果 仅供参考
"createIndex": {
"shards_acknowledged": true,
"acknowledged": true,
"index": "hello_world"
}
*/
try {
return RestUtil.put(url).getBoolean("acknowledged");
} catch (org.springframework.web.client.HttpClientErrorException ex) {
@@ -210,42 +203,12 @@ public class JeroElasticsearchTemplate {
url += "&include_type_name=true";
}
log.info("getIndexMapping-url:" + url);
/*
* 参考返回JSON结构
*
*{
* // 索引名称
* "[indexName]": {
* "mappings": {
* // 分类名称
* "[typeName]": {
* "properties": {
* // 字段名
* "input_number": {
* // 字段类型
* "type": "long"
* },
* "input_string": {
* "type": "text",
* "fields": {
* "keyword": {
* "type": "keyword",
* "ignore_above": 256
* }
* }
* }
* }
* }
* }
* }
* }
*/
try {
return RestUtil.get(url);
} catch (org.springframework.web.client.HttpClientErrorException e) {
String message = e.getMessage();
if (message != null && message.contains("404 Not Found")) {
return null;
return new JSONObject();
}
throw e;
}
@@ -304,22 +267,6 @@ public class JeroElasticsearchTemplate {
*/
public boolean saveOrUpdate(String indexName, String typeName, String dataId, JSONObject data) {
String url = this.getBaseUrl(indexName, typeName).append("/").append(dataId).append("?refresh=wait_for").toString();
/* 返回结果仅供参考
"createIndexA2": {
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 0,
"_index": "test_index_1",
"_type": "test_type_1",
"_id": "a2",
"_version": 1,
"_primary_term": 1
}
*/
try {
// 去掉 data 中为空的值
@@ -368,7 +315,6 @@ public class JeroElasticsearchTemplate {
JSONObject data = dataList.getJSONObject(i);
String id = data.getString("id");
// 该行的操作
// {"create": {"_id":"${id}", "_index": "${indexName}", "_type": "${typeName}"}}
JSONObject action = new JSONObject();
JSONObject actionInfo = new JSONObject();
actionInfo.put("_id", id);
@@ -380,7 +326,7 @@ public class JeroElasticsearchTemplate {
data.remove("id");
bodySB.append(data.toJSONString()).append("\n");
}
System.out.println("+-+-+-: bodySB.toString(): " + bodySB.toString());
log.info("+-+-+-: bodySB.toString(): " + bodySB.toString());
HttpHeaders headers = RestUtil.getHeaderApplicationJson();
RestUtil.request(url, HttpMethod.PUT, headers, null, bodySB, JSONObject.class);
return true;
@@ -393,22 +339,6 @@ public class JeroElasticsearchTemplate {
*/
public boolean delete(String indexName, String typeName, String dataId) {
String url = this.getBaseUrl(indexName, typeName).append("/").append(dataId).toString();
/* 返回结果仅供参考
{
"_index": "es_demo",
"_type": "docs",
"_id": "001",
"_version": 3,
"result": "deleted",
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"_seq_no": 28,
"_primary_term": 18
}
*/
try {
return "deleted".equals(RestUtil.delete(url).getString("result"));
} catch (org.springframework.web.client.HttpClientErrorException ex) {
@@ -481,7 +411,7 @@ public class JeroElasticsearchTemplate {
*/
public JSONObject buildQueryString(String field, String... args) {
if (field == null) {
return null;
return new JSONObject();
}
StringBuilder sb = new StringBuilder(field).append(":(");
if (args != null) {
@@ -1,9 +1,10 @@
package com.jero.common.exception;
import org.apache.shiro.authc.AuthenticationException;
import com.jero.common.api.vo.Results;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import com.jero.common.api.vo.Result;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.connection.PoolException;
@@ -13,11 +14,9 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;
import lombok.extern.slf4j.Slf4j;
/**
* 异常处理器
*
*
* @Author scott
* @Date 2019
*/
@@ -29,43 +28,43 @@ public class JeroBootExceptionHandler {
* 处理自定义异常
*/
@ExceptionHandler(JeroBootException.class)
public Result<?> handleJeroBootException(JeroBootException e){
public Results<T> handleJeroBootException(JeroBootException e){
log.error(e.getMessage(), e);
return Result.error(e.getMessage());
return Results.error(e.getMessage());
}
@ExceptionHandler(NoHandlerFoundException.class)
public Result<?> handlerNoFoundException(Exception e) {
public Results<T> handlerNoFoundException(Exception e) {
log.error(e.getMessage(), e);
return Result.error(404, "路径不存在,请检查路径是否正确");
return Results.error(404, "路径不存在,请检查路径是否正确");
}
@ExceptionHandler(DuplicateKeyException.class)
public Result<?> handleDuplicateKeyException(DuplicateKeyException e){
public Results<T> handleDuplicateKeyException(DuplicateKeyException e){
log.error(e.getMessage(), e);
return Result.error("数据库中已存在该记录");
return Results.error("数据库中已存在该记录");
}
@ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
public Result<?> handleAuthorizationException(AuthorizationException e){
public Results<Object> handleAuthorizationException(AuthorizationException e){
log.error(e.getMessage(), e);
return Result.noauth("没有权限,请联系管理员授权");
return Results.noauth("没有权限,请联系管理员授权");
}
@ExceptionHandler(Exception.class)
public Result<?> handleException(Exception e){
public Results<T> handleException(Exception e){
log.error(e.getMessage(), e);
return Result.error("操作失败,"+e.getMessage());
return Results.error("操作失败,"+e.getMessage());
}
/**
* @Author 政辉
* @param e
* @return
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result<?> HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
StringBuffer sb = new StringBuffer();
public Results<T> httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
StringBuilder sb = new StringBuilder();
sb.append("不支持");
sb.append(e.getMethod());
sb.append("请求方法,");
@@ -78,29 +77,28 @@ public class JeroBootExceptionHandler {
}
}
log.error(sb.toString(), e);
//return Result.error("没有权限,请联系管理员授权");
return Result.error(405,sb.toString());
return Results.error(405,sb.toString());
}
/**
* spring默认上传大小100MB 超出大小捕获异常MaxUploadSizeExceededException
/**
* spring默认上传大小100MB 超出大小捕获异常MaxUploadSizeExceededException
*/
@ExceptionHandler(MaxUploadSizeExceededException.class)
public Result<?> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
public Results<T> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
log.error(e.getMessage(), e);
return Result.error("文件大小超出10MB限制, 请压缩或降低文件质量! ");
return Results.error("文件大小超出10MB限制, 请压缩或降低文件质量! ");
}
@ExceptionHandler(DataIntegrityViolationException.class)
public Result<?> handleDataIntegrityViolationException(DataIntegrityViolationException e) {
public Results<T> handleDataIntegrityViolationException(DataIntegrityViolationException e) {
log.error(e.getMessage(), e);
return Result.error("字段太长,超出数据库字段的长度");
return Results.error("字段太长,超出数据库字段的长度");
}
@ExceptionHandler(PoolException.class)
public Result<?> handlePoolException(PoolException e) {
public Results<T> handlePoolException(PoolException e) {
log.error(e.getMessage(), e);
return Result.error("Redis 连接异常!");
return Results.error("Redis 连接异常!");
}
}
@@ -4,13 +4,13 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import com.jero.common.api.vo.Result;
import com.jero.common.api.vo.Results;
import com.jero.common.system.query.QueryGenerator;
import com.jero.common.system.vo.LoginUser;
import com.jero.common.util.oConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
@@ -36,6 +36,11 @@ import java.util.stream.Collectors;
*/
@Slf4j
public class JeroController<T, S extends IService<T>> {
public static final String CLASS = "entity";
public static final String PARAMS = "params";
public static final String FILE_NAME = "fileName";
@Autowired
S service;
@@ -66,13 +71,13 @@ public class JeroController<T, S extends IService<T>> {
// Step.3 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
mv.addObject(NormalExcelConstants.CLASS, clazz);
mv.addObject(FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
mv.addObject(CLASS, clazz);
//update-begin--Author:liusq Date:20210126 for图片导出报错ImageBasePath未设置--------------------
ExportParams exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
exportParams.setImageBasePath(upLoadPath);
//update-end--Author:liusq Date:20210126 for图片导出报错ImageBasePath未设置----------------------
mv.addObject(NormalExcelConstants.PARAMS,exportParams);
mv.addObject(PARAMS,exportParams);
mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
return mv;
}
@@ -96,9 +101,9 @@ public class JeroController<T, S extends IService<T>> {
double total = service.count();
int count = (int)Math.ceil(total/pageNum);
// Step.3 多sheet处理
List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
List<Map<String, Object>> listMap = new ArrayList<>();
for (int i = 1; i <=count ; i++) {
Page<T> page = new Page<T>(i, pageNum);
Page<T> page = new Page<>(i, pageNum);
IPage<T> pageList = service.page(page, queryWrapper);
List<T> records = pageList.getRecords();
List<T> exportList = null;
@@ -110,18 +115,18 @@ public class JeroController<T, S extends IService<T>> {
} else {
exportList = records;
}
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Object> map = new HashMap<>();
ExportParams exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title+i,upLoadPath);
exportParams.setType(ExcelType.XSSF);
//map.put("title",exportParams);//表格Title
map.put(NormalExcelConstants.PARAMS,exportParams);//表格Title
map.put(NormalExcelConstants.CLASS,clazz);//表格对应实体
map.put(PARAMS,exportParams);//表格Title
map.put(CLASS,clazz);//表格对应实体
map.put(NormalExcelConstants.DATA_LIST, exportList);//数据集合
listMap.add(map);
}
// Step.4 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
mv.addObject(FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
mv.addObject(NormalExcelConstants.MAP_LIST, listMap);
return mv;
}
@@ -155,14 +160,17 @@ public class JeroController<T, S extends IService<T>> {
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
protected Result<?> importExcel(HttpServletRequest request, HttpServletResponse response, Class<T> clazz) {
protected Results<T> importExcel(HttpServletRequest request, HttpServletResponse response, Class<T> clazz) {
if(Objects.isNull(response)){
log.info("打印未使用参数");
}
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
MultipartFile file = entity.getValue();// 获取上传文件对象
// 获取上传文件对象
MultipartFile file = entity.getValue();
ImportParams params = new ImportParams();
params.setTitleRows(2);
params.setHeadRows(1);
@@ -176,10 +184,10 @@ public class JeroController<T, S extends IService<T>> {
//1200条 saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
//update-end-author:taoyan date:20190528 for:批量插入数据
return Result.OK("文件导入成功!数据行数:" + list.size());
return Results.OK("文件导入成功!数据行数:" + list.size());
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error("文件导入失败:" + e.getMessage());
return Results.error("文件导入失败:" + e.getMessage());
} finally {
try {
file.getInputStream().close();
@@ -188,6 +196,6 @@ public class JeroController<T, S extends IService<T>> {
}
}
}
return Result.error("文件导入失败!");
return Results.error("文件导入失败!");
}
}
@@ -34,7 +34,7 @@ public enum MatchTypeEnum {
return null;
}
for (MatchTypeEnum val : values()) {
if (val.getValue().toLowerCase().equals(value.toLowerCase())) {
if (val.getValue().equalsIgnoreCase(value)) {
return val;
}
}
@@ -16,7 +16,7 @@ public class QueryCondition implements Serializable {
private String dbType;
private String rule;
private String val;
public String getField() {
return field;
}
@@ -59,7 +59,7 @@ public class QueryCondition implements Serializable {
@Override
public String toString(){
StringBuffer sb =new StringBuffer();
StringBuilder sb =new StringBuilder();
if(field == null || "".equals(field)){
return "";
}
@@ -14,28 +14,32 @@ import java.util.List;
* @Description: 数据权限查询规则容器工具类
* @Author: 张代浩
* @Date: 2012-12-15 下午11:27:39
*
*
*/
public class JeroDataAutorUtils {
private JeroDataAutorUtils(){
}
public static final String MENU_DATA_AUTHOR_RULES = "MENU_DATA_AUTHOR_RULES";
public static final String MENU_DATA_AUTHOR_RULE_SQL = "MENU_DATA_AUTHOR_RULE_SQL";
public static final String SYS_USER_INFO = "SYS_USER_INFO";
/**
* 往链接请求里面传入数据查询条件
*
*
* @param request
* @param dataRules
*/
public static synchronized void installDataSearchConditon(HttpServletRequest request, List<SysPermissionDataRuleModel> dataRules) {
@SuppressWarnings("unchecked")
List<SysPermissionDataRuleModel> list = (List<SysPermissionDataRuleModel>)loadDataSearchConditon();// 1.先从request获取MENU_DATA_AUTHOR_RULES如果存则获取到LIST
List<SysPermissionDataRuleModel> list = loadDataSearchConditon();// 1.先从request获取MENU_DATA_AUTHOR_RULES如果存则获取到LIST
if (list==null) {
// 2.如果不存在则new一个list
list = new ArrayList<SysPermissionDataRuleModel>();
list = new ArrayList<>();
}
for (SysPermissionDataRuleModel tsDataRule : dataRules) {
list.add(tsDataRule);
@@ -45,18 +49,18 @@ public class JeroDataAutorUtils {
/**
* 获取请求对应的数据权限规则
*
*
* @return
*/
@SuppressWarnings("unchecked")
public static synchronized List<SysPermissionDataRuleModel> loadDataSearchConditon() {
return (List<SysPermissionDataRuleModel>) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULES);
}
/**
* 获取请求对应的数据权限SQL
*
*
* @return
*/
public static synchronized String loadDataSearchConditonSQLString() {
@@ -65,12 +69,12 @@ public class JeroDataAutorUtils {
/**
* 往链接请求里面传入数据查询条件
*
*
* @param request
* @param sql
*/
public static synchronized void installDataSearchConditon(HttpServletRequest request, String sql) {
String ruleSql = (String)loadDataSearchConditonSQLString();
String ruleSql = loadDataSearchConditonSQLString();
if (!StringUtils.hasText(ruleSql)) {
request.setAttribute(MENU_DATA_AUTHOR_RULE_SQL,sql);
}
@@ -99,6 +103,6 @@ public class JeroDataAutorUtils {
*/
public static synchronized SysUserCacheInfo loadUserInfo() {
return (SysUserCacheInfo) SpringContextUtils.getHttpServletRequest().getAttribute(SYS_USER_INFO);
}
}
@@ -27,10 +27,15 @@ import com.jero.common.util.oConvertUtils;
* @Desc JWT工具类
**/
public class JwtUtil {
private JwtUtil(){
}
// Token过期时间24小时用户登录过期时间是此时间的两倍以token在reids缓存时间为准
public static final long EXPIRE_TIME = 1440 * 60 * 1000;
// public static final long EXPIRE_TIME = 2000;
public static final long EXPIRE_TIME = 1440 * 60 * 1000L;
private static final String USERNAME_FIELD = "username";
/**
* 校验token是否正确
@@ -43,9 +48,9 @@ public class JwtUtil {
try {
// 根据密码生成JWT效验器
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
JWTVerifier verifier = JWT.require(algorithm).withClaim(USERNAME_FIELD, username).build();
// 效验TOKEN
DecodedJWT jwt = verifier.verify(token);
verifier.verify(token);
return true;
} catch (Exception exception) {
return false;
@@ -60,7 +65,7 @@ public class JwtUtil {
public static String getUsername(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("username").asString();
return jwt.getClaim(USERNAME_FIELD).asString();
} catch (JWTDecodeException e) {
return null;
}
@@ -77,13 +82,13 @@ public class JwtUtil {
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(secret);
// 附带username信息
return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);
return JWT.create().withClaim(USERNAME_FIELD, username).withExpiresAt(date).sign(algorithm);
}
/**
* 根据request中的token获取用户账号
*
*
* @param request
* @return
* @throws JeroBootException
@@ -96,7 +101,7 @@ public class JwtUtil {
}
return username;
}
/**
* 从session中获取变量
* @param key
@@ -121,98 +126,129 @@ public class JwtUtil {
if(returnValue!=null){returnValue = returnValue + moshi;}
return returnValue;
}
/**
* 从当前用户中获取变量
* @param key
* @param user
* @return
*/
//TODO 急待改造 sckjkdsjsfjdk
// TODO 急待改造 sckjkdsjsfjdk
public static String getUserSystemData(String key,SysUserCacheInfo user) {
if(user==null) {
user = JeroDataAutorUtils.loadUserInfo();
}
//#{sys_user_code}%
// 获取登录用户信息
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
String moshi = "";
if(key.indexOf("}")!=-1){
if(key.contains("}")){
moshi = key.substring(key.indexOf("}")+1);
}
String returnValue = null;
//针对特殊标示处理#{sysOrgCode}判断替换
if (key.contains("#{")) {
key = key.substring(2,key.indexOf("}"));
} else {
key = key;
}
//替换为系统登录用户帐号
if (key.equals(DataBaseConstant.SYS_USER_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_USER_CODE_TABLE)) {
if(user==null) {
returnValue = sysUser.getUsername();
}else {
returnValue = user.getSysUserCode();
}
}
//替换为系统登录用户真实名字
else if (key.equals(DataBaseConstant.SYS_USER_NAME)|| key.toLowerCase().equals(DataBaseConstant.SYS_USER_NAME_TABLE)) {
if(user==null) {
returnValue = sysUser.getRealname();
}else {
returnValue = user.getSysUserName();
}
}
//替换为系统用户登录所使用的机构编码
else if (key.equals(DataBaseConstant.SYS_ORG_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_ORG_CODE_TABLE)) {
if(user==null) {
returnValue = sysUser.getOrgCode();
}else {
returnValue = user.getSysOrgCode();
}
}
//替换为系统用户所拥有的所有机构编码
else if (key.equals(DataBaseConstant.SYS_MULTI_ORG_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_MULTI_ORG_CODE_TABLE)) {
if(user==null){
//TODO 暂时使用用户登录部门存在逻辑缺陷不是用户所拥有的部门
returnValue = sysUser.getOrgCode();
}else{
if(user.isOneDepart()) {
returnValue = user.getSysMultiOrgCode().get(0);
}else {
returnValue = Joiner.on(",").join(user.getSysMultiOrgCode());
}
}
}
//替换为当前系统时间(年月日)
else if (key.equals(DataBaseConstant.SYS_DATE)|| key.toLowerCase().equals(DataBaseConstant.SYS_DATE_TABLE)) {
returnValue = DateUtils.formatDate();
}
//替换为当前系统时间年月日时分秒
else if (key.equals(DataBaseConstant.SYS_TIME)|| key.toLowerCase().equals(DataBaseConstant.SYS_TIME_TABLE)) {
returnValue = DateUtils.now();
}
//流程状态默认值默认未发起
else if (key.equals(DataBaseConstant.BPM_STATUS)|| key.toLowerCase().equals(DataBaseConstant.BPM_STATUS_TABLE)) {
returnValue = "1";
}
//update-begin-author:taoyan date:20210330 for:多租户ID作为系统变量
else if (key.equals(DataBaseConstant.TENANT_ID) || key.toLowerCase().equals(DataBaseConstant.TENANT_ID_TABLE)){
returnValue = sysUser.getRelTenantIds();
if(oConvertUtils.isEmpty(returnValue) || (returnValue!=null && returnValue.indexOf(",")>0)){
returnValue = SpringContextUtils.getHttpServletRequest().getHeader(CommonConstant.TENANT_ID);
}
}
returnValue = setReturnValue(key, user, sysUser, returnValue);
//update-end-author:taoyan date:20210330 for:多租户ID作为系统变量
if(returnValue!=null){returnValue = returnValue + moshi;}
return returnValue;
}
// public static void main(String[] args) {
// String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NjUzMzY1MTMsInVzZXJuYW1lIjoiYWRtaW4ifQ.xjhud_tWCNYBOg_aRlMgOdlZoWFFKB_givNElHNw3X0";
// System.out.println(JwtUtil.getUsername(token));
// }
private static String setReturnValue(String key, SysUserCacheInfo user, LoginUser sysUser, String returnValue) {
//替换为系统登录用户帐号
if (isaBoolean(key, DataBaseConstant.SYS_USER_CODE, DataBaseConstant.SYS_USER_CODE_TABLE)) {
returnValue = setReturnValueUsername(user, sysUser);
}
//替换为系统登录用户真实名字
else if (isaBoolean(key, DataBaseConstant.SYS_USER_NAME, DataBaseConstant.SYS_USER_NAME_TABLE)) {
returnValue = setReturnValueRealName(user, sysUser);
}
//替换为系统用户登录所使用的机构编码
else if (isaBoolean(key, DataBaseConstant.SYS_ORG_CODE, DataBaseConstant.SYS_ORG_CODE_TABLE)) {
returnValue = setReturnValueOrgCode(user, sysUser);
}
//替换为系统用户所拥有的所有机构编码
else if (isaBoolean(key, DataBaseConstant.SYS_MULTI_ORG_CODE, DataBaseConstant.SYS_MULTI_ORG_CODE_TABLE)) {
returnValue = setReturnValueOrgCodeNew(user, sysUser);
}
//替换为当前系统时间(年月日)
else if (isaBoolean(key, DataBaseConstant.SYS_DATE, DataBaseConstant.SYS_DATE_TABLE)) {
returnValue = DateUtils.formatDate();
}
//替换为当前系统时间年月日时分秒
else if (isaBoolean(key, DataBaseConstant.SYS_TIME, DataBaseConstant.SYS_TIME_TABLE)) {
returnValue = DateUtils.now();
}
//流程状态默认值默认未发起
else if (isaBoolean(key, DataBaseConstant.BPM_STATUS, DataBaseConstant.BPM_STATUS_TABLE)) {
returnValue = "1";
}
//update-begin-author:taoyan date:20210330 for:多租户ID作为系统变量
else if (isaBoolean(key, DataBaseConstant.TENANT_ID, DataBaseConstant.TENANT_ID_TABLE)){
returnValue = sysUser.getRelTenantIds();
returnValue = setReturnValueTenantId(returnValue);
}
return returnValue;
}
private static boolean isaBoolean(String key, String sysUserCode, String sysUserCodeTable) {
return key.equals(sysUserCode) || key.equalsIgnoreCase(sysUserCodeTable);
}
private static String setReturnValueTenantId(String returnValue) {
if(oConvertUtils.isEmpty(returnValue) || returnValue.contains(",")){
returnValue = SpringContextUtils.getHttpServletRequest().getHeader(CommonConstant.TENANT_ID);
}
return returnValue;
}
private static String setReturnValueOrgCodeNew(SysUserCacheInfo user, LoginUser sysUser) {
String returnValue;
if(user==null){
// TODO 暂时使用用户登录部门存在逻辑缺陷不是用户所拥有的部门
returnValue = sysUser.getOrgCode();
}else{
if(user.isOneDepart()) {
returnValue = user.getSysMultiOrgCode().get(0);
}else {
returnValue = Joiner.on(",").join(user.getSysMultiOrgCode());
}
}
return returnValue;
}
private static String setReturnValueOrgCode(SysUserCacheInfo user, LoginUser sysUser) {
String returnValue;
if(user==null) {
returnValue = sysUser.getOrgCode();
}else {
returnValue = user.getSysOrgCode();
}
return returnValue;
}
private static String setReturnValueRealName(SysUserCacheInfo user, LoginUser sysUser) {
String returnValue;
if(user==null) {
returnValue = sysUser.getRealname();
}else {
returnValue = user.getSysUserName();
}
return returnValue;
}
private static String setReturnValueUsername(SysUserCacheInfo user, LoginUser sysUser) {
String returnValue;
if(user==null) {
returnValue = sysUser.getUsername();
}else {
returnValue = user.getSysUserCode();
}
return returnValue;
}
}
@@ -25,12 +25,12 @@ public class ComboModel implements Serializable {
public ComboModel(){
};
}
public ComboModel(String id,String title,boolean checked,String username){
this.id = id;
this.title = title;
this.checked = false;
this.checked = checked;
this.username = username;
};
}
}
@@ -1,7 +1,5 @@
package com.jero.common.system.vo;
import org.jeecgframework.poi.excel.annotation.Excel;
/**
* @Author qinfeng
* @Date 2020/2/19 12:01
@@ -10,14 +10,14 @@ import java.util.Objects;
* <p>
* 部门表 存储树结构数据的实体类
* <p>
*
*
* @Author Steve
* @Since 2019-01-22
* @Since 2019-01-22
*/
public class SysDepartTreeModel implements Serializable{
private static final long serialVersionUID = 1L;
/** 对应SysDepart中的id字段,前端数据树中的key*/
private String key;
@@ -30,7 +30,7 @@ public class SysDepartTreeModel implements Serializable{
private boolean isLeaf;
// 以下所有字段均与SysDepart相同
private String id;
private String parentId;
@@ -44,7 +44,7 @@ public class SysDepartTreeModel implements Serializable{
private Integer departOrder;
private String description;
private String orgCategory;
private String orgType;
@@ -151,7 +151,7 @@ public class SysDepartTreeModel implements Serializable{
public void setDepartName(String departName) {
this.departName = departName;
}
public String getOrgCategory() {
return orgCategory;
}
@@ -288,7 +288,9 @@ public class SysDepartTreeModel implements Serializable{
this.updateTime = updateTime;
}
public SysDepartTreeModel() { }
public SysDepartTreeModel() {
// do other
}
/**
* 重写equals方法
@@ -324,7 +326,7 @@ public class SysDepartTreeModel implements Serializable{
Objects.equals(updateTime, model.updateTime) &&
Objects.equals(children, model.children);
}
/**
* 重写hashCode方法
*/
@@ -332,8 +334,8 @@ public class SysDepartTreeModel implements Serializable{
public int hashCode() {
return Objects.hash(id, parentId, departName, departNameEn, departNameAbbr,
departOrder, description, orgCategory, orgType, orgCode, mobile, fax, address,
memo, status, delFlag, createBy, createTime, updateBy, updateTime,
departOrder, description, orgCategory, orgType, orgCode, mobile, fax, address,
memo, status, delFlag, createBy, createTime, updateBy, updateTime,
children);
}
@@ -1,12 +1,5 @@
package com.jero.common.system.vo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
@@ -1,10 +1,10 @@
package com.jero.common.util;
/**
*
*
* @Author 张代浩
*
*/
public enum BrowserType {
IE11,IE10,IE9,IE8,IE7,IE6,Firefox,Safari,Chrome,Opera,Camino,Gecko
IE11,IE10,IE9,IE8,IE7,IE6,FIREFOX,SAFARI,CHROME,OPERA,CAMINO,GECKO
}
@@ -8,22 +8,29 @@ import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
/**
*
*
* @Author 张代浩
*
*
*/
public class BrowserUtils {
private BrowserUtils(){
}
private static final String USER_AGENT = "USER-AGENT";
private static final String RV_11 = "rv:11.0";
// 判断是否是IE
public static boolean isIE(HttpServletRequest request) {
return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request
.getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true
: false;
return (request.getHeader(USER_AGENT).toLowerCase().indexOf("msie") > -1 || request
.getHeader(USER_AGENT).toLowerCase().contains(RV_11));
}
/**
* 获取IE版本
*
*
* @param request
* @return
*/
@@ -47,7 +54,7 @@ public class BrowserUtils {
/**
* 获取浏览器类型
*
*
* @param request
* @return
*/
@@ -72,47 +79,47 @@ public class BrowserUtils {
browserType = BrowserType.IE6;
}
if (getBrowserType(request, FIREFOX)) {
browserType = BrowserType.Firefox;
browserType = BrowserType.FIREFOX;
}
if (getBrowserType(request, SAFARI)) {
browserType = BrowserType.Safari;
browserType = BrowserType.SAFARI;
}
if (getBrowserType(request, CHROME)) {
browserType = BrowserType.Chrome;
browserType = BrowserType.CHROME;
}
if (getBrowserType(request, OPERA)) {
browserType = BrowserType.Opera;
browserType = BrowserType.OPERA;
}
if (getBrowserType(request, "Camino")) {
browserType = BrowserType.Camino;
browserType = BrowserType.CAMINO;
}
return browserType;
}
private static boolean getBrowserType(HttpServletRequest request,
String brosertype) {
return request.getHeader("USER-AGENT").toLowerCase()
.indexOf(brosertype) > 0 ? true : false;
return request.getHeader(USER_AGENT).toLowerCase()
.indexOf(brosertype) > -1;
}
private final static String IE11 = "rv:11.0";
private final static String IE10 = "MSIE 10.0";
private final static String IE9 = "MSIE 9.0";
private final static String IE8 = "MSIE 8.0";
private final static String IE7 = "MSIE 7.0";
private final static String IE6 = "MSIE 6.0";
private final static String MAXTHON = "Maxthon";
private final static String QQ = "QQBrowser";
private final static String GREEN = "GreenBrowser";
private final static String SE360 = "360SE";
private final static String FIREFOX = "Firefox";
private final static String OPERA = "Opera";
private final static String CHROME = "Chrome";
private final static String SAFARI = "Safari";
private final static String OTHER = "其它";
private static final String IE11 = RV_11;
private static final String IE10 = "MSIE 10.0";
private static final String IE9 = "MSIE 9.0";
private static final String IE8 = "MSIE 8.0";
private static final String IE7 = "MSIE 7.0";
private static final String IE6 = "MSIE 6.0";
private static final String MAXTHON = "Maxthon";
private static final String QQ = "QQBrowser";
private static final String GREEN = "GreenBrowser";
private static final String SE360 = "360SE";
private static final String FIREFOX = "Firefox";
private static final String OPERA = "Opera";
private static final String CHROME = "Chrome";
private static final String SAFARI = "Safari";
private static final String OTHER = "其它";
public static String checkBrowse(HttpServletRequest request) {
String userAgent = request.getHeader("USER-AGENT");
String userAgent = request.getHeader(USER_AGENT);
if (regex(OPERA, userAgent)) {
return OPERA;
}
@@ -164,26 +171,26 @@ public class BrowserUtils {
return m.find();
}
private static Map<String, String> langMap = new HashMap<String, String>();
private final static String ZH = "zh";
private final static String ZH_CN = "zh-cn";
private final static String EN = "en";
private final static String EN_US = "en";
static
private static Map<String, String> langMap = new HashMap<>();
private static final String ZH = "zh";
private static final String ZH_CN = "zh-cn";
private static final String EN = "en";
private static final String EN_US = "en";
static
{
langMap.put(ZH, ZH_CN);
langMap.put(EN, EN_US);
}
public static String getBrowserLanguage(HttpServletRequest request) {
String browserLang = request.getLocale().getLanguage();
String browserLangCode = (String)langMap.get(browserLang);
String browserLangCode = langMap.get(browserLang);
if(browserLangCode == null)
{
browserLangCode = EN_US;
@@ -198,7 +205,7 @@ public class BrowserUtils {
/** 判断请求是否来自移动端 */
public static boolean isMobile(HttpServletRequest request) {
String ua = request.getHeader("User-Agent").toLowerCase();
String ua = request.getHeader(USER_AGENT).toLowerCase();
Pattern pattern = Pattern.compile("(phone|pad|pod|iphone|ipod|ios|ipad|android|mobile|blackberry|iemobile|mqqbrowser|juc|fennec|wosbrowser|browserng|webos|symbian|windows phone)");
return pattern.matcher(ua).find();
}
@@ -30,6 +30,10 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CommonUtils {
private CommonUtils(){
}
//中文正则
private static Pattern ZHONGWEN_PATTERN = Pattern.compile("[\u4e00-\u9fa5]");
@@ -49,7 +53,7 @@ public class CommonUtils {
dbPath = bizPath + File.separator + fileName;
}else {
InputStream in = new ByteArrayInputStream(data);
String relativePath = bizPath+"/"+fileName;
String relativePath = bizPath+ File.separator +fileName;
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
dbPath = MinioUtil.upload(in,relativePath);
}else if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
@@ -93,10 +97,7 @@ public class CommonUtils {
return false;
}else{
Matcher m = ZHONGWEN_PATTERN.matcher(str);
if (m.find()) {
return true;
}
return false;
return m.find();
}
}
@@ -177,6 +178,7 @@ public class CommonUtils {
/**
* 全局获取平台数据库类型作废了
* @deprecated 不推荐
* @return
*/
@Deprecated
@@ -188,7 +190,6 @@ public class CommonUtils {
try {
return getDatabaseTypeByDataSource(dataSource);
} catch (SQLException e) {
//e.printStackTrace();
log.warn(e.getMessage(), e);
return "";
}
@@ -202,9 +203,9 @@ public class CommonUtils {
if (oConvertUtils.isNotEmpty(dbTypeEnum)) {
return dbTypeEnum;
}
try {
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
dbTypeEnum = JdbcUtils.getDbType(dataSource.getConnection().getMetaData().getURL());
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
try (Connection connection = dataSource.getConnection();) {
dbTypeEnum = JdbcUtils.getDbType(connection.getMetaData().getURL());
return dbTypeEnum;
} catch (SQLException e) {
log.warn(e.getMessage(), e);
@@ -252,8 +253,7 @@ public class CommonUtils {
*/
public static boolean limitFileSuffix(String fileName,String[] fileSuffixLimits){
final List<String> fileNameList = Arrays.asList(fileSuffixLimits);
boolean isExists = fileNameList.stream().anyMatch(name -> fileName.substring(0,fileName.lastIndexOf('.')).contains(name)||fileName.substring(fileName.lastIndexOf('.')).equals(name));
return isExists;
return fileNameList.stream().anyMatch(name -> fileName.substring(0,fileName.lastIndexOf('.')).contains(name)||fileName.substring(fileName.lastIndexOf('.')).equals(name));
}
/**
* RSA 使用私钥解密
@@ -262,10 +262,10 @@ public class CommonUtils {
* @param RSAPrivateKey 私钥
* @return String 解密后的字符串
*/
public static String decryptBtRsaPriKey(String str,String RSAPrivateKey) throws Exception {
public static String decryptBtRsaPriKey(String str,String RSAPrivateKey){
RSA rsa = new RSA(RSAPrivateKey, null);
byte[] decrypt = rsa.decrypt(str, KeyType.PrivateKey);
return new String(decrypt);
}
}
}
@@ -13,6 +13,7 @@ import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Objects;
import org.springframework.util.StringUtils;
@@ -25,54 +26,19 @@ import org.springframework.util.StringUtils;
*/
public class DateUtils extends PropertyEditorSupport {
public static ThreadLocal<SimpleDateFormat> date_sdf = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
public static ThreadLocal<SimpleDateFormat> yyyyMMdd = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyyMMdd");
}
};
public static ThreadLocal<SimpleDateFormat> date_sdf_wz = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy年MM月dd日");
}
};
public static ThreadLocal<SimpleDateFormat> time_sdf = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm");
}
};
public static ThreadLocal<SimpleDateFormat> yyyymmddhhmmss = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyyMMddHHmmss");
}
};
public static ThreadLocal<SimpleDateFormat> short_time_sdf = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("HH:mm");
}
};
public static ThreadLocal<SimpleDateFormat> datetimeFormat = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
public static ThreadLocal<SimpleDateFormat> date_sdf = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
public static ThreadLocal<SimpleDateFormat> yyyyMMdd = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMdd"));
public static ThreadLocal<SimpleDateFormat> date_sdf_wz = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy年MM月dd日"));
public static ThreadLocal<SimpleDateFormat> time_sdf = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm"));
public static ThreadLocal<SimpleDateFormat> yyyymmddhhmmss = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMddHHmmss"));
public static ThreadLocal<SimpleDateFormat> short_time_sdf = ThreadLocal.withInitial(() -> new SimpleDateFormat("HH:mm"));
public static ThreadLocal<SimpleDateFormat> datetimeFormat = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 以毫秒表示的时间
private static final long DAY_IN_MILLIS = 24 * 3600 * 1000;
private static final long HOUR_IN_MILLIS = 3600 * 1000;
private static final long MINUTE_IN_MILLIS = 60 * 1000;
private static final long SECOND_IN_MILLIS = 1000;
private static final long DAY_IN_MILLIS = 24 * 3600 * 1000L;
private static final long HOUR_IN_MILLIS = 3600 * 1000L;
private static final long MINUTE_IN_MILLIS = 60 * 1000L;
private static final long SECOND_IN_MILLIS = 1000L;
// 指定模式的时间格式
private static SimpleDateFormat getSDFormat(String pattern) {
@@ -96,7 +62,6 @@ public class DateUtils extends PropertyEditorSupport {
*/
public static Calendar getCalendar(long millis) {
Calendar cal = Calendar.getInstance();
// --------------------cal.setTimeInMillis(millis);
cal.setTime(new Date(millis));
return cal;
}
@@ -128,14 +93,9 @@ public class DateUtils extends PropertyEditorSupport {
/**
* 时间戳转换为字符串
*
* @param time
* @return
*/
public static String timestamptoStr(Timestamp time) {
Date date = null;
if (null != time) {
date = new Date(time.getTime());
}
public static String timestamptoStr() {
return date2Str(date_sdf.get());
}
@@ -147,6 +107,9 @@ public class DateUtils extends PropertyEditorSupport {
*/
public static Timestamp str2Timestamp(String str) {
Date date = str2Date(str, date_sdf.get());
if(Objects.isNull(date)){
return null;
}
return new Timestamp(date.getTime());
}
@@ -174,15 +137,12 @@ public class DateUtils extends PropertyEditorSupport {
/**
* 日期转换为字符串
*
* @param date_sdf 日期格式
* @param dateSdf 日期格式
* @return 字符串
*/
public static String date2Str(SimpleDateFormat date_sdf) {
public static String date2Str(SimpleDateFormat dateSdf) {
Date date = getDate();
if (null == date) {
return null;
}
return date_sdf.format(date);
return dateSdf.format(date);
}
/**
@@ -194,28 +154,27 @@ public class DateUtils extends PropertyEditorSupport {
*/
public static String dateformat(String date, String format) {
SimpleDateFormat sformat = new SimpleDateFormat(format);
Date _date = null;
Date dateNew = null;
try {
_date = sformat.parse(date);
dateNew = sformat.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sformat.format(_date);
return sformat.format(dateNew);
}
/**
* 日期转换为字符串
*
* @param date 日期
* @param date_sdf 日期格式
* @param dateSdf 日期格式
* @return 字符串
*/
public static String date2Str(Date date, SimpleDateFormat date_sdf) {
public static String date2Str(Date date, SimpleDateFormat dateSdf) {
if (null == date) {
return null;
}
return date_sdf.format(date);
return dateSdf.format(date);
}
/**
@@ -226,9 +185,6 @@ public class DateUtils extends PropertyEditorSupport {
*/
public static String getDate(String format) {
Date date = new Date();
if (null == date) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
@@ -288,16 +244,14 @@ public class DateUtils extends PropertyEditorSupport {
* @return 指定日历的时间戳
*/
public static Timestamp getCalendarTimestamp(Calendar cal) {
// ---------------------return new Timestamp(cal.getTimeInMillis());
return new Timestamp(cal.getTime().getTime());
}
public static Timestamp gettimestamp() {
public static Timestamp geTimestamps() {
Date dt = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowTime = df.format(dt);
java.sql.Timestamp buydate = java.sql.Timestamp.valueOf(nowTime);
return buydate;
return java.sql.Timestamp.valueOf(nowTime);
}
// ////////////////////////////////////////////////////////////////////////////
@@ -321,7 +275,6 @@ public class DateUtils extends PropertyEditorSupport {
* @return 指定日历的毫秒数
*/
public static long getMillis(Calendar cal) {
// --------------------return cal.getTimeInMillis();
return cal.getTime().getTime();
}
@@ -624,7 +577,7 @@ public class DateUtils extends PropertyEditorSupport {
public static Long getCurrentTimestamp() {
return Long.valueOf(DateUtils.yyyymmddhhmmss.get().format(new Date()));
}
/**
* String类型 转换为Date, 如果参数长度为10 转换格式yyyy-MM-dd 如果参数长度为19 转换格式yyyy-MM-dd
* HH:mm:ss * @param text String类型的时间值
@@ -635,7 +588,7 @@ public class DateUtils extends PropertyEditorSupport {
try {
if (text.indexOf(":") == -1 && text.length() == 10) {
setValue(DateUtils.date_sdf.get().parse(text));
} else if (text.indexOf(":") > 0 && text.length() == 19) {
} else if (text.indexOf(":") > -1 && text.length() == 19) {
setValue(DateUtils.datetimeFormat.get().parse(text));
} else {
throw new IllegalArgumentException("Could not parse date, date format is error ");
@@ -704,4 +657,4 @@ public class DateUtils extends PropertyEditorSupport {
return zonedDateTime.toLocalDateTime();
}
}
}
@@ -1,9 +1,5 @@
package com.jero.common.util;
import com.jero.config.StaticConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
@@ -12,6 +8,10 @@ import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.jero.common.exception.JeroBootException;
import com.jero.config.StaticConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created on 17/6/7.
@@ -25,15 +25,19 @@ import com.aliyuncs.profile.IClientProfile;
* 国际短信发送请勿参照此DEMO
*/
public class DySmsHelper {
private final static Logger logger=LoggerFactory.getLogger(DySmsHelper.class);
private DySmsHelper(){
}
private static final Logger logger=LoggerFactory.getLogger(DySmsHelper.class);
//产品名称:云通信短信API产品,开发者无需替换
static final String product = "Dysmsapi";
static final String PRODUCT = "Dysmsapi";
//产品域名,开发者无需替换
static final String domain = "dysmsapi.aliyuncs.com";
static final String DOMAIN = "dysmsapi.aliyuncs.com";
// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
// 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
static String accessKeyId;
static String accessKeySecret;
@@ -52,8 +56,8 @@ public class DySmsHelper {
public static String getAccessKeySecret() {
return accessKeySecret;
}
public static boolean sendSms(String phone,JSONObject templateParamJson,DySmsEnum dySmsEnum) throws ClientException {
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
@@ -64,15 +68,16 @@ public class DySmsHelper {
setAccessKeyId(staticConfig.getAccessKeyId());
setAccessKeySecret(staticConfig.getAccessKeySecret());
//update-end-authortaoyan date:20200811 for:配置类数据获取
String hangzhou = "cn-hangzhou";
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IClientProfile profile = DefaultProfile.getProfile(hangzhou, accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint(hangzhou, hangzhou, PRODUCT, DOMAIN);
IAcsClient acsClient = new DefaultAcsClient(profile);
//验证json参数
validateParam(templateParamJson,dySmsEnum);
//组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
//必填:待发送手机号
@@ -83,40 +88,28 @@ public class DySmsHelper {
request.setTemplateCode(dySmsEnum.getTemplateCode());
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}",此处的值为
request.setTemplateParam(templateParamJson.toJSONString());
//选填-上行短信扩展码(无特殊需求用户请忽略此字段)
//request.setSmsUpExtendCode("90997");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
//request.setOutId("yourOutId");
boolean result = false;
//hint 此处可能会抛出异常注意catch
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
logger.info("短信接口返回的数据----------------");
logger.info("{Code:" + sendSmsResponse.getCode()+",Message:" + sendSmsResponse.getMessage()+",RequestId:"+ sendSmsResponse.getRequestId()+",BizId:"+sendSmsResponse.getBizId()+"}");
String str = "{Code:" + sendSmsResponse.getCode()+",Message:" + sendSmsResponse.getMessage()+",RequestId:"+ sendSmsResponse.getRequestId()+",BizId:"+sendSmsResponse.getBizId()+"}";
logger.info(str);
if ("OK".equals(sendSmsResponse.getCode())) {
result = true;
}
return result;
}
private static void validateParam(JSONObject templateParamJson,DySmsEnum dySmsEnum) {
String keys = dySmsEnum.getKeys();
String [] keyArr = keys.split(",");
for(String item :keyArr) {
if(!templateParamJson.containsKey(item)) {
throw new RuntimeException("模板缺少参数:"+item);
throw new JeroBootException("模板缺少参数:"+item);
}
}
}
// public static void main(String[] args) throws ClientException, InterruptedException {
// JSONObject obj = new JSONObject();
// obj.put("code", "1234");
// sendSms("13800138000", obj, DySmsEnum.FORGET_PASSWORD_TEMPLATE_CODE);
// }
}
@@ -3,10 +3,12 @@ package com.jero.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jero.common.handler.IFillRuleHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.jero.common.handler.IFillRuleHandler;
import org.apache.poi.ss.formula.functions.T;
/**
@@ -18,6 +20,10 @@ import com.jero.common.handler.IFillRuleHandler;
@Slf4j
public class FillRuleUtil {
private FillRuleUtil(){
}
/**
* @param ruleCode ruleCode
* @return
@@ -27,9 +33,9 @@ public class FillRuleUtil {
if (!StringUtils.isEmpty(ruleCode)) {
try {
// 获取 Service
ServiceImpl impl = (ServiceImpl) SpringContextUtils.getBean("sysFillRuleServiceImpl");
ServiceImpl<BaseMapper<T>,T> impl = (ServiceImpl) SpringContextUtils.getBean("sysFillRuleServiceImpl");
// 根据 ruleCode 查询出实体
QueryWrapper queryWrapper = new QueryWrapper();
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("rule_code", ruleCode);
JSONObject entity = JSON.parseObject(JSON.toJSONString(impl.getOne(queryWrapper)));
if (entity == null) {
@@ -8,6 +8,10 @@ import org.springframework.web.util.HtmlUtils;
*/
public class HTMLUtils {
private HTMLUtils(){
}
/**
* 获取HTML内的文本不包含标签
*
@@ -8,51 +8,54 @@ import org.slf4j.LoggerFactory;
/**
* IP地址
*
*
* @Author scott
* @email test@163.com
* @Date 2019年01月14日
*/
public class IPUtils {
private IPUtils(){
}
private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
/**
* 获取IP地址
*
*
* 使用Nginx等反向代理软件 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话X-Forwarded-For的值并不止一个而是一串IP地址X-Forwarded-For中第一个非unknown的有效IP字符串则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null;
try {
String unknown = "unknown";
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (StringUtils.isEmpty(ip) || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("IPUtils ERROR ", e);
}
// //使用代理则获取第一个IP地址
// if(StringUtils.isEmpty(ip) && ip.length() > 15) {
// if(ip.indexOf(",") > 0) {
// ip = ip.substring(0, ip.indexOf(","));
// }
// }
//使用代理则获取第一个IP地址
if(!StringUtils.isEmpty(ip) && ip.length() > 15 && ip.contains(",")) {
ip = ip.substring(0, ip.indexOf(","));
}
return ip;
}
}
@@ -2,12 +2,12 @@ package com.jero.common.util;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j;
import com.jero.common.api.vo.Result;
import com.jero.common.api.vo.Results;
import com.jero.common.constant.CommonConstant;
import com.jero.common.exception.JeroBootException;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
@@ -15,10 +15,13 @@ import java.util.List;
*/
@Slf4j
public class ImportExcelUtil {
private ImportExcelUtil(){
public static Result<?> imporReturnRes(int errorLines,int successLines,List<String> errorMessage) throws IOException {
}
public static Results<JSONObject> imporReturnRes(int errorLines, int successLines, List<String> errorMessage){
if (errorLines == 0) {
return Result.OK("" + successLines + "行数据全部导入成功!");
return Results.OK("" + successLines + "行数据全部导入成功!");
} else {
JSONObject result = new JSONObject(5);
int totalCount = successLines + errorLines;
@@ -31,20 +34,20 @@ public class ImportExcelUtil {
String fileName = fileUrl.substring(lastIndex + 1);
result.put("fileUrl", "/sys/common/static/" + fileUrl);
result.put("fileName", fileName);
Result res = Result.OK(result);
Results<JSONObject> res = Results.OK(result);
res.setCode(201);
res.setMessage("文件导入成功,但有错误。");
return res;
}
}
public static List<String> importDateSave(List<Object> list, Class serviceClass,List<String> errorMessage,String errorFlag) {
IService bean =(IService) SpringContextUtils.getBean(serviceClass);
public static List<String> importDateSave(List<Object> list, Class<?> serviceClass,List<String> errorMessage,String errorFlag) {
IService<Object> bean =(IService) SpringContextUtils.getBean(serviceClass);
for (int i = 0; i < list.size(); i++) {
try {
boolean save = bean.save(list.get(i));
if(!save){
throw new Exception(errorFlag);
throw new JeroBootException(errorFlag);
}
} catch (Exception e) {
String message = e.getMessage().toLowerCase();
@@ -67,12 +70,12 @@ public class ImportExcelUtil {
return errorMessage;
}
public static List<String> importDateSaveOne(Object obj, Class serviceClass,List<String> errorMessage,int i,String errorFlag) {
IService bean =(IService) SpringContextUtils.getBean(serviceClass);
public static List<String> importDateSaveOne(Object obj, Class<?> serviceClass, List<String> errorMessage, int i, String errorFlag) {
IService<Object> bean = (IService) SpringContextUtils.getBean(serviceClass);
try {
boolean save = bean.save(obj);
if(!save){
throw new Exception(errorFlag);
throw new JeroBootException(errorFlag);
}
} catch (Exception e) {
String message = e.getMessage().toLowerCase();
@@ -4,8 +4,12 @@ import java.security.MessageDigest;
public class MD5Util {
public static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
private MD5Util(){
}
public static String byteArrayToHexString(byte[] b) {
StringBuilder resultSb = new StringBuilder();
for (int i = 0; i < b.length; i++){
resultSb.append(byteToHexString(b[i]));
}
@@ -19,25 +23,26 @@ public class MD5Util {
}
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
return HEX_DIGITS[d1] + HEX_DIGITS[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
resultString = origin;
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname)) {
resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
} else {
resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
}
} catch (Exception exception) {
} catch (Exception e) {
e.printStackTrace();
}
return resultString;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
private static final String[] HEX_DIGITS = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}
@@ -1,19 +1,27 @@
package com.jero.common.util;
import com.jero.common.util.filter.FileTypeFilter;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import com.jero.common.util.filter.StrAttackFilter;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* minio文件上传工具类
*/
@Slf4j
public class MinioUtil {
private MinioUtil(){
}
private static String minioUrl;
private static String minioName;
private static String minioPass;
@@ -51,7 +59,7 @@ public class MinioUtil {
* @return
*/
public static String upload(MultipartFile file, String bizPath, String customBucket) {
String file_url = "";
String fileUrl = "";
//update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符防止攻击
bizPath=StrAttackFilter.filter(bizPath);
//update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符防止攻击
@@ -79,8 +87,8 @@ public class MinioUtil {
orgName=file.getName();
}
orgName = CommonUtils.getFileName(orgName);
String objectName = bizPath+"/"
+( orgName.indexOf(".")==-1
String objectName = bizPath+File.separator
+(!orgName.contains(".")
?orgName + "_" + System.currentTimeMillis()
:orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."))
);
@@ -94,11 +102,11 @@ public class MinioUtil {
.stream(stream,stream.available(),-1).build();
minioClient.putObject(objectArgs);
stream.close();
file_url = minioUrl+newBucket+"/"+objectName;
fileUrl = minioUrl+newBucket+ File.separator +objectName;
}catch (Exception e){
log.error(e.getMessage(), e);
}
return file_url;
return fileUrl;
}
/**
@@ -195,7 +203,7 @@ public class MinioUtil {
* @param relativePath
* @return
*/
public static String upload(InputStream stream,String relativePath) throws Exception {
public static String upload(InputStream stream,String relativePath) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
initMinio(minioUrl, minioName,minioPass);
if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
log.info("Bucket already exists.");
@@ -1,16 +1,21 @@
package com.jero.common.util;
import com.jero.common.exception.JeroBootException;
import org.apache.poi.ss.formula.functions.T;
import java.io.File;
/**
* @Author 张代浩
*/
public class MyClassLoader extends ClassLoader {
public static Class getClassByScn(String className) {
Class myclass = null;
public static Class<?> getClassByScn(String className) {
Class<?> myclass;
try {
myclass = Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(className+" not found!");
throw new JeroBootException(className+" not found!");
}
return myclass;
}
@@ -22,11 +27,10 @@ public class MyClassLoader extends ClassLoader {
throw new java.lang.IllegalArgumentException("参数不能为空!");
}
// 获得类的全名包括包名
String clsName = object.getClass().getName();
return clsName;
return object.getClass().getName();
}
public static String getAppPath(Class cls) {
public static String getAppPath(Class<T> cls) {
// 检查用户传入的参数是否为空
if (cls == null) {
throw new java.lang.IllegalArgumentException("参数不能为空!");
@@ -36,7 +40,7 @@ public class MyClassLoader extends ClassLoader {
String clsName = cls.getName() + ".class";
// 获得传入参数所在的包
Package pack = cls.getPackage();
String path = "";
StringBuilder path = new StringBuilder();
// 如果不是匿名包将包名转化为路径
if (pack != null) {
String packName = pack.getName();
@@ -47,17 +51,17 @@ public class MyClassLoader extends ClassLoader {
// 在类的名称中去掉包名的部分获得类的文件名
clsName = clsName.substring(packName.length() + 1);
// 判定包名是否是简单包名如果是则直接将包名转换为路径
if (packName.indexOf(".") < 0) {
path = packName + "/";
if (!packName.contains(".")) {
path = new StringBuilder(packName + File.separator);
} else {// 否则按照包名的组成部分将包名转换为路径
int start = 0, end = 0;
end = packName.indexOf(".");
int start = 0;
int end = packName.indexOf(".");
while (end != -1) {
path = path + packName.substring(start, end) + "/";
path.append(packName.substring(start, end)).append(File.separator);
start = end + 1;
end = packName.indexOf(".", start);
}
path = path + packName.substring(start) + "/";
path.append(packName.substring(start)).append(File.separator);
}
}
// 调用ClassLoader的getResource方法传入包含路径信息的类文件名
@@ -76,16 +80,16 @@ public class MyClassLoader extends ClassLoader {
if (realPath.endsWith("!")) {
realPath = realPath.substring(0, realPath.lastIndexOf("/"));
}
/*------------------------------------------------------------
ClassLoader的getResource方法使用了utf-8对路径信息进行了编码当路径
中存在中文和空格时他会对这些字符进行转换这样得到的往往不是我们想要
的真实路径在此调用了URLDecoder的decode方法进行解码以便得到原始的
中文及空格路径
/*------------------------------------------------------------
ClassLoader的getResource方法使用了utf-8对路径信息进行了编码当路径
中存在中文和空格时他会对这些字符进行转换这样得到的往往不是我们想要
的真实路径在此调用了URLDecoder的decode方法进行解码以便得到原始的
中文及空格路径
-------------------------------------------------------------*/
try {
realPath = java.net.URLDecoder.decode(realPath, "utf-8");
} catch (Exception e) {
throw new RuntimeException(e);
throw new JeroBootException(e);
}
return realPath;
}// getAppPath定义结束
@@ -1,14 +1,24 @@
package com.jero.common.util;
import java.security.Key;
import java.security.SecureRandom;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;
@Component
public class PasswordUtil {
private PasswordUtil(){
}
/**
* JAVA6支持以下任意一种算法 PBEWITHMD5ANDDES PBEWITHMD5ANDTRIPLEDES
* PBEWITHSHAANDDESEDE PBEWITHSHA1ANDRC2_40 PBKDF2WITHHMACSHA1
@@ -17,8 +27,32 @@ public class PasswordUtil {
/**
* 定义使用的算法为:PBEWITHMD5andDES算法
*/
public static final String ALGORITHM = "PBEWithMD5AndDES";//加密算法
public static final String Salt = "63293188";//密钥
//加密算法
public static String ALGORITHM;
@Value("${jero.password.pbe.algorithm}")
private String algorithmStr;
@PostConstruct
public void setAlgorithm(){
synchronized (PasswordUtil.class){
if(ALGORITHM == null){
ALGORITHM = this.algorithmStr;
}
}
}
public static String SALT;
//密钥
@Value("${jero.password.pbe.salt}")
private String saltStr;
@PostConstruct
public void setSalt(){
synchronized (PasswordUtil.class){
if(SALT == null){
SALT = this.saltStr;
}
}
}
/**
* 定义迭代次数为1000次
@@ -27,10 +61,10 @@ public class PasswordUtil {
/**
* 获取加密算法中使用的盐值,解密中使用的盐值必须与加密中使用的相同才能完成操作. 盐长度必须为8字节
*
*
* @return byte[] 盐值
* */
public static byte[] getSalt() throws Exception {
public static byte[] getSalt() {
// 实例化安全随机数
SecureRandom random = new SecureRandom();
// 产出盐
@@ -39,12 +73,12 @@ public class PasswordUtil {
public static byte[] getStaticSalt() {
// 产出盐
return Salt.getBytes();
return SALT.getBytes();
}
/**
* 根据PBE密码生成一把密钥
*
*
* @param password
* 生成密钥时所使用的密码
* @return Key PBE算法密钥
@@ -60,7 +94,7 @@ public class PasswordUtil {
// 生成密钥
secretKey = keyFactory.generateSecret(keySpec);
} catch (Exception e) {
// TODO Auto-generated catch block
// Auto-generated catch block
e.printStackTrace();
}
@@ -69,7 +103,7 @@ public class PasswordUtil {
/**
* 加密明文字符串
*
*
* @param plaintext
* 待加密的明文字符串
* @param password
@@ -89,9 +123,10 @@ public class PasswordUtil {
cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
//update-begin-author:sccott date:20180815 for:中文作为用户名时加密的密码windows和linux会得到不同的结果 gitee/issues/IZUD7
encipheredData = cipher.doFinal(plaintext.getBytes("utf-8"));
encipheredData = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
//update-end-author:sccott date:20180815 for:中文作为用户名时加密的密码windows和linux会得到不同的结果 gitee/issues/IZUD7
} catch (Exception e) {
e.printStackTrace();
}
return bytesToHexString(encipheredData);
}
@@ -105,13 +140,13 @@ public class PasswordUtil {
* @throws Exception
*/
public static String encrypt(String plaintext) {
return encrypt(plaintext, ALGORITHM, Salt);
return encrypt(plaintext, ALGORITHM, SALT);
}
/**
* 解密密文字符串
*
*
* @param ciphertext
* 待解密的密文字符串
* @param password
@@ -132,17 +167,26 @@ public class PasswordUtil {
cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
passDec = cipher.doFinal(hexStringToBytes(ciphertext));
}
catch (Exception e) {
// TODO: handle exception
}catch (Exception e) {
// handle exception
}
return new String(passDec);
}
/**
* 自定义加密明文字符串
*
* @param ciphertext
* 待解密的密文字符串
* @return 解密后的明文字符串
* @throws Exception
*/
public static String decrypt(String ciphertext) {
return decrypt(ciphertext, ALGORITHM, SALT);
}
/**
* 将字节数组转换为十六进制字符串
*
*
* @param src
* 字节数组
* @return
@@ -165,14 +209,14 @@ public class PasswordUtil {
/**
* 将十六进制字符串转换为字节数组
*
*
* @param hexString
* 十六进制字符串
* @return
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
if (hexString == null || "".equals(hexString)) {
return new byte[0];
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
@@ -180,7 +224,7 @@ public class PasswordUtil {
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]) & 0xff);
}
return d;
}
@@ -189,5 +233,4 @@ public class PasswordUtil {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}
}
@@ -3,18 +3,20 @@ package com.jero.common.util;
import java.util.Collection;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
/**
* 使用Spring自身提供的地址匹配工具匹配URL
*/
@Slf4j
public class PathMatcherUtil {
public static void main(String[] args) {
String url = "/sys/dict/loadDictOrderByValue/tree,s2,2";
String p = "/sys/dict/loadDictOrderByValue/*";
System.out.println(PathMatcherUtil.match(p,url));
log.info("" + PathMatcherUtil.match(p,url));
}
/**
@@ -19,7 +19,12 @@ public class PmsUtil {
@Value("${jero.path.upload}")
public void setUploadPath(String uploadPath) {
PmsUtil.uploadPath = uploadPath;
synchronized (PmsUtil.class){
if(PmsUtil.uploadPath == null){
PmsUtil.uploadPath = uploadPath;
}
}
}
public static String saveErrorTxtByList(List<String> msg, String name) {
@@ -33,25 +38,21 @@ public class PmsUtil {
}
name += DateUtils.yyyymmddhhmmss.get().format(d) + Math.round(Math.random() * 10000);
String saveFilePath = saveFullDir + name + ".txt";
try {
//封装目的地
BufferedWriter bw = new BufferedWriter(new FileWriter(saveFilePath));
//封装目的地
try (BufferedWriter bw = new BufferedWriter(new FileWriter(saveFilePath))) {
//遍历集合
for (String s : msg) {
//写数据
if (s.indexOf("_") > 0) {
String arr[] = s.split("_");
if (s.contains("_")) {
String[] arr = s.split("_");
bw.write("" + arr[0] + "行:" + arr[1]);
} else {
bw.write(s);
}
//bw.newLine();
bw.write("\r\n");
}
//释放资源
bw.flush();
bw.close();
} catch (Exception e) {
log.info("excel导入生成错误日志文件异常:" + e.getMessage());
}
@@ -1,6 +1,7 @@
package com.jero.common.util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@@ -15,7 +16,7 @@ import java.util.regex.Pattern;
@Slf4j
public class ReflectHelper {
private Class cls;
private Class<?> cls;
/**
* 传过来的对象
@@ -25,11 +26,11 @@ public class ReflectHelper {
/**
* 存放get方法
*/
private Hashtable<String, Method> getMethods = null;
private HashMap<String, Method> getMethods = null;
/**
* 存放set方法
*/
private Hashtable<String, Method> setMethods = null;
private HashMap<String, Method> setMethods = null;
/**
* 定义构造方法 -- 一般来说是个pojo
@@ -45,8 +46,8 @@ public class ReflectHelper {
* @desc 初始化
*/
public void initMethods() {
getMethods = new Hashtable<String, Method>();
setMethods = new Hashtable<String, Method>();
getMethods = new HashMap<>();
setMethods = new HashMap<>();
cls = obj.getClass();
Method[] methods = cls.getMethods();
// 定义正则表达式从方法中过滤出getter / setter 函数.
@@ -66,8 +67,6 @@ public class ReflectHelper {
} else if (Pattern.matches(ss, methodName)) {
param = setM.matcher(methodName).replaceAll(rapl).toLowerCase();
setMethods.put(param, m);
} else {
// logger.info(methodName + " 不是getter,setter方法!");
}
}
}
@@ -101,7 +100,7 @@ public class ReflectHelper {
/*
* 调用obj类的setter函数
*/
value = m.invoke(obj, new Object[]{});
value = m.invoke(obj);
} catch (Exception ex) {
log.info("invoke getter on " + property + " error: " + ex.toString());
@@ -117,7 +116,7 @@ public class ReflectHelper {
* @return
*/
public Object setAll(Map<String, Object> data) {
if (data == null || data.keySet().size() <= 0) {
if (data == null || data.keySet().isEmpty()) {
return null;
}
for (Entry<String, Object> entry : data.entrySet()) {
@@ -167,8 +166,8 @@ public class ReflectHelper {
* @return
*/
public static <T> List<T> transList2Entrys(List<Map<String, Object>> mapist, Class<T> clazz) {
List<T> list = new ArrayList<T>();
if (mapist != null && mapist.size() > 0) {
List<T> list = new ArrayList<>();
if (mapist != null && !mapist.isEmpty()) {
for (Map<String, Object> data : mapist) {
list.add(ReflectHelper.setAll(clazz, data));
}
@@ -183,9 +182,8 @@ public class ReflectHelper {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(o, new Object[]{});
return value;
Method method = o.getClass().getMethod(getter);
return method.invoke(o);
} catch (Exception e) {
e.printStackTrace();
return null;
@@ -198,11 +196,10 @@ public class ReflectHelper {
public static Object getFieldVal(String fieldName, Object o) {
try {
// 暴力反射获取属性
Field filed = o.getClass().getDeclaredField(fieldName);
Field field = o.getClass().getDeclaredField(fieldName);
// 设置反射时取消Java的访问检查暴力访问
filed.setAccessible(true);
Object val = filed.get(o);
return val;
ReflectionUtils.makeAccessible(field);
return field.get(o);
} catch (Exception e) {
e.printStackTrace();
return null;
@@ -216,7 +213,6 @@ public class ReflectHelper {
Field[] fields = o.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
//log.info(fields[i].getType());
fieldNames[i] = fields[i].getName();
}
return fieldNames;
@@ -225,13 +221,12 @@ public class ReflectHelper {
/**
* 获取属性类型(type)属性名(name)属性值(value)的map组成的list
*/
public static List<Map> getFiledsInfo(Object o) {
public static List<Map<String, Object>> getFiledsInfo(Object o) {
Field[] fields = o.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
List<Map> list = new ArrayList<Map>();
Map<String, Object> infoMap = null;
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> infoMap;
for (int i = 0; i < fields.length; i++) {
infoMap = new HashMap<String, Object>();
infoMap = new HashMap<>();
infoMap.put("type", fields[i].getType().toString());
infoMap.put("name", fields[i].getName());
infoMap.put("value", getFieldValueByName(fields[i].getName(), o));
@@ -252,4 +247,4 @@ public class ReflectHelper {
return value;
}
}
}
@@ -1,12 +1,15 @@
package com.jero.common.util;
import com.alibaba.fastjson.JSONObject;
import com.jero.common.api.vo.Result;
import com.jero.common.api.vo.Results;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.util.Objects;
/**
* 通过 RESTful 风格的接口操纵 desform 里的数据
*
@@ -14,6 +17,10 @@ import org.springframework.http.ResponseEntity;
*/
public class RestDesformUtil {
private RestDesformUtil(){
}
private static String domain = null;
private static String path = null;
@@ -30,7 +37,7 @@ public class RestDesformUtil {
* @param token
* @return
*/
public static Result queryOne(String desformCode, String dataId, String token) {
public static Results<T> queryOne(String desformCode, String dataId, String token) {
String url = getBaseUrl(desformCode, dataId).toString();
HttpHeaders headers = getHeaders(token);
ResponseEntity<JSONObject> result = RestUtil.request(url, HttpMethod.GET, headers, null, null, JSONObject.class);
@@ -45,7 +52,7 @@ public class RestDesformUtil {
* @param token
* @return
*/
public static Result addOne(String desformCode, JSONObject formData, String token) {
public static Results<T> addOne(String desformCode, JSONObject formData, String token) {
return addOrEditOne(desformCode, formData, token, HttpMethod.POST);
}
@@ -57,11 +64,11 @@ public class RestDesformUtil {
* @param token
* @return
*/
public static Result editOne(String desformCode, JSONObject formData, String token) {
public static Results<T> editOne(String desformCode, JSONObject formData, String token) {
return addOrEditOne(desformCode, formData, token, HttpMethod.PUT);
}
private static Result addOrEditOne(String desformCode, JSONObject formData, String token, HttpMethod method) {
private static Results<T> addOrEditOne(String desformCode, JSONObject formData, String token, HttpMethod method) {
String url = getBaseUrl(desformCode).toString();
HttpHeaders headers = getHeaders(token);
ResponseEntity<JSONObject> result = RestUtil.request(url, method, headers, null, formData, JSONObject.class);
@@ -76,18 +83,19 @@ public class RestDesformUtil {
* @param token
* @return
*/
public static Result removeOne(String desformCode, String dataId, String token) {
public static Results<T> removeOne(String desformCode, String dataId, String token) {
String url = getBaseUrl(desformCode, dataId).toString();
HttpHeaders headers = getHeaders(token);
ResponseEntity<JSONObject> result = RestUtil.request(url, HttpMethod.DELETE, headers, null, null, JSONObject.class);
return packageReturn(result);
}
private static Result packageReturn(ResponseEntity<JSONObject> result) {
if (result.getBody() != null) {
return result.getBody().toJavaObject(Result.class);
private static Results<T> packageReturn(ResponseEntity<JSONObject> result) {
JSONObject json = result.getBody();
if (!Objects.isNull(json)) {
return json.toJavaObject(Results.class);
}
return Result.error("操作失败");
return Results.error("操作失败");
}
private static StringBuilder getBaseUrl() {
@@ -118,4 +126,4 @@ public class RestDesformUtil {
return headers;
}
}
}
@@ -1,6 +1,7 @@
package com.jero.common.util;
import com.alibaba.fastjson.JSONObject;
import com.jero.common.exception.JeroBootException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
@@ -20,6 +21,10 @@ import java.util.Map;
@Slf4j
public class RestUtil {
private RestUtil(){
}
private static String domain = null;
public static String getDomain() {
@@ -47,7 +52,7 @@ public class RestUtil {
/**
* RestAPI 调用器
*/
private final static RestTemplate RT;
private static final RestTemplate RT;
static {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
@@ -188,10 +193,10 @@ public class RestUtil {
public static <T> ResponseEntity<T> request(String url, HttpMethod method, HttpHeaders headers, JSONObject variables, Object params, Class<T> responseType) {
log.info(" RestUtil --- request --- url = "+ url);
if (StringUtils.isEmpty(url)) {
throw new RuntimeException("url 不能为空");
throw new JeroBootException("url 不能为空");
}
if (method == null) {
throw new RuntimeException("method 不能为空");
throw new JeroBootException("method 不能为空");
}
if (headers == null) {
headers = new HttpHeaders();
@@ -243,10 +248,8 @@ public class RestUtil {
String key = it.next();
String value = "";
Object object = source.get(key);
if (object != null) {
if (!StringUtils.isEmpty(object.toString())) {
value = object.toString();
}
if (object != null && !StringUtils.isEmpty(object.toString())) {
value = object.toString();
}
urlVariables.append("&").append(key).append("=").append(value);
}
@@ -1,7 +1,5 @@
package com.jero.common.util;
import javax.servlet.http.HttpServletRequest;
import com.jero.common.constant.ServiceNameConstants;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
@@ -10,6 +8,9 @@ import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
@Component
public class SpringContextUtils implements ApplicationContextAware {
@@ -20,7 +21,11 @@ public class SpringContextUtils implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
synchronized (SpringContextUtils.class){
if(SpringContextUtils.applicationContext == null){
SpringContextUtils.applicationContext = applicationContext;
}
}
}
/**
@@ -36,7 +41,7 @@ public class SpringContextUtils implements ApplicationContextAware {
* 获取HttpServletRequest
*/
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
}
/**
@@ -58,7 +63,7 @@ public class SpringContextUtils implements ApplicationContextAware {
HttpServletRequest request = getHttpServletRequest();
return request.getHeader("Origin");
}
/**
* 通过name获取 Bean.
*
@@ -1,24 +1,38 @@
package com.jero.common.util;
import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;
import com.jero.common.exception.JeroBootException;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;
/**
* sql注入处理工具类
*
*
* @author zhoujf
*/
@Slf4j
public class SqlInjectionUtil {
private SqlInjectionUtil(){
}
/**
* sign 用于表字典加签的盐值SQL漏洞
* 上线修改值 20200501同步修改前端的盐值
*/
private final static String TABLE_DICT_SIGN_SALT = "20200501";
private final static String xssStr = "'|and |exec |insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |;|or |+";
private static final String TABLE_DICT_SIGN_SALT = "20200501";
private static final String XSS_STR = "'|and |exec |insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |;|or |+";
private static final String SYMBOL_CONSTANT = "/\\*.*\\*/";
private static final String SQL_INJECTION_CONSTANT = "请注意,存在SQL注入关键词---> {}";
private static final String SQL_VALUE_INJECTION_CONSTANT = "请注意,值可能存在SQL注入风险!---> {}";
private static final String SQL_VALUE_INJECTION_CONSTANT1 = "请注意,值可能存在SQL注入风险!--->";
private static final String SHOW_S_TABLE_CONSTANT = "show\\s+tables";
/*
* 针对表字典进行额外的sign签名校验增加安全机制
@@ -42,7 +56,7 @@ public class SqlInjectionUtil {
/**
* sql注入过滤处理遇到注入关键字抛异常
*
*
* @param value
* @return
*/
@@ -52,55 +66,54 @@ public class SqlInjectionUtil {
}
// 统一转为小写
value = value.toLowerCase();
value = value.replaceAll("/\\*.*\\*/","");
value = value.replaceAll(SYMBOL_CONSTANT,"");
String[] xssArr = xssStr.split("\\|");
String[] xssArr = XSS_STR.split("\\|");
for (int i = 0; i < xssArr.length; i++) {
if (value.indexOf(xssArr[i]) > -1) {
log.error("请注意,存在SQL注入关键词---> {}", xssArr[i]);
log.error("请注意,值可能存在SQL注入风险!---> {}", value);
throw new RuntimeException("请注意,值可能存在SQL注入风险!--->" + value);
log.error(SQL_INJECTION_CONSTANT, xssArr[i]);
log.error(SQL_VALUE_INJECTION_CONSTANT, value);
throw new JeroBootException(SQL_VALUE_INJECTION_CONSTANT1 + value);
}
}
if(Pattern.matches("show\\s+tables", value)){
throw new RuntimeException("请注意,值可能存在SQL注入风险!--->" + value);
if(Pattern.matches(SHOW_S_TABLE_CONSTANT, value)){
throw new JeroBootException(SQL_VALUE_INJECTION_CONSTANT1 + value);
}
return;
}
/**
* sql注入过滤处理遇到注入关键字抛异常
*
*
* @param values
* @return
*/
public static void filterContent(String[] values) {
String[] xssArr = xssStr.split("\\|");
String[] xssArr = XSS_STR.split("\\|");
for (String value : values) {
if (value == null || "".equals(value)) {
return;
}
// 统一转为小写
value = value.toLowerCase();
value = value.replaceAll("/\\*.*\\*/","");
value = value.replaceAll(SYMBOL_CONSTANT,"");
for (int i = 0; i < xssArr.length; i++) {
if (value.indexOf(xssArr[i]) > -1) {
log.error("请注意,存在SQL注入关键词---> {}", xssArr[i]);
log.error("请注意,值可能存在SQL注入风险!---> {}", value);
throw new RuntimeException("请注意,值可能存在SQL注入风险!--->" + value);
if (value.contains(xssArr[i])) {
log.error(SQL_INJECTION_CONSTANT, xssArr[i]);
log.error(SQL_VALUE_INJECTION_CONSTANT, value);
throw new JeroBootException(SQL_VALUE_INJECTION_CONSTANT1 + value);
}
}
if(Pattern.matches("show\\s+tables", value)){
throw new RuntimeException("请注意,值可能存在SQL注入风险!--->" + value);
if(Pattern.matches(SHOW_S_TABLE_CONSTANT, value)){
throw new JeroBootException(SQL_VALUE_INJECTION_CONSTANT1 + value);
}
}
return;
}
/**
* @特殊方法(不通用) 仅用于字典条件SQL参数注入过滤
* @param value
* @deprecated 不推荐
* @return
*/
@Deprecated
@@ -112,19 +125,18 @@ public class SqlInjectionUtil {
}
// 统一转为小写
value = value.toLowerCase();
value = value.replaceAll("/\\*.*\\*/","");
value = value.replaceAll(SYMBOL_CONSTANT,"");
for (int i = 0; i < xssArr.length; i++) {
if (value.indexOf(xssArr[i]) > -1 || value.startsWith(xssArr[i].trim())) {
log.error("请注意,存在SQL注入关键词---> {}", xssArr[i]);
log.error("请注意,值可能存在SQL注入风险!---> {}", value);
throw new RuntimeException("请注意,值可能存在SQL注入风险!--->" + value);
if (value.contains(xssArr[i]) || value.startsWith(xssArr[i].trim())) {
log.error(SQL_INJECTION_CONSTANT, xssArr[i]);
log.error(SQL_VALUE_INJECTION_CONSTANT, value);
throw new JeroBootException(SQL_VALUE_INJECTION_CONSTANT1 + value);
}
}
if(Pattern.matches("show\\s+tables", value)){
throw new RuntimeException("请注意,值可能存在SQL注入风险!--->" + value);
if(Pattern.matches(SHOW_S_TABLE_CONSTANT, value)){
throw new JeroBootException(SQL_VALUE_INJECTION_CONSTANT1 + value);
}
return;
}
@@ -141,19 +153,18 @@ public class SqlInjectionUtil {
}
// 统一转为小写
value = value.toLowerCase();
value = value.replaceAll("/\\*.*\\*/","");
value = value.replaceAll(SYMBOL_CONSTANT,"");
for (int i = 0; i < xssArr.length; i++) {
if (value.indexOf(xssArr[i]) > -1 || value.startsWith(xssArr[i].trim())) {
log.error("请注意,存在SQL注入关键词---> {}", xssArr[i]);
log.error("请注意,值可能存在SQL注入风险!---> {}", value);
throw new RuntimeException("请注意,值可能存在SQL注入风险!--->" + value);
if (value.contains(xssArr[i]) || value.startsWith(xssArr[i].trim())) {
log.error(SQL_INJECTION_CONSTANT, xssArr[i]);
log.error(SQL_VALUE_INJECTION_CONSTANT, value);
throw new JeroBootException(SQL_VALUE_INJECTION_CONSTANT1 + value);
}
}
if(Pattern.matches("show\\s+tables", value)){
throw new RuntimeException("请注意,值可能存在SQL注入风险!--->" + value);
if(Pattern.matches(SHOW_S_TABLE_CONSTANT, value)){
throw new JeroBootException(SQL_VALUE_INJECTION_CONSTANT1 + value);
}
return;
}
}
@@ -18,6 +18,10 @@ import javax.servlet.http.HttpServletRequest;
@Slf4j
public class TokenUtils {
private TokenUtils(){
}
/**
* 获取 request 里传递的 token
*
@@ -83,13 +87,6 @@ public class TokenUtils {
redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
}
//update-begin--Author:scott Date:20191005 for解决每次请求都重写redis中 token缓存问题
// else {
// redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
// // 设置超时时间
// redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
// }
//update-end--Author:scott Date:20191005 for解决每次请求都重写redis中 token缓存问题
return true;
}
return false;
@@ -4,16 +4,20 @@ package com.jero.common.util;
import java.net.InetAddress;
/**
*
*
* @Author 张代浩
*
*/
public class UUIDGenerator {
private UUIDGenerator(){
}
/**
* 产生一个32位的UUID
*
*
* @return
*/
@@ -21,7 +25,7 @@ public class UUIDGenerator {
return new StringBuilder(32).append(format(getIP())).append(
format(getJVM())).append(format(getHiTime())).append(
format(getLoTime())).append(format(getCount())).toString();
}
private static final int IP;
@@ -39,25 +43,25 @@ public class UUIDGenerator {
private static final int JVM = (int) (System.currentTimeMillis() >>> 8);
private final static String format(int intval) {
private static final String format(int intval) {
String formatted = Integer.toHexString(intval);
StringBuilder buf = new StringBuilder("00000000");
buf.replace(8 - formatted.length(), 8, formatted);
return buf.toString();
}
private final static String format(short shortval) {
private static final String format(short shortval) {
String formatted = Integer.toHexString(shortval);
StringBuilder buf = new StringBuilder("0000");
buf.replace(4 - formatted.length(), 4, formatted);
return buf.toString();
}
private final static int getJVM() {
private static final int getJVM() {
return JVM;
}
private final static short getCount() {
private static final short getCount() {
synchronized (UUIDGenerator.class) {
if (counter < 0) {
counter = 0;
@@ -69,27 +73,26 @@ public class UUIDGenerator {
/**
* Unique in a local network
*/
private final static int getIP() {
private static final int getIP() {
return IP;
}
/**
* Unique down to millisecond
*/
private final static short getHiTime() {
private static final short getHiTime() {
return (short) (System.currentTimeMillis() >>> 32);
}
private final static int getLoTime() {
private static final int getLoTime() {
return (int) System.currentTimeMillis();
}
private final static int toInt(byte[] bytes) {
private static final int toInt(byte[] bytes) {
int result = 0;
for (int i = 0; i < 4; i++) {
result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i];
result = (result << 8) - (Byte.MIN_VALUE & 0xff) + bytes[i];
}
return result;
}
}
@@ -2,6 +2,8 @@ package com.jero.common.util;
import io.netty.util.internal.StringUtil;
import java.util.Objects;
/**
* 流水号生成规则(按默认规则递增数字从1-99开始递增数字到99递增字母;位数不够增加位数)
* A001
@@ -11,16 +13,20 @@ import io.netty.util.internal.StringUtil;
*/
public class YouBianCodeUtil {
private YouBianCodeUtil(){
}
// 数字位数(默认生成3位的数字)
//代表数字位数
private static final int NUM_LENGTH = 2;
private static final int numLength = 2;//代表数字位数
public static final int zhanweiLength = 1+numLength;
public static final int ZHANWEI_LENGTH = 1 + NUM_LENGTH;
/**
* 根据前一个code获取同级下一个code
* 例如:当前最大code为D01A04下一个code为D01A05
*
*
* @param code
* @return
*/
@@ -31,31 +37,31 @@ public class YouBianCodeUtil {
String num = getStrNum(1);
newcode = zimu + num;
} else {
String before_code = code.substring(0, code.length() - 1- numLength);
String after_code = code.substring(code.length() - 1 - numLength,code.length());
char after_code_zimu = after_code.substring(0, 1).charAt(0);
Integer after_code_num = Integer.parseInt(after_code.substring(1));
String beforeCode = code.substring(0, code.length() - 1- NUM_LENGTH);
String afterCode = code.substring(code.length() - 1 - NUM_LENGTH,code.length());
char afterCodeZimu = afterCode.substring(0, 1).charAt(0);
int afterCodeNum = Integer.parseInt(afterCode.substring(1));
String nextNum = "";
char nextZimu = 'A';
String nextNum;
char nextZimu;
// 先判断数字等于999*则计数从1重新开始递增
if (after_code_num == getMaxNumByLength(numLength)) {
if (afterCodeNum == getMaxNumByLength(NUM_LENGTH)) {
nextNum = getNextStrNum(0);
} else {
nextNum = getNextStrNum(after_code_num);
nextNum = getNextStrNum(afterCodeNum);
}
// 先判断数字等于999*则字母从A重新开始,递增
if(after_code_num == getMaxNumByLength(numLength)) {
nextZimu = getNextZiMu(after_code_zimu);
if(afterCodeNum == getMaxNumByLength(NUM_LENGTH)) {
nextZimu = getNextZiMu(afterCodeZimu);
}else{
nextZimu = after_code_zimu;
nextZimu = afterCodeZimu;
}
// 例如Z99下一个code就是Z99A01
if ('Z' == after_code_zimu && getMaxNumByLength(numLength) == after_code_num) {
if ('Z' == afterCodeZimu && getMaxNumByLength(NUM_LENGTH) == afterCodeNum) {
newcode = code + (nextZimu + nextNum);
} else {
newcode = before_code + (nextZimu + nextNum);
newcode = beforeCode + (nextZimu + nextNum);
}
}
return newcode;
@@ -64,19 +70,17 @@ public class YouBianCodeUtil {
/**
* 根据父亲code,获取下级的下一个code
*
*
* 例如父亲CODE:A01
* 当前CODE:A01B03
* 获取的code:A01B04
*
*
* @param parentCode 上级code
* @param localCode 同级code
* @return
*/
public static synchronized String getSubYouBianCode(String parentCode,String localCode) {
if(localCode!=null && localCode!=""){
// return parentCode + getNextYouBianCode(localCode);
if(localCode!=null && Objects.equals("",localCode)){
return getNextYouBianCode(localCode);
}else{
@@ -85,11 +89,11 @@ public class YouBianCodeUtil {
return parentCode;
}
/**
* 将数字前面位数补零
*
*
* @param num
* @return
*/
@@ -99,18 +103,17 @@ public class YouBianCodeUtil {
/**
* 将数字前面位数补零
*
*
* @param num
* @return
*/
private static String getStrNum(int num) {
String s = String.format("%0" + numLength + "d", num);
return s;
return String.format("%0" + NUM_LENGTH + "d", num);
}
/**
* 递增获取下个数字
*
*
* @param num
* @return
*/
@@ -121,8 +124,8 @@ public class YouBianCodeUtil {
/**
* 递增获取下个字母
*
* @param num
*
* @param zimu
* @return
*/
private static char getNextZiMu(char zimu) {
@@ -132,7 +135,7 @@ public class YouBianCodeUtil {
zimu++;
return zimu;
}
/**
* 根据数字位数获取最大值
* @param length
@@ -142,24 +145,24 @@ public class YouBianCodeUtil {
if(length==0){
return 0;
}
String max_num = "";
StringBuilder maxNum = new StringBuilder();
for (int i=0;i<length;i++){
max_num = max_num + "9";
maxNum.append("9");
}
return Integer.parseInt(max_num);
return Integer.parseInt(maxNum.toString());
}
public static String[] cutYouBianCode(String code){
if(code==null || StringUtil.isNullOrEmpty(code)){
return null;
return new String[0];
}else{
//获取标准长度为numLength+1,截取的数量为code.length/numLength+1
int c = code.length()/(numLength+1);
int c = code.length()/(NUM_LENGTH+1);
String[] cutcode = new String[c];
for(int i =0 ; i <c;i++){
cutcode[i] = code.substring(0,(i+1)*(numLength+1));
cutcode[i] = code.substring(0,(i+1)*(NUM_LENGTH+1));
}
return cutcode;
}
}
}
@@ -4,9 +4,9 @@ import com.alibaba.druid.pool.DruidDataSource;
import com.jero.common.api.CommonAPI;
import com.jero.common.constant.CacheConstant;
import com.jero.common.system.vo.DynamicDataSourceModel;
import com.jero.common.util.RedisUtil;
import com.jero.common.util.SpringContextUtils;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.HashMap;
import java.util.Map;
@@ -15,6 +15,10 @@ import java.util.Map;
* 数据源缓存池
*/
public class DataSourceCachePool {
private DataSourceCachePool(){
}
/** 数据源连接池缓存【本地 class缓存 - 不支持分布式】 */
private static Map<String, DruidDataSource> dbSources = new HashMap<>();
private static RedisTemplate<String, Object> redisTemplate;
@@ -34,7 +38,7 @@ public class DataSourceCachePool {
*/
public static DynamicDataSourceModel getCacheDynamicDataSourceModel(String dbKey) {
String redisCacheKey = CacheConstant.SYS_DYNAMICDB_CACHE + dbKey;
if (getRedisTemplate().hasKey(redisCacheKey)) {
if (Boolean.TRUE.equals(getRedisTemplate().hasKey(redisCacheKey))) {
return (DynamicDataSourceModel) getRedisTemplate().opsForValue().get(redisCacheKey);
}
CommonAPI commonAPI = SpringContextUtils.getBean(CommonAPI.class);
@@ -8,6 +8,10 @@ import com.baomidou.mybatisplus.annotation.DbType;
*/
public class DbTypeUtils {
private DbTypeUtils(){
}
public static boolean dbTypeIsMySQL(DbType dbType) {
return dbTypeIf(dbType, DbType.MYSQL, DbType.MARIADB, DbType.CLICK_HOUSE, DbType.SQLITE);
}
@@ -1,21 +1,19 @@
package com.jero.common.util.dynamic.db;
import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import com.jero.common.exception.JeroBootException;
import com.jero.common.exception.JeroBootException;
import com.jero.common.system.vo.DynamicDataSourceModel;
import com.jero.common.util.ReflectHelper;
import com.jero.common.util.oConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Spring JDBC 实时数据库访问
@@ -27,6 +25,10 @@ import java.util.Map;
@Slf4j
public class DynamicDBUtil {
private DynamicDBUtil(){
}
/**
* 获取数据源最底层方法不要随便调用
*
@@ -42,7 +44,6 @@ public class DynamicDBUtil {
String dbPassword = dbSource.getDbPassword();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
//dataSource.setValidationQuery("SELECT 1 FROM DUAL");
dataSource.setTestWhileIdle(true);
dataSource.setTestOnBorrow(false);
dataSource.setTestOnReturn(false);
@@ -76,7 +77,7 @@ public class DynamicDBUtil {
return cacheDbSource;
} else {
DruidDataSource dataSource = getJdbcDataSource(dbSource);
if(dataSource!=null && dataSource.isEnable()){
if(dataSource.isEnable()){
DataSourceCachePool.putCacheBasicDataSource(dbKey, dataSource);
}else{
throw new JeroBootException("动态数据源连接失败,dbKey"+dbKey);
@@ -136,12 +137,12 @@ public class DynamicDBUtil {
* @param data sql语法中需要判断的数据及sql拼接注入中需要的数据
* @return
*/
public static int updateByHash(final String dbKey, String sql, HashMap<String, Object> data) {
public static int updateByHash(final String dbKey, String sql, Map<String, Object> data) {
int effectCount;
JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey);
//根据模板获取sql
sql = FreemarkerParseFactory.parseTemplateContent(sql, data);
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource());
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(Objects.requireNonNull(jdbcTemplate.getDataSource()));
effectCount = namedParameterJdbcTemplate.update(sql, data);
return effectCount;
}
@@ -167,7 +168,7 @@ public class DynamicDBUtil {
* @param data sql语法中需要判断的数据及sql拼接注入中需要的数据
* @return
*/
public static Object findOneByHash(final String dbKey, String sql, HashMap<String, Object> data) {
public static Object findOneByHash(final String dbKey, String sql, Map<String, Object> data) {
List<Map<String, Object>> list;
list = findListByHash(dbKey, sql, data);
if (oConvertUtils.listIsEmpty(list)) {
@@ -204,7 +205,7 @@ public class DynamicDBUtil {
* @return
*/
@SuppressWarnings("unchecked")
public static <T> Object findOneByHash(final String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) {
public static <T> Object findOneByHash(final String dbKey, String sql, Class<T> clazz, Map<String, Object> data) {
Map<String, Object> map = (Map<String, Object>) findOneByHash(dbKey, sql, data);
return ReflectHelper.setAll(clazz, map);
}
@@ -229,12 +230,12 @@ public class DynamicDBUtil {
* @param data sql语法中需要判断的数据及sql拼接注入中需要的数据
* @return
*/
public static List<Map<String, Object>> findListByHash(final String dbKey, String sql, HashMap<String, Object> data) {
public static List<Map<String, Object>> findListByHash(final String dbKey, String sql, Map<String, Object> data) {
List<Map<String, Object>> list;
JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey);
//根据模板获取sql
sql = FreemarkerParseFactory.parseTemplateContent(sql, data);
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource());
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(Objects.requireNonNull(jdbcTemplate.getDataSource()));
list = namedParameterJdbcTemplate.queryForList(sql, data);
return list;
}
@@ -261,12 +262,12 @@ public class DynamicDBUtil {
* @param data sql语法中需要判断的数据及sql拼接注入中需要的数据
* @return
*/
public static <T> List<T> findListByHash(final String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) {
public static <T> List<T> findListByHash(final String dbKey, String sql, Class<T> clazz, Map<String, Object> data) {
List<T> list;
JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey);
//根据模板获取sql
sql = FreemarkerParseFactory.parseTemplateContent(sql, data);
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource());
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(Objects.requireNonNull(jdbcTemplate.getDataSource()));
list = namedParameterJdbcTemplate.queryForList(sql, data, clazz);
return list;
}
@@ -294,7 +295,7 @@ public class DynamicDBUtil {
* @param data sql语法中需要判断的数据及sql拼接注入中需要的数据
* @return
*/
public static <T> List<T> findListEntitiesByHash(final String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) {
public static <T> List<T> findListEntitiesByHash(final String dbKey, String sql, Class<T> clazz, Map<String, Object> data) {
List<Map<String, Object>> queryList = findListByHash(dbKey, sql, data);
return ReflectHelper.transList2Entrys(queryList, clazz);
}
@@ -1,5 +1,6 @@
package com.jero.common.util.dynamic.db;
import com.jero.common.exception.JeroBootException;
import freemarker.cache.StringTemplateLoader;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
@@ -22,6 +23,10 @@ import java.util.regex.Pattern;
@Slf4j
public class FreemarkerParseFactory {
private FreemarkerParseFactory(){
}
private static final String ENCODE = "utf-8";
/**
* 参数格式化工具类
@@ -40,12 +45,12 @@ public class FreemarkerParseFactory {
private static StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
// 使用内嵌的(?ms)打开单行和多行模式
private final static Pattern p = Pattern
private static final Pattern p = Pattern
.compile("(?ms)/\\*.*?\\*/|^\\s*//.*?$");
static {
_tplConfig.setClassForTemplateLoading(
new FreemarkerParseFactory().getClass(), "/");
FreemarkerParseFactory.class, "/");
_tplConfig.setNumberFormat("0.#####################");
_sqlConfig.setTemplateLoader(stringTemplateLoader);
_sqlConfig.setNumberFormat("0.#####################");
@@ -58,7 +63,7 @@ public class FreemarkerParseFactory {
*
* @throws Exception
*/
public static boolean isExistTemplate(String tplName) throws Exception {
public static boolean isExistTemplate(String tplName) throws JeroBootException {
try {
Template mytpl = _tplConfig.getTemplate(tplName, "UTF-8");
if (mytpl == null) {
@@ -68,7 +73,7 @@ public class FreemarkerParseFactory {
//update-begin--Author:scott Date:20180320 for解决问题 - 错误提示sql文件不存在实际问题是sql freemarker用法错误-----
if (e instanceof ParseException) {
log.error(e.getMessage(), e.fillInStackTrace());
throw new Exception(e);
throw new JeroBootException(e);
}
log.debug("----isExistTemplate----" + e.toString());
//update-end--Author:scott Date:20180320 for解决问题 - 错误提示sql文件不存在实际问题是sql freemarker用法错误------
@@ -90,7 +95,7 @@ public class FreemarkerParseFactory {
StringWriter swriter = new StringWriter();
Template mytpl = _tplConfig.getTemplate(tplName, ENCODE);
if (paras.containsKey(MINI_DAO_FORMAT)) {
throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!");
throw new JeroBootException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!");
}
paras.put(MINI_DAO_FORMAT, new SimpleFormat());
mytpl.process(paras, swriter);
@@ -100,9 +105,7 @@ public class FreemarkerParseFactory {
} catch (Exception e) {
log.error(e.getMessage(), e.fillInStackTrace());
log.error("发送一次的模板key:{ " + tplName + " }");
//System.err.println(e.getMessage());
//System.err.println("模板名:{ "+ tplName +" }");
throw new RuntimeException("解析SQL模板异常");
throw new JeroBootException("解析SQL模板异常");
}
}
@@ -122,7 +125,7 @@ public class FreemarkerParseFactory {
}
Template mytpl = _sqlConfig.getTemplate("sql_" + tplContent.hashCode(), ENCODE);
if (paras.containsKey(MINI_DAO_FORMAT)) {
throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!");
throw new JeroBootException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!");
}
paras.put(MINI_DAO_FORMAT, new SimpleFormat());
mytpl.process(paras, swriter);
@@ -132,9 +135,7 @@ public class FreemarkerParseFactory {
} catch (Exception e) {
log.error(e.getMessage(), e.fillInStackTrace());
log.error("发送一次的模板key:{ " + tplContent + " }");
//System.err.println(e.getMessage());
//System.err.println("模板内容:{ "+ tplContent +" }");
throw new RuntimeException("解析SQL模板异常");
throw new JeroBootException("解析SQL模板异常");
}
}
@@ -144,8 +145,8 @@ public class FreemarkerParseFactory {
private static String getSqlText(String sql) {
// 将注释替换成""
sql = p.matcher(sql).replaceAll("");
sql = sql.replaceAll("\\n", " ").replaceAll("\\t", " ")
.replaceAll("\\s{1,}", " ").trim();
sql = sql.replace("\\n", " ").replace("\\t", " ")
.replace("\\s{1,}", " ").trim();
// 去掉 最后是 where这样的问题
if (sql.endsWith("where") || sql.endsWith("where ")) {
sql = sql.substring(0, sql.lastIndexOf("where"));
@@ -168,4 +169,4 @@ public class FreemarkerParseFactory {
}
return sql;
}
}
}
@@ -12,6 +12,10 @@ import java.util.Map;
*/
public class SqlUtils {
private SqlUtils(){
}
public static final String DATABSE_TYPE_MYSQL = "mysql";
public static final String DATABSE_TYPE_POSTGRE = "postgresql";
public static final String DATABSE_TYPE_ORACLE = "oracle";
@@ -30,9 +34,9 @@ public class SqlUtils {
* 获取所有表的SQL
*/
public static final String MYSQL_ALLTABLES_SQL = "select distinct table_name from information_schema.columns where table_schema = {0}";
public static final String POSTGRE__ALLTABLES_SQL = "SELECT distinct c.relname AS table_name FROM pg_class c";
public static final String ORACLE__ALLTABLES_SQL = "select distinct colstable.table_name as table_name from user_tab_cols colstable";
public static final String SQLSERVER__ALLTABLES_SQL = "select distinct c.name as table_name from sys.objects c";
public static final String POST_GRE_ALL_TABLES_SQL = "SELECT distinct c.relname AS table_name FROM pg_class c";
public static final String ORACLE_ALL_TABLES_SQL = "select distinct colstable.table_name as table_name from user_tab_cols colstable";
public static final String SQL_SERVER_ALL_TABLES_SQL = "select distinct c.name as table_name from sys.objects c";
/**
* 获取指定表的所有列名
@@ -82,7 +86,7 @@ public class SqlUtils {
* @param params
* @return
*/
public static String getFullSql(String sql, Map params) {
public static String getFullSql(String sql, Map<String,Object> params) {
return getFullSql(sql, params, null, null);
}
@@ -97,13 +101,14 @@ public class SqlUtils {
* @param orderBy 排序方式只能是 DESC ASC
* @return
*/
public static String getFullSql(String sql, Map params, String orderColumn, String orderBy) {
public static String getFullSql(String sql, Map<String,Object> params, String orderColumn, String orderBy) {
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append("SELECT t.* FROM ( ").append(sql).append(" ) t ");
if (params != null && params.size() >= 1) {
sqlBuilder.append("WHERE 1=1 ");
for (Object key : params.keySet()) {
String value = String.valueOf(params.get(key));
for (Map.Entry<String,Object> entry : params.entrySet()) {
String key = entry.getKey();
String value = String.valueOf(entry.getValue());
if (StringUtils.isNotBlank(value)) {
sqlBuilder.append(" AND (").append(key).append(" = N'").append(value).append("')");
}
@@ -184,11 +189,11 @@ public class SqlUtils {
if (dbTypeIsMySQL(dbType)) {
return MessageFormat.format(MYSQL_ALLTABLES_SQL, params);
} else if (dbTypeIsOracle(dbType)) {
return ORACLE__ALLTABLES_SQL;
return ORACLE_ALL_TABLES_SQL;
} else if (dbTypeIsPostgre(dbType)) {
return POSTGRE__ALLTABLES_SQL;
return POST_GRE_ALL_TABLES_SQL;
} else if (dbTypeIsSQLServer(dbType)) {
return SQLSERVER__ALLTABLES_SQL;
return SQL_SERVER_ALL_TABLES_SQL;
}
}
return null;
@@ -11,9 +11,13 @@ import javax.crypto.spec.SecretKeySpec;
*/
public class AesEncryptUtil {
private AesEncryptUtil(){
}
//使用AES-128-CBC加密模式key需要为16位,key和iv可以相同
private static String KEY = EncryptedString.key;
private static String IV = EncryptedString.iv;
private static final String ENCRYPTED_KEY = EncryptedString.ENCRYPTED_KEY;
private static final String ENCRYPTED_IV = EncryptedString.ENCRYPTED_IV;
/**
* 加密方法
@@ -23,10 +27,10 @@ public class AesEncryptUtil {
* @return 加密的结果
* @throws Exception
*/
public static String encrypt(String data, String key, String iv) throws Exception {
public static String encrypt(String data, String key, String iv) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/补码方式"NoPadding PkcsPadding
//"算法/模式/补码方式"NoPadding PkcsPadding
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
@@ -60,7 +64,7 @@ public class AesEncryptUtil {
* @return 解密的结果
* @throws Exception
*/
public static String desEncrypt(String data, String key, String iv) throws Exception {
public static String desEncrypt(String data, String key, String iv) {
try {
byte[] encrypted1 = Base64.decode(data);
@@ -71,8 +75,7 @@ public class AesEncryptUtil {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
return new String(original);
} catch (Exception e) {
e.printStackTrace();
return null;
@@ -85,8 +88,8 @@ public class AesEncryptUtil {
* @return
* @throws Exception
*/
public static String encrypt(String data) throws Exception {
return encrypt(data, KEY, IV);
public static String encrypt(String data) {
return encrypt(data, ENCRYPTED_KEY, ENCRYPTED_IV);
}
/**
@@ -95,27 +98,7 @@ public class AesEncryptUtil {
* @return
* @throws Exception
*/
public static String desEncrypt(String data) throws Exception {
return desEncrypt(data, KEY, IV);
public static String desEncrypt(String data) {
return desEncrypt(data, ENCRYPTED_KEY, ENCRYPTED_IV);
}
// /**
// * 测试
// */
// public static void main(String args[]) throws Exception {
// String test1 = "sa";
// String test =new String(test1.getBytes(),"UTF-8");
// String data = null;
// String key = KEY;
// String iv = IV;
// // /g2wzfqvMOeazgtsUVbq1kmJawROa6mcRAzwG1/GeJ4=
// data = encrypt(test, key, iv);
// System.out.println("数据:"+test);
// System.out.println("加密:"+data);
// String jiemi =desEncrypt(data, key, iv).trim();
// System.out.println("解密:"+jiemi);
// }
}
@@ -2,11 +2,42 @@ package com.jero.common.util.encryption;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Data
@Component
public class EncryptedString {
public static String key = "1234567890adbcde";//长度为16个字符
private EncryptedString(){
public static String iv = "1234567890hjlkew";//长度为16个字符
}
public static String ENCRYPTED_KEY;
//长度为16个字符
@Value("${jero.password.aes.encrypted_key}")
public String encryptedKeyStr;
@PostConstruct
public void setEncryptedKeyStr(){
synchronized (EncryptedString.class){
if(ENCRYPTED_KEY == null){
ENCRYPTED_KEY = this.encryptedKeyStr;
}
}
}
//长度为16个字符
public static String ENCRYPTED_IV;
@Value("${jero.password.aes.encrypted_iv}")
public String encryptedIvStr;
@PostConstruct
public void setEncryptedIvStr(){
synchronized (EncryptedString.class){
if(ENCRYPTED_IV == null){
ENCRYPTED_IV = this.encryptedIvStr;
}
}
}
}
@@ -1,5 +1,6 @@
package com.jero.common.util.filter;
import com.jero.common.exception.JeroBootException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
@@ -8,74 +9,24 @@ import java.util.HashMap;
import java.util.Iterator;
/**
* @Description: TODO
* @author: lsq
* @date: 2021年08月09日 15:29
*/
public class FileTypeFilter {
private FileTypeFilter(){
}
//文件后缀
private static String[] forbidType = {"jsp","php"};
// 初始化文件头类型不够的自行补充
final static HashMap<String, String> fileTypeMap = new HashMap<>();
static final HashMap<String, String> FILE_TYPE_MAP = new HashMap<>();
static {
fileTypeMap.put("3c25402070616765206c", "jsp");
fileTypeMap.put("3c3f7068700a0a2f2a2a0a202a205048", "php");
/* fileTypeMap.put("ffd8ffe000104a464946", "jpg");
fileTypeMap.put("89504e470d0a1a0a0000", "png");
fileTypeMap.put("47494638396126026f01", "gif");
fileTypeMap.put("49492a00227105008037", "tif");
fileTypeMap.put("424d228c010000000000", "bmp");
fileTypeMap.put("424d8240090000000000", "bmp");
fileTypeMap.put("424d8e1b030000000000", "bmp");
fileTypeMap.put("41433130313500000000", "dwg");
fileTypeMap.put("3c21444f435459504520", "html");
fileTypeMap.put("3c21646f637479706520", "htm");
fileTypeMap.put("48544d4c207b0d0a0942", "css");
fileTypeMap.put("696b2e71623d696b2e71", "js");
fileTypeMap.put("7b5c727466315c616e73", "rtf");
fileTypeMap.put("38425053000100000000", "psd");
fileTypeMap.put("46726f6d3a203d3f6762", "eml");
fileTypeMap.put("d0cf11e0a1b11ae10000", "doc");
fileTypeMap.put("5374616E64617264204A", "mdb");
fileTypeMap.put("252150532D41646F6265", "ps");
fileTypeMap.put("255044462d312e350d0a", "pdf");
fileTypeMap.put("2e524d46000000120001", "rmvb");
fileTypeMap.put("464c5601050000000900", "flv");
fileTypeMap.put("00000020667479706d70", "mp4");
fileTypeMap.put("49443303000000002176", "mp3");
fileTypeMap.put("000001ba210001000180", "mpg");
fileTypeMap.put("3026b2758e66cf11a6d9", "wmv");
fileTypeMap.put("52494646e27807005741", "wav");
fileTypeMap.put("52494646d07d60074156", "avi");
fileTypeMap.put("4d546864000000060001", "mid");
fileTypeMap.put("504b0304140000000800", "zip");
fileTypeMap.put("526172211a0700cf9073", "rar");
fileTypeMap.put("235468697320636f6e66", "ini");
fileTypeMap.put("504b03040a0000000000", "jar");
fileTypeMap.put("4d5a9000030000000400", "exe");
fileTypeMap.put("3c25402070616765206c", "jsp");
fileTypeMap.put("4d616e69666573742d56", "mf");
fileTypeMap.put("3c3f786d6c2076657273", "xml");
fileTypeMap.put("494e5345525420494e54", "sql");
fileTypeMap.put("7061636b616765207765", "java");
fileTypeMap.put("406563686f206f66660d", "bat");
fileTypeMap.put("1f8b0800000000000000", "gz");
fileTypeMap.put("6c6f67346a2e726f6f74", "properties");
fileTypeMap.put("cafebabe0000002e0041", "class");
fileTypeMap.put("49545346030000006000", "chm");
fileTypeMap.put("04000000010000001300", "mxp");
fileTypeMap.put("504b0304140006000800", "docx");
fileTypeMap.put("6431303a637265617465", "torrent");
fileTypeMap.put("6D6F6F76", "mov");
fileTypeMap.put("FF575043", "wpd");
fileTypeMap.put("CFAD12FEC5FD746F", "dbx");
fileTypeMap.put("2142444E", "pst");
fileTypeMap.put("AC9EBD8F", "qdf");
fileTypeMap.put("E3828596", "pwl");
fileTypeMap.put("2E7261FD", "ram");*/
FILE_TYPE_MAP.put("3c25402070616765206c", "jsp");
FILE_TYPE_MAP.put("3c3f7068700a0a2f2a2a0a202a205048", "php");
}
/**
@@ -92,11 +43,11 @@ public class FileTypeFilter {
*
* @param file
*/
public static void fileTypeFilter(MultipartFile file) throws Exception {
public static void fileTypeFilter(MultipartFile file){
String suffix = getFileType(file);
for (String type : forbidType) {
if (type.contains(suffix)) {
throw new Exception("上传失败,文件类型异常:" + suffix);
throw new JeroBootException("上传失败,文件类型异常:" + suffix);
}
}
}
@@ -109,22 +60,21 @@ public class FileTypeFilter {
* @throws Exception
*/
private static String getFileType(MultipartFile file) throws Exception {
private static String getFileType(MultipartFile file) throws JeroBootException {
String fileExtendName = null;
InputStream is;
try {
//is = new FileInputStream(file);
is = file.getInputStream();
byte[] b = new byte[10];
is.read(b, 0, b.length);
String fileTypeHex = String.valueOf(bytesToHexString(b));
Iterator<String> keyIter = fileTypeMap.keySet().iterator();
Iterator<String> keyIter = FILE_TYPE_MAP.keySet().iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
// 验证前5个字符比较
if (key.toLowerCase().startsWith(fileTypeHex.toLowerCase().substring(0, 5))
|| fileTypeHex.toLowerCase().substring(0, 5).startsWith(key.toLowerCase())) {
fileExtendName = fileTypeMap.get(key);
fileExtendName = FILE_TYPE_MAP.get(key);
break;
}
}
@@ -136,7 +86,7 @@ public class FileTypeFilter {
is.close();
return fileExtendName;
} catch (Exception exception) {
throw new Exception(exception.getMessage(), exception);
throw new JeroBootException(exception.getMessage(), exception);
}
}
@@ -9,12 +9,16 @@ import java.util.regex.PatternSyntaxException;
*/
public class StrAttackFilter {
private StrAttackFilter(){
}
public static String filter(String str) throws PatternSyntaxException {
// 清除掉所有特殊字符
String regEx = "[`_《》~!@#$%^&*()+=|{}':;',\\[\\].<>?~@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
String regEx = "[`_《》~!@#$%^&*()+=|{}':;',\\[\\].<>?";
regEx += "~@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
}
@@ -1,5 +1,6 @@
package com.jero.common.util.jsonschema;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jero.common.system.vo.DictModel;
@@ -16,8 +17,8 @@ public abstract class CommonProperty implements Serializable{
protected String key;
/**
* <p>此关键字的值必须是字符串或数组如果它是一个数组那么数组的元素必须是字符串并且必须是唯一的
* <p>字符串值必须是六种基本类型之一nullbooleanobjectarraynumberstringinteger它匹配任何数字零分数部分
@@ -25,31 +26,31 @@ public abstract class CommonProperty implements Serializable{
*
*/
protected String type;
/**
* 对应JsonSchema的enum
* <p>该关键字的值必须是一个数组这个数组应该至少有一个元素数组中的元素应该是唯一的如果实例的值等于此关键字的数组值中的某个元素则实例将对此关键字成功验证
* 数组中的元素可以是任何值包括null
*
*
* {
* "type": "string",
* "enum": ["1", "2", "3"] 需要的话可以通过这个include转一下
* }
*/
protected List<DictModel> include;
protected transient List<DictModel> include;
/**
* 对应JsonSchema的const
* <p>此关键字的值可以是任何类型包括null
* 如果实例的值等于关键字的值则实例将针对此关键字成功验证
*/
protected Object constant;
protected transient Object constant;
//三个自定义 属性
protected String view;// 展示类型
protected String title;//数据库字段备注
protected Integer order;//字段显示排序
protected boolean disabled;//是否禁用
protected String defVal; // 字段默认值
@@ -113,7 +114,7 @@ public abstract class CommonProperty implements Serializable{
public void setConstant(Object constant) {
this.constant = constant;
}
public String getTitle() {
return title;
}
@@ -153,11 +154,11 @@ public abstract class CommonProperty implements Serializable{
* @return
*/
public abstract Map<String,Object> getPropertyJson();
public JSONObject getCommonJson() {
JSONObject json = new JSONObject();
json.put("type", type);
if(include!=null && include.size()>0) {
if(include!=null && !include.isEmpty()) {
json.put("enum", include);
}
if(constant!=null) {
@@ -176,7 +177,7 @@ public abstract class CommonProperty implements Serializable{
}
if(disabled) {
String str = "{\"widgetattrs\":{\"disabled\":true}}";
JSONObject ui = JSONObject.parseObject(str);
JSONObject ui = JSON.parseObject(str);
json.put("ui", ui);
}
if (defVal!=null && defVal.length()>0) {
@@ -190,6 +191,6 @@ public abstract class CommonProperty implements Serializable{
}
return json;
}
}
@@ -1,20 +1,22 @@
package com.jero.common.util.jsonschema;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class JsonschemaUtil {
private JsonschemaUtil(){
}
/**
* 生成JsonSchema
*
*
* @param descrip
* @param propertyList
* @return
@@ -35,10 +37,9 @@ public class JsonschemaUtil {
}
obj.put("properties", properties);
//鬼知道这里为什么报错 com.jero.modules.system.model.DictModel cannot be cast to com.jero.modules.system.model.DictModel
//log.info("---JSONSchema--->"+obj.toJSONString());
return obj;
}
/**
* 生成JsonSchema 用于子对象
* @param title 子对象描述
@@ -53,7 +54,7 @@ public class JsonschemaUtil {
obj.put("title", title);
if(requiredArr==null) {
requiredArr = new ArrayList<String>();
requiredArr = new ArrayList<>();
}
obj.put("required", requiredArr);
@@ -63,7 +64,6 @@ public class JsonschemaUtil {
properties.put(map.get("key").toString(), map.get("prop"));
}
obj.put("properties", properties);
//log.info("---JSONSchema--->"+obj.toString());
return obj;
}
@@ -1,5 +1,6 @@
package com.jero.common.util.jsonschema.validate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jero.common.util.jsonschema.BaseColumn;
import com.jero.common.util.jsonschema.CommonProperty;
@@ -21,7 +22,7 @@ public class LinkDownProperty extends CommonProperty {
/**
* 级联下拉组件 的其他级联列
*/
List<BaseColumn> otherColumns;
transient List<BaseColumn> otherColumns;
public String getDictTable(){
return this.dictTable;
@@ -57,7 +58,7 @@ public class LinkDownProperty extends CommonProperty {
Map<String, Object> map = new HashMap<>();
map.put("key", getKey());
JSONObject prop = getCommonJson();
JSONObject temp = JSONObject.parseObject(this.dictTable);
JSONObject temp = JSON.parseObject(this.dictTable);
prop.put("config", temp);
prop.put("others", otherColumns);
map.put("prop", prop);
@@ -1,23 +1,21 @@
package com.jero.common.util.jsonschema.validate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.jero.common.util.jsonschema.CommonProperty;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class PopupProperty extends CommonProperty {
private static final long serialVersionUID = -3200493311633999539L;
private String code;
private String destFields;
private String orgFields;
public String getCode() {
return code;
}
@@ -43,7 +41,7 @@ public class PopupProperty extends CommonProperty {
}
public PopupProperty() {}
public PopupProperty(String key,String title,String code,String destFields,String orgFields) {
this.view = "popup";
this.type = "string";
@@ -53,7 +51,7 @@ public class PopupProperty extends CommonProperty {
this.destFields=destFields;
this.orgFields=orgFields;
}
@Override
public Map<String, Object> getPropertyJson() {
@@ -1,5 +1,6 @@
package com.jero.common.util.jsonschema.validate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jero.common.util.jsonschema.CommonProperty;
@@ -27,20 +28,19 @@ public class SwitchProperty extends CommonProperty {
this.title = title;
this.extendStr = extendStr;
}
@Override
public Map<String, Object> getPropertyJson() {
Map<String,Object> map = new HashMap<>();
map.put("key",getKey());
JSONObject prop = getCommonJson();
JSONArray array = new JSONArray();
if(extendStr!=null) {
array = JSONArray.parseArray(extendStr);
JSONArray array = JSON.parseArray(extendStr);
prop.put("extendOption",array);
}
map.put("prop",prop);
return map;
}
//TODO 重构问题数据字典 只是字符串类的还是有存储的数值类型只有字符串请跳过这个 只改前端
// TODO 重构问题数据字典 只是字符串类的还是有存储的数值类型只有字符串请跳过这个 只改前端
}
@@ -2,6 +2,7 @@ package com.jero.common.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import javax.servlet.http.HttpServletRequest;
@@ -15,18 +16,23 @@ import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.sql.Date;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*
* @Author 张代浩
*
*/
@Slf4j
public class oConvertUtils {
private oConvertUtils(){
}
public static boolean isEmpty(Object object) {
if (object == null) {
return (true);
@@ -39,7 +45,7 @@ public class oConvertUtils {
}
return (false);
}
public static boolean isNotEmpty(Object object) {
if (object != null && !object.equals("") && !object.equals("null")) {
return (true);
@@ -48,16 +54,15 @@ public class oConvertUtils {
}
public static String decode(String strIn, String sourceCode, String targetCode) {
String temp = code2code(strIn, sourceCode, targetCode);
return temp;
return code2code(strIn, sourceCode, targetCode);
}
public static String StrToUTF(String strIn, String sourceCode, String targetCode) {
strIn = "";
public static String StrToUTF() {
String strIn = "";
try {
strIn = new String(strIn.getBytes("ISO-8859-1"), "GBK");
strIn = new String(strIn.getBytes(StandardCharsets.ISO_8859_1), "GBK");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
// Auto-generated catch block
e.printStackTrace();
}
return strIn;
@@ -72,7 +77,7 @@ public class oConvertUtils {
try {
byte[] b = strIn.getBytes(sourceCode);
for (int i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
log.info(b[i] + " ");
}
strOut = new String(b, targetCode);
} catch (Exception e) {
@@ -83,7 +88,7 @@ public class oConvertUtils {
}
public static int getInt(String s, int defval) {
if (s == null || s == "") {
if (s == null || "".equals(s)) {
return (defval);
}
try {
@@ -94,7 +99,7 @@ public class oConvertUtils {
}
public static int getInt(String s) {
if (s == null || s == "") {
if (s == null || "".equals(s)) {
return 0;
}
try {
@@ -105,7 +110,7 @@ public class oConvertUtils {
}
public static int getInt(String s, Integer df) {
if (s == null || s == "") {
if (s == null || "".equals(s)) {
return df;
}
try {
@@ -117,9 +122,6 @@ public class oConvertUtils {
public static Integer[] getInts(String[] s) {
Integer[] integer = new Integer[s.length];
if (s == null) {
return null;
}
for (int i = 0; i < s.length; i++) {
integer[i] = Integer.parseInt(s[i]);
}
@@ -128,7 +130,7 @@ public class oConvertUtils {
}
public static double getDouble(String s, double defval) {
if (s == null || s == "") {
if (s == null || "".equals(s)) {
return (defval);
}
try {
@@ -145,14 +147,6 @@ public class oConvertUtils {
return s;
}
/*public static Short getShort(String s) {
if (StringUtil.isNotEmpty(s)) {
return (Short.parseShort(s));
} else {
return null;
}
}*/
public static int getInt(Object object, int defval) {
if (isEmpty(object)) {
return (defval);
@@ -163,7 +157,7 @@ public class oConvertUtils {
return (defval);
}
}
public static Integer getInt(Object object) {
if (isEmpty(object)) {
return null;
@@ -191,7 +185,7 @@ public class oConvertUtils {
}
return result;
} catch (NumberFormatException e) {
return null;
return new Integer[0];
}
}
@@ -199,15 +193,6 @@ public class oConvertUtils {
return (getString(s, ""));
}
/**
* 转义成Unicode编码
* @param s
* @return
*/
/*public static String escapeJava(Object s) {
return StringEscapeUtils.escapeJava(getString(s));
}*/
public static String getString(Object object) {
if (isEmpty(object)) {
return "";
@@ -238,12 +223,13 @@ public class oConvertUtils {
}
public static long stringToLong(String str) {
Long test = new Long(0);
long test = 0L;
try {
test = Long.valueOf(str);
test = Long.parseLong(str);
} catch (Exception e) {
log.error("异常",e);
}
return test.longValue();
return test;
}
/**
@@ -263,12 +249,14 @@ public class oConvertUtils {
/**
* 判断一个类是否为基本数据类型
*
*
* @param clazz
* 要判断的类
* @return true 表示为基本数据类型
* @deprecated 未调用
*/
private static boolean isBaseDataType(Class clazz) throws Exception {
@Deprecated
private static boolean isBaseDataType(Class<T> clazz) {
return (clazz.equals(String.class) || clazz.equals(Integer.class) || clazz.equals(Byte.class) || clazz.equals(Long.class) || clazz.equals(Double.class) || clazz.equals(Float.class) || clazz.equals(Character.class) || clazz.equals(Short.class) || clazz.equals(BigDecimal.class) || clazz.equals(BigInteger.class) || clazz.equals(Boolean.class) || clazz.equals(Date.class) || clazz.isPrimitive());
}
@@ -278,14 +266,15 @@ public class oConvertUtils {
* @return IP Address
*/
public static String getIpAddrByRequest(HttpServletRequest request) {
String unknown = "unknown";
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
@@ -326,16 +315,16 @@ public class oConvertUtils {
/**
* java去除字符串中的空格回车换行符制表符
*
*
* @param str
* @return
*/
public static String replaceBlank(String str) {
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
dest = str.replace("\\s*","").replace(" ","")
.replace("\\t","").replace("\\r","")
.replace("\\n","");
}
return dest;
@@ -343,7 +332,7 @@ public class oConvertUtils {
/**
* 判断元素是否在数组内
*
*
* @param substring
* @param source
* @return
@@ -365,18 +354,18 @@ public class oConvertUtils {
* 获取Map对象
*/
public static Map<Object, Object> getHashMap() {
return new HashMap<Object, Object>();
return new HashMap<>();
}
/**
* SET转换MAP
*
*
* @param str
* @return
*/
public static Map<Object, Object> SetToMap(Set<Object> setobj) {
Map<Object, Object> map = getHashMap();
for (Iterator iterator = setobj.iterator(); iterator.hasNext();) {
for (Iterator<Object> iterator = setobj.iterator(); iterator.hasNext();) {
Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) iterator.next();
map.put(entry.getKey().toString(), entry.getValue() == null ? "" : entry.getValue().toString().trim());
}
@@ -407,19 +396,18 @@ public class oConvertUtils {
long c = Integer.parseInt(ip[2]);
long d = Integer.parseInt(ip[3]);
long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
return ipNum;
return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
}
private static boolean isInner(long userIp, long begin, long end) {
return (userIp >= begin) && (userIp <= end);
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式
* 如果转换前的下划线大写方式命名的字符串为空则返回空字符串</br>
* 例如hello_world->helloWorld
*
*
* @param name
* 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
@@ -438,7 +426,7 @@ public class oConvertUtils {
//update-end--Author:zhoujf Date:20180503 forTASK #2500 代码生成器代码生成器开发一通用模板生成功能
}
// 用下划线将原始字符串分割
String camels[] = name.split("_");
String[] camels = name.split("_");
for (String camel : camels) {
// 跳过原始字符串中开头结尾的下换线或双重下划线
if (camel.isEmpty()) {
@@ -456,12 +444,12 @@ public class oConvertUtils {
}
return result.toString();
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式
* 如果转换前的下划线大写方式命名的字符串为空则返回空字符串</br>
* 例如hello_world,test_id->helloWorld,testId
*
*
* @param name
* 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
@@ -470,7 +458,7 @@ public class oConvertUtils {
if(names==null||names.equals("")){
return null;
}
StringBuffer sf = new StringBuffer();
StringBuilder sf = new StringBuilder();
String[] fs = names.split(",");
for (String field : fs) {
field = camelName(field);
@@ -479,13 +467,13 @@ public class oConvertUtils {
String result = sf.toString();
return result.substring(0, result.length() - 1);
}
//update-begin--Author:zhoujf Date:20180503 forTASK #2500 代码生成器代码生成器开发一通用模板生成功能
/**
* 将下划线大写方式命名的字符串转换为驼峰式(首字母写)
* 如果转换前的下划线大写方式命名的字符串为空则返回空字符串</br>
* 例如hello_world->HelloWorld
*
*
* @param name
* 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
@@ -501,7 +489,7 @@ public class oConvertUtils {
return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
}
// 用下划线将原始字符串分割
String camels[] = name.split("_");
String[] camels = name.split("_");
for (String camel : camels) {
// 跳过原始字符串中开头结尾的下换线或双重下划线
if (camel.isEmpty()) {
@@ -514,7 +502,7 @@ public class oConvertUtils {
return result.toString();
}
//update-end--Author:zhoujf Date:20180503 forTASK #2500 代码生成器代码生成器开发一通用模板生成功能
/**
* 将驼峰命名转化成下划线
* @param para
@@ -522,18 +510,18 @@ public class oConvertUtils {
*/
public static String camelToUnderline(String para){
if(para.length()<3){
return para.toLowerCase();
return para.toLowerCase();
}
StringBuilder sb=new StringBuilder(para);
int temp=0;//定位
//从第三个字符开始 避免命名不规范
//从第三个字符开始 避免命名不规范
for(int i=2;i<para.length();i++){
if(Character.isUpperCase(para.charAt(i))){
sb.insert(i+temp, "_");
temp+=1;
}
}
return sb.toString().toLowerCase();
return sb.toString().toLowerCase();
}
/**
@@ -542,17 +530,25 @@ public class oConvertUtils {
*/
public static String randomGen(int place) {
String base = "qwertyuioplkjhgfdsazxcvbnmQAZWSXEDCRFVTGBYHNUJMIKLOP0123456789";
StringBuffer sb = new StringBuffer();
Random rd = new Random();
StringBuilder sb = new StringBuilder();
Random rd = null;
try {
rd = SecureRandom.getInstanceStrong();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if(Objects.isNull(rd)){
return null;
}
for(int i=0;i<place;i++) {
sb.append(base.charAt(rd.nextInt(base.length())));
}
return sb.toString();
}
/**
* 获取类的所有属性包括父类
*
*
* @param object
* @return
*/
@@ -567,7 +563,7 @@ public class oConvertUtils {
fieldList.toArray(fields);
return fields;
}
/**
* 将map的key全部转成小写
* @param list
@@ -577,10 +573,10 @@ public class oConvertUtils {
List<Map<String, Object>> select = new ArrayList<>();
for (Map<String, Object> row : list) {
Map<String, Object> resultMap = new HashMap<>();
Set<String> keySet = row.keySet();
for (String key : keySet) {
String newKey = key.toLowerCase();
resultMap.put(newKey, row.get(key));
Set<String> keySet = row.keySet();
for (String key : keySet) {
String newKey = key.toLowerCase();
resultMap.put(newKey, row.get(key));
}
select.add(resultMap);
}
@@ -597,7 +593,7 @@ public class oConvertUtils {
*/
public static<F,T> List<T> entityListToModelList(List<F> fromList, Class<T> tClass){
if(fromList == null || fromList.isEmpty()){
return null;
return Collections.emptyList();
}
List<T> tList = new ArrayList<>();
for(F f : fromList){
@@ -621,6 +617,7 @@ public class oConvertUtils {
} catch (IllegalAccessException e) {
log.error("entityToModel : 安全权限异常", e);
}
assert model != null;
BeanUtils.copyProperties(entity, model);
return (T)model;
}
@@ -633,8 +630,8 @@ public class oConvertUtils {
* list == null : true
* list.size() == 0 : true
*/
public static boolean listIsEmpty(Collection list) {
return (list == null || list.size() == 0);
public static boolean listIsEmpty(Collection<Map<String, Object>> list) {
return (list == null || list.isEmpty());
}
/**
@@ -645,7 +642,7 @@ public class oConvertUtils {
* list == null : false
* list.size() == 0 : false
*/
public static boolean listIsNotEmpty(Collection list) {
public static boolean listIsNotEmpty(Collection<Map<String, Object>> list) {
return !listIsEmpty(list);
}
@@ -659,7 +656,7 @@ public class oConvertUtils {
try {
//换个写法解决springboot读取jar包中文件的问题
InputStream stream = oConvertUtils.class.getClassLoader().getResourceAsStream(url.replace("classpath:", ""));
json = IOUtils.toString(stream,"UTF-8");
json = IOUtils.toString(stream,StandardCharsets.UTF_8);
} catch (IOException e) {
log.error(e.getMessage(),e);
}
@@ -15,6 +15,7 @@ import com.jero.common.util.oConvertUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
@@ -29,6 +30,10 @@ import java.util.UUID;
@Slf4j
public class OssBootUtil {
private OssBootUtil(){
}
private static String endPoint;
private static String accessKeyId;
private static String accessKeySecret;
@@ -84,6 +89,10 @@ public class OssBootUtil {
*/
private static OSSClient ossClient = null;
private static final String HTTPS_CONSTANT = "https://";
private static final String OSS_UPLOAD_CONSTANT = "------OSS文件上传成功------";
/**
* 上传文件至阿里云 OSS
* 文件上传成功,返回文件完整访问路径
@@ -94,7 +103,7 @@ public class OssBootUtil {
* @return oss 中的相对文件路径
*/
public static String upload(MultipartFile file, String fileDir,String customBucket) {
String FILE_URL = null;
String url;
initOSS(endPoint, accessKeyId, accessKeySecret);
StringBuilder fileUrl = new StringBuilder();
String newBucket = bucketName;
@@ -108,43 +117,38 @@ public class OssBootUtil {
}
// 获取文件名
String orgName = file.getOriginalFilename();
if("" == orgName){
if("".equals(orgName)){
orgName=file.getName();
}
//update-begin-author:liusq date:20210809 for: 过滤上传文件类型
FileTypeFilter.fileTypeFilter(file);
//update-end-author:liusq date:20210809 for: 过滤上传文件类型
orgName = CommonUtils.getFileName(orgName);
String fileName = orgName.indexOf(".")==-1
String fileName = !orgName.contains(".")
?orgName + "_" + System.currentTimeMillis()
:orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
if (!fileDir.endsWith("/")) {
fileDir = fileDir.concat("/");
}
//update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符防止攻击
fileDir=StrAttackFilter.filter(fileDir);
fileDir = StrAttackFilter.filter(fileDir);
//update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符防止攻击
fileUrl = fileUrl.append(fileDir + fileName);
fileUrl.append(fileDir).append(fileName);
if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
FILE_URL = staticDomain + "/" + fileUrl;
url = staticDomain + File.separator + fileUrl;
} else {
FILE_URL = "https://" + newBucket + "." + endPoint + "/" + fileUrl;
url = HTTPS_CONSTANT + newBucket + "." + endPoint + File.separator + fileUrl;
}
PutObjectResult result = ossClient.putObject(newBucket, fileUrl.toString(), file.getInputStream());
// 设置权限(公开读)
// ossClient.setBucketAcl(newBucket, CannedAccessControlList.PublicRead);
if (result != null) {
log.info("------OSS文件上传成功------" + fileUrl);
log.info(OSS_UPLOAD_CONSTANT + fileUrl);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
return null;
}
return FILE_URL;
return url;
}
/**
@@ -153,7 +157,7 @@ public class OssBootUtil {
* @Return: java.lang.String
*/
public static String getOriginalUrl(String url) {
String originalDomain = "https://" + bucketName + "." + endPoint;
String originalDomain = HTTPS_CONSTANT + bucketName + "." + endPoint;
if(oConvertUtils.isNotEmpty(staticDomain) && url.indexOf(staticDomain)!=-1){
url = url.replace(staticDomain,originalDomain);
}
@@ -180,7 +184,7 @@ public class OssBootUtil {
* @return oss 中的相对文件路径
*/
public static String upload(FileItemStream file, String fileDir) {
String FILE_URL = null;
String url;
initOSS(endPoint, accessKeyId, accessKeySecret);
StringBuilder fileUrl = new StringBuilder();
try {
@@ -190,23 +194,23 @@ public class OssBootUtil {
fileDir = fileDir.concat("/");
}
fileDir = StrAttackFilter.filter(fileDir);
fileUrl = fileUrl.append(fileDir + fileName);
fileUrl.append(fileDir).append(fileName);
if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
FILE_URL = staticDomain + "/" + fileUrl;
url = staticDomain + File.separator + fileUrl;
} else {
FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
url = HTTPS_CONSTANT + bucketName + "." + endPoint + File.separator + fileUrl;
}
PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream());
// 设置权限(公开读)
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
if (result != null) {
log.info("------OSS文件上传成功------" + fileUrl);
log.info(OSS_UPLOAD_CONSTANT + fileUrl);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return FILE_URL;
return url;
}
/**
@@ -230,7 +234,7 @@ public class OssBootUtil {
if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
bucketUrl = staticDomain + "/" ;
} else {
bucketUrl = "https://" + newBucket + "." + endPoint + "/";
bucketUrl = HTTPS_CONSTANT + newBucket + "." + endPoint + "/";
}
url = url.replace(bucketUrl,"");
ossClient.deleteObject(newBucket, url);
@@ -317,22 +321,22 @@ public class OssBootUtil {
* @return
*/
public static String upload(InputStream stream, String relativePath) {
String FILE_URL = null;
String url;
String fileUrl = relativePath;
initOSS(endPoint, accessKeyId, accessKeySecret);
if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
FILE_URL = staticDomain + "/" + relativePath;
url = staticDomain + File.separator + relativePath;
} else {
FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
url = HTTPS_CONSTANT + bucketName + "." + endPoint + File.separator + fileUrl;
}
PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(),stream);
PutObjectResult result = ossClient.putObject(bucketName, fileUrl,stream);
// 设置权限(公开读)
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
if (result != null) {
log.info("------OSS文件上传成功------" + fileUrl);
log.info(OSS_UPLOAD_CONSTANT + fileUrl);
}
return FILE_URL;
return url;
}
}
}
@@ -8,12 +8,16 @@ import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson.JSON;
import com.jero.common.util.security.entity.*;
import com.alibaba.fastjson.JSONObject;
import javax.crypto.SecretKey;
import java.security.KeyPair;
public class SecurityTools {
private SecurityTools(){
}
public static final String ALGORITHM = "AES/ECB/PKCS5Padding";
public static SecurityResp valid(SecurityReq req) {
@@ -28,12 +32,10 @@ public class SecurityTools {
byte[] decryptAes = rsa.decrypt(aesKey, KeyType.PublicKey);
//log.info("rsa解密后的秘钥"+ Base64Encoder.encode(decryptAes));
AES aes = SecureUtil.aes(decryptAes);
String dencrptValue =aes.decryptStr(data);
//log.info("解密后报文"+dencrptValue);
resp.setData(JSONObject.parseObject(dencrptValue));
resp.setData(JSON.parseObject(dencrptValue));
boolean verify = sign.verify(dencrptValue.getBytes(), Base64Decoder.decode(signData));
resp.setSuccess(verify);
@@ -51,13 +53,10 @@ public class SecurityTools {
String encrptData =aes.encryptBase64(data);
RSA rsa=new RSA(prikey,null);
byte[] encryptAesKey = rsa.encrypt(secretKey.getEncoded(), KeyType.PrivateKey);
//log.info(("rsa加密过的秘钥=="+Base64Encoder.encode(encryptAesKey));
Sign sign= new Sign(SignAlgorithm.SHA1withRSA,prikey,null);
byte[] signed = sign.sign(data.getBytes());
//log.info(("签名数据===》》"+Base64Encoder.encode(signed));
SecuritySignResp resp=new SecuritySignResp();
resp.setAesKey(Base64Encoder.encode(encryptAesKey));
resp.setData(encrptData);
@@ -4,14 +4,18 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
/**
* 判断类型追加查询规则
*
*
* @Author Scott
* @Date 2019年02月14日
*/
public class ObjectParseUtil {
private ObjectParseUtil(){
}
/**
*
*
* @param queryWrapper QueryWrapper
* @param name 字段名字
* @param rule 查询规则
@@ -17,9 +17,9 @@ import java.util.List;
* 举例 @Excel(name = "性别", width = 15, dicCode = "sex")
* 1导出的时候会根据字典配置把值1,2翻译成;
* 2导入的时候会把男女翻译成1,2存进数据库;
*
* @Author:scott
* @since2019-04-09
*
* @Author:scott
* @since2019-04-09
* @Version:1.0
*/
@Slf4j
@@ -31,14 +31,14 @@ public class AutoPoiDictConfig implements AutoPoiDictServiceI {
/**
* 通过字典查询easypoi所需字典文本
*
* @Author:scott
*
* @Author:scott
* @since2019-04-09
* @return
*/
@Override
public String[] queryDict(String dicTable, String dicCode, String dicText) {
List<String> dictReplaces = new ArrayList<String>();
List<String> dictReplaces = new ArrayList<>();
List<DictModel> dictList = null;
// step.1 如果没有字典表则使用系统字典表
if (oConvertUtils.isEmpty(dicTable)) {
@@ -56,10 +56,10 @@ public class AutoPoiDictConfig implements AutoPoiDictServiceI {
dictReplaces.add(t.getText() + "_" + t.getValue());
}
}
if (dictReplaces != null && dictReplaces.size() != 0) {
if (!dictReplaces.isEmpty()) {
log.info("---AutoPoi--Get_DB_Dict------"+ dictReplaces.toString());
return dictReplaces.toArray(new String[dictReplaces.size()]);
}
return null;
return new String[0];
}
}
@@ -14,9 +14,6 @@ public class CorsFilterCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Object object = context.getEnvironment().getProperty(CommonConstant.CLOUD_SERVER_KEY);
//如果没有服务注册发现的配置 说明是单体应用 则加载跨域配置 返回true
if(object==null){
return true;
}
return false;
return object == null;
}
}
@@ -2,20 +2,17 @@ package com.jero.config;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jero.common.api.vo.Result;
import com.jero.common.api.vo.Results;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@@ -28,6 +25,8 @@ import java.util.List;
@Component
public class CsrfFilter implements Filter {
private static final String UNKNOWN_CONSTANT = "unknown";
/**
* LOGGER
*/
@@ -67,7 +66,7 @@ public class CsrfFilter implements Filter {
log = "跨站请求---->>>" + ip + "||" + date + "||" + referurl + "||" + url;
LOGGER.warn(log);
//发送错误信息
JSONObject json = JSONUtil.parseObj(Result.error("监测到跨站请求,请求失败"), false);
JSONObject json = JSONUtil.parseObj(Results.error("监测到跨站请求,请求失败"), false);
res.setCharacterEncoding("UTF-8");
res.setContentType("application/json; charset=utf-8");
PrintWriter out = res.getWriter();
@@ -106,13 +105,13 @@ public class CsrfFilter implements Filter {
*/
public String getIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || UNKNOWN_CONSTANT.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || UNKNOWN_CONSTANT.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || UNKNOWN_CONSTANT.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip.equals("0:0:0:0:0:0:0:1")) {
@@ -122,6 +121,6 @@ public class CsrfFilter implements Filter {
}
@Override
public void destroy() {
// do other
}
}
@@ -47,7 +47,7 @@ public class DruidConfig {
DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
// 提取common.js的配置路径
String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
String commonJsPattern = pattern.replace("*", "js/common.js");
// 获取common.js
String text = Utils.readFromResource(FILE_PATH);
// 屏蔽 this.buildFooter(); 不构建广告
@@ -14,9 +14,6 @@ public class JeroCloudCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Object object = context.getEnvironment().getProperty(CommonConstant.CLOUD_SERVER_KEY);
//如果没有服务注册发现的配置 说明是单体应用
if(object==null){
return false;
}
return true;
return object != null;
}
}
@@ -25,12 +25,4 @@ public class StaticConfig {
*/
@Value(value = "${jero.signatureSecret}")
private String signatureSecret;
/*@Bean
public void initStatic() {
DySmsHelper.setAccessKeyId(accessKeyId);
DySmsHelper.setAccessKeySecret(accessKeySecret);
EmailSendMsgHandle.setEmailFrom(emailFrom);
}*/
}
@@ -2,13 +2,10 @@ package com.jero.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import com.jero.common.constant.CommonConstant;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
@@ -70,7 +67,6 @@ public class Swagger2Config implements WebMvcConfigurer {
.build()
.securitySchemes(Collections.singletonList(securityScheme()))
.securityContexts(securityContexts());
//.globalOperationParameters(setHeaderToken());
}
/***
@@ -86,7 +82,9 @@ public class Swagger2Config implements WebMvcConfigurer {
/**
* JWT token
* @return
* @deprecated 未调用
*/
@Deprecated
private List<Parameter> setHeaderToken() {
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
@@ -120,7 +118,7 @@ public class Swagger2Config implements WebMvcConfigurer {
* 新增 securityContexts 保持登录状态
*/
private List<SecurityContext> securityContexts() {
return new ArrayList(
return new ArrayList<>(
Collections.singleton(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
@@ -132,7 +130,7 @@ public class Swagger2Config implements WebMvcConfigurer {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return new ArrayList(
return new ArrayList<>(
Collections.singleton(new SecurityReference(CommonConstant.X_ACCESS_TOKEN, authorizationScopes)));
}
@@ -1,18 +1,13 @@
package com.jero.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.trace.http.InMemoryHttpTraceRepository;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@@ -90,14 +85,4 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
converters.add(jackson2HttpMessageConverter);
}
// /**
// * SpringBootAdmin的Httptrace不见了
// * https://blog.csdn.net/u013810234/article/details/110097201
// */
// @Bean
// public InMemoryHttpTraceRepository getInMemoryHttpTrace(){
// return new InMemoryHttpTraceRepository();
// }
}
@@ -10,6 +10,7 @@ import org.apache.shiro.SecurityUtils;
import com.jero.common.system.vo.LoginUser;
import com.jero.common.util.oConvertUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.util.Date;
@@ -41,54 +42,11 @@ public class MybatisInterceptor implements Interceptor {
if (SqlCommandType.INSERT == sqlCommandType) {
LoginUser sysUser = this.getLoginUser();
Field[] fields = oConvertUtils.getAllFields(parameter);
for (Field field : fields) {
log.debug("------field.name------" + field.getName());
try {
if ("createBy".equals(field.getName())) {
field.setAccessible(true);
Object local_createBy = field.get(parameter);
field.setAccessible(false);
if (local_createBy == null || local_createBy.equals("")) {
if (sysUser != null) {
// 登录人账号
field.setAccessible(true);
field.set(parameter, sysUser.getUsername());
field.setAccessible(false);
}
}
}
// 注入创建时间
if ("createTime".equals(field.getName())) {
field.setAccessible(true);
Object local_createDate = field.get(parameter);
field.setAccessible(false);
if (local_createDate == null || local_createDate.equals("")) {
field.setAccessible(true);
field.set(parameter, new Date());
field.setAccessible(false);
}
}
//注入部门编码
if ("sysOrgCode".equals(field.getName())) {
field.setAccessible(true);
Object local_sysOrgCode = field.get(parameter);
field.setAccessible(false);
if (local_sysOrgCode == null || local_sysOrgCode.equals("")) {
// 获取登录用户信息
if (sysUser != null) {
field.setAccessible(true);
field.set(parameter, sysUser.getOrgCode());
field.setAccessible(false);
}
}
}
} catch (Exception e) {
}
}
setInsert(parameter, sysUser, fields);
}
if (SqlCommandType.UPDATE == sqlCommandType) {
LoginUser sysUser = this.getLoginUser();
Field[] fields = null;
Field[] fields;
if (parameter instanceof ParamMap) {
ParamMap<?> p = (ParamMap<?>) parameter;
//update-begin-author:scott date:20190729 for:批量更新报错issues/IZA3Q--
@@ -110,31 +68,73 @@ public class MybatisInterceptor implements Interceptor {
fields = oConvertUtils.getAllFields(parameter);
}
for (Field field : fields) {
log.debug("------field.name------" + field.getName());
try {
if ("updateBy".equals(field.getName())) {
//获取登录用户信息
if (sysUser != null) {
// 登录账号
field.setAccessible(true);
field.set(parameter, sysUser.getUsername());
field.setAccessible(false);
}
}
if ("updateTime".equals(field.getName())) {
field.setAccessible(true);
field.set(parameter, new Date());
field.setAccessible(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
setUpdateField(parameter, sysUser, fields);
}
return invocation.proceed();
}
private void setUpdateField(Object parameter, LoginUser sysUser, Field[] fields) {
for (Field field : fields) {
log.debug("------field.name------" + field.getName());
try {
if ("updateBy".equals(field.getName()) && sysUser != null) {
//获取登录用户信息
// 登录账号
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field,parameter,sysUser.getUsername());
}
if ("updateTime".equals(field.getName())) {
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field,parameter,new Date());
}
} catch (Exception e) {
log.error("异常", e);
}
}
}
private void setInsert(Object parameter, LoginUser sysUser, Field[] fields) {
for (Field field : fields) {
log.debug("------field.name------" + field.getName());
setInsertField(parameter, sysUser, field);
}
}
private void setInsertField(Object parameter, LoginUser sysUser, Field field) {
try {
if ("createBy".equals(field.getName()) && sysUser != null) {
ReflectionUtils.makeAccessible(field);
Object localCreateBy = ReflectionUtils.getField(field,parameter);
if (localCreateBy == null || "".equals(localCreateBy)) {
// 登录人账号
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field,parameter,sysUser.getUsername());
}
}
// 注入创建时间
if ("createTime".equals(field.getName())) {
ReflectionUtils.makeAccessible(field);
Object localCreateDate = ReflectionUtils.getField(field,parameter);
if (localCreateDate == null || "".equals(localCreateDate)) {
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field,parameter,new Date());
}
}
//注入部门编码
if ("sysOrgCode".equals(field.getName()) && sysUser != null) {
ReflectionUtils.makeAccessible(field);
Object localSysOrgCode = ReflectionUtils.getField(field,parameter);
if (localSysOrgCode == null || "".equals(localSysOrgCode)) {
// 获取登录用户信息
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field,parameter,sysUser.getOrgCode());
}
}
} catch (Exception e) {
log.error("异常", e);
}
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
@@ -142,7 +142,7 @@ public class MybatisInterceptor implements Interceptor {
@Override
public void setProperties(Properties properties) {
// TODO Auto-generated method stub
// Auto-generated method stub
}
//update-begin--Author:scott Date:20191213 for关于使用Quzrtz 开启线程任务 #465
@@ -151,7 +151,6 @@ public class MybatisInterceptor implements Interceptor {
try {
sysUser = SecurityUtils.getSubject().getPrincipal() != null ? (LoginUser) SecurityUtils.getSubject().getPrincipal() : null;
} catch (Exception e) {
//e.printStackTrace();
sysUser = null;
}
return sysUser;
@@ -29,7 +29,7 @@ public class MybatisPlusSaasConfig {
/**
* 哪些表需要做多租户 表需要添加一个字段 tenant_id
*/
private static final List<String> tenantTable = new ArrayList<String>();
private static final List<String> tenantTable = new ArrayList<>();
static {
tenantTable.add("demo");
@@ -43,8 +43,8 @@ public class MybatisPlusSaasConfig {
interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
@Override
public Expression getTenantId() {
String tenant_id = oConvertUtils.getString(TenantContext.getTenant(),"0");
return new LongValue(tenant_id);
String tenantId = oConvertUtils.getString(TenantContext.getTenant(),"0");
return new LongValue(tenantId);
}
@Override
@@ -8,6 +8,10 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TenantContext {
private TenantContext(){
}
private static ThreadLocal<String> currentTenant = new ThreadLocal<>();
public static void setTenant(String tenant) {
@@ -22,4 +26,4 @@ public class TenantContext {
public static void clear(){
currentTenant.remove();
}
}
}
@@ -1,5 +1,6 @@
package com.jero.config.shiro;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationToken;
/**
@@ -7,20 +8,22 @@ import org.apache.shiro.authc.AuthenticationToken;
* @create 2018-07-12 15:19
* @desc
**/
@Slf4j
public class JwtToken implements AuthenticationToken {
private static final long serialVersionUID = 1L;
private String token;
public JwtToken(String token) {
this.token = token;
}
@Override
public Object getPrincipal() {
log.info("实现重复");
return token;
}
@Override
public Object getCredentials() {
return token;
@@ -1,5 +1,9 @@
package com.jero.config.shiro;
import com.jero.common.constant.CommonConstant;
import com.jero.common.util.oConvertUtils;
import com.jero.config.shiro.filters.CustomShiroFilterFactoryBean;
import com.jero.config.shiro.filters.JwtFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
@@ -13,17 +17,13 @@ import org.crazycake.shiro.IRedisManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisClusterManager;
import org.crazycake.shiro.RedisManager;
import com.jero.common.constant.CommonConstant;
import com.jero.common.util.oConvertUtils;
import com.jero.config.shiro.filters.CustomShiroFilterFactoryBean;
import com.jero.config.shiro.filters.JwtFilter;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
@@ -47,7 +47,7 @@ public class ShiroConfig {
private String excludeUrls;
@Resource
LettuceConnectionFactory lettuceConnectionFactory;
@Autowired
@Resource
private Environment env;
@@ -63,7 +63,7 @@ public class ShiroConfig {
CustomShiroFilterFactoryBean shiroFilterFactoryBean = new CustomShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 拦截器
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
if(oConvertUtils.isNotEmpty(excludeUrls)){
String[] permissionUrl = excludeUrls.split(",");
for(String url : permissionUrl){
@@ -134,7 +134,7 @@ public class ShiroConfig {
filterChainDefinitionMap.put("/actuator/**", "anon");
// 添加自己的过滤器并且取名为jwt
Map<String, Filter> filterMap = new HashMap<String, Filter>(1);
Map<String, Filter> filterMap = new HashMap<>(1);
//如果cloudServer为空 则说明是单体 需要加载跨域配置微服务跨域切换
Object cloudServer = env.getProperty(CommonConstant.CLOUD_SERVER_KEY);
filterMap.put("jwt", new JwtFilter(cloudServer==null));
@@ -227,7 +227,8 @@ public class ShiroConfig {
log.info("===============(2)创建RedisManager,连接Redis..");
IRedisManager manager;
// redis 单机支持在集群为空或者集群无机器时候使用 add by jzyadmin@163.com
if (lettuceConnectionFactory.getClusterConfiguration() == null || lettuceConnectionFactory.getClusterConfiguration().getClusterNodes().isEmpty()) {
RedisClusterConfiguration redisClusterConfiguration = lettuceConnectionFactory.getClusterConfiguration();
if (lettuceConnectionFactory.getClusterConfiguration() == null || (!Objects.isNull(redisClusterConfiguration) && redisClusterConfiguration.getClusterNodes().isEmpty())) {
RedisManager redisManager = new RedisManager();
redisManager.setHost(lettuceConnectionFactory.getHostName());
redisManager.setPort(lettuceConnectionFactory.getPort());
@@ -241,11 +242,13 @@ public class ShiroConfig {
// redis集群支持优先使用集群配置
RedisClusterManager redisManager = new RedisClusterManager();
Set<HostAndPort> portSet = new HashSet<>();
lettuceConnectionFactory.getClusterConfiguration().getClusterNodes().forEach(node -> portSet.add(new HostAndPort(node.getHost() , node.getPort())));
if(!Objects.isNull(redisClusterConfiguration)){
redisClusterConfiguration.getClusterNodes().forEach(node -> portSet.add(new HostAndPort(node.getHost() , node.getPort())));
}
//update-begin--Author:scott Date:20210531 for修改集群模式下未设置redis密码的bug issues/I3QNIC
if (oConvertUtils.isNotEmpty(lettuceConnectionFactory.getPassword())) {
JedisCluster jedisCluster = new JedisCluster(portSet, 2000, 2000, 5,
lettuceConnectionFactory.getPassword(), new GenericObjectPoolConfig());
lettuceConnectionFactory.getPassword(), new GenericObjectPoolConfig<>());
redisManager.setPassword(lettuceConnectionFactory.getPassword());
redisManager.setJedisCluster(jedisCluster);
} else {
@@ -69,13 +69,11 @@ public class ShiroRealm extends AuthorizingRealm {
// 设置用户拥有的角色集合比如admin,test
Set<String> roleSet = commonAPI.queryUserRoles(username);
System.out.println(roleSet.toString());
info.setRoles(roleSet);
// 设置用户拥有的权限集合比如sys:role:add,sys:user:add
Set<String> permissionSet = commonAPI.queryUserAuths(username);
info.addStringPermissions(permissionSet);
System.out.println(permissionSet);
log.info("===============Shiro权限认证成功==============");
return info;
}
@@ -131,10 +129,8 @@ public class ShiroRealm extends AuthorizingRealm {
String userTenantIds = loginUser.getRelTenantIds();
if(oConvertUtils.isNotEmpty(userTenantIds)){
String contextTenantId = TenantContext.getTenant();
if(oConvertUtils.isNotEmpty(contextTenantId) && !"0".equals(contextTenantId)){
if(String.join(",",userTenantIds).indexOf(contextTenantId)<0){
throw new AuthenticationException("用户租户信息变更,请重新登陆!");
}
if(oConvertUtils.isNotEmpty(contextTenantId) && !"0".equals(contextTenantId) && !String.join(",", userTenantIds).contains(contextTenantId)){
throw new AuthenticationException("用户租户信息变更,请重新登陆!");
}
}
//update-end-author:taoyan date:20210609 for:校验用户的tenant_id和前端传过来的是否一致
@@ -94,8 +94,8 @@ public class JwtFilter extends BasicHttpAuthenticationFilter {
return false;
}
//update-begin-author:taoyan date:20200708 for:多租户用到
String tenant_id = httpServletRequest.getHeader(CommonConstant.TENANT_ID);
TenantContext.setTenant(tenant_id);
String tenantId = httpServletRequest.getHeader(CommonConstant.TENANT_ID);
TenantContext.setTenant(tenantId);
//update-end-author:taoyan date:20200708 for:多租户用到
return super.preHandle(request, response);
}
@@ -6,7 +6,7 @@ import java.util.SortedMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jero.common.api.vo.Result;
import com.jero.common.api.vo.Results;
import com.jero.common.constant.CommonConstant;
import com.jero.common.util.DateUtils;
import com.jero.config.sign.util.BodyReaderHttpServletRequestWrapper;
@@ -27,7 +27,7 @@ public class SignAuthInterceptor implements HandlerInterceptor {
/**
* 5分钟有效期
*/
private final static long MAX_EXPIRE = 5 * 60;
private static final long MAX_EXPIRE = 5 * 60L;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
@@ -64,7 +64,7 @@ public class SignAuthInterceptor implements HandlerInterceptor {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = response.getWriter();
Result<?> result = Result.error("Sign签名校验失败!");
Results<?> result = Results.error("Sign签名校验失败!");
out.print(JSON.toJSON(result));
return false;
}
@@ -6,11 +6,11 @@ import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* 保存过滤器里面的流
*
*
* @author jero
* @date 20210621
*/
@@ -22,7 +22,7 @@ public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapp
super(request);
String sessionStream = getBodyString(request);
body = sessionStream.getBytes(Charset.forName("UTF-8"));
body = sessionStream.getBytes(StandardCharsets.UTF_8);
}
/**
@@ -35,7 +35,7 @@ public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapp
StringBuilder sb = new StringBuilder();
try (InputStream inputStream = cloneInputStream(request.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")))) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
@@ -100,8 +100,8 @@ public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapp
@Override
public void setReadListener(ReadListener readListener) {
// do other
}
};
}
}
}
@@ -1,8 +1,8 @@
package com.jero.config.sign.util;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import com.jero.common.util.oConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import javax.servlet.http.HttpServletRequest;
@@ -11,10 +11,7 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.*;
/**
* http 工具类 获取请求中的参数
@@ -25,6 +22,10 @@ import java.util.TreeMap;
@Slf4j
public class HttpUtils {
private HttpUtils(){
}
/**
* 将URL的参数和body参数合并
*
@@ -41,12 +42,12 @@ public class HttpUtils {
log.info(" pathVariable: {}",pathVariable);
String deString = URLDecoder.decode(pathVariable, "UTF-8");
log.info(" pathVariable decode: {}",deString);
result.put(SignUtil.xPathVariable, deString);
result.put(SignUtil.X_PATH_VARIABLE, deString);
}
// 获取URL上的参数
Map<String, String> urlParams = getUrlParams(request);
for (Map.Entry entry : urlParams.entrySet()) {
result.put((String)entry.getKey(), (String)entry.getValue());
for (Map.Entry<String, String> entry : urlParams.entrySet()) {
result.put(entry.getKey(), entry.getValue());
}
Map<String, String> allRequestParam = new HashMap<>(16);
// get请求不需要拿body参数
@@ -55,8 +56,8 @@ public class HttpUtils {
}
// 将URL的参数和body参数进行合并
if (allRequestParam != null) {
for (Map.Entry entry : allRequestParam.entrySet()) {
result.put((String)entry.getKey(), (String)entry.getValue());
for (Map.Entry<String, String> entry : allRequestParam.entrySet()) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
@@ -79,12 +80,12 @@ public class HttpUtils {
log.info(" pathVariable: {}",pathVariable);
String deString = URLDecoder.decode(pathVariable, "UTF-8");
log.info(" pathVariable decode: {}",deString);
result.put(SignUtil.xPathVariable, deString);
result.put(SignUtil.X_PATH_VARIABLE, deString);
}
// 获取URL上的参数
Map<String, String> urlParams = getUrlParams(queryString);
for (Map.Entry entry : urlParams.entrySet()) {
result.put((String)entry.getKey(), (String)entry.getValue());
for (Map.Entry<String, String> entry : urlParams.entrySet()) {
result.put(entry.getKey(), entry.getValue());
}
Map<String, String> allRequestParam = new HashMap<>(16);
// get请求不需要拿body参数
@@ -93,8 +94,8 @@ public class HttpUtils {
}
// 将URL的参数和body参数进行合并
if (allRequestParam != null) {
for (Map.Entry entry : allRequestParam.entrySet()) {
result.put((String)entry.getKey(), (String)entry.getValue());
for (Map.Entry<String, String> entry : allRequestParam.entrySet()) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
@@ -105,18 +106,19 @@ public class HttpUtils {
*
* @date 15:04 20210621
* @param request
* @return
*/
public static Map<String, String> getAllRequestParam(final HttpServletRequest request) throws IOException {
public static Map<String,String> getAllRequestParam(final HttpServletRequest request) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String str = "";
String str;
StringBuilder wholeStr = new StringBuilder();
// 一行一行的读取body体里面的内容
while ((str = reader.readLine()) != null) {
wholeStr.append(str);
}
// 转化成json对象
return JSONObject.parseObject(wholeStr.toString(), Map.class);
return JSON.parseObject(wholeStr.toString(), Map.class);
}
/**
@@ -125,13 +127,13 @@ public class HttpUtils {
* @date 15:04 20210621
* @param body
*/
public static Map<String, String> getAllRequestParam(final byte[] body) throws IOException {
public static Map<String, String> getAllRequestParam(final byte[] body){
if(body==null){
return null;
return Collections.emptyMap();
}
String wholeStr = new String(body);
// 转化成json对象
return JSONObject.parseObject(wholeStr.toString(), Map.class);
return JSON.parseObject(wholeStr, Map.class);
}
/**
@@ -160,7 +162,7 @@ public class HttpUtils {
/**
* 将URL请求参数转换成Map
*
*
* @param queryString
*/
public static Map<String, String> getUrlParams(String queryString) {
@@ -181,4 +183,4 @@ public class HttpUtils {
}
return result;
}
}
}
@@ -1,5 +1,6 @@
package com.jero.config.sign.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import com.jero.common.exception.JeroBootException;
@@ -8,18 +9,24 @@ import com.jero.common.util.oConvertUtils;
import com.jero.config.StaticConfig;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.SortedMap;
/**
* 签名工具类
*
*
* @author jeecg
* @date 20210621
*/
@Slf4j
public class SignUtil {
public static final String xPathVariable = "x-path-variable";
private SignUtil(){
}
public static final String X_PATH_VARIABLE = "x-path-variable";
/**
* @param params
@@ -44,7 +51,7 @@ public class SignUtil {
public static String getParamsSign(SortedMap<String, String> params) {
//去掉 Url 里的时间戳
params.remove("_t");
String paramsJsonStr = JSONObject.toJSONString(params);
String paramsJsonStr = JSON.toJSONString(params);
log.info("Param paramsJsonStr : {}", paramsJsonStr);
StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class);
String signatureSecret = staticConfig.getSignatureSecret();
@@ -53,4 +60,4 @@ public class SignUtil {
}
return DigestUtils.md5DigestAsHex((paramsJsonStr + signatureSecret).getBytes()).toUpperCase();
}
}
}
@@ -16,19 +16,19 @@ public interface BaseCommonService {
/**
* 保存日志
* @param LogContent
* @param logContent
* @param logType
* @param operateType
* @param user
*/
void addLog(String LogContent, Integer logType, Integer operateType, LoginUser user);
void addLog(String logContent, Integer logType, Integer operateType, LoginUser user);
/**
* 保存日志
* @param LogContent
* @param logContent
* @param logType
* @param operateType
*/
void addLog(String LogContent, Integer logType, Integer operateType);
void addLog(String logContent, Integer logType, Integer operateType);
}
@@ -64,7 +64,7 @@ public class BaseCommonServiceImpl implements BaseCommonService {
try {
user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
} catch (Exception e) {
//e.printStackTrace();
log.error("异常",e.getMessage());
}
}
if(user!=null){

Some files were not shown because too many files have changed in this diff Show More