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

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