3.2.0-beta,重构很大:升级springboot2.6.6、spring-cloud-alibaba 2021.1、mybatisplus3.5.1、代码规范部分重构

pull/3612/head
zhangdaiscott 2022-04-18 09:37:28 +08:00
parent 948e1668b6
commit 9dcff93372
487 changed files with 9754 additions and 2928 deletions

View File

@ -7,7 +7,7 @@
JEECG BOOT 低代码开发平台(前后端分离版本) JEECG BOOT 低代码开发平台(前后端分离版本)
=============== ===============
当前最新版本: 3.1.0发布日期2022-03-01 当前最新版本: 3.2.0-beta发布日期2022-04-18
[![AUR](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](https://github.com/zhangdaiscott/jeecg-boot/blob/master/LICENSE) [![AUR](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](https://github.com/zhangdaiscott/jeecg-boot/blob/master/LICENSE)
@ -132,13 +132,13 @@ Vue3版前端Beta版
#### 后端 #### 后端
- 基础框架Spring Boot 2.3.5.RELEASE - 基础框架Spring Boot 2.6.6
- 微服务框架: Spring Cloud Alibaba 2.2.3.RELEASE - 微服务框架: Spring Cloud Alibaba 2021.1
- 持久层框架MybatisPlus 3.4.3.1 - 持久层框架MybatisPlus 3.5.1
- 报表工具: JimuReport 1.4.32 - 报表工具: JimuReport 1.5.0-beta
- 安全框架Apache Shiro 1.8.0Jwt 3.11.0 - 安全框架Apache Shiro 1.8.0Jwt 3.11.0
@ -192,7 +192,7 @@ Vue3版前端Beta版
4、分布式 http feign √ 4、分布式 http feign √
5、熔断降级 Sentinel √ 5、熔断降级限流 Sentinel √
6、分布式文件 Minio、阿里OSS √ 6、分布式文件 Minio、阿里OSS √

View File

@ -1,15 +1,15 @@
Jeecg-Boot 低代码开发平台 Jeecg-Boot 低代码开发平台
=============== ===============
当前最新版本: 3.1.0发布日期20220301 当前最新版本: 3.2.0发布日期20220425
## 后端技术架构 ## 后端技术架构
- 基础框架Spring Boot 2.3.5.RELEASE - 基础框架Spring Boot 2.6.6
- 持久层框架Mybatis-plus 3.4.3.1 - 持久层框架Mybatis-plus 3.5.1
- 安全框架Apache Shiro 1.7.0Jwt 3.11.0 - 安全框架Apache Shiro 1.8.0Jwt 3.11.0
- 数据库连接池阿里巴巴Druid 1.1.22 - 数据库连接池阿里巴巴Druid 1.1.22

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,39 +0,0 @@
-- 第三方用户表应该加上创建人,创建时间、修改人、修改时间
ALTER TABLE `sys_third_account`
ADD COLUMN `create_by` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人登录名称' AFTER `third_user_id`,
ADD COLUMN `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建日期' AFTER `create_by`,
ADD COLUMN `update_by` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '更新人登录名称' AFTER `create_time`,
ADD COLUMN `update_time` datetime(0) NULL DEFAULT NULL COMMENT '更新日期' AFTER `update_by`;
-- online 表单字段db类型区分年月日和年月日时分秒
UPDATE onl_cgform_field SET db_type = 'Datetime' where db_type = 'Date';
-- 对象存储字段太短
ALTER TABLE `oss_file`
MODIFY COLUMN `url` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件地址' AFTER `file_name`;
-- 地址获取到多个地址, 地址过长导致权限菜单修改失败
ALTER TABLE `sys_role_permission`
MODIFY COLUMN `operate_ip` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '操作ip' AFTER `operate_date`;
-- 修改 sys_permission 下的两个字段为 tinyint 类型
ALTER TABLE `sys_permission`
MODIFY COLUMN `hidden` tinyint(1) NULL DEFAULT 0 COMMENT '是否隐藏路由: 0否,1是' AFTER `keep_alive`,
MODIFY COLUMN `hide_tab` tinyint(1) NULL DEFAULT NULL COMMENT '是否隐藏tab: 0否,1是' AFTER `hidden`;
-- 默认示例内嵌百度改成jeecg.com官网
UPDATE sys_permission SET name = 'JEECG官方网站' , url = 'http://www.jeecg.com' WHERE id = 'a400e4f4d54f79bf5ce160ae432231af';
-- 菜单名和代码改名 erp风格
UPDATE `sys_permission` SET `parent_id` = '2a470fc0c3954d9dbb61de6d80846549', `name` = '一对多erp风格示例', `url` = '/jeecg/tablist/JeecgOrderDMainList', `component` = 'jeecg/tablist/JeecgOrderDMainList', `component_name` = NULL, `redirect` = NULL, `menu_type` = 1, `perms` = NULL, `perms_type` = NULL, `sort_no` = 2.00, `always_show` = 0, `icon` = NULL, `is_route` = 1, `is_leaf` = 1, `keep_alive` = 0, `hidden` = 0, `description` = NULL, `status` = NULL, `del_flag` = 0, `rule_flag` = 0, `create_by` = 'admin', `create_time` = '2019-02-20 14:45:09', `update_by` = 'admin', `update_time` = '2022-01-17 17:02:51', `internal_or_external` = 0, `hide_tab` = '0' WHERE `id` = '6ad53fd1b220989a8b71ff482d683a5a';
-- 分类字典 列表页 显示数据id
UPDATE sys_category SET code='B01-2-3' WHERE id='1404629269499936770';
UPDATE sys_category SET code='B01-2-2' WHERE id='937fd2e9aa13b8bab1da1ca36d3fd344';
-- 新的表格合计菜单
INSERT INTO `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`, `status`, `del_flag`, `rule_flag`, `create_by`, `create_time`, `update_by`, `update_time`, `internal_or_external`, `hide_tab`) VALUES ('1494641317580423169', '2a470fc0c3954d9dbb61de6d80846549', '表格合计News', '/jeecg/tableOrderTotal', 'jeecg/TableOrderTotal', NULL, NULL, 1, NULL, '1', 3.00, 0, NULL, 1, 1, 0, 0, NULL, '1', 0, 0, 'admin', '2022-02-18 19:53:54', 'admin', '2022-02-18 19:55:04', 0, '0');
-- online老数据,存在字符串类型key值不一致的情况,String改为string
UPDATE onl_cgform_field SET db_type = 'string' where binary db_type = 'String';

View File

@ -0,0 +1,16 @@
-- ----------------------------
-- Table structure for sys_role_index
-- ----------------------------
CREATE TABLE `sys_role_index` (
`id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`role_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色编码',
`url` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '路由地址',
`priority` int(11) NULL DEFAULT 0 COMMENT '优先级',
`status` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '0' COMMENT '状态0:无效 1:有效',
`create_by` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人登录名称',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建日期',
`update_by` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '更新人登录名称',
`update_time` datetime NULL DEFAULT NULL COMMENT '更新日期',
`sys_org_code` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '所属部门',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '角色首页表' ROW_FORMAT = Dynamic;

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>jeecg-boot-base-api</artifactId> <artifactId>jeecg-boot-base-api</artifactId>
<groupId>org.jeecgframework.boot</groupId> <groupId>org.jeecgframework.boot</groupId>
<version>3.1.0</version> <version>3.2.0</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -1,89 +0,0 @@
package org.jeecg.common.bpm.api;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.ServiceNameConstants;
import org.jeecg.common.online.api.factory.OnlineBaseExtAPIFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
*
*
* @author scott
*/
@Component
@FeignClient(contextId = "bpmBaseRemoteApi", value = ServiceNameConstants.SYSTEM_SERVICE,
fallbackFactory = OnlineBaseExtAPIFallbackFactory.class)
public interface IBpmBaseExtAPI {
/**
* 23. online
*
* @param flowCode
* joa_leave_01
* @param id
* data id
* @param formUrl
* PC
* @param formUrlMobile
*
* @param username
*
* @param jsonData
* Json
* @return
* @throws Exception
*/
@PostMapping(value = "/act/process/extActProcess/startMutilProcess")
Result<String> startMutilProcess(@RequestParam("flowCode") String flowCode, @RequestParam("id") String id,
@RequestParam("formUrl") String formUrl, @RequestParam("formUrlMobile") String formUrlMobile,
@RequestParam("username") String username, @RequestParam("jsonData") String jsonData) throws Exception;
/**
* 24.
*
* @param flowCode
* joa_leave_01
* @param id
* data id
* @param formUrl
* PC
* @param formUrlMobile
*
* @param username
*
* @param jsonData
* Json
* @return
* @throws Exception
*/
@PostMapping(value = "/act/process/extActProcess/startDesFormMutilProcess")
Result<String> startDesFormMutilProcess(@RequestParam("flowCode") String flowCode, @RequestParam("id") String id,
@RequestParam("formUrl") String formUrl, @RequestParam("formUrlMobile") String formUrlMobile,
@RequestParam("username") String username, @RequestParam("jsonData") String jsonData) throws Exception;
/**
* 25. 稿online
*
* @param flowCode
* joa_leave_01
* @param id
* data id
* @param formUrl
* PC
* @param formUrlMobile
*
* @param username
*
* @param jsonData
* Json
* @return
* @throws Exception
*/
@PostMapping(value = "/act/process/extActProcess/saveMutilProcessDraft")
Result<String> saveMutilProcessDraft(@RequestParam("flowCode") String flowCode, @RequestParam("id") String id,
@RequestParam("formUrl") String formUrl, @RequestParam("formUrlMobile") String formUrlMobile,
@RequestParam("username") String username, @RequestParam("jsonData") String jsonData) throws Exception;
}

View File

@ -1,18 +0,0 @@
package org.jeecg.common.bpm.api.factory;
import org.jeecg.common.bpm.api.IBpmBaseExtAPI;
import org.jeecg.common.bpm.api.fallback.BpmBaseExtAPIFallback;
import org.springframework.stereotype.Component;
import feign.hystrix.FallbackFactory;
@Component
public class BpmBaseExtAPIFallbackFactory implements FallbackFactory<IBpmBaseExtAPI> {
@Override
public IBpmBaseExtAPI create(Throwable throwable) {
BpmBaseExtAPIFallback fallback = new BpmBaseExtAPIFallback();
fallback.setCause(throwable);
return fallback;
}
}

View File

@ -1,42 +0,0 @@
package org.jeecg.common.bpm.api.fallback;
import java.util.List;
import java.util.Map;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.bpm.api.IBpmBaseExtAPI;
import org.jeecg.common.online.api.IOnlineBaseExtAPI;
import org.jeecg.common.system.vo.DictModel;
import com.alibaba.fastjson.JSONObject;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
/**
* fallback token
*/
@Slf4j
public class BpmBaseExtAPIFallback implements IBpmBaseExtAPI {
@Setter
private Throwable cause;
@Override
public Result<String> startMutilProcess(String flowCode, String id, String formUrl, String formUrlMobile,
String username, String jsonData) throws Exception {
return null;
}
@Override
public Result<String> startDesFormMutilProcess(String flowCode, String id, String formUrl, String formUrlMobile,
String username, String jsonData) throws Exception {
return null;
}
@Override
public Result<String> saveMutilProcessDraft(String flowCode, String id, String formUrl, String formUrlMobile,
String username, String jsonData) throws Exception {
return null;
}
}

View File

@ -1,73 +0,0 @@
package org.jeecg.common.online.api;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.constant.ServiceNameConstants;
import org.jeecg.common.online.api.factory.OnlineBaseExtAPIFallbackFactory;
import org.jeecg.common.system.vo.DictModel;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* OnlineFeign API
*/
@Component
@FeignClient(contextId = "onlineBaseRemoteApi", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = OnlineBaseExtAPIFallbackFactory.class)
//@FeignClient(contextId = "onlineBaseRemoteApi", value = ServiceNameConstants.SYSTEM_ONLINE, fallbackFactory = OnlineBaseExtAPIFallbackFactory.class)
public interface IOnlineBaseExtAPI {
/**
* Online
*/
@PostMapping(value = "/online/api/cgform/crazyForm/{name}")
String cgformPostCrazyForm(@PathVariable("name") String tableName, @RequestBody JSONObject jsonObject) throws Exception;
/**
* Online
*/
@PutMapping(value = "/online/api/cgform/crazyForm/{name}")
String cgformPutCrazyForm(@PathVariable("name") String tableName, @RequestBody JSONObject jsonObject) throws Exception;
/**
* online
*
* @param tableName online
* @param dataIds onlineID
* @return
*/
@GetMapping(value = "/online/api/cgform/queryAllDataByTableName")
JSONObject cgformQueryAllDataByTableName(@RequestParam("tableName") String tableName, @RequestParam("dataIds") String dataIds);
/**
* online
*
* @param cgformCode Onlinecode
* @param dataIds ID
* @return
*/
@DeleteMapping("/online/api/cgform/cgformDeleteDataByCode")
String cgformDeleteDataByCode(@RequestParam("cgformCode") String cgformCode, @RequestParam("dataIds") String dataIds);
/**
* cgreport head code sql
*
* @param code CodeIDcode
* @param forceKey
* @param dataList
* @return
*/
@GetMapping("/online/api/cgreportGetData")
Map<String, Object> cgreportGetData(@RequestParam("code") String code, @RequestParam("forceKey") String forceKey, @RequestParam("dataList") String dataList);
/**
* cgreport cgreportGetData DictModel
*
* @return
*/
@GetMapping("/online/api/cgreportGetDataPackage")
List<DictModel> cgreportGetDataPackage(@RequestParam("code") String code, @RequestParam("dictText") String dictText, @RequestParam("dictCode") String dictCode, @RequestParam("dataList") String dataList);
}

View File

@ -1,17 +0,0 @@
package org.jeecg.common.online.api.factory;
import feign.hystrix.FallbackFactory;
import org.jeecg.common.online.api.IOnlineBaseExtAPI;
import org.jeecg.common.online.api.fallback.OnlineBaseExtAPIFallback;
import org.springframework.stereotype.Component;
@Component
public class OnlineBaseExtAPIFallbackFactory implements FallbackFactory<IOnlineBaseExtAPI> {
@Override
public IOnlineBaseExtAPI create(Throwable throwable) {
OnlineBaseExtAPIFallback fallback = new OnlineBaseExtAPIFallback();
fallback.setCause(throwable);
return fallback;
}
}

View File

@ -1,51 +0,0 @@
package org.jeecg.common.online.api.fallback;
import com.alibaba.fastjson.JSONObject;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.online.api.IOnlineBaseExtAPI;
import org.jeecg.common.system.vo.DictModel;
import java.util.List;
import java.util.Map;
/**
* fallback token
*/
@Slf4j
public class OnlineBaseExtAPIFallback implements IOnlineBaseExtAPI {
@Setter
private Throwable cause;
@Override
public String cgformPostCrazyForm(String tableName, JSONObject jsonObject) {
return null;
}
@Override
public String cgformPutCrazyForm(String tableName, JSONObject jsonObject) {
return null;
}
@Override
public JSONObject cgformQueryAllDataByTableName(String tableName, String dataIds) {
return null;
}
@Override
public String cgformDeleteDataByCode(String cgformCode, String dataIds) {
return null;
}
@Override
public Map<String, Object> cgreportGetData(String code, String forceKey, String dataList) {
return null;
}
@Override
public List<DictModel> cgreportGetDataPackage(String code, String dictText, String dictCode, String dataList) {
return null;
}
}

View File

@ -7,6 +7,7 @@ import org.jeecg.common.api.dto.message.*;
import org.jeecg.common.constant.ServiceNameConstants; import org.jeecg.common.constant.ServiceNameConstants;
import org.jeecg.common.system.api.factory.SysBaseAPIFallbackFactory; import org.jeecg.common.system.api.factory.SysBaseAPIFallbackFactory;
import org.jeecg.common.system.vo.*; import org.jeecg.common.system.vo.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -16,18 +17,17 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
* local
*
* addLog getDatabaseType queryAllDepart
* queryAllUser(Wrapper wrapper) queryAllUser(String[] userIds, int pageNo, int pageSize)
*
* createLog
* sendSysAnnouncement
* *
* cloud43 local35 common9 queryAllRole * 1cloud43 local35 common9 queryAllRole
* - local
* - addLoggetDatabaseTypequeryAllDepartqueryAllUser(Wrapper wrapper)queryAllUser(String[] userIds, int pageNo, int pageSize)
* - createLogsendSysAnnouncement
* 2@ConditionalOnMissingClass("org.jeecg.modules.system.service.impl.SysBaseApiImpl")=> Feign
* @author: jeecg-boot
*/ */
@Component @Component
@FeignClient(contextId = "sysBaseRemoteApi", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = SysBaseAPIFallbackFactory.class) @FeignClient(contextId = "sysBaseRemoteApi", value = ServiceNameConstants.SERVICE_SYSTEM, fallbackFactory = SysBaseAPIFallbackFactory.class)
@ConditionalOnMissingClass("org.jeecg.modules.system.service.impl.SysBaseApiImpl")
public interface ISysBaseAPI extends CommonAPI { public interface ISysBaseAPI extends CommonAPI {
/** /**
@ -103,6 +103,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @param code * @param code
* @return * @return
*/ */
@Override
@GetMapping("/sys/api/queryDictItemsByCode") @GetMapping("/sys/api/queryDictItemsByCode")
List<DictModel> queryDictItemsByCode(@RequestParam("code") String code); List<DictModel> queryDictItemsByCode(@RequestParam("code") String code);
@ -111,10 +112,13 @@ public interface ISysBaseAPI extends CommonAPI {
* @param code * @param code
* @return * @return
*/ */
@Override
@GetMapping("/sys/api/queryEnableDictItemsByCode") @GetMapping("/sys/api/queryEnableDictItemsByCode")
public List<DictModel> queryEnableDictItemsByCode(@RequestParam("code") String code); public List<DictModel> queryEnableDictItemsByCode(@RequestParam("code") String code);
/** 11查询所有的父级字典按照create_time排序 */ /** 11create_time
* @return List<DictModel>
*/
@GetMapping("/sys/api/queryAllDict") @GetMapping("/sys/api/queryAllDict")
List<DictModel> queryAllDict(); List<DictModel> queryAllDict();
@ -122,8 +126,8 @@ public interface ISysBaseAPI extends CommonAPI {
* 12 * 12
* @return * @return
*/ */
@GetMapping("/sys/api/queryAllDSysCategory") @GetMapping("/sys/api/queryAllSysCategory")
List<SysCategoryModel> queryAllDSysCategory(); List<SysCategoryModel> queryAllSysCategory();
/** /**
* 13 * 13
@ -132,6 +136,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @param code * @param code
* @return * @return
*/ */
@Override
@GetMapping("/sys/api/queryTableDictItemsByCode") @GetMapping("/sys/api/queryTableDictItemsByCode")
List<DictModel> queryTableDictItemsByCode(@RequestParam("table") String table, @RequestParam("text") String text, @RequestParam("code") String code); List<DictModel> queryTableDictItemsByCode(@RequestParam("table") String table, @RequestParam("text") String text, @RequestParam("code") String code);
@ -144,6 +149,8 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 15 busType busId * 15 busType busId
* @param busType
* @param busId id
*/ */
@GetMapping("/sys/api/updateSysAnnounReadFlag") @GetMapping("/sys/api/updateSysAnnounReadFlag")
public void updateSysAnnounReadFlag(@RequestParam("busType") String busType, @RequestParam("busId")String busId); public void updateSysAnnounReadFlag(@RequestParam("busType") String busType, @RequestParam("busId")String busId);
@ -180,6 +187,9 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 19 JSONObject * 19 JSONObject
* @param userIds id
* @param pageNo
* @param pageSize
* @return * @return
*/ */
@GetMapping("/sys/api/queryAllUser") @GetMapping("/sys/api/queryAllUser")
@ -188,7 +198,7 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 20 * 20
* roleIds * @param roleIds
* @return * @return
*/ */
@GetMapping("/sys/api/queryAllRole") @GetMapping("/sys/api/queryAllRole")
@ -243,7 +253,7 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 27id * 27id
* userIds * @param userIds id
* @return * @return
*/ */
@GetMapping("/sys/api/queryAllUserByIds") @GetMapping("/sys/api/queryAllUserByIds")
@ -260,7 +270,7 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 29name * 29name
* userNames * @param userNames
* @return * @return
*/ */
@GetMapping("/sys/api/queryUserByNames") @GetMapping("/sys/api/queryUserByNames")
@ -293,6 +303,8 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 33id * 33id
* @param id id
* @return SysDepartModel
*/ */
@GetMapping("/sys/api/selectAllById") @GetMapping("/sys/api/selectAllById")
SysDepartModel selectAllById(@RequestParam("id") String id); SysDepartModel selectAllById(@RequestParam("id") String id);
@ -313,6 +325,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @param username * @param username
* @return * @return
*/ */
@Override
@GetMapping("/sys/api/queryUserRoles") @GetMapping("/sys/api/queryUserRoles")
Set<String> queryUserRoles(@RequestParam("username")String username); Set<String> queryUserRoles(@RequestParam("username")String username);
@ -321,6 +334,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @param username * @param username
* @return * @return
*/ */
@Override
@GetMapping("/sys/api/queryUserAuths") @GetMapping("/sys/api/queryUserAuths")
Set<String> queryUserAuths(@RequestParam("username")String username); Set<String> queryUserAuths(@RequestParam("username")String username);
@ -330,6 +344,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @param dbSourceId * @param dbSourceId
* @return * @return
*/ */
@Override
@GetMapping("/sys/api/getDynamicDbSourceById") @GetMapping("/sys/api/getDynamicDbSourceById")
DynamicDataSourceModel getDynamicDbSourceById(@RequestParam("dbSourceId") String dbSourceId); DynamicDataSourceModel getDynamicDbSourceById(@RequestParam("dbSourceId") String dbSourceId);
@ -339,13 +354,16 @@ public interface ISysBaseAPI extends CommonAPI {
* @param dbSourceCode * @param dbSourceCode
* @return * @return
*/ */
@Override
@GetMapping("/sys/api/getDynamicDbSourceByCode") @GetMapping("/sys/api/getDynamicDbSourceByCode")
DynamicDataSourceModel getDynamicDbSourceByCode(@RequestParam("dbSourceCode") String dbSourceCode); DynamicDataSourceModel getDynamicDbSourceByCode(@RequestParam("dbSourceCode") String dbSourceCode);
/** /**
* 39 CommonAPI * 39 CommonAPI
* @param username * @param username
* @return LoginUser
*/ */
@Override
@GetMapping("/sys/api/getUserByName") @GetMapping("/sys/api/getUserByName")
LoginUser getUserByName(@RequestParam("username") String username); LoginUser getUserByName(@RequestParam("username") String username);
@ -357,6 +375,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @param key * @param key
* @return * @return
*/ */
@Override
@GetMapping("/sys/api/translateDictFromTable") @GetMapping("/sys/api/translateDictFromTable")
String translateDictFromTable(@RequestParam("table") String table, @RequestParam("text") String text, @RequestParam("code") String code, @RequestParam("key") String key); String translateDictFromTable(@RequestParam("table") String table, @RequestParam("text") String text, @RequestParam("code") String code, @RequestParam("key") String key);
@ -366,13 +385,18 @@ public interface ISysBaseAPI extends CommonAPI {
* @param key * @param key
* @return * @return
*/ */
@Override
@GetMapping("/sys/api/translateDict") @GetMapping("/sys/api/translateDict")
String translateDict(@RequestParam("code") String code, @RequestParam("key") String key); String translateDict(@RequestParam("code") String code, @RequestParam("key") String key);
/** /**
* 42 * 42
* @param component
* @param requestPath
* @param username
* @return * @return
*/ */
@Override
@GetMapping("/sys/api/queryPermissionDataRule") @GetMapping("/sys/api/queryPermissionDataRule")
List<SysPermissionDataRuleModel> queryPermissionDataRule(@RequestParam("component") String component, @RequestParam("requestPath")String requestPath, @RequestParam("username") String username); List<SysPermissionDataRuleModel> queryPermissionDataRule(@RequestParam("component") String component, @RequestParam("requestPath")String requestPath, @RequestParam("username") String username);
@ -381,6 +405,7 @@ public interface ISysBaseAPI extends CommonAPI {
* @param username * @param username
* @return * @return
*/ */
@Override
@GetMapping("/sys/api/getCacheUser") @GetMapping("/sys/api/getCacheUser")
SysUserCacheInfo getCacheUser(@RequestParam("username") String username); SysUserCacheInfo getCacheUser(@RequestParam("username") String username);
@ -426,13 +451,16 @@ public interface ISysBaseAPI extends CommonAPI {
void sendEmailMsg(@RequestParam("email")String email,@RequestParam("title")String title,@RequestParam("content")String content); void sendEmailMsg(@RequestParam("email")String email,@RequestParam("title")String title,@RequestParam("content")String content);
/** /**
* 41 id * 41 id
* @param orgCode * @param orgCode
* @return List<Map>
*/ */
@GetMapping("/sys/api/getDeptUserByOrgCode") @GetMapping("/sys/api/getDeptUserByOrgCode")
List<Map> getDeptUserByOrgCode(@RequestParam("orgCode")String orgCode); List<Map> getDeptUserByOrgCode(@RequestParam("orgCode")String orgCode);
/** /**
* 42 * 42
* @param ids id
* @return List<String>
*/ */
@GetMapping("/sys/api/loadCategoryDictItem") @GetMapping("/sys/api/loadCategoryDictItem")
List<String> loadCategoryDictItem(@RequestParam("ids") String ids); List<String> loadCategoryDictItem(@RequestParam("ids") String ids);
@ -472,6 +500,7 @@ public interface ISysBaseAPI extends CommonAPI {
* *
* @param dictCode codetable,text,code * @param dictCode codetable,text,code
* @param keyword * @param keyword
* @param pageSize
* @return * @return
*/ */
@GetMapping("/sys/api/loadDictItemByKeyword") @GetMapping("/sys/api/loadDictItemByKeyword")

View File

@ -1,10 +1,14 @@
package org.jeecg.common.system.api.factory; package org.jeecg.common.system.api.factory;
import feign.hystrix.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import org.jeecg.common.system.api.ISysBaseAPI; import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.api.fallback.SysBaseAPIFallback; import org.jeecg.common.system.api.fallback.SysBaseAPIFallback;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/**
* @Description: SysBaseAPIFallbackFactory
* @author: jeecg-boot
*/
@Component @Component
public class SysBaseAPIFallbackFactory implements FallbackFactory<ISysBaseAPI> { public class SysBaseAPIFallbackFactory implements FallbackFactory<ISysBaseAPI> {

View File

@ -14,6 +14,7 @@ import java.util.Set;
/** /**
* fallback token * fallback token
* @author: jeecg-boot
*/ */
@Slf4j @Slf4j
public class SysBaseAPIFallback implements ISysBaseAPI { public class SysBaseAPIFallback implements ISysBaseAPI {
@ -79,11 +80,12 @@ public class SysBaseAPIFallback implements ISysBaseAPI {
@Override @Override
public List<DictModel> queryAllDict() { public List<DictModel> queryAllDict() {
log.error("fegin接口queryAllDict失败"+cause.getMessage(), cause);
return null; return null;
} }
@Override @Override
public List<SysCategoryModel> queryAllDSysCategory() { public List<SysCategoryModel> queryAllSysCategory() {
return null; return null;
} }
@ -221,7 +223,7 @@ public class SysBaseAPIFallback implements ISysBaseAPI {
@Override @Override
public LoginUser getUserByName(String username) { public LoginUser getUserByName(String username) {
log.error("通过用户名获取当前登录用户信息 {}", cause); log.error("jeecg-system服务节点不通导致获取登录用户信息失败 " + cause.getMessage(), cause);
return null; return null;
} }

View File

@ -1,164 +1,180 @@
package org.jeecg.config; //package org.jeecg.config;
//
import java.io.IOException; //import java.io.IOException;
import java.util.ArrayList; //import java.util.ArrayList;
import java.util.Arrays; //import java.util.Arrays;
import java.util.List; //import java.util.List;
import java.util.SortedMap; //import java.util.SortedMap;
//
import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletRequest;
//
import org.jeecg.common.config.mqtoken.UserTokenContext; //import org.jeecg.common.config.mqtoken.UserTokenContext;
import org.jeecg.common.constant.CommonConstant; //import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.DateUtils; //import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.PathMatcherUtil; //import org.jeecg.common.util.PathMatcherUtil;
import org.jeecg.config.sign.interceptor.SignAuthConfiguration; //import org.jeecg.config.sign.interceptor.SignAuthConfiguration;
import org.jeecg.config.sign.util.HttpUtils; //import org.jeecg.config.sign.util.HttpUtils;
import org.jeecg.config.sign.util.SignUtil; //import org.jeecg.config.sign.util.SignUtil;
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;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters; //import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.FeignAutoConfiguration; //import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.support.SpringDecoder; //import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder; //import org.springframework.cloud.openfeign.support.SpringEncoder;
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.Primary; //import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType; //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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature; //import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig; //import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; //import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.alibaba.fastjson.support.springfox.SwaggerJsonSerializer; //import com.alibaba.fastjson.support.springfox.SwaggerJsonSerializer;
//
import feign.Feign; //import feign.Feign;
import feign.Logger; //import feign.Logger;
import feign.RequestInterceptor; //import feign.RequestInterceptor;
import feign.codec.Decoder; //import feign.codec.Decoder;
import feign.codec.Encoder; //import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder; //import feign.form.spring.SpringFormEncoder;
import lombok.extern.slf4j.Slf4j; //import lombok.extern.slf4j.Slf4j;
//
@ConditionalOnClass(Feign.class) ///**
@AutoConfigureBefore(FeignAutoConfiguration.class) // * @Description: FeignConfig
@Slf4j // * @author: JeecgBoot
@Configuration // */
public class FeignConfig { //@ConditionalOnClass(Feign.class)
//@AutoConfigureBefore(FeignAutoConfiguration.class)
@Bean //@Slf4j
public RequestInterceptor requestInterceptor() { //@Configuration
return requestTemplate -> { //public class FeignConfig {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); //
if (null != attributes) { // /**
HttpServletRequest request = attributes.getRequest(); // * 设置feign header参数
log.debug("Feign request: {}", request.getRequestURI()); // * 【X_ACCESS_TOKEN】【X_SIGN】【X_TIMESTAMP】
// 将token信息放入header中 // * @return
String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN); // */
if(token==null || "".equals(token)){ // @Bean
token = request.getParameter("token"); // public RequestInterceptor requestInterceptor() {
} // return requestTemplate -> {
log.debug("Feign request token: {}", token); // ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
requestTemplate.header(CommonConstant.X_ACCESS_TOKEN, token); // if (null != attributes) {
// HttpServletRequest request = attributes.getRequest();
//根据URL地址过滤请求 【字典表参数签名验证】 // log.debug("Feign request: {}", request.getRequestURI());
if (PathMatcherUtil.matches(Arrays.asList(SignAuthConfiguration.urlList),requestTemplate.path())) { // // 将token信息放入header中
try { // String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
log.info("============================ [begin] fegin api url ============================"); // if(token==null || "".equals(token)){
log.info(requestTemplate.path()); // token = request.getParameter("token");
log.info(requestTemplate.method()); // }
String queryLine = requestTemplate.queryLine(); // log.info("Feign Login Request token: {}", token);
if(queryLine!=null && queryLine.startsWith("?")){ // requestTemplate.header(CommonConstant.X_ACCESS_TOKEN, token);
queryLine = queryLine.substring(1); // }else{
} // //解决后台任务、MQ中调用feign接口无会话token的问题
log.info(queryLine); // String token = UserTokenContext.getToken();
if(requestTemplate.body()!=null){ // log.info("Feign No Login token: {}", token);
log.info(new String(requestTemplate.body())); // requestTemplate.header(CommonConstant.X_ACCESS_TOKEN, token);
} // }
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); // //针对特殊接口,进行加签验证 ——根据URL地址过滤请求 【字典表参数签名验证】
log.info("============================ [end] fegin api url ============================"); // if (PathMatcherUtil.matches(Arrays.asList(SignAuthConfiguration.SIGN_URL_LIST),requestTemplate.path())) {
requestTemplate.header(CommonConstant.X_SIGN, sign); // try {
requestTemplate.header(CommonConstant.X_TIMESTAMP, DateUtils.getCurrentTimestamp().toString()); // log.info("============================ [begin] fegin api url ============================");
} catch (IOException e) { // log.info(requestTemplate.path());
e.printStackTrace(); // log.info(requestTemplate.method());
} // String queryLine = requestTemplate.queryLine();
} // String questionMark="?";
}else{ // if(queryLine!=null && queryLine.startsWith(questionMark)){
String token = UserTokenContext.getToken(); // queryLine = queryLine.substring(1);
log.debug("Feign request token: {}", token); // }
requestTemplate.header(CommonConstant.X_ACCESS_TOKEN, token); // 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 ============================");
* Feign NONE // requestTemplate.header(CommonConstant.X_SIGN, sign);
* Logger.Level // requestTemplate.header(CommonConstant.X_TIMESTAMP, DateUtils.getCurrentTimestamp().toString());
* NONE // } catch (IOException e) {
* BASICURL // e.printStackTrace();
* HEADERS BASIC // }
* FULL // }
*/ // //================================================================================================================
@Bean // };
Logger.Level feignLoggerLevel() { // }
return Logger.Level.FULL; //
} //
//
/** // /**
* Feign // * Feign 客户端的日志记录默认级别为NONE
* @param messageConverters // * Logger.Level 的具体级别如下:
* @return // * NONE不记录任何信息
*/ // * BASIC仅记录请求方法、URL以及响应状态码和执行时间
@Bean // * HEADERS除了记录 BASIC级别的信息外还会记录请求和响应的头信息
@Primary // * FULL记录所有请求与响应的明细包括头信息、请求体、元数据
@Scope("prototype") // */
public Encoder multipartFormEncoder(ObjectFactory<HttpMessageConverters> messageConverters) { // @Bean
return new SpringFormEncoder(new SpringEncoder(messageConverters)); // Logger.Level feignLoggerLevel() {
} // return Logger.Level.FULL;
// }
// update-begin--Author:sunjianlei Date:20210604 for 给 Feign 添加 FastJson 的解析支持 ---------- //
@Bean // /**
public Encoder feignEncoder() { // * Feign支持文件上传
return new SpringEncoder(feignHttpMessageConverter()); // * @param messageConverters
} // * @return
// */
@Bean // @Bean
public Decoder feignDecoder() { // @Primary
return new SpringDecoder(feignHttpMessageConverter()); // @Scope("prototype")
} // public Encoder multipartFormEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
// return new SpringFormEncoder(new SpringEncoder(messageConverters));
/** // }
* fastjson //
* // // update-begin--Author:sunjianlei Date:20210604 for 给 Feign 添加 FastJson 的解析支持 ----------
* @return // /**
*/ // * 给 Feign 添加 FastJson 的解析支持
private ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() { // */
final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(this.getFastJsonConverter()); // @Bean
return () -> httpMessageConverters; // public Encoder feignEncoder() {
} // return new SpringEncoder(feignHttpMessageConverter());
// }
private FastJsonHttpMessageConverter getFastJsonConverter() { //
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); // @Bean
// public Decoder feignDecoder() {
List<MediaType> supportedMediaTypes = new ArrayList<>(); // return new SpringDecoder(feignHttpMessageConverter());
MediaType mediaTypeJson = MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE); // }
supportedMediaTypes.add(mediaTypeJson); //
converter.setSupportedMediaTypes(supportedMediaTypes); // /**
FastJsonConfig config = new FastJsonConfig(); // * 设置解码器为fastjson
config.getSerializeConfig().put(JSON.class, new SwaggerJsonSerializer()); // *
config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect); // * @return
converter.setFastJsonConfig(config); // */
// private ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
return converter; // final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(this.getFastJsonConverter());
} // return () -> httpMessageConverters;
// update-end--Author:sunjianlei Date:20210604 for 给 Feign 添加 FastJson 的解析支持 ---------- // }
//
} // private FastJsonHttpMessageConverter getFastJsonConverter() {
// FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
//
// List<MediaType> supportedMediaTypes = new ArrayList<>();
// MediaType mediaTypeJson = MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE);
// supportedMediaTypes.add(mediaTypeJson);
// converter.setSupportedMediaTypes(supportedMediaTypes);
// FastJsonConfig config = new FastJsonConfig();
// config.getSerializeConfig().put(JSON.class, new SwaggerJsonSerializer());
// config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);
// converter.setFastJsonConfig(config);
//
// return converter;
// }
// // update-end--Author:sunjianlei Date:20210604 for 给 Feign 添加 FastJson 的解析支持 ----------
//
//}

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>jeecg-boot-base-api</artifactId> <artifactId>jeecg-boot-base-api</artifactId>
<groupId>org.jeecgframework.boot</groupId> <groupId>org.jeecgframework.boot</groupId>
<version>3.1.0</version> <version>3.2.0</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -1,55 +0,0 @@
package org.jeecg.common.bpm.api;
import java.util.List;
import java.util.Map;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.DictModel;
import com.alibaba.fastjson.JSONObject;
/**
*
*
* @author scott
*/
public interface IBpmBaseExtAPI {
/**
* 23. online
* @param flowCode joa_leave_01
* @param id data id
* @param formUrl PC
* @param formUrlMobile
* @param username
* @param jsonData Json
* @return
* @throws Exception
*/
Result<String> startMutilProcess(String flowCode, String id, String formUrl, String formUrlMobile, String username, String jsonData) throws Exception;
/**
* 24.
* @param flowCode joa_leave_01
* @param id data id
* @param formUrl PC
* @param formUrlMobile
* @param username
* @param jsonData Json
* @return
* @throws Exception
*/
Result<String> startDesFormMutilProcess(String flowCode, String id, String formUrl, String formUrlMobile, String username, String jsonData) throws Exception;
/**
* 25. 稿online
* @param flowCode joa_leave_01
* @param id data id
* @param formUrl PC
* @param formUrlMobile
* @param username
* @param jsonData Json
* @return
* @throws Exception
*/
Result<String> saveMutilProcessDraft(String flowCode, String id, String formUrl, String formUrlMobile, String username, String jsonData) throws Exception;
}

View File

@ -1,61 +0,0 @@
package org.jeecg.common.online.api;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.system.vo.DictModel;
import java.util.List;
import java.util.Map;
/**
* OnlineAPI
*
* @author sunjianlei
*/
public interface IOnlineBaseExtAPI {
/**
* Online
*/
String cgformPostCrazyForm(String tableName, JSONObject jsonObject) throws Exception;
/**
* Online
*/
String cgformPutCrazyForm(String tableName, JSONObject jsonObject) throws Exception;
/**
* online
*
* @param cgformCode Onlinecode
* @param dataIds ID
* @return
*/
String cgformDeleteDataByCode(String cgformCode, String dataIds);
/**
* online
*
* @param tableName online
* @param dataIds onlineID
* @return
*/
JSONObject cgformQueryAllDataByTableName(String tableName, String dataIds);
/**
* cgreportGetData DictModel
*
* @return
*/
List<DictModel> cgreportGetDataPackage(String code, String dictText, String dictCode, String dataList);
/**
* cgreport head code sql
*
* @param code CodeIDcode
* @param forceKey
* @param dataList
* @return
*/
Map<String, Object> cgreportGetData(String code, String forceKey, String dataList);
}

View File

@ -80,14 +80,16 @@ public interface ISysBaseAPI extends CommonAPI {
/** 11查询所有的父级字典按照create_time排序 */ /** 11create_time
* @return List<DictModel>
*/
public List<DictModel> queryAllDict(); public List<DictModel> queryAllDict();
/** /**
* 12 * 12
* @return * @return
*/ */
public List<SysCategoryModel> queryAllDSysCategory(); public List<SysCategoryModel> queryAllSysCategory();
/** /**
@ -132,6 +134,9 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 19 JSONObject * 19 JSONObject
* @param userIds id
* @param pageNo
* @param pageSize
* @return * @return
*/ */
public JSONObject queryAllUser(String userIds, Integer pageNo, Integer pageSize); public JSONObject queryAllUser(String userIds, Integer pageNo, Integer pageSize);
@ -144,7 +149,7 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 21 * 21
* roleIds * @param roleIds
* @return * @return
*/ */
public List<ComboModel> queryAllRole(String[] roleIds ); public List<ComboModel> queryAllRole(String[] roleIds );
@ -192,7 +197,7 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 28id * 28id
* userIds * @param userIds id
* @return * @return
*/ */
public List<LoginUser> queryAllUserByIds(String[] userIds); public List<LoginUser> queryAllUserByIds(String[] userIds);
@ -207,7 +212,7 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 30name * 30name
* userNames * @param userNames
* @return * @return
*/ */
List<LoginUser> queryUserByNames(String[] userNames); List<LoginUser> queryUserByNames(String[] userNames);
@ -236,6 +241,8 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 34id * 34id
* @param id id
* @return SysDepartModel
*/ */
SysDepartModel selectAllById(String id); SysDepartModel selectAllById(String id);
@ -284,11 +291,14 @@ public interface ISysBaseAPI extends CommonAPI {
/** /**
* 41 * 41
* @param orgCode * @param orgCode
* @return List<Map>
*/ */
List<Map> getDeptUserByOrgCode(String orgCode); List<Map> getDeptUserByOrgCode(String orgCode);
/** /**
* *
* @param ids id
* @return List<String>
*/ */
List<String> loadCategoryDictItem(String ids); List<String> loadCategoryDictItem(String ids);
@ -323,6 +333,7 @@ public interface ISysBaseAPI extends CommonAPI {
* *
* @param dictCode codetable,text,code * @param dictCode codetable,text,code
* @param keyword * @param keyword
* @param pageSize
* @return * @return
*/ */
List<DictModel> loadDictItemByKeyword(String dictCode, String keyword, Integer pageSize); List<DictModel> loadDictItemByKeyword(String dictCode, String keyword, Integer pageSize);

View File

@ -5,7 +5,7 @@
<parent> <parent>
<artifactId>jeecg-boot-base</artifactId> <artifactId>jeecg-boot-base</artifactId>
<groupId>org.jeecgframework.boot</groupId> <groupId>org.jeecgframework.boot</groupId>
<version>3.1.0</version> <version>3.2.0</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -4,7 +4,7 @@
<parent> <parent>
<groupId>org.jeecgframework.boot</groupId> <groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-base</artifactId> <artifactId>jeecg-boot-base</artifactId>
<version>3.1.0</version> <version>3.2.0</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -63,6 +63,11 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId> <artifactId>spring-boot-starter-validation</artifactId>
</dependency> </dependency>
<!--springboot2.6+解决metrics端点不显示jvm信息的问题-->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<!-- commons --> <!-- commons -->
<dependency> <dependency>
@ -114,7 +119,7 @@
<dependency> <dependency>
<groupId>org.jeecgframework.boot</groupId> <groupId>org.jeecgframework.boot</groupId>
<artifactId>hibernate-re</artifactId> <artifactId>hibernate-re</artifactId>
<version>3.1.0-beta2</version> <version>3.2.0-beta</version>
</dependency> </dependency>
<!-- 数据库驱动 --> <!-- 数据库驱动 -->
@ -176,6 +181,11 @@
<groupId>org.apache.shiro</groupId> <groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId> <artifactId>shiro-core</artifactId>
</exclusion> </exclusion>
<!-- [issues/3596] 解决启动报错Cannot resolve com.sun:tools:1.8.0 -->
<exclusion>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>

View File

@ -6,6 +6,10 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
/**
* api
* @author: jeecg-boot
*/
public interface CommonAPI { public interface CommonAPI {
/** /**
@ -67,6 +71,9 @@ public interface CommonAPI {
/** /**
* 8 * 8
* @param component
* @param username
* @param requestPath
* @return * @return
*/ */
List<SysPermissionDataRuleModel> queryPermissionDataRule(String component, String requestPath, String username); List<SysPermissionDataRuleModel> queryPermissionDataRule(String component, String requestPath, String username);

View File

@ -8,6 +8,7 @@ import java.io.Serializable;
/** /**
* *
* cloud api * cloud api
* @author: jeecg-boot
*/ */
@Data @Data
public class FileDownDTO implements Serializable { public class FileDownDTO implements Serializable {

View File

@ -8,6 +8,7 @@ import java.io.Serializable;
/** /**
* *
* cloud api * cloud api
* @author: jeecg-boot
*/ */
@Data @Data
public class FileUploadDTO implements Serializable { public class FileUploadDTO implements Serializable {

View File

@ -7,6 +7,7 @@ import java.util.Date;
/** /**
* *
* cloud api * cloud api
* @author: jeecg-boot
*/ */
@Data @Data
public class LogDTO implements Serializable { public class LogDTO implements Serializable {

View File

@ -8,6 +8,7 @@ import java.util.List;
/** /**
* online * online
* cloud api * cloud api
* @author: jeecg-boot
*/ */
@Data @Data
public class OnlineAuthDTO implements Serializable { public class OnlineAuthDTO implements Serializable {

View File

@ -6,6 +6,7 @@ import java.io.Serializable;
/** /**
* *
* @author: jeecg-boot
*/ */
@Data @Data
public class BusMessageDTO extends MessageDTO implements Serializable { public class BusMessageDTO extends MessageDTO implements Serializable {

View File

@ -7,6 +7,7 @@ import java.util.Map;
/** /**
* *
* @author: jeecg-boot
*/ */
@Data @Data
public class BusTemplateMessageDTO extends TemplateMessageDTO implements Serializable { public class BusTemplateMessageDTO extends TemplateMessageDTO implements Serializable {

View File

@ -7,6 +7,7 @@ import java.io.Serializable;
/** /**
* *
* @author: jeecg-boot
*/ */
@Data @Data
public class MessageDTO implements Serializable { public class MessageDTO implements Serializable {
@ -26,7 +27,7 @@ public class MessageDTO implements Serializable {
/** /**
* *
*/ */
protected boolean toAll; protected Boolean toAll;
/** /**
* *

View File

@ -7,6 +7,7 @@ import java.util.Map;
/** /**
* dto * dto
* @author: jeecg-boot
*/ */
@Data @Data
public class TemplateDTO implements Serializable { public class TemplateDTO implements Serializable {

View File

@ -6,6 +6,7 @@ import java.util.Map;
/** /**
* *
* @author: jeecg-boot
*/ */
@Data @Data
public class TemplateMessageDTO extends TemplateDTO implements Serializable { public class TemplateMessageDTO extends TemplateDTO implements Serializable {

View File

@ -70,7 +70,6 @@ public class Result<T> implements Serializable {
return this; return this;
} }
@Deprecated
public static<T> Result<T> ok() { public static<T> Result<T> ok() {
Result<T> r = new Result<T>(); Result<T> r = new Result<T>();
r.setSuccess(true); r.setSuccess(true);
@ -78,16 +77,16 @@ public class Result<T> implements Serializable {
return r; return r;
} }
@Deprecated
public static<T> Result<T> ok(String msg) { public static<T> Result<T> ok(String msg) {
Result<T> r = new Result<T>(); Result<T> r = new Result<T>();
r.setSuccess(true); r.setSuccess(true);
r.setCode(CommonConstant.SC_OK_200); r.setCode(CommonConstant.SC_OK_200);
//Result OK(String msg)方法会造成兼容性问题 issues/I4IP3D
r.setResult((T) msg);
r.setMessage(msg); r.setMessage(msg);
return r; return r;
} }
@Deprecated
public static<T> Result<T> ok(T data) { public static<T> Result<T> ok(T data) {
Result<T> r = new Result<T>(); Result<T> r = new Result<T>();
r.setSuccess(true); r.setSuccess(true);
@ -103,7 +102,13 @@ public class Result<T> implements Serializable {
return r; return r;
} }
@Deprecated /**
*
*
* @param msg
* @param <T>
* @return
*/
public static<T> Result<T> OK(String msg) { public static<T> Result<T> OK(String msg) {
Result<T> r = new Result<T>(); Result<T> r = new Result<T>();
r.setSuccess(true); r.setSuccess(true);

View File

@ -14,9 +14,10 @@ import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog; import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ModuleType; import org.jeecg.common.constant.enums.ModuleType;
import org.jeecg.common.constant.enums.OperateTypeEnum;
import org.jeecg.modules.base.service.BaseCommonService; import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.common.system.vo.LoginUser; import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.IPUtils; import org.jeecg.common.util.IpUtils;
import org.jeecg.common.util.SpringContextUtils; import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils; import org.jeecg.common.util.oConvertUtils;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
@ -97,7 +98,7 @@ public class AutoLogAspect {
//请求的参数 //请求的参数
dto.setRequestParam(getReqestParams(request,joinPoint)); dto.setRequestParam(getReqestParams(request,joinPoint));
//设置IP地址 //设置IP地址
dto.setIp(IPUtils.getIpAddr(request)); dto.setIp(IpUtils.getIpAddr(request));
//获取登录用户信息 //获取登录用户信息
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
if(sysUser!=null){ if(sysUser!=null){
@ -120,25 +121,9 @@ public class AutoLogAspect {
if (operateType > 0) { if (operateType > 0) {
return operateType; return operateType;
} }
if (methodName.startsWith("list")) { //update-begin---author:wangshuai ---date:20220331 for阿里云代码扫描规范(不允许任何魔法值出现在代码中)------------
return CommonConstant.OPERATE_TYPE_1; return OperateTypeEnum.getTypeByMethodName(methodName);
} //update-end---author:wangshuai ---date:20220331 for阿里云代码扫描规范(不允许任何魔法值出现在代码中)------------
if (methodName.startsWith("add")) {
return CommonConstant.OPERATE_TYPE_2;
}
if (methodName.startsWith("edit")) {
return CommonConstant.OPERATE_TYPE_3;
}
if (methodName.startsWith("delete")) {
return CommonConstant.OPERATE_TYPE_4;
}
if (methodName.startsWith("import")) {
return CommonConstant.OPERATE_TYPE_5;
}
if (methodName.startsWith("export")) {
return CommonConstant.OPERATE_TYPE_6;
}
return CommonConstant.OPERATE_TYPE_1;
} }
/** /**
@ -152,7 +137,7 @@ 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 = ""; String params = "";
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) { if (CommonConstant.HTTP_POST.equals(httpMethod) || CommonConstant.HTTP_PUT.equals(httpMethod) || CommonConstant.HTTP_PATCH.equals(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
@ -169,7 +154,8 @@ public class AutoLogAspect {
PropertyFilter profilter = new PropertyFilter() { PropertyFilter profilter = new PropertyFilter() {
@Override @Override
public boolean apply(Object o, String name, Object value) { public boolean apply(Object o, String name, Object value) {
if(value!=null && value.toString().length()>500){ int length = 500;
if(value!=null && value.toString().length()>length){
return false; return false;
} }
return true; return true;

View File

@ -42,11 +42,13 @@ import java.util.stream.Collectors;
public class DictAspect { public class DictAspect {
@Lazy @Lazy
@Autowired @Autowired
private CommonAPI commonAPI; private CommonAPI commonApi;
@Autowired @Autowired
public RedisTemplate redisTemplate; public RedisTemplate redisTemplate;
// 定义切点Pointcut /**
* Pointcut
*/
@Pointcut("execution(public * org.jeecg.modules..*.*Controller.*(..)) || @annotation(org.jeecg.common.aspect.annotation.AutoDict)") @Pointcut("execution(public * org.jeecg.modules..*.*Controller.*(..)) || @annotation(org.jeecg.common.aspect.annotation.AutoDict)")
public void excudeService() { public void excudeService() {
} }
@ -94,7 +96,7 @@ public class DictAspect {
//step.1 筛选出加了 Dict 注解的字段列表 //step.1 筛选出加了 Dict 注解的字段列表
List<Field> dictFieldList = new ArrayList<>(); List<Field> dictFieldList = new ArrayList<>();
// 字典数据列表, key = 字典codevalue=数据列表 // 字典数据列表, key = 字典codevalue=数据列表
Map<String, List<String>> dataListMap = new HashMap<>(); Map<String, List<String>> dataListMap = new HashMap<>(5);
for (Object record : ((IPage) ((Result) result).getResult()).getRecords()) { for (Object record : ((IPage) ((Result) result).getResult()).getRecords()) {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
@ -135,7 +137,7 @@ public class DictAspect {
this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(","))); this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(",")));
} }
//date类型默认转换string格式化日期 //date类型默认转换string格式化日期
if (field.getType().getName().equals("java.util.Date")&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){ if (CommonConstant.JAVA_UTIL_DATE.equals(field.getType().getName())&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName())))); item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
} }
@ -204,7 +206,7 @@ public class DictAspect {
*/ */
private Map<String, List<DictModel>> translateAllDict(Map<String, List<String>> dataListMap) { private Map<String, List<DictModel>> translateAllDict(Map<String, List<String>> dataListMap) {
// 翻译后的字典文本key=dictCode // 翻译后的字典文本key=dictCode
Map<String, List<DictModel>> translText = new HashMap<>(); Map<String, List<DictModel>> translText = new HashMap<>(5);
// 需要翻译的数据有些可以从redis缓存中获取就不走数据库查询 // 需要翻译的数据有些可以从redis缓存中获取就不走数据库查询
List<String> needTranslData = new ArrayList<>(); List<String> needTranslData = new ArrayList<>();
//step.1 先通过redis中获取缓存字典数据 //step.1 先通过redis中获取缓存字典数据
@ -258,7 +260,7 @@ public class DictAspect {
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);
List<DictModel> texts = commonAPI.translateDictFromTableByKeys(table, text, code, values); List<DictModel> texts = commonApi.translateDictFromTableByKeys(table, text, code, values);
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);
@ -287,7 +289,7 @@ public class DictAspect {
String values = String.join(",", needTranslData); String values = String.join(",", needTranslData);
log.info("translateManyDict.dictCodes:" + dictCodes); log.info("translateManyDict.dictCodes:" + dictCodes);
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 (String dictCode : manyDict.keySet()) {
List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>()); List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
@ -365,7 +367,7 @@ public class DictAspect {
log.warn(e.getMessage()); log.warn(e.getMessage());
} }
}else { }else {
tmpValue= commonAPI.translateDictFromTable(table,text,code,k.trim()); tmpValue= commonApi.translateDictFromTable(table,text,code,k.trim());
} }
}else { }else {
String keyString = String.format("sys:cache:dict::%s:%s",code,k.trim()); String keyString = String.format("sys:cache:dict::%s:%s",code,k.trim());
@ -376,7 +378,7 @@ public class DictAspect {
log.warn(e.getMessage()); log.warn(e.getMessage());
} }
}else { }else {
tmpValue = commonAPI.translateDict(code, k.trim()); tmpValue = commonApi.translateDict(code, k.trim());
} }
} }
//update-end--Author:scott -- Date:20210531 ----for !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题----- //update-end--Author:scott -- Date:20210531 ----for !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题-----

View File

@ -9,6 +9,8 @@ import org.aspectj.lang.reflect.MethodSignature;
import org.jeecg.common.api.CommonAPI; import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.aspect.annotation.PermissionData; import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.util.JeecgDataAutorUtils; import org.jeecg.common.system.util.JeecgDataAutorUtils;
import org.jeecg.common.system.util.JwtUtil; import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.SysPermissionDataRuleModel; import org.jeecg.common.system.vo.SysPermissionDataRuleModel;
@ -28,6 +30,7 @@ import java.util.List;
* PermissionData,request * PermissionData,request
* @Date 2019410 * @Date 2019410
* @Version: 1.0 * @Version: 1.0
* @author: jeecg-boot
*/ */
@Aspect @Aspect
@Component @Component
@ -35,7 +38,7 @@ import java.util.List;
public class PermissionDataAspect { public class PermissionDataAspect {
@Lazy @Lazy
@Autowired @Autowired
private CommonAPI commonAPI; private CommonAPI commonApi;
@Pointcut("@annotation(org.jeecg.common.aspect.annotation.PermissionData)") @Pointcut("@annotation(org.jeecg.common.aspect.annotation.PermissionData)")
public void pointCut() { public void pointCut() {
@ -55,7 +58,7 @@ public class PermissionDataAspect {
//update-begin-author:taoyan date:20211027 for:JTC-132【online报表权限】online报表带参数的菜单配置数据权限无效 //update-begin-author:taoyan date:20211027 for:JTC-132【online报表权限】online报表带参数的菜单配置数据权限无效
//先判断是否online报表请求 //先判断是否online报表请求
// TODO 参数顺序调整有隐患 // TODO 参数顺序调整有隐患
if(requestPath.indexOf(UrlMatchEnum.CGREPORT_DATA.getMatch_url())>=0){ if(requestPath.indexOf(UrlMatchEnum.CGREPORT_DATA.getMatchUrl())>=0){
// 获取地址栏参数 // 获取地址栏参数
String urlParamString = request.getParameter(CommonConstant.ONL_REP_URL_PARAM_STR); String urlParamString = request.getParameter(CommonConstant.ONL_REP_URL_PARAM_STR);
if(oConvertUtils.isNotEmpty(urlParamString)){ if(oConvertUtils.isNotEmpty(urlParamString)){
@ -67,12 +70,12 @@ public class PermissionDataAspect {
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.size()>0) {
//临时存储 //临时存储
JeecgDataAutorUtils.installDataSearchConditon(request, dataRules); JeecgDataAutorUtils.installDataSearchConditon(request, dataRules);
//TODO 微服务情况下也得支持缓存机制 //TODO 微服务情况下也得支持缓存机制
SysUserCacheInfo userinfo = commonAPI.getCacheUser(username); SysUserCacheInfo userinfo = commonApi.getCacheUser(username);
JeecgDataAutorUtils.installUserInfo(request, userinfo); JeecgDataAutorUtils.installUserInfo(request, userinfo);
} }
return point.proceed(); return point.proceed();
@ -83,7 +86,7 @@ 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.indexOf(SymbolConstant.DOUBLE_SLASH)>=0){
url = filterUrl(url); url = filterUrl(url);
} }
/*if(url.startsWith("/")){ /*if(url.startsWith("/")){
@ -105,17 +108,19 @@ public class PermissionDataAspect {
if(oConvertUtils.isNotEmpty(queryString)){ if(oConvertUtils.isNotEmpty(queryString)){
requestPath += "?" + queryString; requestPath += "?" + queryString;
} }
if (requestPath.indexOf("&") > -1) {// 去掉其他参数(保留一个参数) 例如loginController.do?login // 去掉其他参数(保留一个参数) 例如loginController.do?login
if (requestPath.indexOf(SymbolConstant.AND) > -1) {
requestPath = requestPath.substring(0, requestPath.indexOf("&")); requestPath = requestPath.substring(0, requestPath.indexOf("&"));
} }
if(requestPath.indexOf("=")!=-1){ if(requestPath.indexOf(QueryRuleEnum.EQ.getValue())!=-1){
if(requestPath.indexOf(".do")!=-1){ if(requestPath.indexOf(CommonConstant.SPOT_DO)!=-1){
requestPath = requestPath.substring(0,requestPath.indexOf(".do")+3); requestPath = requestPath.substring(0,requestPath.indexOf(".do")+3);
}else{ }else{
requestPath = requestPath.substring(0,requestPath.indexOf("?")); requestPath = requestPath.substring(0,requestPath.indexOf("?"));
} }
} }
requestPath = requestPath.substring(request.getContextPath().length() + 1);// 去掉项目路径 // 去掉项目路径
requestPath = requestPath.substring(request.getContextPath().length() + 1);
return filterUrl(requestPath); return filterUrl(requestPath);
} }

View File

@ -6,16 +6,22 @@ package org.jeecg.common.aspect;
* @Description: URLURL便URL * @Description: URLURL便URL
*/ */
public enum UrlMatchEnum { public enum UrlMatchEnum {
/**求URL与菜单路由URL转换规则 /online/cgform/api/getData/ */
CGFORM_DATA("/online/cgform/api/getData/", "/online/cgformList/"), CGFORM_DATA("/online/cgform/api/getData/", "/online/cgformList/"),
/**求URL与菜单路由URL转换规则 /online/cgform/api/exportXls/ */
CGFORM_EXCEL_DATA("/online/cgform/api/exportXls/", "/online/cgformList/"), CGFORM_EXCEL_DATA("/online/cgform/api/exportXls/", "/online/cgformList/"),
/**求URL与菜单路由URL转换规则 /online/cgform/api/getTreeData/ */
CGFORM_TREE_DATA("/online/cgform/api/getTreeData/", "/online/cgformList/"), CGFORM_TREE_DATA("/online/cgform/api/getTreeData/", "/online/cgformList/"),
/**求URL与菜单路由URL转换规则 /online/cgreport/api/getColumnsAndData/ */
CGREPORT_DATA("/online/cgreport/api/getColumnsAndData/", "/online/cgreport/"), CGREPORT_DATA("/online/cgreport/api/getColumnsAndData/", "/online/cgreport/"),
/**求URL与菜单路由URL转换规则 /online/cgreport/api/exportXls/ */
CGREPORT_EXCEL_DATA("/online/cgreport/api/exportXls/", "/online/cgreport/"), CGREPORT_EXCEL_DATA("/online/cgreport/api/exportXls/", "/online/cgreport/"),
/**求URL与菜单路由URL转换规则 /online/cgreport/api/exportManySheetXls/ */
CGREPORT_EXCEL_DATA2("/online/cgreport/api/exportManySheetXls/", "/online/cgreport/"); CGREPORT_EXCEL_DATA2("/online/cgreport/api/exportManySheetXls/", "/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 +31,7 @@ public enum UrlMatchEnum {
/** /**
* URL () * URL ()
*/ */
private String match_url; private String matchUrl;
/** /**
* req url URL * req url URL
@ -41,14 +47,14 @@ 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 String getMatch_url() { public String getMatchUrl() {
return match_url; return matchUrl;
} }
// public static void main(String[] args) { // public static void main(String[] args) {
// /** // /**

View File

@ -6,9 +6,9 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
/** /**
* : *
* dangzhenghui * @author: dangzhenghui
* 20190317-9:37:16 * @date: 20190317-9:37:16
*/ */
@Target(ElementType.FIELD) @Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)

View File

@ -4,6 +4,7 @@ import java.lang.annotation.*;
/** /**
* online * online
* @author: jeecg-boot
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD}) @Target({ElementType.TYPE,ElementType.METHOD})

View File

@ -1,5 +1,9 @@
package org.jeecg.common.constant; package org.jeecg.common.constant;
/**
* @Description:
* @author: jeecg-boot
*/
public interface CommonConstant { public interface CommonConstant {
/** /**
@ -75,8 +79,8 @@ public interface CommonConstant {
public static String PREFIX_USER_SHIRO_CACHE = "shiro:cache:org.jeecg.config.shiro.ShiroRealm.authorizationCache:"; public static String PREFIX_USER_SHIRO_CACHE = "shiro:cache:org.jeecg.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;
/** 登录二维码 */ /** 登录二维码 */
public static final String LOGIN_QRCODE_PRE = "QRCODELOGIN:"; public static final String LOGIN_QRCODE_PRE = "QRCODELOGIN:";
@ -339,4 +343,34 @@ public interface CommonConstant {
/**ONLINE 报表权限用 从request中获取地址栏后的参数*/ /**ONLINE 报表权限用 从request中获取地址栏后的参数*/
String ONL_REP_URL_PARAM_STR="onlRepUrlParamStr"; String ONL_REP_URL_PARAM_STR="onlRepUrlParamStr";
/**POST请求*/
String HTTP_POST = "POST";
/**PUT请求*/
String HTTP_PUT = "PUT";
/**PATCH请求*/
String HTTP_PATCH = "PATCH";
/**未知的*/
String UNKNOWN = "unknown";
/**字符串http*/
String STR_HTTP = "http";
/**String 类型的空值*/
String STRING_NULL = "null";
/**java.util.Date 包*/
String JAVA_UTIL_DATE = "java.util.Date";
/**.do*/
String SPOT_DO = ".do";
/**前端vue版本标识*/
String VERSION="X-Version";
/**前端vue版本*/
String VERSION_VUE3="vue3";
} }

View File

@ -7,14 +7,25 @@ package org.jeecg.common.constant;
*/ */
public interface CommonSendStatus { public interface 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"; //撤销 /**
//app端推送会话标识后缀 *
public static final String APP_SESSION_SUFFIX = "_app"; //app端推送会话标识后缀 */
public static final String REVOKE_STATUS_2 = "2";
/**
* app
*/
public static final String APP_SESSION_SUFFIX = "_app";
/**流程催办——系统通知消息模板*/ /**流程催办——系统通知消息模板*/

View File

@ -1,16 +1,33 @@
package org.jeecg.common.constant; package org.jeecg.common.constant;
/** /**
* *
* @author: jeecg-boot
*/ */
public interface DataBaseConstant { public interface DataBaseConstant {
//*********数据库类型**************************************** //*********数据库类型****************************************
/**MYSQL数据库*/
public static final String DB_TYPE_MYSQL = "MYSQL"; public static final String DB_TYPE_MYSQL = "MYSQL";
/** ORACLE*/
public static final String DB_TYPE_ORACLE = "ORACLE"; public static final String DB_TYPE_ORACLE = "ORACLE";
public static final String DB_TYPE_DM = "DM";//达梦数据库
/**达梦数据库*/
public static final String DB_TYPE_DM = "DM";
/**postgreSQL达梦数据库*/
public static final String DB_TYPE_POSTGRESQL = "POSTGRESQL"; public static final String DB_TYPE_POSTGRESQL = "POSTGRESQL";
/**sqlserver数据库*/
public static final String DB_TYPE_SQLSERVER = "SQLSERVER"; public static final String DB_TYPE_SQLSERVER = "SQLSERVER";
/**mariadb 数据库*/
public static final String DB_TYPE_MARIADB = "MARIADB"; public static final String DB_TYPE_MARIADB = "MARIADB";
/**DB2 数据库*/
public static final String DB_TYPE_DB2 = "DB2"; public static final String DB_TYPE_DB2 = "DB2";
/**HSQL 数据库*/
public static final String DB_TYPE_HSQL = "HSQL"; public static final String DB_TYPE_HSQL = "HSQL";
// // 数据库类型,对应 database_type 字典 // // 数据库类型,对应 database_type 字典
@ -131,4 +148,9 @@ public interface DataBaseConstant {
* ID * ID
*/ */
String TENANT_ID_TABLE = "tenant_id"; String TENANT_ID_TABLE = "tenant_id";
/**
* sql where
*/
String SQL_WHERE = "where";
} }

View File

@ -13,6 +13,10 @@ import java.util.Scanner;
import java.util.Set; import java.util.Set;
import java.util.List; import java.util.List;
/**
* @Description:
* @author: jeecg-boot
*/
@Component("pca") @Component("pca")
public class ProvinceCityArea { public class ProvinceCityArea {
List<Area> areaList; List<Area> areaList;

View File

@ -26,10 +26,13 @@ package org.jeecg.common.constant;
public interface ServiceNameConstants { public interface ServiceNameConstants {
/** /**
* admin *
*/ */
String SYSTEM_SERVICE = "jeecg-system"; String SERVICE_SYSTEM = "jeecg-system";
String SYSTEM_ONLINE = "jeecg-online"; /**
* Demo
*/
String SERVICE_DEMO = "jeecg-demo";
/** /**
* gatewayheader basePath * gatewayheader basePath

View File

@ -0,0 +1,89 @@
package org.jeecg.common.constant;
/**
* @Description:
* @author: wangshuai
* @date: 20220330 17:44
*/
public class SymbolConstant {
/**
*
*/
public static final String SPOT = ".";
/**
*
*/
public static final String DOUBLE_BACKSLASH = "\\";
/**
*
*/
public static final String COLON = ":";
/**
*
*/
public static final String COMMA = ",";
/**
* }
*/
public static final String LEFT_CURLY_BRACKET = "{";
/**
* }
*/
public static final String RIGHT_CURLY_BRACKET = "}";
/**
* #
*/
public static final String WELL_NUMBER = "#";
/**
*
*/
public static final String SINGLE_SLASH = "/";
/**
*
*/
public static final String DOUBLE_SLASH = "//";
/**
*
*/
public static final String EXCLAMATORY_MARK = "!";
/**
* 线
*/
public static final String UNDERLINE = "_";
/**
*
*/
public static final String SINGLE_QUOTATION_MARK = "'";
/**
*
*/
public static final String ASTERISK = "*";
/**
*
*/
public static final String PERCENT_SIGN = "%";
/**
* $
*/
public static final String DOLLAR = "$";
/**
* &
*/
public static final String AND = "&";
}

View File

@ -2,8 +2,9 @@ package org.jeecg.common.constant;
/** /**
* VXESocket * VXESocket
* @author: jeecg-boot
*/ */
public class VXESocketConst { public class VxeSocketConst {
/** /**
* *

View File

@ -7,6 +7,7 @@ import java.util.Map;
/** /**
* online * online
* @author: jeecg-boot
*/ */
public enum CgformEnum { public enum CgformEnum {

View File

@ -3,6 +3,7 @@ package org.jeecg.common.constant.enums;
/** /**
* LowApp * LowApp
* @date 2022-1-5 * @date 2022-1-5
* @author: jeecg-boot
*/ */
public enum LowAppAopEnum { public enum LowAppAopEnum {

View File

@ -2,6 +2,7 @@ package org.jeecg.common.constant.enums;
/** /**
* *
* @author: jeecg-boot
*/ */
public enum ModuleType { public enum ModuleType {

View File

@ -0,0 +1,95 @@
package org.jeecg.common.constant.enums;
import org.jeecg.common.constant.CommonConstant;
/**
* @Description:
* @author: jeecg-boot
* @date: 2022/3/31 10:05
*/
public enum OperateTypeEnum {
/**
*
*/
LIST(CommonConstant.OPERATE_TYPE_1, "list"),
/**
*
*/
ADD(CommonConstant.OPERATE_TYPE_2, "add"),
/**
*
*/
EDIT(CommonConstant.OPERATE_TYPE_3, "edit"),
/**
*
*/
DELETE(CommonConstant.OPERATE_TYPE_4, "delete"),
/**
*
*/
IMPORT(CommonConstant.OPERATE_TYPE_5, "import"),
/**
*
*/
EXPORT(CommonConstant.OPERATE_TYPE_6, "export");
/**
* 1,2,3,4,5,6
*/
int type;
/**
* ()
*/
String code;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
/**
*
*
* @param type
* @param code ()
*/
OperateTypeEnum(int type, String code) {
this.type = type;
this.code = code;
}
/**
*
*
* @param methodName
* @return Integer
*/
public static Integer getTypeByMethodName(String methodName) {
for (OperateTypeEnum e : OperateTypeEnum.values()) {
if (methodName.startsWith(e.getCode())) {
return e.getType();
}
}
return CommonConstant.OPERATE_TYPE_1;
}
}

View File

@ -8,11 +8,14 @@ import java.util.List;
* *
* *
* *
* @author: jeecg-boot
*/ */
public enum RoleIndexConfigEnum { public enum RoleIndexConfigEnum {
/**首页自定义 admin*/
ADMIN("admin", "dashboard/Analysis"), ADMIN("admin", "dashboard/Analysis"),
//TEST("test", "dashboard/IndexChart"), //TEST("test", "dashboard/IndexChart"),
/**首页自定义 hr*/
HR("hr", "dashboard/IndexBdc"); HR("hr", "dashboard/IndexBdc");
//DM("dm", "dashboard/IndexTask"), //DM("dm", "dashboard/IndexTask"),

View File

@ -29,9 +29,15 @@ public class JeecgElasticsearchTemplate {
/** Elasticsearch 的版本号 */ /** Elasticsearch 的版本号 */
private String version = null; private String version = null;
// ElasticSearch 最大可返回条目数 /**ElasticSearch 最大可返回条目数*/
public static final int ES_MAX_SIZE = 10000; public static final int ES_MAX_SIZE = 10000;
/**es7*/
public static final String IE_SEVEN = "7";
/**url not found 404*/
public static final String URL_NOT_FOUND = "404 Not Found";
public JeecgElasticsearchTemplate(@Value("${jeecg.elasticsearch.cluster-nodes}") String baseUrl, @Value("${jeecg.elasticsearch.check-enabled}") boolean checkEnabled) { public JeecgElasticsearchTemplate(@Value("${jeecg.elasticsearch.cluster-nodes}") String baseUrl, @Value("${jeecg.elasticsearch.check-enabled}") boolean checkEnabled) {
log.debug("JeecgElasticsearchTemplate BaseURL" + baseUrl); log.debug("JeecgElasticsearchTemplate BaseURL" + baseUrl);
if (StringUtils.isNotEmpty(baseUrl)) { if (StringUtils.isNotEmpty(baseUrl)) {
@ -81,7 +87,7 @@ public class JeecgElasticsearchTemplate {
/** /**
* cat ElasticSearchjson * cat ElasticSearchjson
*/ */
public <T> ResponseEntity<T> _cat(String urlAfter, Class<T> responseType) { private <T> ResponseEntity<T> cat(String urlAfter, Class<T> responseType) {
String url = this.getBaseUrl().append("/_cat").append(urlAfter).append("?").append(FORMAT_JSON).toString(); String url = this.getBaseUrl().append("/_cat").append(urlAfter).append("?").append(FORMAT_JSON).toString();
return RestUtil.request(url, HttpMethod.GET, null, null, null, responseType); return RestUtil.request(url, HttpMethod.GET, null, null, null, responseType);
} }
@ -106,7 +112,7 @@ public class JeecgElasticsearchTemplate {
if (!StringUtils.isEmpty(indexName)) { if (!StringUtils.isEmpty(indexName)) {
urlAfter.append("/").append(indexName.trim().toLowerCase()); urlAfter.append("/").append(indexName.trim().toLowerCase());
} }
return _cat(urlAfter.toString(), JSONArray.class).getBody(); return cat(urlAfter.toString(), JSONArray.class).getBody();
} }
/** /**
@ -205,7 +211,7 @@ public class JeecgElasticsearchTemplate {
String url = this.getBaseUrl(indexName, typeName).append("/_mapping?").append(FORMAT_JSON).toString(); String url = this.getBaseUrl(indexName, typeName).append("/_mapping?").append(FORMAT_JSON).toString();
// 针对 es 7.x 版本做兼容 // 针对 es 7.x 版本做兼容
this.getElasticsearchVersion(); this.getElasticsearchVersion();
if (oConvertUtils.isNotEmpty(this.version) && this.version.startsWith("7")) { if (oConvertUtils.isNotEmpty(this.version) && this.version.startsWith(IE_SEVEN)) {
url += "&include_type_name=true"; url += "&include_type_name=true";
} }
log.info("getIndexMapping-url:" + url); log.info("getIndexMapping-url:" + url);
@ -243,7 +249,7 @@ public class JeecgElasticsearchTemplate {
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(URL_NOT_FOUND)) {
return null; return null;
} }
throw e; throw e;
@ -259,7 +265,7 @@ public class JeecgElasticsearchTemplate {
*/ */
public <T> Map<String, T> getIndexMappingFormat(String indexName, String typeName, Class<T> clazz) { public <T> Map<String, T> getIndexMappingFormat(String indexName, String typeName, Class<T> clazz) {
JSONObject mapping = this.getIndexMapping(indexName, typeName); JSONObject mapping = this.getIndexMapping(indexName, typeName);
Map<String, T> map = new HashMap<>(); Map<String, T> map = new HashMap<>(5);
if (mapping == null) { if (mapping == null) {
return map; return map;
} }
@ -362,7 +368,7 @@ public class JeecgElasticsearchTemplate {
*/ */
public boolean saveBatch(String indexName, String typeName, JSONArray dataList) { public boolean saveBatch(String indexName, String typeName, JSONArray dataList) {
String url = this.getBaseUrl().append("/_bulk").append("?refresh=wait_for").toString(); String url = this.getBaseUrl().append("/_bulk").append("?refresh=wait_for").toString();
StringBuilder bodySB = new StringBuilder(); StringBuilder bodySb = new StringBuilder();
for (int i = 0; i < dataList.size(); i++) { for (int i = 0; i < dataList.size(); i++) {
JSONObject data = dataList.getJSONObject(i); JSONObject data = dataList.getJSONObject(i);
String id = data.getString("id"); String id = data.getString("id");
@ -374,14 +380,14 @@ public class JeecgElasticsearchTemplate {
actionInfo.put("_index", indexName); actionInfo.put("_index", indexName);
actionInfo.put("_type", typeName); actionInfo.put("_type", typeName);
action.put("create", actionInfo); action.put("create", actionInfo);
bodySB.append(action.toJSONString()).append("\n"); bodySb.append(action.toJSONString()).append("\n");
// 该行的数据 // 该行的数据
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()); System.out.println("+-+-+-: 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;
} }
@ -437,16 +443,16 @@ public class JeecgElasticsearchTemplate {
} }
/** /**
* @param _source null * @param source null
* @param query * @param query
* @param from * @param from
* @param size * @param size
* @return { "query": query } * @return { "query": query }
*/ */
public JSONObject buildQuery(List<String> _source, JSONObject query, int from, int size) { public JSONObject buildQuery(List<String> source, JSONObject query, int from, int size) {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
if (_source != null) { if (source != null) {
json.put("_source", _source); json.put("_source", source);
} }
json.put("query", query); json.put("query", query);
json.put("from", from); json.put("from", from);

View File

@ -1,5 +1,9 @@
package org.jeecg.common.exception; package org.jeecg.common.exception;
/**
* @Description: jeecg-boot401
* @author: jeecg-boot
*/
public class JeecgBoot401Exception extends RuntimeException { public class JeecgBoot401Exception extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;

View File

@ -1,5 +1,9 @@
package org.jeecg.common.exception; package org.jeecg.common.exception;
/**
* @Description: jeecg-boot
* @author: jeecg-boot
*/
public class JeecgBootException extends RuntimeException { public class JeecgBootException extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;

View File

@ -1,10 +1,10 @@
package org.jeecg.common.exception; package org.jeecg.common.exception;
import io.lettuce.core.RedisConnectionException; import cn.hutool.core.util.ObjectUtil;
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 org.jeecg.common.api.vo.Result; import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Value; import org.jeecg.common.enums.SentinelErrorInfoEnum;
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;
@ -27,8 +27,7 @@ import lombok.extern.slf4j.Slf4j;
@RestControllerAdvice @RestControllerAdvice
@Slf4j @Slf4j
public class JeecgBootExceptionHandler { public class JeecgBootExceptionHandler {
@Value("${spring.servlet.multipart.max-file-size}")
private String maxFileSize;
/** /**
* *
*/ */
@ -69,6 +68,13 @@ public class JeecgBootExceptionHandler {
@ExceptionHandler(Exception.class) @ExceptionHandler(Exception.class)
public Result<?> handleException(Exception e){ public Result<?> handleException(Exception e){
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
//update-begin---author:zyf ---date:20220411 for处理Sentinel限流自定义异常
Throwable throwable = e.getCause();
SentinelErrorInfoEnum errorInfoEnum = SentinelErrorInfoEnum.getErrorByException(throwable);
if (ObjectUtil.isNotEmpty(errorInfoEnum)) {
return Result.error(errorInfoEnum.getError());
}
//update-end---author:zyf ---date:20220411 for处理Sentinel限流自定义异常
return Result.error("操作失败,"+e.getMessage()); return Result.error("操作失败,"+e.getMessage());
} }
@ -78,7 +84,7 @@ public class JeecgBootExceptionHandler {
* @return * @return
*/ */
@ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result<?> HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){ public Result<?> httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append("不支持"); sb.append("不支持");
sb.append(e.getMethod()); sb.append(e.getMethod());
@ -102,7 +108,7 @@ public class JeecgBootExceptionHandler {
@ExceptionHandler(MaxUploadSizeExceededException.class) @ExceptionHandler(MaxUploadSizeExceededException.class)
public Result<?> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) { public Result<?> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return Result.error(String.format("文件大小超出%s限制, 请压缩或降低文件质量! ", maxFileSize)); return Result.error("文件大小超出10MB限制, 请压缩或降低文件质量! ");
} }
@ExceptionHandler(DataIntegrityViolationException.class) @ExceptionHandler(DataIntegrityViolationException.class)

View File

@ -11,6 +11,7 @@ import com.alibaba.fastjson.JSONObject;
public interface IFillRuleHandler { public interface IFillRuleHandler {
/** /**
*
* @param params * @param params
* @param formData * @param formData
* @return * @return

View File

@ -37,7 +37,7 @@ import java.util.stream.Collectors;
*/ */
@Slf4j @Slf4j
public class JeecgController<T, S extends IService<T>> { public class JeecgController<T, S extends IService<T>> {
//issues/2933 JeecgController注入service时改用protected修饰能避免重复引用service /**issues/2933 JeecgController注入service时改用protected修饰能避免重复引用service*/
@Autowired @Autowired
protected S service; protected S service;
@ -68,7 +68,8 @@ public class JeecgController<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无效 ,前端会重更新设置一下 //此处设置的filename无效 ,前端会重更新设置一下
mv.addObject(NormalExcelConstants.FILE_NAME, title);
mv.addObject(NormalExcelConstants.CLASS, clazz); mv.addObject(NormalExcelConstants.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);
@ -111,18 +112,22 @@ public class JeecgController<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<>(5);
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);
map.put(NormalExcelConstants.PARAMS,exportParams);//表格Title //表格Title
map.put(NormalExcelConstants.CLASS,clazz);//表格对应实体 map.put(NormalExcelConstants.PARAMS,exportParams);
map.put(NormalExcelConstants.DATA_LIST, exportList);//数据集合 //表格对应实体
map.put(NormalExcelConstants.CLASS,clazz);
//数据集合
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无效 ,前端会重更新设置一下 //此处设置的filename无效 ,前端会重更新设置一下
mv.addObject(NormalExcelConstants.FILE_NAME, title);
mv.addObject(NormalExcelConstants.MAP_LIST, listMap); mv.addObject(NormalExcelConstants.MAP_LIST, listMap);
return mv; return mv;
} }
@ -164,7 +169,8 @@ public class JeecgController<T, S extends IService<T>> {
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);

View File

@ -1,6 +1,7 @@
package org.jeecg.common.system.base.entity; package org.jeecg.common.system.base.entity;
import java.io.Serializable; import java.io.Serializable;
import org.jeecgframework.poi.excel.annotation.Excel; import org.jeecgframework.poi.excel.annotation.Excel;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
@ -25,28 +26,43 @@ import lombok.experimental.Accessors;
public class JeecgEntity implements Serializable { public class JeecgEntity implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** ID */ /**
* ID
*/
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.ASSIGN_ID)
@ApiModelProperty(value = "ID") @ApiModelProperty(value = "ID")
private java.lang.String id; private java.lang.String id;
/** 创建人 */
/**
*
*/
@ApiModelProperty(value = "创建人") @ApiModelProperty(value = "创建人")
@Excel(name = "创建人", width = 15) @Excel(name = "创建人", width = 15)
private java.lang.String createBy; private java.lang.String createBy;
/** 创建时间 */
/**
*
*/
@ApiModelProperty(value = "创建时间") @ApiModelProperty(value = "创建时间")
@Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private java.util.Date createTime; private java.util.Date createTime;
/** 更新人 */
/**
*
*/
@ApiModelProperty(value = "更新人") @ApiModelProperty(value = "更新人")
@Excel(name = "更新人", width = 15) @Excel(name = "更新人", width = 15)
private java.lang.String updateBy; private java.lang.String updateBy;
/** 更新时间 */
/**
*
*/
@ApiModelProperty(value = "更新时间") @ApiModelProperty(value = "更新时间")
@Excel(name = "更新时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @Excel(name = "更新时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private java.util.Date updateTime; private java.util.Date updateTime;
} }

View File

@ -9,7 +9,9 @@ import org.jeecg.common.util.oConvertUtils;
*/ */
public enum MatchTypeEnum { public enum MatchTypeEnum {
/**查询链接规则 AND*/
AND("AND"), AND("AND"),
/**查询链接规则 OR*/
OR("OR"); OR("OR");
private String value; private String value;

View File

@ -2,6 +2,10 @@ package org.jeecg.common.system.query;
import java.io.Serializable; import java.io.Serializable;
/**
* @Description: QueryCondition
* @author: jeecg-boot
*/
public class QueryCondition implements Serializable { public class QueryCondition implements Serializable {
private static final long serialVersionUID = 4740166316629191651L; private static final long serialVersionUID = 4740166316629191651L;

View File

@ -15,6 +15,7 @@ import java.util.stream.Collectors;
import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.PropertyUtils;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.DataBaseConstant; import org.jeecg.common.constant.DataBaseConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.system.util.JeecgDataAutorUtils; import org.jeecg.common.system.util.JeecgDataAutorUtils;
import org.jeecg.common.system.util.JwtUtil; import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.SysPermissionDataRuleModel; import org.jeecg.common.system.vo.SysPermissionDataRuleModel;
@ -30,6 +31,10 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
/**
* @Description:
* @author: jeecg-boot
*/
@Slf4j @Slf4j
public class QueryGenerator { public class QueryGenerator {
public static final String SQL_RULES_COLUMN = "SQL_RULES_COLUMN"; public static final String SQL_RULES_COLUMN = "SQL_RULES_COLUMN";
@ -64,13 +69,19 @@ public class QueryGenerator {
/**mysql 模糊查询之特殊字符下划线 _、\*/ /**mysql 模糊查询之特殊字符下划线 _、\*/
public static final String LIKE_MYSQL_SPECIAL_STRS = "_,%"; public static final String LIKE_MYSQL_SPECIAL_STRS = "_,%";
/**日期格式化yyyy-MM-dd*/
public static final String YYYY_MM_DD = "yyyy-MM-dd";
/**to_date*/
public static final String TO_DATE = "to_date";
/**时间格式化 */ /**时间格式化 */
private static final ThreadLocal<SimpleDateFormat> local = new ThreadLocal<SimpleDateFormat>(); private static final ThreadLocal<SimpleDateFormat> LOCAL = new ThreadLocal<SimpleDateFormat>();
private static SimpleDateFormat getTime(){ private static SimpleDateFormat getTime(){
SimpleDateFormat time = local.get(); SimpleDateFormat time = LOCAL.get();
if(time == null){ if(time == null){
time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
local.set(time); LOCAL.set(time);
} }
return time; return time;
} }
@ -107,7 +118,7 @@ public class QueryGenerator {
*/ */
//区间条件组装 模糊查询 高级查询组装 简单排序 权限查询 //区间条件组装 模糊查询 高级查询组装 简单排序 权限查询
PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(searchObj); PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(searchObj);
Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap(); Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap();
//权限规则自定义SQL表达式 //权限规则自定义SQL表达式
@ -120,7 +131,7 @@ public class QueryGenerator {
String name, type, column; String name, type, column;
// update-begin--Author:taoyan Date:20200923 forissues/1671 如果字段加注解了@TableField(exist = false),不走DB查询------- // update-begin--Author:taoyan Date:20200923 forissues/1671 如果字段加注解了@TableField(exist = false),不走DB查询-------
//定义实体字段和数据库字段名称的映射 高级查询中 只能获取实体字段 如果设置TableField注解 那么查询条件会出问题 //定义实体字段和数据库字段名称的映射 高级查询中 只能获取实体字段 如果设置TableField注解 那么查询条件会出问题
Map<String,String> fieldColumnMap = new HashMap<String,String>(); Map<String,String> fieldColumnMap = new HashMap<>(5);
for (int i = 0; i < origDescriptors.length; i++) { for (int i = 0; i < origDescriptors.length; i++) {
//aliasName = origDescriptors[i].getName(); mybatis 不存在实体属性 不用处理别名的情况 //aliasName = origDescriptors[i].getName(); mybatis 不存在实体属性 不用处理别名的情况
name = origDescriptors[i].getName(); name = origDescriptors[i].getName();
@ -217,7 +228,7 @@ public class QueryGenerator {
} }
} }
//多字段排序 TODO 需要修改前端 /**多字段排序 TODO 需要修改前端*/
private static void doMultiFieldsOrder(QueryWrapper<?> queryWrapper,Map<String, String[]> parameterMap) { private static void doMultiFieldsOrder(QueryWrapper<?> queryWrapper,Map<String, String[]> parameterMap) {
String column=null,order=null; String column=null,order=null;
if(parameterMap!=null&& parameterMap.containsKey(ORDER_COLUMN)) { if(parameterMap!=null&& parameterMap.containsKey(ORDER_COLUMN)) {
@ -327,6 +338,7 @@ public class QueryGenerator {
case "boolean": case "boolean":
queryValue = Boolean.parseBoolean(valueStr); queryValue = Boolean.parseBoolean(valueStr);
break; break;
default:
} }
} catch (Exception e) { } catch (Exception e) {
log.error("高级查询值转换失败:", e); log.error("高级查询值转换失败:", e);
@ -376,20 +388,27 @@ public class QueryGenerator {
//update-begin--Author:scott Date:20190724 forinitQueryWrapper组装sql查询条件错误 #284------------------- //update-begin--Author:scott Date:20190724 forinitQueryWrapper组装sql查询条件错误 #284-------------------
//TODO 此处规则,只适用于 le lt ge gt //TODO 此处规则,只适用于 le lt ge gt
// step 2 .>= =< // step 2 .>= =<
if (rule == null && val.length() >= 3) { int length2 = 2;
if(QUERY_SEPARATE_KEYWORD.equals(val.substring(2, 3))){ int length3 = 3;
if (rule == null && val.length() >= length3) {
if(QUERY_SEPARATE_KEYWORD.equals(val.substring(length2, length3))){
rule = QueryRuleEnum.getByValue(val.substring(0, 2)); rule = QueryRuleEnum.getByValue(val.substring(0, 2));
} }
} }
// step 1 .> < // step 1 .> <
if (rule == null && val.length() >= 2) { if (rule == null && val.length() >= length2) {
if(QUERY_SEPARATE_KEYWORD.equals(val.substring(1, 2))){ if(QUERY_SEPARATE_KEYWORD.equals(val.substring(1, length2))){
rule = QueryRuleEnum.getByValue(val.substring(0, 1)); rule = QueryRuleEnum.getByValue(val.substring(0, 1));
} }
} }
//update-end--Author:scott Date:20190724 forinitQueryWrapper组装sql查询条件错误 #284--------------------- //update-end--Author:scott Date:20190724 forinitQueryWrapper组装sql查询条件错误 #284---------------------
// step 3 like // step 3 like
//update-begin-author:taoyan for: /issues/3382 默认带*就走模糊,但是如果只有一个*,那么走等于查询
if(rule == null && val.equals(STAR)){
rule = QueryRuleEnum.EQ;
}
//update-end-author:taoyan for: /issues/3382 默认带*就走模糊,但是如果只有一个*,那么走等于查询
if (rule == null && val.contains(STAR)) { if (rule == null && val.contains(STAR)) {
if (val.startsWith(STAR) && val.endsWith(STAR)) { if (val.startsWith(STAR) && val.endsWith(STAR)) {
rule = QueryRuleEnum.LIKE; rule = QueryRuleEnum.LIKE;
@ -416,7 +435,7 @@ public class QueryGenerator {
//update-begin--Author:taoyan Date:20201229 forinitQueryWrapper组装sql查询条件错误 #284--------------------- //update-begin--Author:taoyan Date:20201229 forinitQueryWrapper组装sql查询条件错误 #284---------------------
//特殊处理Oracle的表达式to_date('xxx','yyyy-MM-dd')含有逗号会被识别为in查询转为等于查询 //特殊处理Oracle的表达式to_date('xxx','yyyy-MM-dd')含有逗号会被识别为in查询转为等于查询
if(rule == QueryRuleEnum.IN && val.indexOf("yyyy-MM-dd")>=0 && val.indexOf("to_date")>=0){ if(rule == QueryRuleEnum.IN && val.indexOf(YYYY_MM_DD)>=0 && val.indexOf(TO_DATE)>=0){
rule = QueryRuleEnum.EQ; rule = QueryRuleEnum.EQ;
} }
//update-end--Author:taoyan Date:20201229 forinitQueryWrapper组装sql查询条件错误 #284--------------------- //update-end--Author:taoyan Date:20201229 forinitQueryWrapper组装sql查询条件错误 #284---------------------
@ -439,6 +458,11 @@ public class QueryGenerator {
return value; return value;
} }
String val = (value + "").toString().trim(); String val = (value + "").toString().trim();
//update-begin-author:taoyan date:20220302 for: 查询条件的值为等号(=bug #3443
if(QueryRuleEnum.EQ.getValue().equals(val)){
return val;
}
//update-end-author:taoyan date:20220302 for: 查询条件的值为等号(=bug #3443
if (rule == QueryRuleEnum.LIKE) { if (rule == QueryRuleEnum.LIKE) {
value = val.substring(1, val.length() - 1); value = val.substring(1, val.length() - 1);
//mysql 模糊查询之特殊字符下划线 _、\ //mysql 模糊查询之特殊字符下划线 _、\
@ -538,7 +562,8 @@ public class QueryGenerator {
*/ */
private static Date getDateQueryByRule(String value,QueryRuleEnum rule) throws ParseException { private static Date getDateQueryByRule(String value,QueryRuleEnum rule) throws ParseException {
Date date = null; Date date = null;
if(value.length()==10) { int length = 10;
if(value.length()==length) {
if(rule==QueryRuleEnum.GE) { if(rule==QueryRuleEnum.GE) {
//比较大于 //比较大于
date = getTime().parse(value + " 00:00:00"); date = getTime().parse(value + " 00:00:00");
@ -633,7 +658,7 @@ public class QueryGenerator {
* @return * @return
*/ */
public static Map<String, SysPermissionDataRuleModel> getRuleMap() { public static Map<String, SysPermissionDataRuleModel> getRuleMap() {
Map<String, SysPermissionDataRuleModel> ruleMap = new HashMap<String, SysPermissionDataRuleModel>(); Map<String, SysPermissionDataRuleModel> ruleMap = new HashMap<>(5);
List<SysPermissionDataRuleModel> list =JeecgDataAutorUtils.loadDataSearchConditon(); List<SysPermissionDataRuleModel> list =JeecgDataAutorUtils.loadDataSearchConditon();
if(list != null&&list.size()>0){ if(list != null&&list.size()>0){
if(list.get(0)==null){ if(list.get(0)==null){
@ -664,7 +689,8 @@ public class QueryGenerator {
addEasyQuery(queryWrapper, name, rule, converRuleValue(dataRule.getRuleValue())); addEasyQuery(queryWrapper, name, rule, converRuleValue(dataRule.getRuleValue()));
}else if (propertyType.equals(Date.class)) { }else if (propertyType.equals(Date.class)) {
String dateStr =converRuleValue(dataRule.getRuleValue()); String dateStr =converRuleValue(dataRule.getRuleValue());
if(dateStr.length()==10){ int length = 10;
if(dateStr.length()==length){
addEasyQuery(queryWrapper, name, rule, DateUtils.str2Date(dateStr,DateUtils.date_sdf.get())); addEasyQuery(queryWrapper, name, rule, DateUtils.str2Date(dateStr,DateUtils.date_sdf.get()));
}else{ }else{
addEasyQuery(queryWrapper, name, rule, DateUtils.str2Date(dateStr,DateUtils.datetimeFormat.get())); addEasyQuery(queryWrapper, name, rule, DateUtils.str2Date(dateStr,DateUtils.datetimeFormat.get()));
@ -836,15 +862,15 @@ public class QueryGenerator {
*/ */
private static String getFieldConditionValue(Object value,boolean isString, String dataBaseType) { private static String getFieldConditionValue(Object value,boolean isString, String dataBaseType) {
String str = value.toString().trim(); String str = value.toString().trim();
if(str.startsWith("!")) { if(str.startsWith(SymbolConstant.EXCLAMATORY_MARK)) {
str = str.substring(1); str = str.substring(1);
}else if(str.startsWith(">=")) { }else if(str.startsWith(QueryRuleEnum.GE.getValue())) {
str = str.substring(2); str = str.substring(2);
}else if(str.startsWith("<=")) { }else if(str.startsWith(QueryRuleEnum.LE.getValue())) {
str = str.substring(2); str = str.substring(2);
}else if(str.startsWith(">")) { }else if(str.startsWith(QueryRuleEnum.GT.getValue())) {
str = str.substring(1); str = str.substring(1);
}else if(str.startsWith("<")) { }else if(str.startsWith(QueryRuleEnum.LT.getValue())) {
str = str.substring(1); str = str.substring(1);
}else if(str.indexOf(QUERY_COMMA_ESCAPE)>0) { }else if(str.indexOf(QUERY_COMMA_ESCAPE)>0) {
str = str.replaceAll("\\+\\+", COMMA); str = str.replaceAll("\\+\\+", COMMA);
@ -860,7 +886,7 @@ public class QueryGenerator {
} }
}else { }else {
// 如果不是字符串 有一种特殊情况 popup调用都走这个逻辑 参数传递的可能是“admin”这种格式的 // 如果不是字符串 有一种特殊情况 popup调用都走这个逻辑 参数传递的可能是“admin”这种格式的
if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(dataBaseType) && str.endsWith("'") && str.startsWith("'")){ if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(dataBaseType) && str.endsWith(SymbolConstant.SINGLE_QUOTATION_MARK) && str.startsWith(SymbolConstant.SINGLE_QUOTATION_MARK)){
return " N"+str; return " N"+str;
} }
return value.toString(); return value.toString();
@ -891,34 +917,34 @@ public class QueryGenerator {
private static String getLikeConditionValue(Object value) { private static String getLikeConditionValue(Object value) {
String str = value.toString().trim(); String str = value.toString().trim();
if(str.startsWith("*") && str.endsWith("*")) { if(str.startsWith(SymbolConstant.ASTERISK) && str.endsWith(SymbolConstant.ASTERISK)) {
if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){ if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){
return "N'%"+str.substring(1,str.length()-1)+"%'"; return "N'%"+str.substring(1,str.length()-1)+"%'";
}else{ }else{
return "'%"+str.substring(1,str.length()-1)+"%'"; return "'%"+str.substring(1,str.length()-1)+"%'";
} }
}else if(str.startsWith("*")) { }else if(str.startsWith(SymbolConstant.ASTERISK)) {
if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){ if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){
return "N'%"+str.substring(1)+"'"; return "N'%"+str.substring(1)+"'";
}else{ }else{
return "'%"+str.substring(1)+"'"; return "'%"+str.substring(1)+"'";
} }
}else if(str.endsWith("*")) { }else if(str.endsWith(SymbolConstant.ASTERISK)) {
if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){ if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){
return "N'"+str.substring(0,str.length()-1)+"%'"; return "N'"+str.substring(0,str.length()-1)+"%'";
}else{ }else{
return "'"+str.substring(0,str.length()-1)+"%'"; return "'"+str.substring(0,str.length()-1)+"%'";
} }
}else { }else {
if(str.indexOf("%")>=0) { if(str.indexOf(SymbolConstant.PERCENT_SIGN)>=0) {
if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){ if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){
if(str.startsWith("'") && str.endsWith("'")){ if(str.startsWith(SymbolConstant.SINGLE_QUOTATION_MARK) && str.endsWith(SymbolConstant.SINGLE_QUOTATION_MARK)){
return "N"+str; return "N"+str;
}else{ }else{
return "N"+"'"+str+"'"; return "N"+"'"+str+"'";
} }
}else{ }else{
if(str.startsWith("'") && str.endsWith("'")){ if(str.startsWith(SymbolConstant.SINGLE_QUOTATION_MARK) && str.endsWith(SymbolConstant.SINGLE_QUOTATION_MARK)){
return str; return str;
}else{ }else{
return "'"+str+"'"; return "'"+str+"'";
@ -944,11 +970,11 @@ public class QueryGenerator {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
//权限查询 //权限查询
Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap(); Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap();
PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(clazz); PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(clazz);
String sql_and = " and "; String sqlAnd = " and ";
for (String c : ruleMap.keySet()) { for (String c : ruleMap.keySet()) {
if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){ if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
sb.append(sql_and+getSqlRuleValue(ruleMap.get(c).getRuleValue())); sb.append(sqlAnd+getSqlRuleValue(ruleMap.get(c).getRuleValue()));
} }
} }
String name, column; String name, column;
@ -973,7 +999,7 @@ public class QueryGenerator {
value = NumberUtils.parseNumber(dataRule.getRuleValue(),propType); value = NumberUtils.parseNumber(dataRule.getRuleValue(),propType);
} }
String filedSql = getSingleSqlByRule(rule, oConvertUtils.camelToUnderline(column), value,isString); String filedSql = getSingleSqlByRule(rule, oConvertUtils.camelToUnderline(column), value,isString);
sb.append(sql_and+filedSql); sb.append(sqlAnd+filedSql);
} }
} }
log.info("query auth sql is:"+sb.toString()); log.info("query auth sql is:"+sb.toString());
@ -989,7 +1015,7 @@ public class QueryGenerator {
public static void installAuthMplus(QueryWrapper<?> queryWrapper,Class<?> clazz) { public static void installAuthMplus(QueryWrapper<?> queryWrapper,Class<?> clazz) {
//权限查询 //权限查询
Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap(); Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap();
PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(clazz); PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(clazz);
for (String c : ruleMap.keySet()) { for (String c : ruleMap.keySet()) {
if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){ if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
queryWrapper.and(i ->i.apply(getSqlRuleValue(ruleMap.get(c).getRuleValue()))); queryWrapper.and(i ->i.apply(getSqlRuleValue(ruleMap.get(c).getRuleValue())));
@ -1028,7 +1054,7 @@ public class QueryGenerator {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
//权限查询 //权限查询
Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap(); Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap();
String sql_and = " and "; String sqlAnd = " and ";
for (String c : ruleMap.keySet()) { for (String c : ruleMap.keySet()) {
SysPermissionDataRuleModel dataRule = ruleMap.get(c); SysPermissionDataRuleModel dataRule = ruleMap.get(c);
String ruleValue = dataRule.getRuleValue(); String ruleValue = dataRule.getRuleValue();
@ -1036,7 +1062,7 @@ public class QueryGenerator {
continue; continue;
} }
if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){ if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){
sb.append(sql_and+getSqlRuleValue(ruleValue)); sb.append(sqlAnd+getSqlRuleValue(ruleValue));
}else{ }else{
boolean isString = false; boolean isString = false;
ruleValue = ruleValue.trim(); ruleValue = ruleValue.trim();
@ -1047,7 +1073,7 @@ public class QueryGenerator {
QueryRuleEnum rule = QueryRuleEnum.getByValue(dataRule.getRuleConditions()); QueryRuleEnum rule = QueryRuleEnum.getByValue(dataRule.getRuleConditions());
String value = converRuleValue(ruleValue); String value = converRuleValue(ruleValue);
String filedSql = getSingleSqlByRule(rule, c, value,isString); String filedSql = getSingleSqlByRule(rule, c, value,isString);
sb.append(sql_and+filedSql); sb.append(sqlAnd+filedSql);
} }
} }
log.info("query auth sql is = "+sb.toString()); log.info("query auth sql is = "+sb.toString());
@ -1136,8 +1162,8 @@ public class QueryGenerator {
*/ */
private static String specialStrConvert(String value) { private static String specialStrConvert(String value) {
if (DataBaseConstant.DB_TYPE_MYSQL.equals(getDbType()) || DataBaseConstant.DB_TYPE_MARIADB.equals(getDbType())) { if (DataBaseConstant.DB_TYPE_MYSQL.equals(getDbType()) || DataBaseConstant.DB_TYPE_MARIADB.equals(getDbType())) {
String[] special_str = QueryGenerator.LIKE_MYSQL_SPECIAL_STRS.split(","); String[] specialStr = QueryGenerator.LIKE_MYSQL_SPECIAL_STRS.split(",");
for (String str : special_str) { for (String str : specialStr) {
if (value.indexOf(str) !=-1) { if (value.indexOf(str) !=-1) {
value = value.replace(str, "\\" + str); value = value.replace(str, "\\" + str);
} }

View File

@ -9,18 +9,31 @@ import org.jeecg.common.util.oConvertUtils;
*/ */
public enum QueryRuleEnum { public enum QueryRuleEnum {
/**查询规则 大于*/
GT(">","gt","大于"), GT(">","gt","大于"),
/**查询规则 大于等于*/
GE(">=","ge","大于等于"), GE(">=","ge","大于等于"),
/**查询规则 小于*/
LT("<","lt","小于"), LT("<","lt","小于"),
/**查询规则 小于等于*/
LE("<=","le","小于等于"), LE("<=","le","小于等于"),
/**查询规则 等于*/
EQ("=","eq","等于"), EQ("=","eq","等于"),
/**查询规则 不等于*/
NE("!=","ne","不等于"), NE("!=","ne","不等于"),
/**查询规则 包含*/
IN("IN","in","包含"), IN("IN","in","包含"),
/**查询规则 全模糊*/
LIKE("LIKE","like","全模糊"), LIKE("LIKE","like","全模糊"),
/**查询规则 左模糊*/
LEFT_LIKE("LEFT_LIKE","left_like","左模糊"), LEFT_LIKE("LEFT_LIKE","left_like","左模糊"),
/**查询规则 右模糊*/
RIGHT_LIKE("RIGHT_LIKE","right_like","右模糊"), RIGHT_LIKE("RIGHT_LIKE","right_like","右模糊"),
/**查询规则 带加号等于*/
EQ_WITH_ADD("EQWITHADD","eq_with_add","带加号等于"), EQ_WITH_ADD("EQWITHADD","eq_with_add","带加号等于"),
/**查询规则 多词模糊匹配*/
LIKE_WITH_AND("LIKEWITHAND","like_with_and","多词模糊匹配————暂时未用上"), LIKE_WITH_AND("LIKEWITHAND","like_with_and","多词模糊匹配————暂时未用上"),
/**查询规则 自定义SQL片段*/
SQL_RULES("USE_SQL_RULES","ext","自定义SQL片段"); SQL_RULES("USE_SQL_RULES","ext","自定义SQL片段");
private String value; private String value;

View File

@ -32,7 +32,8 @@ public class JeecgDataAutorUtils {
*/ */
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 // 1.先从request获取MENU_DATA_AUTHOR_RULES如果存则获取到LIST
List<SysPermissionDataRuleModel> list = (List<SysPermissionDataRuleModel>)loadDataSearchConditon();
if (list==null) { if (list==null) {
// 2.如果不存在则new一个list // 2.如果不存在则new一个list
list = new ArrayList<SysPermissionDataRuleModel>(); list = new ArrayList<SysPermissionDataRuleModel>();
@ -40,7 +41,8 @@ public class JeecgDataAutorUtils {
for (SysPermissionDataRuleModel tsDataRule : dataRules) { for (SysPermissionDataRuleModel tsDataRule : dataRules) {
list.add(tsDataRule); list.add(tsDataRule);
} }
request.setAttribute(MENU_DATA_AUTHOR_RULES, list); // 3.往list里面增量存指 // 3.往list里面增量存指
request.setAttribute(MENU_DATA_AUTHOR_RULES, list);
} }
/** /**
@ -59,7 +61,7 @@ public class JeecgDataAutorUtils {
* *
* @return * @return
*/ */
public static synchronized String loadDataSearchConditonSQLString() { public static synchronized String loadDataSearchConditonSqlString() {
return (String) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULE_SQL); return (String) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULE_SQL);
} }
@ -70,7 +72,7 @@ public class JeecgDataAutorUtils {
* @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 = (String) 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);
} }

View File

@ -20,6 +20,7 @@ import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result; import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.DataBaseConstant; import org.jeecg.common.constant.DataBaseConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.exception.JeecgBootException; import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser; import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysUserCacheInfo; import org.jeecg.common.system.vo.SysUserCacheInfo;
@ -34,8 +35,9 @@ import org.jeecg.common.util.oConvertUtils;
**/ **/
public class JwtUtil { public class JwtUtil {
// Token过期时间2小时用户登录过期时间是此时间的两倍以token在reids缓存时间为准 /**Token有效期为1小时Token在reids中缓存时间为两倍*/
public static final long EXPIRE_TIME = 2 * 60 * 60 * 1000; public static final long EXPIRE_TIME = 60 * 60 * 1000;
static final String WELL_NUMBER = SymbolConstant.WELL_NUMBER + SymbolConstant.LEFT_CURLY_BRACKET;
/** /**
* *
@ -45,6 +47,8 @@ public class JwtUtil {
*/ */
public static void responseError(ServletResponse response, Integer code, String errorMsg) { public static void responseError(ServletResponse response, Integer code, String errorMsg) {
HttpServletResponse httpServletResponse = (HttpServletResponse) response; HttpServletResponse httpServletResponse = (HttpServletResponse) response;
// issues/I4YH95浏览器显示乱码问题
httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
Result jsonResult = new Result(code, errorMsg); Result jsonResult = new Result(code, errorMsg);
OutputStream os = null; OutputStream os = null;
try { try {
@ -133,11 +137,13 @@ public class JwtUtil {
//${myVar}% //${myVar}%
//得到${} 后面的值 //得到${} 后面的值
String moshi = ""; String moshi = "";
if(key.indexOf("}")!=-1){ String wellNumber = WELL_NUMBER;
if(key.indexOf(SymbolConstant.RIGHT_CURLY_BRACKET)!=-1){
moshi = key.substring(key.indexOf("}")+1); moshi = key.substring(key.indexOf("}")+1);
} }
String returnValue = null; String returnValue = null;
if (key.contains("#{")) { if (key.contains(wellNumber)) {
key = key.substring(2,key.indexOf("}")); key = key.substring(2,key.indexOf("}"));
} }
if (oConvertUtils.isNotEmpty(key)) { if (oConvertUtils.isNotEmpty(key)) {
@ -165,12 +171,13 @@ public class JwtUtil {
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
String moshi = ""; String moshi = "";
if(key.indexOf("}")!=-1){ String wellNumber = WELL_NUMBER;
if(key.indexOf(SymbolConstant.RIGHT_CURLY_BRACKET)!=-1){
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(wellNumber)) {
key = key.substring(2,key.indexOf("}")); key = key.substring(2,key.indexOf("}"));
} else { } else {
key = key; key = key;
@ -228,7 +235,8 @@ public class JwtUtil {
//update-begin-author:taoyan date:20210330 for:多租户ID作为系统变量 //update-begin-author:taoyan date:20210330 for:多租户ID作为系统变量
else if (key.equals(DataBaseConstant.TENANT_ID) || key.toLowerCase().equals(DataBaseConstant.TENANT_ID_TABLE)){ else if (key.equals(DataBaseConstant.TENANT_ID) || key.toLowerCase().equals(DataBaseConstant.TENANT_ID_TABLE)){
returnValue = sysUser.getRelTenantIds(); returnValue = sysUser.getRelTenantIds();
if(oConvertUtils.isEmpty(returnValue) || (returnValue!=null && returnValue.indexOf(",")>0)){ boolean flag = returnValue != null && returnValue.indexOf(SymbolConstant.COMMA) > 0;
if(oConvertUtils.isEmpty(returnValue) || flag){
returnValue = SpringContextUtils.getHttpServletRequest().getHeader(CommonConstant.TENANT_ID); returnValue = SpringContextUtils.getHttpServletRequest().getHeader(CommonConstant.TENANT_ID);
} }
} }

View File

@ -7,6 +7,10 @@ import lombok.experimental.Accessors;
import java.io.Serializable; import java.io.Serializable;
/**
* @Description:
* @author: jeecg-boot
*/
@Data @Data
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
@Accessors(chain = true) @Accessors(chain = true)

View File

@ -8,6 +8,10 @@ import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
/**
* @Description:
* @author: jeecg-boot
*/
@Data @Data
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
@Accessors(chain = true) @Accessors(chain = true)

View File

@ -5,6 +5,7 @@ import lombok.EqualsAndHashCode;
/** /**
* *
* @author: jeecg-boot
*/ */
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)

View File

@ -4,6 +4,7 @@ import lombok.Data;
/** /**
* *
* @author: jeecg-boot
*/ */
@Data @Data
public class DictQuery { public class DictQuery {

View File

@ -3,6 +3,10 @@ package org.jeecg.common.system.vo;
import lombok.Data; import lombok.Data;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
/**
* @Description:
* @author: jeecg-boot
*/
@Data @Data
public class DynamicDataSourceModel { public class DynamicDataSourceModel {

View File

@ -1,7 +1,8 @@
package org.jeecg.common.system.vo; package org.jeecg.common.system.vo;
/** /**
* lvdandan model * model
* @author: lvdandan
*/ */
public class SysDepartModel { public class SysDepartModel {
/**ID*/ /**ID*/

View File

@ -4,6 +4,10 @@ import java.util.List;
import org.jeecg.common.util.DateUtils; import org.jeecg.common.util.DateUtils;
/**
* @Description:
* @author: jeecg-boot
*/
public class SysUserCacheInfo { public class SysUserCacheInfo {
private String sysUserCode; private String sysUserCode;

View File

@ -6,5 +6,8 @@ package org.jeecg.common.util;
* *
*/ */
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 IE11,IE10,IE9,IE8,IE7,IE6,Firefox,Safari,Chrome,Opera,Camino,Gecko
} }

View File

@ -14,8 +14,12 @@ import javax.servlet.http.HttpServletRequest;
*/ */
public class BrowserUtils { public class BrowserUtils {
// 判断是否是IE /**
public static boolean isIE(HttpServletRequest request) { * IE
* @param request
* @return
*/
public static boolean isIe(HttpServletRequest request) {
return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request
.getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true .getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true
: false; : false;
@ -27,7 +31,7 @@ public class BrowserUtils {
* @param request * @param request
* @return * @return
*/ */
public static Double getIEversion(HttpServletRequest request) { public static Double getIeVersion(HttpServletRequest request) {
Double version = 0.0; Double version = 0.0;
if (getBrowserType(request, IE11)) { if (getBrowserType(request, IE11)) {
version = 11.0; version = 11.0;
@ -83,7 +87,7 @@ public class BrowserUtils {
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;
@ -110,6 +114,7 @@ public class BrowserUtils {
private final static String CHROME = "Chrome"; private final static String CHROME = "Chrome";
private final static String SAFARI = "Safari"; private final static String SAFARI = "Safari";
private final static String OTHER = "其它"; private final static String OTHER = "其它";
private final static String CAMINO = "Camino";
public static String checkBrowse(HttpServletRequest request) { public static String checkBrowse(HttpServletRequest request) {
String userAgent = request.getHeader("USER-AGENT"); String userAgent = request.getHeader("USER-AGENT");
@ -199,7 +204,8 @@ 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)"); String type = "(phone|pad|pod|iphone|ipod|ios|ipad|android|mobile|blackberry|iemobile|mqqbrowser|juc|fennec|wosbrowser|browserng|webos|symbian|windows phone)";
Pattern pattern = Pattern.compile(type);
return pattern.matcher(ua).find(); return pattern.matcher(ua).find();
} }

View File

@ -7,6 +7,7 @@ import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.DataBaseConstant; import org.jeecg.common.constant.DataBaseConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.util.filter.FileTypeFilter; import org.jeecg.common.util.filter.FileTypeFilter;
import org.jeecg.common.util.oss.OssBootUtil; import org.jeecg.common.util.oss.OssBootUtil;
import org.jeecgframework.poi.util.PoiPublicUtil; import org.jeecgframework.poi.util.PoiPublicUtil;
@ -27,12 +28,24 @@ import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/**
* @Description:
* @author: jeecg-boot
*/
@Slf4j @Slf4j
public class CommonUtils { public class CommonUtils {
//中文正则 /**
*
*/
private static Pattern ZHONGWEN_PATTERN = Pattern.compile("[\u4e00-\u9fa5]"); private static Pattern ZHONGWEN_PATTERN = Pattern.compile("[\u4e00-\u9fa5]");
/**
*
* .-_()
*/
private static String FILE_NAME_REGEX = "[^A-Za-z\\.\\(\\)\\-\\_0-9\\u4e00-\\u9fa5]";
public static String uploadOnlineImage(byte[] data,String basePath,String bizPath,String uploadType){ public static String uploadOnlineImage(byte[] data,String basePath,String bizPath,String uploadType){
String dbPath = null; String dbPath = null;
String fileName = "image" + Math.round(Math.random() * 100000000000L); String fileName = "image" + Math.round(Math.random() * 100000000000L);
@ -84,10 +97,17 @@ public class CommonUtils {
.replace("#", "").replace("“", "").replace("”", ""); .replace("#", "").replace("“", "").replace("”", "");
//替换上传文件名字中的空格 //替换上传文件名字中的空格
fileName=fileName.replaceAll("\\s",""); fileName=fileName.replaceAll("\\s","");
//update-beign-author:taoyan date:20220302 for: /issues/3381 online 在线表单 使用文件组件时,上传文件名中含%,下载异常
fileName = fileName.replaceAll(FILE_NAME_REGEX, "");
//update-end-author:taoyan date:20220302 for: /issues/3381 online 在线表单 使用文件组件时,上传文件名中含%,下载异常
return fileName; return fileName;
} }
// java 判断字符串里是否包含中文字符 /**
* java
* @param str
* @return
*/
public static boolean ifContainChinese(String str) { public static boolean ifContainChinese(String str) {
if(str.getBytes().length == str.length()){ if(str.getBytes().length == str.length()){
return false; return false;
@ -127,11 +147,13 @@ public class CommonUtils {
String fileName = null; String fileName = null;
File file = new File(uploadpath + File.separator + bizPath + File.separator ); File file = new File(uploadpath + File.separator + bizPath + File.separator );
if (!file.exists()) { if (!file.exists()) {
file.mkdirs();// 创建文件根目录 // 创建文件根目录
file.mkdirs();
} }
String orgName = mf.getOriginalFilename();// 获取文件名 // 获取文件名
String orgName = mf.getOriginalFilename();
orgName = CommonUtils.getFileName(orgName); orgName = CommonUtils.getFileName(orgName);
if(orgName.indexOf(".")!=-1){ if(orgName.indexOf(SymbolConstant.SPOT)!=-1){
fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf(".")); fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
}else{ }else{
fileName = orgName+ "_" + System.currentTimeMillis(); fileName = orgName+ "_" + System.currentTimeMillis();
@ -145,7 +167,7 @@ public class CommonUtils {
}else{ }else{
dbpath = fileName; dbpath = fileName;
} }
if (dbpath.contains("\\")) { if (dbpath.contains(SymbolConstant.DOUBLE_BACKSLASH)) {
dbpath = dbpath.replace("\\", "/"); dbpath = dbpath.replace("\\", "/");
} }
return dbpath; return dbpath;
@ -259,16 +281,17 @@ public class CommonUtils {
Connection connection = dataSource.getConnection(); Connection connection = dataSource.getConnection();
try { try {
DatabaseMetaData md = connection.getMetaData(); DatabaseMetaData md = connection.getMetaData();
String dbType = md.getDatabaseProductName().toLowerCase(); String dbType = md.getDatabaseProductName().toUpperCase();
if(dbType.indexOf("mysql")>=0) { String sqlserver= "SQL SERVER";
if(dbType.indexOf(DataBaseConstant.DB_TYPE_MYSQL)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL; DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL;
}else if(dbType.indexOf("oracle")>=0 ||dbType.indexOf("dm")>=0) { }else if(dbType.indexOf(DataBaseConstant.DB_TYPE_ORACLE)>=0 ||dbType.indexOf(DataBaseConstant.DB_TYPE_DM)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE; DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE;
}else if(dbType.indexOf("sqlserver")>=0||dbType.indexOf("sql server")>=0) { }else if(dbType.indexOf(DataBaseConstant.DB_TYPE_SQLSERVER)>=0||dbType.indexOf(sqlserver)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER; DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER;
}else if(dbType.indexOf("postgresql")>=0) { }else if(dbType.indexOf(DataBaseConstant.DB_TYPE_POSTGRESQL)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL; DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL;
}else if(dbType.indexOf("mariadb")>=0) { }else if(dbType.indexOf(DataBaseConstant.DB_TYPE_MARIADB)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_MARIADB; DB_TYPE = DataBaseConstant.DB_TYPE_MARIADB;
}else { }else {
log.error("数据库类型:[" + dbType + "]不识别!"); log.error("数据库类型:[" + dbType + "]不识别!");
@ -291,10 +314,10 @@ public class CommonUtils {
*/ */
public static String getBaseUrl(HttpServletRequest request) { public static String getBaseUrl(HttpServletRequest request) {
//1.【兼容】兼容微服务下的 base path------- //1.【兼容】兼容微服务下的 base path-------
String x_gateway_base_path = request.getHeader("X_GATEWAY_BASE_PATH"); String xGatewayBasePath = request.getHeader("X_GATEWAY_BASE_PATH");
if(oConvertUtils.isNotEmpty(x_gateway_base_path)){ if(oConvertUtils.isNotEmpty(xGatewayBasePath)){
log.info("x_gateway_base_path = "+ x_gateway_base_path); log.info("x_gateway_base_path = "+ xGatewayBasePath);
return x_gateway_base_path; return xGatewayBasePath;
} }
//2.【兼容】SSL认证之后request.getScheme()获取不到https的问题 //2.【兼容】SSL认证之后request.getScheme()获取不到https的问题
// https://blog.csdn.net/weixin_34376986/article/details/89767950 // https://blog.csdn.net/weixin_34376986/article/details/89767950
@ -310,7 +333,8 @@ public class CommonUtils {
//返回 host domain //返回 host domain
String baseDomainPath = null; String baseDomainPath = null;
if(80 == serverPort){ int length = 80;
if(length == serverPort){
baseDomainPath = scheme + "://" + serverName + contextPath ; baseDomainPath = scheme + "://" + serverName + contextPath ;
}else{ }else{
baseDomainPath = scheme + "://" + serverName + ":" + serverPort + contextPath ; baseDomainPath = scheme + "://" + serverName + ":" + serverPort + contextPath ;

View File

@ -9,6 +9,7 @@ import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import org.jeecg.common.constant.SymbolConstant;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
@ -63,14 +64,20 @@ public class DateUtils extends PropertyEditorSupport {
} }
}; };
// 以毫秒表示的时间 /**
*
*/
private static final long DAY_IN_MILLIS = 24 * 3600 * 1000; private static final long DAY_IN_MILLIS = 24 * 3600 * 1000;
private static final long HOUR_IN_MILLIS = 3600 * 1000; private static final long HOUR_IN_MILLIS = 3600 * 1000;
private static final long MINUTE_IN_MILLIS = 60 * 1000; private static final long MINUTE_IN_MILLIS = 60 * 1000;
private static final long SECOND_IN_MILLIS = 1000; private static final long SECOND_IN_MILLIS = 1000;
// 指定模式的时间格式 /**
private static SimpleDateFormat getSDFormat(String pattern) { *
* @param pattern
* @return
*/
private static SimpleDateFormat getSdFormat(String pattern) {
return new SimpleDateFormat(pattern); return new SimpleDateFormat(pattern);
} }
@ -169,15 +176,17 @@ 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) {
synchronized (dateSdf) {
Date date = getDate(); Date date = getDate();
if (null == date) { if (null == date) {
return null; return null;
} }
return date_sdf.format(date); return dateSdf.format(date);
}
} }
/** /**
@ -189,28 +198,30 @@ 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 nowDate = null;
try { try {
_date = sformat.parse(date); nowDate = sformat.parse(date);
} catch (ParseException e) { } catch (ParseException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
return sformat.format(_date); return sformat.format(nowDate);
} }
/** /**
* *
* *
* @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) {
synchronized (dateSdf) {
if (null == date) { if (null == date) {
return null; return null;
} }
return date_sdf.format(date); return dateSdf.format(date);
}
} }
/** /**
@ -367,8 +378,10 @@ public class DateUtils extends PropertyEditorSupport {
* *
*/ */
public static String getDataString(SimpleDateFormat formatstr) { public static String getDataString(SimpleDateFormat formatstr) {
synchronized (formatstr) {
return formatstr.format(getCalendar().getTime()); return formatstr.format(getCalendar().getTime());
} }
}
/** /**
* -- * --
@ -407,7 +420,7 @@ public class DateUtils extends PropertyEditorSupport {
* @return * @return
*/ */
public static String formatDate(String pattern) { public static String formatDate(String pattern) {
return getSDFormat(pattern).format(getCalendar().getTime()); return getSdFormat(pattern).format(getCalendar().getTime());
} }
/** /**
@ -418,7 +431,7 @@ public class DateUtils extends PropertyEditorSupport {
* @return * @return
*/ */
public static String formatDate(Calendar cal, String pattern) { public static String formatDate(Calendar cal, String pattern) {
return getSDFormat(pattern).format(cal.getTime()); return getSdFormat(pattern).format(cal.getTime());
} }
/** /**
@ -429,7 +442,7 @@ public class DateUtils extends PropertyEditorSupport {
* @return * @return
*/ */
public static String formatDate(Date date, String pattern) { public static String formatDate(Date date, String pattern) {
return getSDFormat(pattern).format(date); return getSdFormat(pattern).format(date);
} }
// //////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////////
@ -536,7 +549,7 @@ public class DateUtils extends PropertyEditorSupport {
* @throws ParseException * @throws ParseException
*/ */
public static Date parseDate(String src, String pattern) throws ParseException { public static Date parseDate(String src, String pattern) throws ParseException {
return getSDFormat(pattern).parse(src); return getSdFormat(pattern).parse(src);
} }
@ -592,24 +605,29 @@ public class DateUtils extends PropertyEditorSupport {
public static int dateDiff(char flag, Calendar calSrc, Calendar calDes) { public static int dateDiff(char flag, Calendar calSrc, Calendar calDes) {
long millisDiff = getMillis(calSrc) - getMillis(calDes); long millisDiff = getMillis(calSrc) - getMillis(calDes);
char year = 'y';
char day = 'd';
char hour = 'h';
char minute = 'm';
char second = 's';
if (flag == 'y') { if (flag == year) {
return (calSrc.get(Calendar.YEAR) - calDes.get(Calendar.YEAR)); return (calSrc.get(Calendar.YEAR) - calDes.get(Calendar.YEAR));
} }
if (flag == 'd') { if (flag == day) {
return (int) (millisDiff / DAY_IN_MILLIS); return (int) (millisDiff / DAY_IN_MILLIS);
} }
if (flag == 'h') { if (flag == hour) {
return (int) (millisDiff / HOUR_IN_MILLIS); return (int) (millisDiff / HOUR_IN_MILLIS);
} }
if (flag == 'm') { if (flag == minute) {
return (int) (millisDiff / MINUTE_IN_MILLIS); return (int) (millisDiff / MINUTE_IN_MILLIS);
} }
if (flag == 's') { if (flag == second) {
return (int) (millisDiff / SECOND_IN_MILLIS); return (int) (millisDiff / SECOND_IN_MILLIS);
} }
@ -628,9 +646,11 @@ public class DateUtils extends PropertyEditorSupport {
public void setAsText(String text) throws IllegalArgumentException { public void setAsText(String text) throws IllegalArgumentException {
if (StringUtils.hasText(text)) { if (StringUtils.hasText(text)) {
try { try {
if (text.indexOf(":") == -1 && text.length() == 10) { int length10 = 10;
int length19 = 19;
if (text.indexOf(SymbolConstant.COLON) == -1 && text.length() == length10) {
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(SymbolConstant.COLON) > 0 && text.length() == length19) {
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 ");

View File

@ -2,10 +2,17 @@ package org.jeecg.common.util;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
/**
* @Description:
* @author: jeecg-boot
*/
public enum DySmsEnum { public enum DySmsEnum {
/**登录短信模板编码*/
LOGIN_TEMPLATE_CODE("SMS_175435174","JEECG","code"), LOGIN_TEMPLATE_CODE("SMS_175435174","JEECG","code"),
/**忘记密码短信模板编码*/
FORGET_PASSWORD_TEMPLATE_CODE("SMS_175435174","JEECG","code"), FORGET_PASSWORD_TEMPLATE_CODE("SMS_175435174","JEECG","code"),
/**注册账号短信模板编码*/
REGISTER_TEMPLATE_CODE("SMS_175430166","JEECG","code"), REGISTER_TEMPLATE_CODE("SMS_175430166","JEECG","code"),
/**会议通知*/ /**会议通知*/
MEET_NOTICE_TEMPLATE_CODE("SMS_201480469","H5活动之家","username,title,minute,time"), MEET_NOTICE_TEMPLATE_CODE("SMS_201480469","H5活动之家","username,title,minute,time"),

View File

@ -23,17 +23,18 @@ import com.aliyuncs.profile.IClientProfile;
* *
* :DemoUTF-8 * :DemoUTF-8
* DEMO * DEMO
* @author: jeecg-boot
*/ */
public class DySmsHelper { public class DySmsHelper {
private final static Logger logger=LoggerFactory.getLogger(DySmsHelper.class); private final static 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(在阿里云访问控制台寻找) /**TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)*/
static String accessKeyId; static String accessKeyId;
static String accessKeySecret; static String accessKeySecret;
@ -67,7 +68,7 @@ public class DySmsHelper {
//初始化acsClient,暂不支持region化 //初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", PRODUCT, DOMAIN);
IAcsClient acsClient = new DefaultAcsClient(profile); IAcsClient acsClient = new DefaultAcsClient(profile);
//验证json参数 //验证json参数
@ -96,7 +97,8 @@ public class DySmsHelper {
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()+"}"); logger.info("{Code:" + sendSmsResponse.getCode()+",Message:" + sendSmsResponse.getMessage()+",RequestId:"+ sendSmsResponse.getRequestId()+",BizId:"+sendSmsResponse.getBizId()+"}");
if ("OK".equals(sendSmsResponse.getCode())) { String ok = "OK";
if (ok.equals(sendSmsResponse.getCode())) {
result = true; result = true;
} }
return result; return result;

View File

@ -5,7 +5,10 @@ import org.springframework.web.util.HtmlUtils;
/** /**
* HTML * HTML
* @author: jeecg-boot
* @date: 2022/3/30 14:43
*/ */
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
public class HTMLUtils { public class HTMLUtils {
/** /**

View File

@ -3,6 +3,7 @@ package org.jeecg.common.util;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -13,8 +14,8 @@ import org.slf4j.LoggerFactory;
* @email jeecgos@163.com * @email jeecgos@163.com
* @Date 20190114 * @Date 20190114
*/ */
public class IPUtils { public class IpUtils {
private static Logger logger = LoggerFactory.getLogger(IPUtils.class); private static Logger logger = LoggerFactory.getLogger(IpUtils.class);
/** /**
* IP * IP
@ -26,19 +27,19 @@ public class IPUtils {
String ip = null; String ip = null;
try { try {
ip = request.getHeader("x-forwarded-for"); ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { if (StringUtils.isEmpty(ip) || CommonConstant.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 ||CommonConstant.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) || CommonConstant.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) || CommonConstant.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) || CommonConstant.UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr(); ip = request.getRemoteAddr();
} }
} catch (Exception e) { } catch (Exception e) {

View File

@ -12,6 +12,7 @@ import java.util.List;
/** /**
* *
* @author: jeecg-boot
*/ */
@Slf4j @Slf4j
public class ImportExcelUtil { public class ImportExcelUtil {

View File

@ -2,9 +2,16 @@ package org.jeecg.common.util;
import java.security.MessageDigest; import java.security.MessageDigest;
public class MD5Util { /**
* @Description:
* @author: jeecg-boot
*/
public class Md5Util {
public static String byteArrayToHexString(byte b[]) { private static final String[] HEXDIGITS = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public static String byteArrayToHexString(byte[] b) {
StringBuffer resultSb = new StringBuffer(); StringBuffer resultSb = new StringBuffer();
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,10 +26,10 @@ 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 HEXDIGITS[d1] + HEXDIGITS[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 = new String(origin);
@ -37,7 +44,4 @@ public class MD5Util {
return resultString; return resultString;
} }
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
} }

View File

@ -3,6 +3,7 @@ package org.jeecg.common.util;
import io.minio.*; import io.minio.*;
import io.minio.http.Method; import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.util.filter.FileTypeFilter; import org.jeecg.common.util.filter.FileTypeFilter;
import org.jeecg.common.util.filter.StrAttackFilter; import org.jeecg.common.util.filter.StrAttackFilter;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@ -12,6 +13,7 @@ import java.net.URLDecoder;
/** /**
* minio * minio
* @author: jeecg-boot
*/ */
@Slf4j @Slf4j
public class MinioUtil { public class MinioUtil {
@ -52,7 +54,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: 过滤上传文件夹名特殊字符,防止攻击
@ -87,7 +89,7 @@ public class MinioUtil {
); );
// 使用putObject上传一个本地文件到存储桶中。 // 使用putObject上传一个本地文件到存储桶中。
if(objectName.startsWith("/")){ if(objectName.startsWith(SymbolConstant.SINGLE_SLASH)){
objectName = objectName.substring(1); objectName = objectName.substring(1);
} }
PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName) PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
@ -96,11 +98,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+"/"+objectName;
}catch (Exception e){ }catch (Exception e){
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
return file_url; return fileUrl;
} }
/** /**
@ -156,7 +158,7 @@ public class MinioUtil {
* @param expires * @param expires
* @return * @return
*/ */
public static String getObjectURL(String bucketName, String objectName, Integer expires) { public static String getObjectUrl(String bucketName, String objectName, Integer expires) {
initMinio(minioUrl, minioName,minioPass); initMinio(minioUrl, minioName,minioPass);
try{ try{
//update-begin---author:liusq Date:20220121 for获取文件外链报错提示method不能为空导致文件下载和预览失败---- //update-begin---author:liusq Date:20220121 for获取文件外链报错提示method不能为空导致文件下载和预览失败----

View File

@ -1,5 +1,7 @@
package org.jeecg.common.util; package org.jeecg.common.util;
import org.jeecg.common.constant.SymbolConstant;
/** /**
* @Author * @Author
*/ */
@ -15,7 +17,11 @@ public class MyClassLoader extends ClassLoader {
return myclass; return myclass;
} }
// 获得类的全名,包括包名 /**
*
* @param object
* @return
*/
public static String getPackPath(Object object) { public static String getPackPath(Object object) {
// 检查用户传入的参数是否为空 // 检查用户传入的参数是否为空
if (object == null) { if (object == null) {
@ -40,22 +46,29 @@ public class MyClassLoader extends ClassLoader {
// 如果不是匿名包,将包名转化为路径 // 如果不是匿名包,将包名转化为路径
if (pack != null) { if (pack != null) {
String packName = pack.getName(); String packName = pack.getName();
String javaSpot="java.";
String javaxSpot="javax.";
// 此处简单判定是否是Java基础类库防止用户传入JDK内置的类库 // 此处简单判定是否是Java基础类库防止用户传入JDK内置的类库
if (packName.startsWith("java.") || packName.startsWith("javax.")) { if (packName.startsWith(javaSpot) || packName.startsWith(javaxSpot)) {
throw new java.lang.IllegalArgumentException("不要传送系统类!"); throw new java.lang.IllegalArgumentException("不要传送系统类!");
} }
// 在类的名称中,去掉包名的部分,获得类的文件名 // 在类的名称中,去掉包名的部分,获得类的文件名
clsName = clsName.substring(packName.length() + 1); clsName = clsName.substring(packName.length() + 1);
// 判定包名是否是简单包名,如果是,则直接将包名转换为路径, // 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
if (packName.indexOf(".") < 0) { if (packName.indexOf(SymbolConstant.SPOT) < 0) {
path = packName + "/"; path = packName + "/";
} else {// 否则按照包名的组成部分,将包名转换为路径 } else {
// 否则按照包名的组成部分,将包名转换为路径
int start = 0, end = 0; int start = 0, end = 0;
end = packName.indexOf("."); end = packName.indexOf(".");
StringBuilder pathBuilder = new StringBuilder();
while (end != -1) { while (end != -1) {
path = path + packName.substring(start, end) + "/"; pathBuilder.append(packName, start, end).append("/");
start = end + 1; start = end + 1;
end = packName.indexOf(".", start); end = packName.indexOf(".", start);
}
if(oConvertUtils.isNotEmpty(pathBuilder.toString())){
path = pathBuilder.toString();
} }
path = path + packName.substring(start) + "/"; path = path + packName.substring(start) + "/";
} }
@ -73,7 +86,7 @@ public class MyClassLoader extends ClassLoader {
pos = realPath.indexOf(path + clsName); pos = realPath.indexOf(path + clsName);
realPath = realPath.substring(0, pos - 1); realPath = realPath.substring(0, pos - 1);
// 如果类文件被打包到JAR等文件中时去掉对应的JAR等打包文件名 // 如果类文件被打包到JAR等文件中时去掉对应的JAR等打包文件名
if (realPath.endsWith("!")) { if (realPath.endsWith(SymbolConstant.EXCLAMATORY_MARK)) {
realPath = realPath.substring(0, realPath.lastIndexOf("/")); realPath = realPath.substring(0, realPath.lastIndexOf("/"));
} }
/*------------------------------------------------------------ /*------------------------------------------------------------

View File

@ -7,6 +7,11 @@ 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;
/**
* @Description:
* @author: jeecg-boot
*/
public class PasswordUtil { public class PasswordUtil {
/** /**
@ -16,9 +21,15 @@ public class PasswordUtil {
/** /**
* 使:PBEWITHMD5andDES * 使:PBEWITHMD5andDES
*
*/ */
public static final String ALGORITHM = "PBEWithMD5AndDES";//加密算法 public static final String ALGORITHM = "PBEWithMD5AndDES";
public static final String Salt = "63293188";//密钥
/**
* 使:PBEWITHMD5andDES
*
*/
public static final String SALT = "63293188";
/** /**
* 1000 * 1000
@ -39,7 +50,7 @@ public class PasswordUtil {
public static byte[] getStaticSalt() { public static byte[] getStaticSalt() {
// 产出盐 // 产出盐
return Salt.getBytes(); return SALT.getBytes();
} }
/** /**
@ -49,7 +60,7 @@ public class PasswordUtil {
* 使 * 使
* @return Key PBE * @return Key PBE
* */ * */
private static Key getPBEKey(String password) { private static Key getPbeKey(String password) {
// 实例化使用的算法 // 实例化使用的算法
SecretKeyFactory keyFactory; SecretKeyFactory keyFactory;
SecretKey secretKey = null; SecretKey secretKey = null;
@ -81,7 +92,7 @@ public class PasswordUtil {
*/ */
public static String encrypt(String plaintext, String password, String salt) { public static String encrypt(String plaintext, String password, String salt) {
Key key = getPBEKey(password); Key key = getPbeKey(password);
byte[] encipheredData = null; byte[] encipheredData = null;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT); PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT);
try { try {
@ -110,7 +121,7 @@ public class PasswordUtil {
*/ */
public static String decrypt(String ciphertext, String password, String salt) { public static String decrypt(String ciphertext, String password, String salt) {
Key key = getPBEKey(password); Key key = getPbeKey(password);
byte[] passDec = null; byte[] passDec = null;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT); PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT);
try { try {
@ -158,7 +169,7 @@ public class PasswordUtil {
* @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 null;
} }
hexString = hexString.toUpperCase(); hexString = hexString.toUpperCase();

View File

@ -7,6 +7,7 @@ import org.springframework.util.AntPathMatcher;
/** /**
* 使SpringURL * 使SpringURL
* @author: jeecg-boot
*/ */
public class PathMatcherUtil { public class PathMatcherUtil {
@ -77,8 +78,19 @@ public class PathMatcherUtil {
} }
private interface Matcher { private interface Matcher {
/**
*
* @param var1
* @return
*/
boolean matches(String var1); boolean matches(String var1);
/**
* path
* @param var1
* @return
*/
Map<String, String> extractUriTemplateVariables(String var1); Map<String, String> extractUriTemplateVariables(String var1);
} }
} }

View File

@ -10,6 +10,10 @@ import java.io.FileWriter;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
/**
* @Description: PmsUtil
* @author: jeecg-boot
*/
@Slf4j @Slf4j
@Component @Component
public class PmsUtil { public class PmsUtil {
@ -41,7 +45,7 @@ public class PmsUtil {
for (String s : msg) { for (String s : msg) {
//写数据 //写数据
if (s.indexOf("_") > 0) { if (s.indexOf("_") > 0) {
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);

View File

@ -231,7 +231,7 @@ public class ReflectHelper {
List<Map> list = new ArrayList<Map>(); List<Map> list = new ArrayList<Map>();
Map<String, Object> infoMap = null; 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<>(5);
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));

View File

@ -28,7 +28,8 @@ public class RestUtil {
// issues/2959 // issues/2959
// 微服务版集成企业微信单点登录 // 微服务版集成企业微信单点登录
// 因为微服务版没有端口号,导致 SpringContextUtils.getDomain() 方法获取的域名的端口号变成了:-1所以出问题了只需要把这个-1给去掉就可以了。 // 因为微服务版没有端口号,导致 SpringContextUtils.getDomain() 方法获取的域名的端口号变成了:-1所以出问题了只需要把这个-1给去掉就可以了。
if (domain.endsWith(":-1")) { String port=":-1";
if (domain.endsWith(port)) {
domain = domain.substring(0, domain.length() - 3); domain = domain.substring(0, domain.length() - 3);
} }
} }

View File

@ -11,6 +11,10 @@ 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;
/**
* @Description: spring
* @author: jeecg-boot
*/
@Component @Component
public class SpringContextUtils implements ApplicationContextAware { public class SpringContextUtils implements ApplicationContextAware {

View File

@ -3,7 +3,6 @@ package org.jeecg.common.util;
import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException; import org.jeecg.common.exception.JeecgBootException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -19,9 +18,12 @@ public class SqlInjectionUtil {
* 线 20200501 * 线 20200501
*/ */
private final static String TABLE_DICT_SIGN_SALT = "20200501"; private final static String TABLE_DICT_SIGN_SALT = "20200501";
private final static String xssStr = "and |exec |insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |;|or |+|user()"; private final static String XSS_STR = "and |exec |insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |;|or |+|user()";
/* /**show tables*/
private final static String SHOW_TABLES = "show\\s+tables";
/**
* sign * sign
* @param dictCode: * @param dictCode:
* @param sign: * @param sign:
@ -56,7 +58,7 @@ public class SqlInjectionUtil {
//SQL注入检测存在绕过风险 https://gitee.com/jeecg/jeecg-boot/issues/I4NZGE //SQL注入检测存在绕过风险 https://gitee.com/jeecg/jeecg-boot/issues/I4NZGE
value = value.replaceAll("/\\*.*\\*/",""); value = value.replaceAll("/\\*.*\\*/","");
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注入关键词---> {}", xssArr[i]);
@ -64,7 +66,7 @@ public class SqlInjectionUtil {
throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value); throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value);
} }
} }
if(Pattern.matches("show\\s+tables", value)){ if(Pattern.matches(SHOW_TABLES, value)){
throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value); throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value);
} }
return; return;
@ -77,7 +79,7 @@ public class SqlInjectionUtil {
* @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;
@ -94,7 +96,7 @@ public class SqlInjectionUtil {
throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value); throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value);
} }
} }
if(Pattern.matches("show\\s+tables", value)){ if(Pattern.matches(SHOW_TABLES, value)){
throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value); throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value);
} }
} }
@ -102,11 +104,13 @@ public class SqlInjectionUtil {
} }
/** /**
* @() SQL *
* SQL
*
* @param value * @param value
* @return * @return
*/ */
@Deprecated //@Deprecated
public static void specialFilterContent(String value) { public static void specialFilterContent(String value) {
String specialXssStr = " exec | insert | select | delete | update | drop | count | chr | mid | master | truncate | char | declare |;|+|"; String specialXssStr = " exec | insert | select | delete | update | drop | count | chr | mid | master | truncate | char | declare |;|+|";
String[] xssArr = specialXssStr.split("\\|"); String[] xssArr = specialXssStr.split("\\|");
@ -125,7 +129,7 @@ public class SqlInjectionUtil {
throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value); throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value);
} }
} }
if(Pattern.matches("show\\s+tables", value)){ if(Pattern.matches(SHOW_TABLES, value)){
throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value); throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value);
} }
return; return;
@ -133,11 +137,12 @@ public class SqlInjectionUtil {
/** /**
* @() OnlineSQL *
* OnlineSQL
* @param value * @param value
* @return * @return
*/ */
@Deprecated //@Deprecated
public static void specialFilterContentForOnlineReport(String value) { public static void specialFilterContentForOnlineReport(String value) {
String specialXssStr = " exec | insert | delete | update | drop | chr | mid | master | truncate | char | declare |"; String specialXssStr = " exec | insert | delete | update | drop | chr | mid | master | truncate | char | declare |";
String[] xssArr = specialXssStr.split("\\|"); String[] xssArr = specialXssStr.split("\\|");
@ -157,7 +162,7 @@ public class SqlInjectionUtil {
} }
} }
if(Pattern.matches("show\\s+tables", value)){ if(Pattern.matches(SHOW_TABLES, value)){
throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value); throw new RuntimeException("请注意值可能存在SQL注入风险!--->" + value);
} }
return; return;

View File

@ -2,6 +2,7 @@ package org.jeecg.common.util;
/** /**
* *
* @author: jeecg-boot
*/ */
public enum SysAnnmentTypeEnum { public enum SysAnnmentTypeEnum {
/** /**

View File

@ -3,6 +3,7 @@ package org.jeecg.common.util;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.CommonAPI; import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBoot401Exception; import org.jeecg.common.exception.JeecgBoot401Exception;
import org.jeecg.common.system.util.JwtUtil; import org.jeecg.common.system.util.JwtUtil;
@ -35,40 +36,16 @@ public class TokenUtils {
/** /**
* Token * Token
*/ */
public static boolean verifyToken(HttpServletRequest request, CommonAPI commonAPI, RedisUtil redisUtil) { public static boolean verifyToken(HttpServletRequest request, CommonAPI commonApi, RedisUtil redisUtil) {
log.debug(" -- url --" + request.getRequestURL()); log.debug(" -- url --" + request.getRequestURL());
String token = getTokenByRequest(request); String token = getTokenByRequest(request);
return TokenUtils.verifyToken(token, commonApi, redisUtil);
if (StringUtils.isBlank(token)) {
throw new JeecgBoot401Exception("Token不能为空!");
}
// 解密获得username用于和数据库进行对比
String username = JwtUtil.getUsername(token);
if (username == null) {
throw new JeecgBoot401Exception("Token非法无效!");
}
// 查询用户信息
LoginUser user = commonAPI.getUserByName(username);
if (user == null) {
throw new JeecgBoot401Exception("用户不存在!");
}
// 判断用户状态
if (user.getStatus() != 1) {
throw new JeecgBoot401Exception("账号已锁定,请联系管理员!");
}
// 校验token是否超时失效 & 或者账号密码是否错误
if (!jwtTokenRefresh(token, username, user.getPassword(), redisUtil)) {
throw new JeecgBoot401Exception("Token失效请重新登录");
}
return true;
} }
/** /**
* Token * Token
*/ */
public static boolean verifyToken(String token, CommonAPI commonAPI, RedisUtil redisUtil) { public static boolean verifyToken(String token, CommonAPI commonApi, RedisUtil redisUtil) {
if (StringUtils.isBlank(token)) { if (StringUtils.isBlank(token)) {
throw new JeecgBoot401Exception("token不能为空!"); throw new JeecgBoot401Exception("token不能为空!");
} }
@ -80,7 +57,8 @@ public class TokenUtils {
} }
// 查询用户信息 // 查询用户信息
LoginUser user = commonAPI.getUserByName(username); LoginUser user = TokenUtils.getLoginUser(username, commonApi, redisUtil);
//LoginUser user = commonApi.getUserByName(username);
if (user == null) { if (user == null) {
throw new JeecgBoot401Exception("用户不存在!"); throw new JeecgBoot401Exception("用户不存在!");
} }
@ -104,7 +82,7 @@ public class TokenUtils {
* @return * @return
*/ */
private static boolean jwtTokenRefresh(String token, String userName, String passWord, RedisUtil redisUtil) { private static boolean jwtTokenRefresh(String token, String userName, String passWord, RedisUtil redisUtil) {
String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token)); String cacheToken = oConvertUtils.getString(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
if (oConvertUtils.isNotEmpty(cacheToken)) { if (oConvertUtils.isNotEmpty(cacheToken)) {
// 校验token有效性 // 校验token有效性
if (!JwtUtil.verify(cacheToken, userName, passWord)) { if (!JwtUtil.verify(cacheToken, userName, passWord)) {
@ -113,16 +91,27 @@ 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 * 2 / 1000); redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 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;
} }
/**
*
*
* @param commonApi
* @param username
* @return
*/
public static LoginUser getLoginUser(String username, CommonAPI commonApi, RedisUtil redisUtil) {
LoginUser loginUser = null;
String loginUserKey = CacheConstant.SYS_USERS_CACHE + "::" + username;
if(redisUtil.hasKey(loginUserKey)){
loginUser = (LoginUser) redisUtil.get(loginUserKey);
}else{
// 查询用户信息
loginUser = commonApi.getUserByName(username);
}
return loginUser;
}
} }

View File

@ -18,8 +18,8 @@ public class UUIDGenerator {
*/ */
public static String generate() { public static String generate() {
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();
} }
@ -53,7 +53,7 @@ public class UUIDGenerator {
return buf.toString(); return buf.toString();
} }
private final static int getJVM() { private final static int getJvm() {
return JVM; return JVM;
} }
@ -69,7 +69,7 @@ public class UUIDGenerator {
/** /**
* Unique in a local network * Unique in a local network
*/ */
private final static int getIP() { private final static int getIp() {
return IP; return IP;
} }
@ -86,7 +86,8 @@ public class UUIDGenerator {
private final static int toInt(byte[] bytes) { private final static int toInt(byte[] bytes) {
int result = 0; int result = 0;
for (int i = 0; i < 4; i++) { int length = 4;
for (int i = 0; i < length; i++) {
result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i]; result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i];
} }
return result; return result;

View File

@ -13,9 +13,12 @@ public class YouBianCodeUtil {
// 数字位数(默认生成3位的数字) // 数字位数(默认生成3位的数字)
private static final int numLength = 2;//代表数字位数 /**代表数字位数*/
private static final int NUM_LENGTH = 2;
public static final int zhanweiLength = 1+numLength; public static final int ZHANWEI_LENGTH = 1+ NUM_LENGTH;
public static final char LETTER= 'Z';
/** /**
* codecode * codecode
@ -31,10 +34,10 @@ 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)); Integer afterCodeNum = Integer.parseInt(afterCode.substring(1));
// org.jeecgframework.core.util.LogUtil.info(after_code); // org.jeecgframework.core.util.LogUtil.info(after_code);
// org.jeecgframework.core.util.LogUtil.info(after_code_zimu); // org.jeecgframework.core.util.LogUtil.info(after_code_zimu);
// org.jeecgframework.core.util.LogUtil.info(after_code_num); // org.jeecgframework.core.util.LogUtil.info(after_code_num);
@ -42,23 +45,23 @@ public class YouBianCodeUtil {
String nextNum = ""; String nextNum = "";
char nextZimu = 'A'; char nextZimu = 'A';
// 先判断数字等于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 (LETTER == 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;
@ -107,7 +110,7 @@ public class YouBianCodeUtil {
* @return * @return
*/ */
private static String getStrNum(int num) { private static String getStrNum(int num) {
String s = String.format("%0" + numLength + "d", num); String s = String.format("%0" + NUM_LENGTH + "d", num);
return s; return s;
} }
@ -129,7 +132,7 @@ public class YouBianCodeUtil {
* @return * @return
*/ */
private static char getNextZiMu(char zimu) { private static char getNextZiMu(char zimu) {
if (zimu == 'Z') { if (zimu == LETTER) {
return 'A'; return 'A';
} }
zimu++; zimu++;
@ -145,21 +148,21 @@ 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 null;
}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;
} }

View File

@ -4,7 +4,6 @@ import com.alibaba.druid.pool.DruidDataSource;
import org.jeecg.common.api.CommonAPI; import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.constant.CacheConstant; import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.vo.DynamicDataSourceModel; import org.jeecg.common.system.vo.DynamicDataSourceModel;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils; import org.jeecg.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;
@ -13,6 +12,7 @@ import java.util.Map;
/** /**
* *
* @author: jeecg-boot
*/ */
public class DataSourceCachePool { public class DataSourceCachePool {
/** 数据源连接池缓存【本地 class缓存 - 不支持分布式】 */ /** 数据源连接池缓存【本地 class缓存 - 不支持分布式】 */
@ -37,8 +37,8 @@ public class DataSourceCachePool {
if (getRedisTemplate().hasKey(redisCacheKey)) { if (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);
DynamicDataSourceModel dbSource = commonAPI.getDynamicDbSourceByCode(dbKey); DynamicDataSourceModel dbSource = commonApi.getDynamicDbSourceByCode(dbKey);
if (dbSource != null) { if (dbSource != null) {
getRedisTemplate().opsForValue().set(redisCacheKey, dbSource); getRedisTemplate().opsForValue().set(redisCacheKey, dbSource);
} }

View File

@ -9,38 +9,58 @@ import java.util.Map;
/** /**
* *
* *
* @author: jeecg-boot
*/ */
public class DbTypeUtils { public class DbTypeUtils {
public static Map<String, String> dialectMap = new HashMap<String, String>(); public static Map<String, String> dialectMap = new HashMap<String, String>();
static{ static{
dialectMap.put("mysql", "org.hibernate.dialect.MySQL5InnoDBDialect"); dialectMap.put("mysql", "org.hibernate.dialect.MySQL5InnoDBDialect");
dialectMap.put("mariadb", "org.hibernate.dialect.MariaDBDialect");// 1 -- // mariadb数据库 1 --
dialectMap.put("oracle", "org.hibernate.dialect.OracleDialect");//1 dialectMap.put("mariadb", "org.hibernate.dialect.MariaDBDialect");
dialectMap.put("oracle12c", "org.hibernate.dialect.OracleDialect"); // TODO 没找到不确定 //oracle数据库 1
dialectMap.put("db2", "org.hibernate.dialect.DB2390Dialect"); // 1xx dialectMap.put("oracle", "org.hibernate.dialect.OracleDialect");
dialectMap.put("h2", "org.hibernate.dialect.HSQLDialect");// H2数据库 // TODO 没找到不确定
dialectMap.put("hsql", "org.hibernate.dialect.HSQLDialect");// HSQL数据库 1 dialectMap.put("oracle12c", "org.hibernate.dialect.OracleDialect");
dialectMap.put("sqlite", "org.jeecg.modules.online.config.dialect.SQLiteDialect"); //SQLite数据库 应用平台mobile // db2数据库 1xx
dialectMap.put("postgresql", "org.hibernate.dialect.PostgreSQLDialect"); //1 -- dialectMap.put("db2", "org.hibernate.dialect.DB2390Dialect");
// H2数据库
dialectMap.put("h2", "org.hibernate.dialect.HSQLDialect");
// HSQL数据库 1
dialectMap.put("hsql", "org.hibernate.dialect.HSQLDialect");
//SQLite数据库 应用平台mobile
dialectMap.put("sqlite", "org.jeecg.modules.online.config.dialect.SQLiteDialect");
//PostgreSQL数据库1 --
dialectMap.put("postgresql", "org.hibernate.dialect.PostgreSQLDialect");
dialectMap.put("sqlserver2005", "org.hibernate.dialect.SQLServer2005Dialect"); dialectMap.put("sqlserver2005", "org.hibernate.dialect.SQLServer2005Dialect");
dialectMap.put("sqlserver", "org.hibernate.dialect.SQLServerDialect"); //1 //sqlserver数据库1
dialectMap.put("dm", "org.hibernate.dialect.DmDialect");//达梦数据库 [国产] 1-- dialectMap.put("sqlserver", "org.hibernate.dialect.SQLServerDialect");
dialectMap.put("xugu", "org.hibernate.dialect.HSQLDialect"); //虚谷数据库 //达梦数据库 [国产] 1--
dialectMap.put("kingbasees", "org.hibernate.dialect.PostgreSQLDialect"); //人大金仓 [国产] 1 dialectMap.put("dm", "org.hibernate.dialect.DmDialect");
dialectMap.put("phoenix", "org.hibernate.dialect.HSQLDialect"); // Phoenix HBase数据库 //虚谷数据库
dialectMap.put("zenith", "org.hibernate.dialect.PostgreSQLDialect"); // Gauss 数据库 dialectMap.put("xugu", "org.hibernate.dialect.HSQLDialect");
dialectMap.put("clickhouse", "org.hibernate.dialect.MySQLDialect"); //阿里云PolarDB //人大金仓 [国产] 1
dialectMap.put("gbase", "org.hibernate.dialect.PostgreSQLDialect"); // 南大通用数据库 TODO 没找到不确定 dialectMap.put("kingbasees", "org.hibernate.dialect.PostgreSQLDialect");
dialectMap.put("oscar", "org.hibernate.dialect.PostgreSQLDialect"); //神通数据库 [国产] TODO 没找到不确定 // Phoenix HBase数据库
dialectMap.put("sybase", "org.hibernate.dialect.SybaseDialect"); //Sybase ASE 数据库 dialectMap.put("phoenix", "org.hibernate.dialect.HSQLDialect");
dialectMap.put("oceanbase", "org.hibernate.dialect.PostgreSQLDialect"); //OceanBase 数据库 TODO 没找到不确定 // Gauss 数据库
dialectMap.put("zenith", "org.hibernate.dialect.PostgreSQLDialect");
//阿里云PolarDB
dialectMap.put("clickhouse", "org.hibernate.dialect.MySQLDialect");
// 南大通用数据库 TODO 没找到不确定
dialectMap.put("gbase", "org.hibernate.dialect.PostgreSQLDialect");
//神通数据库 [国产] TODO 没找到不确定
dialectMap.put("oscar", "org.hibernate.dialect.PostgreSQLDialect");
//Sybase ASE 数据库
dialectMap.put("sybase", "org.hibernate.dialect.SybaseDialect");
dialectMap.put("oceanbase", "org.hibernate.dialect.PostgreSQLDialect");
dialectMap.put("Firebird", "org.hibernate.dialect.FirebirdDialect"); dialectMap.put("Firebird", "org.hibernate.dialect.FirebirdDialect");
dialectMap.put("highgo", "org.hibernate.dialect.HSQLDialect"); //瀚高数据库 //瀚高数据库
dialectMap.put("highgo", "org.hibernate.dialect.HSQLDialect");
dialectMap.put("other", "org.hibernate.dialect.PostgreSQLDialect"); dialectMap.put("other", "org.hibernate.dialect.PostgreSQLDialect");
} }
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);
} }
@ -48,7 +68,7 @@ public class DbTypeUtils {
return dbTypeIf(dbType, DbType.ORACLE, DbType.ORACLE_12C, DbType.DM); return dbTypeIf(dbType, DbType.ORACLE, DbType.ORACLE_12C, DbType.DM);
} }
public static boolean dbTypeIsSQLServer(DbType dbType) { public static boolean dbTypeIsSqlServer(DbType dbType) {
return dbTypeIf(dbType, DbType.SQL_SERVER, DbType.SQL_SERVER2005); return dbTypeIf(dbType, DbType.SQL_SERVER, DbType.SQL_SERVER2005);
} }
@ -70,7 +90,7 @@ public class DbTypeUtils {
return DataBaseConstant.DB_TYPE_HSQL; return DataBaseConstant.DB_TYPE_HSQL;
}else if(dbTypeIsOracle(dbType)){ }else if(dbTypeIsOracle(dbType)){
return DataBaseConstant.DB_TYPE_ORACLE; return DataBaseConstant.DB_TYPE_ORACLE;
}else if(dbTypeIsSQLServer(dbType)){ }else if(dbTypeIsSqlServer(dbType)){
return DataBaseConstant.DB_TYPE_SQLSERVER; return DataBaseConstant.DB_TYPE_SQLSERVER;
}else if(dbTypeIsPostgre(dbType)){ }else if(dbTypeIsPostgre(dbType)){
return DataBaseConstant.DB_TYPE_POSTGRESQL; return DataBaseConstant.DB_TYPE_POSTGRESQL;

View File

@ -274,7 +274,15 @@ public class DynamicDBUtil {
return list; return list;
} }
//此方法只能返回单列,不能返回实体类 /**
*
* @param dbKey key
* @param sql sal
* @param clazz
* @param param
* @param <T>
* @return
*/
public static <T> List<T> findList(final String dbKey, String sql, Class<T> clazz, Object... param) { public static <T> List<T> findList(final String dbKey, String sql, Class<T> clazz, Object... param) {
List<T> list; List<T> list;
JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey);

View File

@ -6,6 +6,8 @@ import freemarker.template.Configuration;
import freemarker.template.Template; import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.DataBaseConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecgframework.codegenerate.generate.util.SimpleFormat; import org.jeecgframework.codegenerate.generate.util.SimpleFormat;
import java.io.StringWriter; import java.io.StringWriter;
@ -31,26 +33,26 @@ public class FreemarkerParseFactory {
/** /**
* *
*/ */
private static final Configuration _tplConfig = new Configuration(); private static final Configuration TPL_CONFIG = new Configuration();
/** /**
* SQL * SQL
*/ */
private static final Configuration _sqlConfig = new Configuration(); private static final Configuration SQL_CONFIG = new Configuration();
private static StringTemplateLoader stringTemplateLoader = new StringTemplateLoader(); private static StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
// 使用内嵌的(?ms)打开单行和多行模式 /**使用内嵌的(?ms)打开单行和多行模式*/
private final static Pattern p = Pattern private final static Pattern NOTES_PATTERN = Pattern
.compile("(?ms)/\\*.*?\\*/|^\\s*//.*?$"); .compile("(?ms)/\\*.*?\\*/|^\\s*//.*?$");
static { static {
_tplConfig.setClassForTemplateLoading( TPL_CONFIG.setClassForTemplateLoading(
new FreemarkerParseFactory().getClass(), "/"); new FreemarkerParseFactory().getClass(), "/");
_tplConfig.setNumberFormat("0.#####################"); TPL_CONFIG.setNumberFormat("0.#####################");
_sqlConfig.setTemplateLoader(stringTemplateLoader); SQL_CONFIG.setTemplateLoader(stringTemplateLoader);
_sqlConfig.setNumberFormat("0.#####################"); SQL_CONFIG.setNumberFormat("0.#####################");
//classic_compatible设置解决报空指针错误 //classic_compatible设置解决报空指针错误
_sqlConfig.setClassicCompatible(true); SQL_CONFIG.setClassicCompatible(true);
} }
/** /**
@ -60,7 +62,7 @@ public class FreemarkerParseFactory {
*/ */
public static boolean isExistTemplate(String tplName) throws Exception { public static boolean isExistTemplate(String tplName) throws Exception {
try { try {
Template mytpl = _tplConfig.getTemplate(tplName, "UTF-8"); Template mytpl = TPL_CONFIG.getTemplate(tplName, "UTF-8");
if (mytpl == null) { if (mytpl == null) {
return false; return false;
} }
@ -88,7 +90,7 @@ public class FreemarkerParseFactory {
try { try {
log.debug(" minidao sql templdate : " + tplName); log.debug(" minidao sql templdate : " + tplName);
StringWriter swriter = new StringWriter(); StringWriter swriter = new StringWriter();
Template mytpl = _tplConfig.getTemplate(tplName, ENCODE); Template mytpl = TPL_CONFIG.getTemplate(tplName, ENCODE);
if (paras.containsKey(MINI_DAO_FORMAT)) { if (paras.containsKey(MINI_DAO_FORMAT)) {
throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!"); throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!");
} }
@ -116,11 +118,12 @@ public class FreemarkerParseFactory {
public static String parseTemplateContent(String tplContent, public static String parseTemplateContent(String tplContent,
Map<String, Object> paras) { Map<String, Object> paras) {
try { try {
String sqlUnderline="sql_";
StringWriter swriter = new StringWriter(); StringWriter swriter = new StringWriter();
if (stringTemplateLoader.findTemplateSource("sql_" + tplContent.hashCode()) == null) { if (stringTemplateLoader.findTemplateSource(sqlUnderline + tplContent.hashCode()) == null) {
stringTemplateLoader.putTemplate("sql_" + tplContent.hashCode(), tplContent); stringTemplateLoader.putTemplate(sqlUnderline + tplContent.hashCode(), tplContent);
} }
Template mytpl = _sqlConfig.getTemplate("sql_" + tplContent.hashCode(), ENCODE); Template mytpl = SQL_CONFIG.getTemplate(sqlUnderline + tplContent.hashCode(), ENCODE);
if (paras.containsKey(MINI_DAO_FORMAT)) { if (paras.containsKey(MINI_DAO_FORMAT)) {
throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!"); throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!");
} }
@ -143,27 +146,35 @@ public class FreemarkerParseFactory {
*/ */
private static String getSqlText(String sql) { private static String getSqlText(String sql) {
// 将注释替换成"" // 将注释替换成""
sql = p.matcher(sql).replaceAll(""); sql = NOTES_PATTERN.matcher(sql).replaceAll("");
sql = sql.replaceAll("\\n", " ").replaceAll("\\t", " ") sql = sql.replaceAll("\\n", " ").replaceAll("\\t", " ")
.replaceAll("\\s{1,}", " ").trim(); .replaceAll("\\s{1,}", " ").trim();
// 去掉 最后是 where这样的问题 // 去掉 最后是 where这样的问题
if (sql.endsWith("where") || sql.endsWith("where ")) { //where空格 "where "
String whereSpace = DataBaseConstant.SQL_WHERE+" ";
//"where and"
String whereAnd = DataBaseConstant.SQL_WHERE+" and";
//", where"
String commaWhere = SymbolConstant.COMMA+" "+DataBaseConstant.SQL_WHERE;
//", "
String commaSpace = SymbolConstant.COMMA + " ";
if (sql.endsWith(DataBaseConstant.SQL_WHERE) || sql.endsWith(whereSpace)) {
sql = sql.substring(0, sql.lastIndexOf("where")); sql = sql.substring(0, sql.lastIndexOf("where"));
} }
// 去掉where and 这样的问题 // 去掉where and 这样的问题
int index = 0; int index = 0;
while ((index = StringUtils.indexOfIgnoreCase(sql, "where and", index)) != -1) { while ((index = StringUtils.indexOfIgnoreCase(sql, whereAnd, index)) != -1) {
sql = sql.substring(0, index + 5) sql = sql.substring(0, index + 5)
+ sql.substring(index + 9, sql.length()); + sql.substring(index + 9, sql.length());
} }
// 去掉 , where 这样的问题 // 去掉 , where 这样的问题
index = 0; index = 0;
while ((index = StringUtils.indexOfIgnoreCase(sql, ", where", index)) != -1) { while ((index = StringUtils.indexOfIgnoreCase(sql, commaWhere, index)) != -1) {
sql = sql.substring(0, index) sql = sql.substring(0, index)
+ sql.substring(index + 1, sql.length()); + sql.substring(index + 1, sql.length());
} }
// 去掉 最后是 ,这样的问题 // 去掉 最后是 ,这样的问题
if (sql.endsWith(",") || sql.endsWith(", ")) { if (sql.endsWith(SymbolConstant.COMMA) || sql.endsWith(commaSpace)) {
sql = sql.substring(0, sql.lastIndexOf(",")); sql = sql.substring(0, sql.lastIndexOf(","));
} }
return sql; return sql;

View File

@ -7,11 +7,15 @@ import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
/** /**
* AES * @Description: AES
* @author: jeecg-boot
* @date: 2022/3/30 11:48
*/ */
public class AesEncryptUtil { public class AesEncryptUtil {
//使用AES-128-CBC加密模式key需要为16位,key和iv可以相同 /**
* 使AES-128-CBC keyiv
*/
private static String KEY = EncryptedString.key; private static String KEY = EncryptedString.key;
private static String IV = EncryptedString.iv; private static String IV = EncryptedString.iv;
@ -26,7 +30,8 @@ public class AesEncryptUtil {
public static String encrypt(String data, String key, String iv) throws Exception { public static String encrypt(String data, String key, String iv) throws Exception {
try { try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/补码方式"NoPadding PkcsPadding //"算法/模式/补码方式"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();

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