forked from rzdata/demo-empty
Compare commits
14 Commits
Author | SHA1 | Date | |
---|---|---|---|
d9bbc025fe | |||
c81e66b0a1 | |||
826633ceee | |||
e0945abac7 | |||
5d488f9d55 | |||
5c333b071c | |||
7e6e0f6dc9 | |||
92c6df2689 | |||
42b6c95ac2 | |||
387935247f | |||
9d35b66041 | |||
657b581f8d | |||
95ca20b2a0 | |||
bd01521998 |
89
README.md
89
README.md
@ -1,89 +1,14 @@
|
||||
|
||||
## 代码架构
|
||||
## 业务模块框架结构
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
demo-service-aaa-->demo-common
|
||||
demo-service-bbb-->demo-common
|
||||
demo-service-bbb-->demo-sdk
|
||||
demo-common-->demo-core
|
||||
demo-sdk--> demo-core
|
||||
```
|
||||
1. DDD 四层架构
|
||||
|
||||
- demo
|
||||
- demo-core
|
||||
- demo-sdk
|
||||
- demo-common
|
||||
- demo-service
|
||||
- demo-service-aaa
|
||||
- net.rzdata
|
||||
- AaaApplication
|
||||
- aaa
|
||||
- xxx
|
||||
- XxxController
|
||||
- XxxService
|
||||
- XxxRepository
|
||||
- service
|
||||
- IXxxService4Yyy
|
||||
- IXxxService4Zzz
|
||||
- mapper
|
||||
- XxxMapper
|
||||
- domain
|
||||
- Xxx
|
||||
- XxxAddReq
|
||||
- XxxModifyReq
|
||||
- yyy
|
||||
- zzz
|
||||
- demo-service-bbb
|
||||

|
||||
|
||||
### 工程结构
|
||||
2. 服务调用流程
|
||||
|
||||
demo 是一个系统的顶级POM,其 parent 为公司的顶级POM,对系统内部的依赖进行管理。
|
||||

|
||||
|
||||
demo-service 下是该系统的全部后端服务,每一个子模块对应一个后端服务。最终发布为一个 Docker 镜像。
|
||||
demo-service 的 POM 中添加所有服务的公共依赖,如 spring-boot-starter-web、mybatis-spring-boot-starter 等。
|
||||
3. 数据对象传输过程
|
||||
|
||||
demo-common 中为该系统内服务的公共配置、公共接口、异常定义等。
|
||||
|
||||
demo-sdk 是各服务之间相互调用的 SDK,最终发布为一个 jar 包。
|
||||
当 aaa 服务需要调用 bbb 服务时,则引入 demo-sdk 依赖,并使用其中的 BbbClient 进行调用。
|
||||
|
||||
demo-core 包含本系统内使用的 util 和服务间通信模型 DTO。
|
||||
|
||||
### 包结构
|
||||
|
||||
XxxService 是该包的逻辑组织中枢。
|
||||
其方法分为 3 部分 —— protected 方法,用于向 XxxController 提供服务;public 方法,是对 service 包中的接口的实现。private 方法,对 protected 方法和 public 方法提供服务。
|
||||
如果要依赖其他包的服务,只能注入对应的接口(如 yyy 包需要依赖 xxx 包的服务,则在 YyyService 中注入 IXxxService4Yyy)。IXxxService4Yyy 向其他包提供有限的方法,由 XxxService 实现。
|
||||
|
||||
XxxController 是向前端提供服务的门面。通常只依赖于 XxxService。
|
||||
|
||||
domain.Xxx 是该包的核心模型,也是唯一的充血模型。Service 是基于核心模型进行逻辑组织。
|
||||
|
||||
domain.XxxReq、domain.XxxResp 对应 Controller 中不同请求和响应的返回模型。
|
||||
大部分请求是不需要核心模型的全部字段的,比如新增请求不需要id,修改请求有部分字段不可变,不同的请求需要不同的返回字段等,这时可以定义 XxxReq、XxxResp 来实现,并在 Controller 层转换为核心模型。有些请求需要用到完整的核心模型的结构,则可以省略这一步骤。
|
||||
|
||||
mapper 包下的类均继承自 mybatis-plus 的 BaseMapper,每一个类对应一张数据库表。
|
||||
XxxRepository 是对 XxxMapper 的封装。
|
||||
|
||||
## 部署架构
|
||||
|
||||
## 如何运行
|
||||
|
||||
### 本地运行
|
||||
|
||||
复制服务配置文件 application.yml 中的可配置项到 application-local.yml。
|
||||
|
||||
在 application-local.yml 中修改配置,其中的配置项会覆盖 application.yml,但不会提交到 git。
|
||||
|
||||
### 项目发布
|
||||
|
||||
通过 jib-maven-plugin 发布 Docker 镜像到镜像仓库。
|
||||
|
||||
### 线上部署
|
||||
|
||||
将 opentelemetry-javaagent.jar 映射到容器中的 /opt/agent 目录。
|
||||
|
||||
与本地开发不同,部署时通过环境变量进行配置。application.yml 中有如 ${CONTEXT_PATH} 的可配置项,则能在环境变量中设置 CONTEXT_PATH 的值。
|
||||
|
||||
## [开发规范](https://github.com/alibaba/p3c)
|
||||

|
@ -18,11 +18,6 @@
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>net.rzdata</groupId>
|
||||
<artifactId>demo-core</artifactId>
|
||||
<version>5.1.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
@ -31,10 +26,26 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-websocket</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.redisson</groupId>
|
||||
<artifactId>redisson-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>lock4j-redisson-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.dev33</groupId>
|
||||
<artifactId>sa-token-core</artifactId>
|
||||
@ -44,5 +55,37 @@
|
||||
<artifactId>lombok</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-extra</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-http</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-crypto</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>transmittable-thread-local</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.linpeilie</groupId>
|
||||
<artifactId>mapstruct-plus-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>easyexcel</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lionsoul</groupId>
|
||||
<artifactId>ip2region</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
@ -0,0 +1,17 @@
|
||||
package net.rzdata.demo.core.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||
|
||||
/**
|
||||
* 程序注解配置
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Configuration
|
||||
// 表示通过aop框架暴露该代理对象,AopContext能够访问
|
||||
@EnableAspectJAutoProxy(exposeProxy = true)
|
||||
public class ApplicationConfig {
|
||||
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package net.rzdata.demo.core.config;
|
||||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import net.rzdata.demo.core.exception.ServiceException;
|
||||
import net.rzdata.demo.core.utils.SpringUtils;
|
||||
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.AsyncConfigurer;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
/**
|
||||
* 异步配置
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@EnableAsync(proxyTargetClass = true)
|
||||
@Configuration
|
||||
public class AsyncConfig implements AsyncConfigurer {
|
||||
|
||||
/**
|
||||
* 自定义 @Async 注解使用系统线程池
|
||||
*/
|
||||
@Override
|
||||
public Executor getAsyncExecutor() {
|
||||
return SpringUtils.getBean("scheduledExecutorService");
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行异常处理
|
||||
*/
|
||||
@Override
|
||||
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
|
||||
return (throwable, method, objects) -> {
|
||||
throwable.printStackTrace();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Exception message - ").append(throwable.getMessage())
|
||||
.append(", Method name - ").append(method.getName());
|
||||
if (ArrayUtil.isNotEmpty(objects)) {
|
||||
sb.append(", Parameter value - ").append(Arrays.toString(objects));
|
||||
}
|
||||
throw new ServiceException(sb.toString());
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package net.rzdata.demo.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 读取项目相关配置
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "demo")
|
||||
public class DemoConfig {
|
||||
|
||||
/**
|
||||
* 项目名称
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 版本
|
||||
*/
|
||||
private String version;
|
||||
|
||||
/**
|
||||
* 版权年份
|
||||
*/
|
||||
private String copyrightYear;
|
||||
|
||||
}
|
@ -0,0 +1,78 @@
|
||||
package net.rzdata.demo.core.config;
|
||||
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.rzdata.demo.core.config.properties.ThreadPoolProperties;
|
||||
import net.rzdata.demo.core.utils.Threads;
|
||||
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
|
||||
/**
|
||||
* 线程池配置
|
||||
*
|
||||
* @author Lion Li
|
||||
**/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(ThreadPoolProperties.class)
|
||||
public class ThreadPoolConfig {
|
||||
|
||||
/**
|
||||
* 核心线程数 = cpu 核心数 + 1
|
||||
*/
|
||||
private final int core = Runtime.getRuntime().availableProcessors() + 1;
|
||||
|
||||
private ScheduledExecutorService scheduledExecutorService;
|
||||
|
||||
@Bean(name = "threadPoolTaskExecutor")
|
||||
@ConditionalOnProperty(prefix = "thread-pool", name = "enabled", havingValue = "true")
|
||||
public ThreadPoolTaskExecutor threadPoolTaskExecutor(ThreadPoolProperties threadPoolProperties) {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(core);
|
||||
executor.setMaxPoolSize(core * 2);
|
||||
executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
|
||||
executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
return executor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行周期性或定时任务
|
||||
*/
|
||||
@Bean(name = "scheduledExecutorService")
|
||||
protected ScheduledExecutorService scheduledExecutorService() {
|
||||
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(core,
|
||||
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
|
||||
new ThreadPoolExecutor.CallerRunsPolicy()) {
|
||||
@Override
|
||||
protected void afterExecute(Runnable r, Throwable t) {
|
||||
super.afterExecute(r, t);
|
||||
Threads.printException(r, t);
|
||||
}
|
||||
};
|
||||
this.scheduledExecutorService = scheduledThreadPoolExecutor;
|
||||
return scheduledThreadPoolExecutor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 销毁事件
|
||||
*/
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
try {
|
||||
log.info("====关闭后台任务任务线程池====");
|
||||
Threads.shutdownAndAwaitTermination(scheduledExecutorService);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package net.rzdata.demo.core.config;
|
||||
|
||||
import jakarta.validation.Validator;
|
||||
import org.hibernate.validator.HibernateValidator;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* 校验框架配置类
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Configuration
|
||||
public class ValidatorConfig {
|
||||
|
||||
/**
|
||||
* 配置校验框架 快速返回模式
|
||||
*/
|
||||
@Bean
|
||||
public Validator validator(MessageSource messageSource) {
|
||||
try (LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean()) {
|
||||
// 国际化
|
||||
factoryBean.setValidationMessageSource(messageSource);
|
||||
// 设置使用 HibernateValidator 校验器
|
||||
factoryBean.setProviderClass(HibernateValidator.class);
|
||||
Properties properties = new Properties();
|
||||
// 设置 快速异常返回
|
||||
properties.setProperty("hibernate.validator.fail_fast", "true");
|
||||
factoryBean.setValidationProperties(properties);
|
||||
// 加载配置
|
||||
factoryBean.afterPropertiesSet();
|
||||
return factoryBean.getValidator();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package net.rzdata.demo.core.config.properties;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* 线程池 配置属性
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "thread-pool")
|
||||
public class ThreadPoolProperties {
|
||||
|
||||
/**
|
||||
* 是否开启线程池
|
||||
*/
|
||||
private boolean enabled;
|
||||
|
||||
/**
|
||||
* 队列最大长度
|
||||
*/
|
||||
private int queueCapacity;
|
||||
|
||||
/**
|
||||
* 线程池维护线程所允许的空闲时间
|
||||
*/
|
||||
private int keepAliveSeconds;
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package net.rzdata.demo.core.constant;
|
||||
|
||||
/**
|
||||
* 缓存的key 常量
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface CacheConstants {
|
||||
|
||||
/**
|
||||
* 在线用户 redis key
|
||||
*/
|
||||
String ONLINE_TOKEN_KEY = "online_tokens:";
|
||||
|
||||
/**
|
||||
* 参数管理 cache key
|
||||
*/
|
||||
String SYS_CONFIG_KEY = "sys_config:";
|
||||
|
||||
/**
|
||||
* 字典管理 cache key
|
||||
*/
|
||||
String SYS_DICT_KEY = "sys_dict:";
|
||||
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
package net.rzdata.demo.core.constant;
|
||||
|
||||
/**
|
||||
* 缓存组名称常量
|
||||
* <p>
|
||||
* key 格式为 cacheNames#ttl#maxIdleTime#maxSize
|
||||
* <p>
|
||||
* ttl 过期时间 如果设置为0则不过期 默认为0
|
||||
* maxIdleTime 最大空闲时间 根据LRU算法清理空闲数据 如果设置为0则不检测 默认为0
|
||||
* maxSize 组最大长度 根据LRU算法清理溢出数据 如果设置为0则无限长 默认为0
|
||||
* <p>
|
||||
* 例子: test#60s、test#0#60s、test#0#1m#1000、test#1h#0#500
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface CacheNames {
|
||||
|
||||
/**
|
||||
* 演示案例
|
||||
*/
|
||||
String DEMO_CACHE = "demo:cache#60s#10m#20";
|
||||
|
||||
/**
|
||||
* 系统配置
|
||||
*/
|
||||
String SYS_CONFIG = "sys_config";
|
||||
|
||||
/**
|
||||
* 数据字典
|
||||
*/
|
||||
String SYS_DICT = "sys_dict";
|
||||
|
||||
/**
|
||||
* 用户账户
|
||||
*/
|
||||
String SYS_USER_NAME = "sys_user_name#30d";
|
||||
|
||||
/**
|
||||
* 用户名称
|
||||
*/
|
||||
String SYS_NICKNAME = "sys_nickname#30d";
|
||||
|
||||
/**
|
||||
* OSS内容
|
||||
*/
|
||||
String SYS_OSS = "sys_oss#30d";
|
||||
|
||||
/**
|
||||
* OSS配置
|
||||
*/
|
||||
String SYS_OSS_CONFIG = GlobalConstants.GLOBAL_REDIS_KEY + "sys_oss_config";
|
||||
|
||||
/**
|
||||
* 在线用户
|
||||
*/
|
||||
String ONLINE_TOKEN = "online_tokens";
|
||||
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
package net.rzdata.demo.core.constant;
|
||||
|
||||
/**
|
||||
* 通用常量信息
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public interface Constants {
|
||||
|
||||
/**
|
||||
* UTF-8 字符集
|
||||
*/
|
||||
String UTF8 = "UTF-8";
|
||||
|
||||
/**
|
||||
* GBK 字符集
|
||||
*/
|
||||
String GBK = "GBK";
|
||||
|
||||
/**
|
||||
* www主域
|
||||
*/
|
||||
String WWW = "www.";
|
||||
|
||||
/**
|
||||
* http请求
|
||||
*/
|
||||
String HTTP = "http://";
|
||||
|
||||
/**
|
||||
* https请求
|
||||
*/
|
||||
String HTTPS = "https://";
|
||||
|
||||
/**
|
||||
* 通用成功标识
|
||||
*/
|
||||
String SUCCESS = "0";
|
||||
|
||||
/**
|
||||
* 通用失败标识
|
||||
*/
|
||||
String FAIL = "1";
|
||||
|
||||
/**
|
||||
* 登录成功
|
||||
*/
|
||||
String LOGIN_SUCCESS = "Success";
|
||||
|
||||
/**
|
||||
* 注销
|
||||
*/
|
||||
String LOGOUT = "Logout";
|
||||
|
||||
/**
|
||||
* 注册
|
||||
*/
|
||||
String REGISTER = "Register";
|
||||
|
||||
/**
|
||||
* 登录失败
|
||||
*/
|
||||
String LOGIN_FAIL = "Error";
|
||||
|
||||
/**
|
||||
* 令牌
|
||||
*/
|
||||
String TOKEN = "token";
|
||||
|
||||
/**
|
||||
* 顶级部门id
|
||||
*/
|
||||
Long TOP_PARENT_ID = 0L;
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,34 @@
|
||||
package net.rzdata.demo.core.constant;
|
||||
|
||||
/**
|
||||
* 全局的key常量 (业务无关的key)
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface GlobalConstants {
|
||||
|
||||
/**
|
||||
* 全局 redis key (业务无关的key)
|
||||
*/
|
||||
String GLOBAL_REDIS_KEY = "global:";
|
||||
|
||||
/**
|
||||
* 防重提交 redis key
|
||||
*/
|
||||
String REPEAT_SUBMIT_KEY = GLOBAL_REDIS_KEY + "repeat_submit:";
|
||||
|
||||
/**
|
||||
* 限流 redis key
|
||||
*/
|
||||
String RATE_LIMIT_KEY = GLOBAL_REDIS_KEY + "rate_limit:";
|
||||
|
||||
/**
|
||||
* 登录账户密码错误次数 redis key
|
||||
*/
|
||||
String PWD_ERR_CNT_KEY = GLOBAL_REDIS_KEY + "pwd_err_cnt:";
|
||||
|
||||
/**
|
||||
* 三方认证 redis key
|
||||
*/
|
||||
String SOCIAL_AUTH_CODE_KEY = GLOBAL_REDIS_KEY + "social_auth_codes:";
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
package net.rzdata.demo.core.constant;
|
||||
|
||||
/**
|
||||
* 返回状态码
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface HttpStatus {
|
||||
/**
|
||||
* 操作成功
|
||||
*/
|
||||
int SUCCESS = 200;
|
||||
|
||||
/**
|
||||
* 对象创建成功
|
||||
*/
|
||||
int CREATED = 201;
|
||||
|
||||
/**
|
||||
* 请求已经被接受
|
||||
*/
|
||||
int ACCEPTED = 202;
|
||||
|
||||
/**
|
||||
* 操作已经执行成功,但是没有返回数据
|
||||
*/
|
||||
int NO_CONTENT = 204;
|
||||
|
||||
/**
|
||||
* 资源已被移除
|
||||
*/
|
||||
int MOVED_PERM = 301;
|
||||
|
||||
/**
|
||||
* 重定向
|
||||
*/
|
||||
int SEE_OTHER = 303;
|
||||
|
||||
/**
|
||||
* 资源没有被修改
|
||||
*/
|
||||
int NOT_MODIFIED = 304;
|
||||
|
||||
/**
|
||||
* 参数列表错误(缺少,格式不匹配)
|
||||
*/
|
||||
int BAD_REQUEST = 400;
|
||||
|
||||
/**
|
||||
* 未授权
|
||||
*/
|
||||
int UNAUTHORIZED = 401;
|
||||
|
||||
/**
|
||||
* 访问受限,授权过期
|
||||
*/
|
||||
int FORBIDDEN = 403;
|
||||
|
||||
/**
|
||||
* 资源,服务未找到
|
||||
*/
|
||||
int NOT_FOUND = 404;
|
||||
|
||||
/**
|
||||
* 不允许的http方法
|
||||
*/
|
||||
int BAD_METHOD = 405;
|
||||
|
||||
/**
|
||||
* 资源冲突,或者资源被锁
|
||||
*/
|
||||
int CONFLICT = 409;
|
||||
|
||||
/**
|
||||
* 不支持的数据,媒体类型
|
||||
*/
|
||||
int UNSUPPORTED_TYPE = 415;
|
||||
|
||||
/**
|
||||
* 系统内部错误
|
||||
*/
|
||||
int ERROR = 500;
|
||||
|
||||
/**
|
||||
* 接口未实现
|
||||
*/
|
||||
int NOT_IMPLEMENTED = 501;
|
||||
|
||||
/**
|
||||
* 系统警告消息
|
||||
*/
|
||||
int WARN = 601;
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package net.rzdata.demo.core.constant;
|
||||
|
||||
/**
|
||||
* 租户常量信息
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface TenantConstants {
|
||||
|
||||
/**
|
||||
* 超级管理员角色 roleKey
|
||||
*/
|
||||
String SUPER_ADMIN_ROLE_KEY = "superadmin";
|
||||
|
||||
/**
|
||||
* 租户管理员角色 roleKey
|
||||
*/
|
||||
String TENANT_ADMIN_ROLE_KEY = "admin";
|
||||
|
||||
}
|
@ -0,0 +1,132 @@
|
||||
package net.rzdata.demo.core.constant;
|
||||
|
||||
/**
|
||||
* 用户常量信息
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public interface UserConstants {
|
||||
|
||||
/**
|
||||
* 平台内系统用户的唯一标志
|
||||
*/
|
||||
String SYS_USER = "SYS_USER";
|
||||
|
||||
/**
|
||||
* 正常状态
|
||||
*/
|
||||
String NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 异常状态
|
||||
*/
|
||||
String EXCEPTION = "1";
|
||||
|
||||
/**
|
||||
* 用户正常状态
|
||||
*/
|
||||
String USER_NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 用户封禁状态
|
||||
*/
|
||||
String USER_DISABLE = "1";
|
||||
|
||||
/**
|
||||
* 角色正常状态
|
||||
*/
|
||||
String ROLE_NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 角色封禁状态
|
||||
*/
|
||||
String ROLE_DISABLE = "1";
|
||||
|
||||
/**
|
||||
* 岗位正常状态
|
||||
*/
|
||||
String POST_NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 岗位停用状态
|
||||
*/
|
||||
String POST_DISABLE = "1";
|
||||
|
||||
/**
|
||||
* 字典正常状态
|
||||
*/
|
||||
String DICT_NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 是否为系统默认(是)
|
||||
*/
|
||||
String YES = "Y";
|
||||
|
||||
/**
|
||||
* 是否菜单外链(是)
|
||||
*/
|
||||
String YES_FRAME = "0";
|
||||
|
||||
/**
|
||||
* 是否菜单外链(否)
|
||||
*/
|
||||
String NO_FRAME = "1";
|
||||
|
||||
/**
|
||||
* 菜单正常状态
|
||||
*/
|
||||
String MENU_NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 菜单停用状态
|
||||
*/
|
||||
String MENU_DISABLE = "1";
|
||||
|
||||
/**
|
||||
* 菜单类型(目录)
|
||||
*/
|
||||
String TYPE_DIR = "M";
|
||||
|
||||
/**
|
||||
* 菜单类型(菜单)
|
||||
*/
|
||||
String TYPE_MENU = "C";
|
||||
|
||||
/**
|
||||
* 菜单类型(按钮)
|
||||
*/
|
||||
String TYPE_BUTTON = "F";
|
||||
|
||||
/**
|
||||
* Layout组件标识
|
||||
*/
|
||||
String LAYOUT = "Layout";
|
||||
|
||||
/**
|
||||
* ParentView组件标识
|
||||
*/
|
||||
String PARENT_VIEW = "ParentView";
|
||||
|
||||
/**
|
||||
* InnerLink组件标识
|
||||
*/
|
||||
String INNER_LINK = "InnerLink";
|
||||
|
||||
/**
|
||||
* 用户名长度限制
|
||||
*/
|
||||
int USERNAME_MIN_LENGTH = 2;
|
||||
int USERNAME_MAX_LENGTH = 20;
|
||||
|
||||
/**
|
||||
* 密码长度限制
|
||||
*/
|
||||
int PASSWORD_MIN_LENGTH = 5;
|
||||
int PASSWORD_MAX_LENGTH = 20;
|
||||
|
||||
/**
|
||||
* 超级管理员ID
|
||||
*/
|
||||
Long SUPER_ADMIN_ID = 1L;
|
||||
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package net.rzdata.domain;
|
||||
package net.rzdata.demo.core.domain;
|
||||
|
||||
public record Id(String id) {
|
||||
|
110
common/src/main/java/net/rzdata/demo/core/domain/R.java
Normal file
110
common/src/main/java/net/rzdata/demo/core/domain/R.java
Normal file
@ -0,0 +1,110 @@
|
||||
package net.rzdata.demo.core.domain;
|
||||
|
||||
import net.rzdata.demo.core.constant.HttpStatus;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 响应信息主体
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class R<T> implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 成功
|
||||
*/
|
||||
public static final int SUCCESS = 200;
|
||||
|
||||
/**
|
||||
* 失败
|
||||
*/
|
||||
public static final int FAIL = 500;
|
||||
|
||||
private int code;
|
||||
|
||||
private String msg;
|
||||
|
||||
private T data;
|
||||
|
||||
public static <T> R<T> ok() {
|
||||
return restResult(null, SUCCESS, "操作成功");
|
||||
}
|
||||
|
||||
public static <T> R<T> ok(T data) {
|
||||
return restResult(data, SUCCESS, "操作成功");
|
||||
}
|
||||
|
||||
public static <T> R<T> ok(String msg) {
|
||||
return restResult(null, SUCCESS, msg);
|
||||
}
|
||||
|
||||
public static <T> R<T> ok(String msg, T data) {
|
||||
return restResult(data, SUCCESS, msg);
|
||||
}
|
||||
|
||||
public static <T> R<T> fail() {
|
||||
return restResult(null, FAIL, "操作失败");
|
||||
}
|
||||
|
||||
public static <T> R<T> fail(String msg) {
|
||||
return restResult(null, FAIL, msg);
|
||||
}
|
||||
|
||||
public static <T> R<T> fail(T data) {
|
||||
return restResult(data, FAIL, "操作失败");
|
||||
}
|
||||
|
||||
public static <T> R<T> fail(String msg, T data) {
|
||||
return restResult(data, FAIL, msg);
|
||||
}
|
||||
|
||||
public static <T> R<T> fail(int code, String msg) {
|
||||
return restResult(null, code, msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回警告消息
|
||||
*
|
||||
* @param msg 返回内容
|
||||
* @return 警告消息
|
||||
*/
|
||||
public static <T> R<T> warn(String msg) {
|
||||
return restResult(null, HttpStatus.WARN, msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回警告消息
|
||||
*
|
||||
* @param msg 返回内容
|
||||
* @param data 数据对象
|
||||
* @return 警告消息
|
||||
*/
|
||||
public static <T> R<T> warn(String msg, T data) {
|
||||
return restResult(data, HttpStatus.WARN, msg);
|
||||
}
|
||||
|
||||
private static <T> R<T> restResult(T data, int code, String msg) {
|
||||
R<T> r = new R<>();
|
||||
r.setCode(code);
|
||||
r.setData(data);
|
||||
r.setMsg(msg);
|
||||
return r;
|
||||
}
|
||||
|
||||
public static <T> Boolean isError(R<T> ret) {
|
||||
return !isSuccess(ret);
|
||||
}
|
||||
|
||||
public static <T> Boolean isSuccess(R<T> ret) {
|
||||
return R.SUCCESS == ret.getCode();
|
||||
}
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
package net.rzdata.demo.core.domain.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 角色
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class RoleDTO implements Serializable {
|
||||
|
||||
/**
|
||||
* 角色ID
|
||||
*/
|
||||
private Long roleId;
|
||||
|
||||
/**
|
||||
* 角色名称
|
||||
*/
|
||||
private String roleName;
|
||||
|
||||
/**
|
||||
* 角色权限
|
||||
*/
|
||||
private String roleKey;
|
||||
|
||||
/**
|
||||
* 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限;5:仅本人数据权限)
|
||||
*/
|
||||
private String dataScope;
|
||||
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
package net.rzdata.demo.core.domain.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 当前在线会话
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class UserOnlineDTO implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 会话编号
|
||||
*/
|
||||
private String tokenId;
|
||||
|
||||
/**
|
||||
* 用户名称
|
||||
*/
|
||||
private String userName;
|
||||
|
||||
/**
|
||||
* 客户端
|
||||
*/
|
||||
private String clientKey;
|
||||
|
||||
/**
|
||||
* 设备类型
|
||||
*/
|
||||
private String deviceType;
|
||||
|
||||
/**
|
||||
* 登录IP地址
|
||||
*/
|
||||
private String ipaddr;
|
||||
|
||||
/**
|
||||
* 登录地址
|
||||
*/
|
||||
private String loginLocation;
|
||||
|
||||
/**
|
||||
* 浏览器类型
|
||||
*/
|
||||
private String browser;
|
||||
|
||||
/**
|
||||
* 操作系统
|
||||
*/
|
||||
private String os;
|
||||
|
||||
/**
|
||||
* 登录时间
|
||||
*/
|
||||
private Long loginTime;
|
||||
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package net.rzdata.demo.core.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 设备类型
|
||||
* 针对一套 用户体系
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum DeviceType {
|
||||
|
||||
/**
|
||||
* pc端
|
||||
*/
|
||||
PC("pc"),
|
||||
|
||||
/**
|
||||
* app端
|
||||
*/
|
||||
APP("app"),
|
||||
|
||||
/**
|
||||
* 小程序端
|
||||
*/
|
||||
XCX("xcx"),
|
||||
|
||||
/**
|
||||
* social第三方端
|
||||
*/
|
||||
SOCIAL("social");
|
||||
|
||||
private final String device;
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package net.rzdata.demo.core.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 登录类型
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum LoginType {
|
||||
|
||||
/**
|
||||
* 密码登录
|
||||
*/
|
||||
PASSWORD("user.password.retry.limit.exceed", "user.password.retry.limit.count"),
|
||||
|
||||
/**
|
||||
* 短信登录
|
||||
*/
|
||||
SMS("sms.code.retry.limit.exceed", "sms.code.retry.limit.count"),
|
||||
|
||||
/**
|
||||
* 邮箱登录
|
||||
*/
|
||||
EMAIL("email.code.retry.limit.exceed", "email.code.retry.limit.count"),
|
||||
|
||||
/**
|
||||
* 小程序登录
|
||||
*/
|
||||
XCX("", "");
|
||||
|
||||
/**
|
||||
* 登录重试超出限制提示
|
||||
*/
|
||||
final String retryLimitExceed;
|
||||
|
||||
/**
|
||||
* 登录重试限制计数提示
|
||||
*/
|
||||
final String retryLimitCount;
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package net.rzdata.demo.core.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 用户状态
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum UserStatus {
|
||||
/**
|
||||
* 正常
|
||||
*/
|
||||
OK("0", "正常"),
|
||||
/**
|
||||
* 停用
|
||||
*/
|
||||
DISABLE("1", "停用"),
|
||||
/**
|
||||
* 删除
|
||||
*/
|
||||
DELETED("2", "删除");
|
||||
|
||||
private final String code;
|
||||
private final String info;
|
||||
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package net.rzdata.demo.core.enums;
|
||||
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 设备类型
|
||||
* 针对多套 用户体系
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum UserType {
|
||||
|
||||
/**
|
||||
* pc端
|
||||
*/
|
||||
SYS_USER("sys_user"),
|
||||
|
||||
/**
|
||||
* app端
|
||||
*/
|
||||
APP_USER("app_user");
|
||||
|
||||
private final String userType;
|
||||
|
||||
public static UserType getUserType(String str) {
|
||||
for (UserType value : values()) {
|
||||
if (StringUtils.contains(str, value.getUserType())) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("'UserType' not found By " + str);
|
||||
}
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package net.rzdata.demo.core.exception;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 业务异常
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public final class ServiceException extends RuntimeException {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 错误码
|
||||
*/
|
||||
private Integer code;
|
||||
|
||||
/**
|
||||
* 错误提示
|
||||
*/
|
||||
private String message;
|
||||
|
||||
/**
|
||||
* 错误明细,内部调试错误
|
||||
*/
|
||||
private String detailMessage;
|
||||
|
||||
public ServiceException(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public ServiceException(String message, Integer code) {
|
||||
this.message = message;
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getDetailMessage() {
|
||||
return detailMessage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public ServiceException setMessage(String message) {
|
||||
this.message = message;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ServiceException setDetailMessage(String detailMessage) {
|
||||
this.detailMessage = detailMessage;
|
||||
return this;
|
||||
}
|
||||
}
|
@ -0,0 +1,74 @@
|
||||
package net.rzdata.demo.core.exception.base;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import net.rzdata.demo.core.utils.MessageUtils;
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 基础异常
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BaseException extends RuntimeException {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 所属模块
|
||||
*/
|
||||
private String module;
|
||||
|
||||
/**
|
||||
* 错误码
|
||||
*/
|
||||
private String code;
|
||||
|
||||
/**
|
||||
* 错误码对应的参数
|
||||
*/
|
||||
private Object[] args;
|
||||
|
||||
/**
|
||||
* 错误消息
|
||||
*/
|
||||
private String defaultMessage;
|
||||
|
||||
public BaseException(String module, String code, Object[] args) {
|
||||
this(module, code, args, null);
|
||||
}
|
||||
|
||||
public BaseException(String module, String defaultMessage) {
|
||||
this(module, null, null, defaultMessage);
|
||||
}
|
||||
|
||||
public BaseException(String code, Object[] args) {
|
||||
this(null, code, args, null);
|
||||
}
|
||||
|
||||
public BaseException(String defaultMessage) {
|
||||
this(null, null, null, defaultMessage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
String message = null;
|
||||
if (!StringUtils.isEmpty(code)) {
|
||||
message = MessageUtils.message(code, args);
|
||||
}
|
||||
if (message == null) {
|
||||
message = defaultMessage;
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package net.rzdata.demo.core.exception.file;
|
||||
|
||||
import net.rzdata.demo.core.exception.base.BaseException;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 文件信息异常类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class FileException extends BaseException {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public FileException(String code, Object[] args) {
|
||||
super("file", code, args, null);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package net.rzdata.demo.core.exception.file;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 文件名称超长限制异常类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class FileNameLengthLimitExceededException extends FileException {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public FileNameLengthLimitExceededException(int defaultFileNameLength) {
|
||||
super("upload.filename.exceed.length", new Object[]{defaultFileNameLength});
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package net.rzdata.demo.core.exception.file;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 文件名大小限制异常类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class FileSizeLimitExceededException extends FileException {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public FileSizeLimitExceededException(long defaultMaxSize) {
|
||||
super("upload.exceed.maxSize", new Object[]{defaultMaxSize});
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package net.rzdata.demo.core.exception.user;
|
||||
|
||||
import net.rzdata.demo.core.exception.base.BaseException;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 用户信息异常类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class UserException extends BaseException {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public UserException(String code, Object... args) {
|
||||
super("user", code, args, null);
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package net.rzdata.demo.core.factory;
|
||||
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
|
||||
import org.springframework.core.env.PropertiesPropertySource;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.io.support.DefaultPropertySourceFactory;
|
||||
import org.springframework.core.io.support.EncodedResource;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* yml 配置源工厂
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public class YmlPropertySourceFactory extends DefaultPropertySourceFactory {
|
||||
|
||||
@Override
|
||||
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
|
||||
String sourceName = resource.getResource().getFilename();
|
||||
if (StringUtils.isNotBlank(sourceName) && StringUtils.endsWithAny(sourceName, ".yml", ".yaml")) {
|
||||
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
|
||||
factory.setResources(resource.getResource());
|
||||
factory.afterPropertiesSet();
|
||||
return new PropertiesPropertySource(sourceName, factory.getObject());
|
||||
}
|
||||
return super.createPropertySource(name, resource);
|
||||
}
|
||||
|
||||
}
|
168
common/src/main/java/net/rzdata/demo/core/utils/DateUtils.java
Normal file
168
common/src/main/java/net/rzdata/demo/core/utils/DateUtils.java
Normal file
@ -0,0 +1,168 @@
|
||||
package net.rzdata.demo.core.utils;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.apache.commons.lang3.time.DateFormatUtils;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 时间工具类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
|
||||
|
||||
public static final String YYYY = "yyyy";
|
||||
|
||||
public static final String YYYY_MM = "yyyy-MM";
|
||||
|
||||
public static final String YYYY_MM_DD = "yyyy-MM-dd";
|
||||
|
||||
public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
|
||||
|
||||
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
private static final String[] PARSE_PATTERNS = {
|
||||
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
|
||||
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
|
||||
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
|
||||
|
||||
/**
|
||||
* 获取当前Date型日期
|
||||
*
|
||||
* @return Date() 当前日期
|
||||
*/
|
||||
public static Date getNowDate() {
|
||||
return new Date();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期, 默认格式为yyyy-MM-dd
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String getDate() {
|
||||
return dateTimeNow(YYYY_MM_DD);
|
||||
}
|
||||
|
||||
public static String getTime() {
|
||||
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
|
||||
}
|
||||
|
||||
public static String dateTimeNow() {
|
||||
return dateTimeNow(YYYYMMDDHHMMSS);
|
||||
}
|
||||
|
||||
public static String dateTimeNow(final String format) {
|
||||
return parseDateToStr(format, new Date());
|
||||
}
|
||||
|
||||
public static String dateTime(final Date date) {
|
||||
return parseDateToStr(YYYY_MM_DD, date);
|
||||
}
|
||||
|
||||
public static String parseDateToStr(final String format, final Date date) {
|
||||
return new SimpleDateFormat(format).format(date);
|
||||
}
|
||||
|
||||
public static Date dateTime(final String format, final String ts) {
|
||||
try {
|
||||
return new SimpleDateFormat(format).parse(ts);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期路径 即年/月/日 如2018/08/08
|
||||
*/
|
||||
public static String datePath() {
|
||||
Date now = new Date();
|
||||
return DateFormatUtils.format(now, "yyyy/MM/dd");
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期路径 即年/月/日 如20180808
|
||||
*/
|
||||
public static String dateTime() {
|
||||
Date now = new Date();
|
||||
return DateFormatUtils.format(now, "yyyyMMdd");
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期型字符串转化为日期 格式
|
||||
*/
|
||||
public static Date parseDate(Object str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return parseDate(str.toString(), PARSE_PATTERNS);
|
||||
} catch (ParseException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务器启动时间
|
||||
*/
|
||||
public static Date getServerStartDate() {
|
||||
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
|
||||
return new Date(time);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算相差天数
|
||||
*/
|
||||
public static int differentDaysByMillisecond(Date date1, Date date2) {
|
||||
return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算两个时间差
|
||||
*/
|
||||
public static String getDatePoor(Date endDate, Date nowDate) {
|
||||
long nd = 1000 * 24 * 60 * 60;
|
||||
long nh = 1000 * 60 * 60;
|
||||
long nm = 1000 * 60;
|
||||
// long ns = 1000;
|
||||
// 获得两个时间的毫秒时间差异
|
||||
long diff = endDate.getTime() - nowDate.getTime();
|
||||
// 计算差多少天
|
||||
long day = diff / nd;
|
||||
// 计算差多少小时
|
||||
long hour = diff % nd / nh;
|
||||
// 计算差多少分钟
|
||||
long min = diff % nd % nh / nm;
|
||||
// 计算差多少秒//输出结果
|
||||
// long sec = diff % nd % nh % nm / ns;
|
||||
return day + "天" + hour + "小时" + min + "分钟";
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加 LocalDateTime ==> Date
|
||||
*/
|
||||
public static Date toDate(LocalDateTime temporalAccessor) {
|
||||
ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
|
||||
return Date.from(zdt.toInstant());
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加 LocalDate ==> Date
|
||||
*/
|
||||
public static Date toDate(LocalDate temporalAccessor) {
|
||||
LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
|
||||
ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
|
||||
return Date.from(zdt.toInstant());
|
||||
}
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
package net.rzdata.demo.core.utils;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import io.github.linpeilie.Converter;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Mapstruct 工具类
|
||||
* <p>参考文档:<a href="https://mapstruct.plus/introduction/quick-start.html">mapstruct-plus</a></p>
|
||||
*
|
||||
*
|
||||
* @author Michelle.Chung
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class MapstructUtils {
|
||||
|
||||
private final static Converter CONVERTER = SpringUtils.getBean(Converter.class);
|
||||
|
||||
/**
|
||||
* 将 T 类型对象,转换为 desc 类型的对象并返回
|
||||
*
|
||||
* @param source 数据来源实体
|
||||
* @param desc 描述对象 转换后的对象
|
||||
* @return desc
|
||||
*/
|
||||
public static <T, V> V convert(T source, Class<V> desc) {
|
||||
if (ObjectUtil.isNull(source)) {
|
||||
return null;
|
||||
}
|
||||
if (ObjectUtil.isNull(desc)) {
|
||||
return null;
|
||||
}
|
||||
return CONVERTER.convert(source, desc);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 T 类型对象,按照配置的映射字段规则,给 desc 类型的对象赋值并返回 desc 对象
|
||||
*
|
||||
* @param source 数据来源实体
|
||||
* @param desc 转换后的对象
|
||||
* @return desc
|
||||
*/
|
||||
public static <T, V> V convert(T source, V desc) {
|
||||
if (ObjectUtil.isNull(source)) {
|
||||
return null;
|
||||
}
|
||||
if (ObjectUtil.isNull(desc)) {
|
||||
return null;
|
||||
}
|
||||
return CONVERTER.convert(source, desc);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 T 类型的集合,转换为 desc 类型的集合并返回
|
||||
*
|
||||
* @param sourceList 数据来源实体列表
|
||||
* @param desc 描述对象 转换后的对象
|
||||
* @return desc
|
||||
*/
|
||||
public static <T, V> List<V> convert(List<T> sourceList, Class<V> desc) {
|
||||
if (ObjectUtil.isNull(sourceList)) {
|
||||
return null;
|
||||
}
|
||||
if (CollUtil.isEmpty(sourceList)) {
|
||||
return CollUtil.newArrayList();
|
||||
}
|
||||
return CONVERTER.convert(sourceList, desc);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Map 转换为 beanClass 类型的集合并返回
|
||||
*
|
||||
* @param map 数据来源
|
||||
* @param beanClass bean类
|
||||
* @return bean对象
|
||||
*/
|
||||
public static <T> T convert(Map<String, Object> map, Class<T> beanClass) {
|
||||
if (MapUtil.isEmpty(map)) {
|
||||
return null;
|
||||
}
|
||||
if (ObjectUtil.isNull(beanClass)) {
|
||||
return null;
|
||||
}
|
||||
return CONVERTER.convert(map, beanClass);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package net.rzdata.demo.core.utils;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.NoSuchMessageException;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
|
||||
/**
|
||||
* 获取i18n资源文件
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class MessageUtils {
|
||||
|
||||
private static final MessageSource MESSAGE_SOURCE = SpringUtils.getBean(MessageSource.class);
|
||||
|
||||
/**
|
||||
* 根据消息键和参数 获取消息 委托给spring messageSource
|
||||
*
|
||||
* @param code 消息键
|
||||
* @param args 参数
|
||||
* @return 获取国际化翻译值
|
||||
*/
|
||||
public static String message(String code, Object... args) {
|
||||
try {
|
||||
return MESSAGE_SOURCE.getMessage(code, args, LocaleContextHolder.getLocale());
|
||||
} catch (NoSuchMessageException e) {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,228 @@
|
||||
package net.rzdata.demo.core.utils;
|
||||
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.extra.servlet.JakartaServletUtil;
|
||||
import cn.hutool.http.HttpStatus;
|
||||
import jakarta.servlet.ServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.util.LinkedCaseInsensitiveMap;
|
||||
import org.springframework.web.context.request.RequestAttributes;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 客户端工具类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class ServletUtils extends JakartaServletUtil {
|
||||
|
||||
/**
|
||||
* 获取String参数
|
||||
*/
|
||||
public static String getParameter(String name) {
|
||||
return getRequest().getParameter(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取String参数
|
||||
*/
|
||||
public static String getParameter(String name, String defaultValue) {
|
||||
return Convert.toStr(getRequest().getParameter(name), defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Integer参数
|
||||
*/
|
||||
public static Integer getParameterToInt(String name) {
|
||||
return Convert.toInt(getRequest().getParameter(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Integer参数
|
||||
*/
|
||||
public static Integer getParameterToInt(String name, Integer defaultValue) {
|
||||
return Convert.toInt(getRequest().getParameter(name), defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Boolean参数
|
||||
*/
|
||||
public static Boolean getParameterToBool(String name) {
|
||||
return Convert.toBool(getRequest().getParameter(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Boolean参数
|
||||
*/
|
||||
public static Boolean getParameterToBool(String name, Boolean defaultValue) {
|
||||
return Convert.toBool(getRequest().getParameter(name), defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得所有请求参数
|
||||
*
|
||||
* @param request 请求对象{@link ServletRequest}
|
||||
* @return Map
|
||||
*/
|
||||
public static Map<String, String[]> getParams(ServletRequest request) {
|
||||
final Map<String, String[]> map = request.getParameterMap();
|
||||
return Collections.unmodifiableMap(map);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得所有请求参数
|
||||
*
|
||||
* @param request 请求对象{@link ServletRequest}
|
||||
* @return Map
|
||||
*/
|
||||
public static Map<String, String> getParamMap(ServletRequest request) {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
for (Map.Entry<String, String[]> entry : getParams(request).entrySet()) {
|
||||
params.put(entry.getKey(), StringUtils.join(entry.getValue(), StringUtils.SEPARATOR));
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取request
|
||||
*/
|
||||
public static HttpServletRequest getRequest() {
|
||||
try {
|
||||
return getRequestAttributes().getRequest();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取response
|
||||
*/
|
||||
public static HttpServletResponse getResponse() {
|
||||
try {
|
||||
return getRequestAttributes().getResponse();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取session
|
||||
*/
|
||||
public static HttpSession getSession() {
|
||||
return getRequest().getSession();
|
||||
}
|
||||
|
||||
public static ServletRequestAttributes getRequestAttributes() {
|
||||
try {
|
||||
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
|
||||
return (ServletRequestAttributes) attributes;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getHeader(HttpServletRequest request, String name) {
|
||||
String value = request.getHeader(name);
|
||||
if (StringUtils.isEmpty(value)) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
return urlDecode(value);
|
||||
}
|
||||
|
||||
public static Map<String, String> getHeaders(HttpServletRequest request) {
|
||||
Map<String, String> map = new LinkedCaseInsensitiveMap<>();
|
||||
Enumeration<String> enumeration = request.getHeaderNames();
|
||||
if (enumeration != null) {
|
||||
while (enumeration.hasMoreElements()) {
|
||||
String key = enumeration.nextElement();
|
||||
String value = request.getHeader(key);
|
||||
map.put(key, value);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字符串渲染到客户端
|
||||
*
|
||||
* @param response 渲染对象
|
||||
* @param string 待渲染的字符串
|
||||
*/
|
||||
public static void renderString(HttpServletResponse response, String string) {
|
||||
try {
|
||||
response.setStatus(HttpStatus.HTTP_OK);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
|
||||
response.getWriter().print(string);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否是Ajax异步请求
|
||||
*
|
||||
* @param request
|
||||
*/
|
||||
public static boolean isAjaxRequest(HttpServletRequest request) {
|
||||
|
||||
String accept = request.getHeader("accept");
|
||||
if (accept != null && accept.contains(MediaType.APPLICATION_JSON_VALUE)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String xRequestedWith = request.getHeader("X-Requested-With");
|
||||
if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String uri = request.getRequestURI();
|
||||
if (StringUtils.equalsAnyIgnoreCase(uri, ".json", ".xml")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String ajax = request.getParameter("__ajax");
|
||||
return StringUtils.equalsAnyIgnoreCase(ajax, "json", "xml");
|
||||
}
|
||||
|
||||
public static String getClientIP() {
|
||||
return getClientIP(getRequest());
|
||||
}
|
||||
|
||||
/**
|
||||
* 内容编码
|
||||
*
|
||||
* @param str 内容
|
||||
* @return 编码后的内容
|
||||
*/
|
||||
public static String urlEncode(String str) {
|
||||
return URLEncoder.encode(str, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* 内容解码
|
||||
*
|
||||
* @param str 内容
|
||||
* @return 解码后的内容
|
||||
*/
|
||||
public static String urlDecode(String str) {
|
||||
return URLDecoder.decode(str, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package net.rzdata.demo.core.utils;
|
||||
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import org.springframework.aop.framework.AopContext;
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* spring工具类
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Component
|
||||
public final class SpringUtils extends SpringUtil {
|
||||
|
||||
/**
|
||||
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
|
||||
*/
|
||||
public static boolean containsBean(String name) {
|
||||
return getBeanFactory().containsBean(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
|
||||
* 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
|
||||
*/
|
||||
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
|
||||
return getBeanFactory().isSingleton(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Class 注册对象的类型
|
||||
*/
|
||||
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
|
||||
return getBeanFactory().getType(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
|
||||
*/
|
||||
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
|
||||
return getBeanFactory().getAliases(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取aop代理对象
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T getAopProxy(T invoker) {
|
||||
return (T) AopContext.currentProxy();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取spring上下文
|
||||
*/
|
||||
public static ApplicationContext context() {
|
||||
return getApplicationContext();
|
||||
}
|
||||
|
||||
}
|
254
common/src/main/java/net/rzdata/demo/core/utils/StreamUtils.java
Normal file
254
common/src/main/java/net/rzdata/demo/core/utils/StreamUtils.java
Normal file
@ -0,0 +1,254 @@
|
||||
package net.rzdata.demo.core.utils;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* stream 流工具类
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class StreamUtils {
|
||||
|
||||
/**
|
||||
* 将collection过滤
|
||||
*
|
||||
* @param collection 需要转化的集合
|
||||
* @param function 过滤方法
|
||||
* @return 过滤后的list
|
||||
*/
|
||||
public static <E> List<E> filter(Collection<E> collection, Predicate<E> function) {
|
||||
if (CollUtil.isEmpty(collection)) {
|
||||
return CollUtil.newArrayList();
|
||||
}
|
||||
// 注意此处不要使用 .toList() 新语法 因为返回的是不可变List 会导致序列化问题
|
||||
return collection.stream().filter(function).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 将collection拼接
|
||||
*
|
||||
* @param collection 需要转化的集合
|
||||
* @param function 拼接方法
|
||||
* @return 拼接后的list
|
||||
*/
|
||||
public static <E> String join(Collection<E> collection, Function<E, String> function) {
|
||||
return join(collection, function, StringUtils.SEPARATOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将collection拼接
|
||||
*
|
||||
* @param collection 需要转化的集合
|
||||
* @param function 拼接方法
|
||||
* @param delimiter 拼接符
|
||||
* @return 拼接后的list
|
||||
*/
|
||||
public static <E> String join(Collection<E> collection, Function<E, String> function, CharSequence delimiter) {
|
||||
if (CollUtil.isEmpty(collection)) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
return collection.stream().map(function).filter(Objects::nonNull).collect(Collectors.joining(delimiter));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将collection排序
|
||||
*
|
||||
* @param collection 需要转化的集合
|
||||
* @param comparing 排序方法
|
||||
* @return 排序后的list
|
||||
*/
|
||||
public static <E> List<E> sorted(Collection<E> collection, Comparator<E> comparing) {
|
||||
if (CollUtil.isEmpty(collection)) {
|
||||
return CollUtil.newArrayList();
|
||||
}
|
||||
// 注意此处不要使用 .toList() 新语法 因为返回的是不可变List 会导致序列化问题
|
||||
return collection.stream().filter(Objects::nonNull).sorted(comparing).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 将collection转化为类型不变的map<br>
|
||||
* <B>{@code Collection<V> ----> Map<K,V>}</B>
|
||||
*
|
||||
* @param collection 需要转化的集合
|
||||
* @param key V类型转化为K类型的lambda方法
|
||||
* @param <V> collection中的泛型
|
||||
* @param <K> map中的key类型
|
||||
* @return 转化后的map
|
||||
*/
|
||||
public static <V, K> Map<K, V> toIdentityMap(Collection<V> collection, Function<V, K> key) {
|
||||
if (CollUtil.isEmpty(collection)) {
|
||||
return MapUtil.newHashMap();
|
||||
}
|
||||
return collection.stream().filter(Objects::nonNull).collect(Collectors.toMap(key, Function.identity(), (l, r) -> l));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将Collection转化为map(value类型与collection的泛型不同)<br>
|
||||
* <B>{@code Collection<E> -----> Map<K,V> }</B>
|
||||
*
|
||||
* @param collection 需要转化的集合
|
||||
* @param key E类型转化为K类型的lambda方法
|
||||
* @param value E类型转化为V类型的lambda方法
|
||||
* @param <E> collection中的泛型
|
||||
* @param <K> map中的key类型
|
||||
* @param <V> map中的value类型
|
||||
* @return 转化后的map
|
||||
*/
|
||||
public static <E, K, V> Map<K, V> toMap(Collection<E> collection, Function<E, K> key, Function<E, V> value) {
|
||||
if (CollUtil.isEmpty(collection)) {
|
||||
return MapUtil.newHashMap();
|
||||
}
|
||||
return collection.stream().filter(Objects::nonNull).collect(Collectors.toMap(key, value, (l, r) -> l));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将collection按照规则(比如有相同的班级id)分类成map<br>
|
||||
* <B>{@code Collection<E> -------> Map<K,List<E>> } </B>
|
||||
*
|
||||
* @param collection 需要分类的集合
|
||||
* @param key 分类的规则
|
||||
* @param <E> collection中的泛型
|
||||
* @param <K> map中的key类型
|
||||
* @return 分类后的map
|
||||
*/
|
||||
public static <E, K> Map<K, List<E>> groupByKey(Collection<E> collection, Function<E, K> key) {
|
||||
if (CollUtil.isEmpty(collection)) {
|
||||
return MapUtil.newHashMap();
|
||||
}
|
||||
return collection
|
||||
.stream().filter(Objects::nonNull)
|
||||
.collect(Collectors.groupingBy(key, LinkedHashMap::new, Collectors.toList()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将collection按照两个规则(比如有相同的年级id,班级id)分类成双层map<br>
|
||||
* <B>{@code Collection<E> ---> Map<T,Map<U,List<E>>> } </B>
|
||||
*
|
||||
* @param collection 需要分类的集合
|
||||
* @param key1 第一个分类的规则
|
||||
* @param key2 第二个分类的规则
|
||||
* @param <E> 集合元素类型
|
||||
* @param <K> 第一个map中的key类型
|
||||
* @param <U> 第二个map中的key类型
|
||||
* @return 分类后的map
|
||||
*/
|
||||
public static <E, K, U> Map<K, Map<U, List<E>>> groupBy2Key(Collection<E> collection, Function<E, K> key1, Function<E, U> key2) {
|
||||
if (CollUtil.isEmpty(collection)) {
|
||||
return MapUtil.newHashMap();
|
||||
}
|
||||
return collection
|
||||
.stream().filter(Objects::nonNull)
|
||||
.collect(Collectors.groupingBy(key1, LinkedHashMap::new, Collectors.groupingBy(key2, LinkedHashMap::new, Collectors.toList())));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将collection按照两个规则(比如有相同的年级id,班级id)分类成双层map<br>
|
||||
* <B>{@code Collection<E> ---> Map<T,Map<U,E>> } </B>
|
||||
*
|
||||
* @param collection 需要分类的集合
|
||||
* @param key1 第一个分类的规则
|
||||
* @param key2 第二个分类的规则
|
||||
* @param <T> 第一个map中的key类型
|
||||
* @param <U> 第二个map中的key类型
|
||||
* @param <E> collection中的泛型
|
||||
* @return 分类后的map
|
||||
*/
|
||||
public static <E, T, U> Map<T, Map<U, E>> group2Map(Collection<E> collection, Function<E, T> key1, Function<E, U> key2) {
|
||||
if (CollUtil.isEmpty(collection) || key1 == null || key2 == null) {
|
||||
return MapUtil.newHashMap();
|
||||
}
|
||||
return collection
|
||||
.stream().filter(Objects::nonNull)
|
||||
.collect(Collectors.groupingBy(key1, LinkedHashMap::new, Collectors.toMap(key2, Function.identity(), (l, r) -> l)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将collection转化为List集合,但是两者的泛型不同<br>
|
||||
* <B>{@code Collection<E> ------> List<T> } </B>
|
||||
*
|
||||
* @param collection 需要转化的集合
|
||||
* @param function collection中的泛型转化为list泛型的lambda表达式
|
||||
* @param <E> collection中的泛型
|
||||
* @param <T> List中的泛型
|
||||
* @return 转化后的list
|
||||
*/
|
||||
public static <E, T> List<T> toList(Collection<E> collection, Function<E, T> function) {
|
||||
if (CollUtil.isEmpty(collection)) {
|
||||
return CollUtil.newArrayList();
|
||||
}
|
||||
return collection
|
||||
.stream()
|
||||
.map(function)
|
||||
.filter(Objects::nonNull)
|
||||
// 注意此处不要使用 .toList() 新语法 因为返回的是不可变List 会导致序列化问题
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 将collection转化为Set集合,但是两者的泛型不同<br>
|
||||
* <B>{@code Collection<E> ------> Set<T> } </B>
|
||||
*
|
||||
* @param collection 需要转化的集合
|
||||
* @param function collection中的泛型转化为set泛型的lambda表达式
|
||||
* @param <E> collection中的泛型
|
||||
* @param <T> Set中的泛型
|
||||
* @return 转化后的Set
|
||||
*/
|
||||
public static <E, T> Set<T> toSet(Collection<E> collection, Function<E, T> function) {
|
||||
if (CollUtil.isEmpty(collection) || function == null) {
|
||||
return CollUtil.newHashSet();
|
||||
}
|
||||
return collection
|
||||
.stream()
|
||||
.map(function)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 合并两个相同key类型的map
|
||||
*
|
||||
* @param map1 第一个需要合并的 map
|
||||
* @param map2 第二个需要合并的 map
|
||||
* @param merge 合并的lambda,将key value1 value2合并成最终的类型,注意value可能为空的情况
|
||||
* @param <K> map中的key类型
|
||||
* @param <X> 第一个 map的value类型
|
||||
* @param <Y> 第二个 map的value类型
|
||||
* @param <V> 最终map的value类型
|
||||
* @return 合并后的map
|
||||
*/
|
||||
public static <K, X, Y, V> Map<K, V> merge(Map<K, X> map1, Map<K, Y> map2, BiFunction<X, Y, V> merge) {
|
||||
if (MapUtil.isEmpty(map1) && MapUtil.isEmpty(map2)) {
|
||||
return MapUtil.newHashMap();
|
||||
} else if (MapUtil.isEmpty(map1)) {
|
||||
map1 = MapUtil.newHashMap();
|
||||
} else if (MapUtil.isEmpty(map2)) {
|
||||
map2 = MapUtil.newHashMap();
|
||||
}
|
||||
Set<K> key = new HashSet<>();
|
||||
key.addAll(map1.keySet());
|
||||
key.addAll(map2.keySet());
|
||||
Map<K, V> map = new HashMap<>();
|
||||
for (K t : key) {
|
||||
X x = map1.get(t);
|
||||
Y y = map2.get(t);
|
||||
V z = merge.apply(x, y);
|
||||
if (z != null) {
|
||||
map.put(t, z);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
}
|
321
common/src/main/java/net/rzdata/demo/core/utils/StringUtils.java
Normal file
321
common/src/main/java/net/rzdata/demo/core/utils/StringUtils.java
Normal file
@ -0,0 +1,321 @@
|
||||
package net.rzdata.demo.core.utils;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.lang.Validator;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 字符串工具类
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class StringUtils extends org.apache.commons.lang3.StringUtils {
|
||||
|
||||
public static final String SEPARATOR = ",";
|
||||
|
||||
/**
|
||||
* 获取参数不为空值
|
||||
*
|
||||
* @param str defaultValue 要判断的value
|
||||
* @return value 返回值
|
||||
*/
|
||||
public static String blankToDefault(String str, String defaultValue) {
|
||||
return StrUtil.blankToDefault(str, defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个字符串是否为空串
|
||||
*
|
||||
* @param str String
|
||||
* @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isEmpty(String str) {
|
||||
return StrUtil.isEmpty(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个字符串是否为非空串
|
||||
*
|
||||
* @param str String
|
||||
* @return true:非空串 false:空串
|
||||
*/
|
||||
public static boolean isNotEmpty(String str) {
|
||||
return !isEmpty(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* 去空格
|
||||
*/
|
||||
public static String trim(String str) {
|
||||
return StrUtil.trim(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串
|
||||
*
|
||||
* @param str 字符串
|
||||
* @param start 开始
|
||||
* @return 结果
|
||||
*/
|
||||
public static String substring(final String str, int start) {
|
||||
return substring(str, start, str.length());
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串
|
||||
*
|
||||
* @param str 字符串
|
||||
* @param start 开始
|
||||
* @param end 结束
|
||||
* @return 结果
|
||||
*/
|
||||
public static String substring(final String str, int start, int end) {
|
||||
return StrUtil.sub(str, start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化文本, {} 表示占位符<br>
|
||||
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
|
||||
* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
|
||||
* 例:<br>
|
||||
* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
|
||||
* 转义{}: format("this is \\{} for {}", "a", "b") -> this is {} for a<br>
|
||||
* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
|
||||
*
|
||||
* @param template 文本模板,被替换的部分用 {} 表示
|
||||
* @param params 参数值
|
||||
* @return 格式化后的文本
|
||||
*/
|
||||
public static String format(String template, Object... params) {
|
||||
return StrUtil.format(template, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为http(s)://开头
|
||||
*
|
||||
* @param link 链接
|
||||
* @return 结果
|
||||
*/
|
||||
public static boolean ishttp(String link) {
|
||||
return Validator.isUrl(link);
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转set
|
||||
*
|
||||
* @param str 字符串
|
||||
* @param sep 分隔符
|
||||
* @return set集合
|
||||
*/
|
||||
public static Set<String> str2Set(String str, String sep) {
|
||||
return new HashSet<>(str2List(str, sep, true, false));
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转list
|
||||
*
|
||||
* @param str 字符串
|
||||
* @param sep 分隔符
|
||||
* @param filterBlank 过滤纯空白
|
||||
* @param trim 去掉首尾空白
|
||||
* @return list集合
|
||||
*/
|
||||
public static List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
|
||||
List<String> list = new ArrayList<>();
|
||||
if (isEmpty(str)) {
|
||||
return list;
|
||||
}
|
||||
|
||||
// 过滤空白字符串
|
||||
if (filterBlank && isBlank(str)) {
|
||||
return list;
|
||||
}
|
||||
String[] split = str.split(sep);
|
||||
for (String string : split) {
|
||||
if (filterBlank && isBlank(string)) {
|
||||
continue;
|
||||
}
|
||||
if (trim) {
|
||||
string = trim(string);
|
||||
}
|
||||
list.add(string);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写
|
||||
*
|
||||
* @param cs 指定字符串
|
||||
* @param searchCharSequences 需要检查的字符串数组
|
||||
* @return 是否包含任意一个字符串
|
||||
*/
|
||||
public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {
|
||||
return StrUtil.containsAnyIgnoreCase(cs, searchCharSequences);
|
||||
}
|
||||
|
||||
/**
|
||||
* 驼峰转下划线命名
|
||||
*/
|
||||
public static String toUnderScoreCase(String str) {
|
||||
return StrUtil.toUnderlineCase(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否包含字符串
|
||||
*
|
||||
* @param str 验证字符串
|
||||
* @param strs 字符串组
|
||||
* @return 包含返回true
|
||||
*/
|
||||
public static boolean inStringIgnoreCase(String str, String... strs) {
|
||||
return StrUtil.equalsAnyIgnoreCase(str, strs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld
|
||||
*
|
||||
* @param name 转换前的下划线大写方式命名的字符串
|
||||
* @return 转换后的驼峰式命名的字符串
|
||||
*/
|
||||
public static String convertToCamelCase(String name) {
|
||||
return StrUtil.upperFirst(StrUtil.toCamelCase(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 驼峰式命名法 例如:user_name->userName
|
||||
*/
|
||||
public static String toCamelCase(String s) {
|
||||
return StrUtil.toCamelCase(s);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
|
||||
*
|
||||
* @param str 指定字符串
|
||||
* @param strs 需要检查的字符串数组
|
||||
* @return 是否匹配
|
||||
*/
|
||||
public static boolean matches(String str, List<String> strs) {
|
||||
if (isEmpty(str) || CollUtil.isEmpty(strs)) {
|
||||
return false;
|
||||
}
|
||||
for (String pattern : strs) {
|
||||
if (isMatch(pattern, str)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断url是否与规则配置:
|
||||
* ? 表示单个字符;
|
||||
* * 表示一层路径内的任意字符串,不可跨层级;
|
||||
* ** 表示任意层路径;
|
||||
*
|
||||
* @param pattern 匹配规则
|
||||
* @param url 需要匹配的url
|
||||
*/
|
||||
public static boolean isMatch(String pattern, String url) {
|
||||
AntPathMatcher matcher = new AntPathMatcher();
|
||||
return matcher.match(pattern, url);
|
||||
}
|
||||
|
||||
/**
|
||||
* 数字左边补齐0,使之达到指定长度。注意,如果数字转换为字符串后,长度大于size,则只保留 最后size个字符。
|
||||
*
|
||||
* @param num 数字对象
|
||||
* @param size 字符串指定长度
|
||||
* @return 返回数字的字符串格式,该字符串为指定长度。
|
||||
*/
|
||||
public static String padl(final Number num, final int size) {
|
||||
return padl(num.toString(), size, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串左补齐。如果原始字符串s长度大于size,则只保留最后size个字符。
|
||||
*
|
||||
* @param s 原始字符串
|
||||
* @param size 字符串指定长度
|
||||
* @param c 用于补齐的字符
|
||||
* @return 返回指定长度的字符串,由原字符串左补齐或截取得到。
|
||||
*/
|
||||
public static String padl(final String s, final int size, final char c) {
|
||||
final StringBuilder sb = new StringBuilder(size);
|
||||
if (s != null) {
|
||||
final int len = s.length();
|
||||
if (s.length() <= size) {
|
||||
sb.append(String.valueOf(c).repeat(size - len));
|
||||
sb.append(s);
|
||||
} else {
|
||||
return s.substring(len - size, len);
|
||||
}
|
||||
} else {
|
||||
sb.append(String.valueOf(c).repeat(Math.max(0, size)));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 切分字符串(分隔符默认逗号)
|
||||
*
|
||||
* @param str 被切分的字符串
|
||||
* @return 分割后的数据列表
|
||||
*/
|
||||
public static List<String> splitList(String str) {
|
||||
return splitTo(str, Convert::toStr);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切分字符串
|
||||
*
|
||||
* @param str 被切分的字符串
|
||||
* @param separator 分隔符
|
||||
* @return 分割后的数据列表
|
||||
*/
|
||||
public static List<String> splitList(String str, String separator) {
|
||||
return splitTo(str, separator, Convert::toStr);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切分字符串自定义转换(分隔符默认逗号)
|
||||
*
|
||||
* @param str 被切分的字符串
|
||||
* @param mapper 自定义转换
|
||||
* @return 分割后的数据列表
|
||||
*/
|
||||
public static <T> List<T> splitTo(String str, Function<? super Object, T> mapper) {
|
||||
return splitTo(str, SEPARATOR, mapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切分字符串自定义转换
|
||||
*
|
||||
* @param str 被切分的字符串
|
||||
* @param separator 分隔符
|
||||
* @param mapper 自定义转换
|
||||
* @return 分割后的数据列表
|
||||
*/
|
||||
public static <T> List<T> splitTo(String str, String separator, Function<? super Object, T> mapper) {
|
||||
if (isBlank(str)) {
|
||||
return new ArrayList<>(0);
|
||||
}
|
||||
return StrUtil.split(str, separator)
|
||||
.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(mapper)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
75
common/src/main/java/net/rzdata/demo/core/utils/Threads.java
Normal file
75
common/src/main/java/net/rzdata/demo/core/utils/Threads.java
Normal file
@ -0,0 +1,75 @@
|
||||
package net.rzdata.demo.core.utils;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/**
|
||||
* 线程相关工具类.
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Slf4j
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class Threads {
|
||||
|
||||
/**
|
||||
* sleep等待,单位为毫秒
|
||||
*/
|
||||
public static void sleep(long milliseconds) {
|
||||
try {
|
||||
Thread.sleep(milliseconds);
|
||||
} catch (InterruptedException e) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止线程池
|
||||
* 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
|
||||
* 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
|
||||
* 如果仍然超時,則強制退出.
|
||||
* 另对在shutdown时线程本身被调用中断做了处理.
|
||||
*/
|
||||
public static void shutdownAndAwaitTermination(ExecutorService pool) {
|
||||
if (pool != null && !pool.isShutdown()) {
|
||||
pool.shutdown();
|
||||
try {
|
||||
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
|
||||
pool.shutdownNow();
|
||||
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
|
||||
log.info("Pool did not terminate");
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException ie) {
|
||||
pool.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印线程异常信息
|
||||
*/
|
||||
public static void printException(Runnable r, Throwable t) {
|
||||
if (t == null && r instanceof Future<?>) {
|
||||
try {
|
||||
Future<?> future = (Future<?>) r;
|
||||
if (future.isDone()) {
|
||||
future.get();
|
||||
}
|
||||
} catch (CancellationException ce) {
|
||||
t = ce;
|
||||
} catch (ExecutionException ee) {
|
||||
t = ee.getCause();
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
if (t != null) {
|
||||
log.error(t.getMessage(), t);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package net.rzdata.demo.core.utils;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.lang.tree.Tree;
|
||||
import cn.hutool.core.lang.tree.TreeNodeConfig;
|
||||
import cn.hutool.core.lang.tree.TreeUtil;
|
||||
import cn.hutool.core.lang.tree.parser.NodeParser;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import net.rzdata.demo.core.utils.reflect.ReflectUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 扩展 hutool TreeUtil 封装系统树构建
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class TreeBuildUtils extends TreeUtil {
|
||||
|
||||
/**
|
||||
* 根据前端定制差异化字段
|
||||
*/
|
||||
public static final TreeNodeConfig DEFAULT_CONFIG = TreeNodeConfig.DEFAULT_CONFIG.setNameKey("label");
|
||||
|
||||
public static <T, K> List<Tree<K>> build(List<T> list, NodeParser<T, K> nodeParser) {
|
||||
if (CollUtil.isEmpty(list)) {
|
||||
return null;
|
||||
}
|
||||
K k = ReflectUtils.invokeGetter(list.get(0), "parentId");
|
||||
return TreeUtil.build(list, k, DEFAULT_CONFIG, nodeParser);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package net.rzdata.demo.core.utils;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import jakarta.validation.Validator;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Validator 校验框架工具
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class ValidatorUtils {
|
||||
|
||||
private static final Validator VALID = SpringUtils.getBean(Validator.class);
|
||||
|
||||
public static <T> void validate(T object, Class<?>... groups) {
|
||||
Set<ConstraintViolation<T>> validate = VALID.validate(object, groups);
|
||||
if (!validate.isEmpty()) {
|
||||
throw new ConstraintViolationException("参数校验异常", validate);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package net.rzdata.demo.core.utils.file;
|
||||
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 文件处理工具类
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class FileUtils extends FileUtil {
|
||||
|
||||
/**
|
||||
* 下载文件名重新编码
|
||||
*
|
||||
* @param response 响应对象
|
||||
* @param realFileName 真实文件名
|
||||
*/
|
||||
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) {
|
||||
String percentEncodedFileName = percentEncode(realFileName);
|
||||
String contentDispositionValue = "attachment; filename=%s;filename*=utf-8''%s".formatted(percentEncodedFileName, percentEncodedFileName);
|
||||
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
|
||||
response.setHeader("Content-disposition", contentDispositionValue);
|
||||
response.setHeader("download-filename", percentEncodedFileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 百分号编码工具方法
|
||||
*
|
||||
* @param s 需要百分号编码的字符串
|
||||
* @return 百分号编码后的字符串
|
||||
*/
|
||||
public static String percentEncode(String s) {
|
||||
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8);
|
||||
return encode.replaceAll("\\+", "%20");
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package net.rzdata.demo.core.utils.file;
|
||||
|
||||
/**
|
||||
* 媒体类型工具类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class MimeTypeUtils {
|
||||
public static final String IMAGE_PNG = "image/png";
|
||||
|
||||
public static final String IMAGE_JPG = "image/jpg";
|
||||
|
||||
public static final String IMAGE_JPEG = "image/jpeg";
|
||||
|
||||
public static final String IMAGE_BMP = "image/bmp";
|
||||
|
||||
public static final String IMAGE_GIF = "image/gif";
|
||||
|
||||
public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};
|
||||
|
||||
public static final String[] FLASH_EXTENSION = {"swf", "flv"};
|
||||
|
||||
public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
|
||||
"asf", "rm", "rmvb"};
|
||||
|
||||
public static final String[] VIDEO_EXTENSION = {"mp4", "avi", "rmvb"};
|
||||
|
||||
public static final String[] DEFAULT_ALLOWED_EXTENSION = {
|
||||
// 图片
|
||||
"bmp", "gif", "jpg", "jpeg", "png",
|
||||
// word excel powerpoint
|
||||
"doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
|
||||
// 压缩文件
|
||||
"rar", "zip", "gz", "bz2",
|
||||
// 视频格式
|
||||
"mp4", "avi", "rmvb",
|
||||
// pdf
|
||||
"pdf"};
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package net.rzdata.demo.core.utils.ip;
|
||||
|
||||
import cn.hutool.core.net.NetUtil;
|
||||
import cn.hutool.http.HtmlUtil;
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* 获取地址类
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class AddressUtils {
|
||||
|
||||
// 未知地址
|
||||
public static final String UNKNOWN = "XX XX";
|
||||
|
||||
public static String getRealAddressByIP(String ip) {
|
||||
if (StringUtils.isBlank(ip)) {
|
||||
return UNKNOWN;
|
||||
}
|
||||
// 内网不查询
|
||||
ip = StringUtils.contains(ip, "0:0:0:0:0:0:0:1") ? "127.0.0.1" : HtmlUtil.cleanHtmlTag(ip);
|
||||
if (NetUtil.isInnerIP(ip)) {
|
||||
return "内网IP";
|
||||
}
|
||||
return RegionUtils.getCityInfo(ip);
|
||||
}
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
package net.rzdata.demo.core.utils.ip;
|
||||
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.io.resource.ClassPathResource;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import net.rzdata.demo.core.exception.ServiceException;
|
||||
import net.rzdata.demo.core.utils.file.FileUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.lionsoul.ip2region.xdb.Searcher;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* 根据ip地址定位工具类,离线方式
|
||||
* 参考地址:<a href="https://gitee.com/lionsoul/ip2region/tree/master/binding/java">集成 ip2region 实现离线IP地址定位库</a>
|
||||
*
|
||||
* @author lishuyan
|
||||
*/
|
||||
@Slf4j
|
||||
public class RegionUtils {
|
||||
|
||||
private static final Searcher SEARCHER;
|
||||
|
||||
static {
|
||||
String fileName = "/ip2region.xdb";
|
||||
File existFile = FileUtils.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
|
||||
if (!FileUtils.exist(existFile)) {
|
||||
ClassPathResource fileStream = new ClassPathResource(fileName);
|
||||
if (ObjectUtil.isEmpty(fileStream.getStream())) {
|
||||
throw new ServiceException("RegionUtils初始化失败,原因:IP地址库数据不存在!");
|
||||
}
|
||||
FileUtils.writeFromStream(fileStream.getStream(), existFile);
|
||||
}
|
||||
|
||||
String dbPath = existFile.getPath();
|
||||
|
||||
// 1、从 dbPath 加载整个 xdb 到内存。
|
||||
byte[] cBuff;
|
||||
try {
|
||||
cBuff = Searcher.loadContentFromFile(dbPath);
|
||||
} catch (Exception e) {
|
||||
throw new ServiceException("RegionUtils初始化失败,原因:从ip2region.xdb文件加载内容失败!" + e.getMessage());
|
||||
}
|
||||
// 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
|
||||
try {
|
||||
SEARCHER = Searcher.newWithBuffer(cBuff);
|
||||
} catch (Exception e) {
|
||||
throw new ServiceException("RegionUtils初始化失败,原因:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据IP地址离线获取城市
|
||||
*/
|
||||
public static String getCityInfo(String ip) {
|
||||
try {
|
||||
ip = ip.trim();
|
||||
// 3、执行查询
|
||||
String region = SEARCHER.search(ip);
|
||||
return region.replace("0|", "").replace("|0", "");
|
||||
} catch (Exception e) {
|
||||
log.error("IP地址离线获取城市异常 {}", ip);
|
||||
return "未知";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package net.rzdata.demo.core.utils.reflect;
|
||||
|
||||
import cn.hutool.core.util.ReflectUtil;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class ReflectUtils extends ReflectUtil {
|
||||
|
||||
private static final String SETTER_PREFIX = "set";
|
||||
|
||||
private static final String GETTER_PREFIX = "get";
|
||||
|
||||
/**
|
||||
* 调用Getter方法.
|
||||
* 支持多级,如:对象名.对象名.方法
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <E> E invokeGetter(Object obj, String propertyName) {
|
||||
Object object = obj;
|
||||
for (String name : StringUtils.split(propertyName, ".")) {
|
||||
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
|
||||
object = invoke(object, getterMethodName);
|
||||
}
|
||||
return (E) object;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用Setter方法, 仅匹配方法名。
|
||||
* 支持多级,如:对象名.对象名.方法
|
||||
*/
|
||||
public static <E> void invokeSetter(Object obj, String propertyName, E value) {
|
||||
Object object = obj;
|
||||
String[] names = StringUtils.split(propertyName, ".");
|
||||
for (int i = 0; i < names.length; i++) {
|
||||
if (i < names.length - 1) {
|
||||
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
|
||||
object = invoke(object, getterMethodName);
|
||||
} else {
|
||||
String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
|
||||
Method method = getMethodByName(object.getClass(), setterMethodName);
|
||||
invoke(object, method, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package net.rzdata.demo.core.utils.sql;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
|
||||
/**
|
||||
* sql操作工具类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class SqlUtil {
|
||||
|
||||
/**
|
||||
* 定义常用的 sql关键字
|
||||
*/
|
||||
public static final String SQL_REGEX = "select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare ";
|
||||
|
||||
/**
|
||||
* 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)
|
||||
*/
|
||||
public static final String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+";
|
||||
|
||||
/**
|
||||
* 检查字符,防止注入绕过
|
||||
*/
|
||||
public static String escapeOrderBySql(String value) {
|
||||
if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {
|
||||
throw new IllegalArgumentException("参数不符合规范,不能进行查询");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 order by 语法是否符合规范
|
||||
*/
|
||||
public static boolean isValidOrderBySql(String value) {
|
||||
return value.matches(SQL_PATTERN);
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL关键字检查
|
||||
*/
|
||||
public static void filterKeyword(String value) {
|
||||
if (StringUtils.isEmpty(value)) {
|
||||
return;
|
||||
}
|
||||
String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|");
|
||||
for (String sqlKeyword : sqlKeywords) {
|
||||
if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1) {
|
||||
throw new IllegalArgumentException("参数存在SQL注入风险");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package net.rzdata.demo.core.validate;
|
||||
|
||||
/**
|
||||
* 校验分组 add
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface AddGroup {
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package net.rzdata.demo.core.validate;
|
||||
|
||||
/**
|
||||
* 校验分组 edit
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface EditGroup {
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package net.rzdata.demo.core.validate;
|
||||
|
||||
/**
|
||||
* 校验分组 query
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface QueryGroup {
|
||||
}
|
26
common/src/main/java/net/rzdata/demo/core/xss/Xss.java
Normal file
26
common/src/main/java/net/rzdata/demo/core/xss/Xss.java
Normal file
@ -0,0 +1,26 @@
|
||||
package net.rzdata.demo.core.xss;
|
||||
|
||||
import jakarta.validation.Constraint;
|
||||
import jakarta.validation.Payload;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 自定义xss校验注解
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(value = {ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
|
||||
@Constraint(validatedBy = {XssValidator.class})
|
||||
public @interface Xss {
|
||||
|
||||
String message() default "不允许任何脚本运行";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package net.rzdata.demo.core.xss;
|
||||
|
||||
import cn.hutool.core.util.ReUtil;
|
||||
import cn.hutool.http.HtmlUtil;
|
||||
|
||||
import jakarta.validation.ConstraintValidator;
|
||||
import jakarta.validation.ConstraintValidatorContext;
|
||||
|
||||
/**
|
||||
* 自定义xss校验注解实现
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public class XssValidator implements ConstraintValidator<Xss, String> {
|
||||
|
||||
@Override
|
||||
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
|
||||
return !ReUtil.contains(HtmlUtil.RE_HTML_MARK, value);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package net.rzdata.demo.encrypt.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 强制加密注解
|
||||
*
|
||||
* @author Michelle.Chung
|
||||
*/
|
||||
@Documented
|
||||
@Target({ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface ApiEncrypt {
|
||||
|
||||
/**
|
||||
* 响应加密忽略,默认不加密,为 true 时加密
|
||||
*/
|
||||
boolean response() default false;
|
||||
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package net.rzdata.demo.encrypt.annotation;
|
||||
|
||||
import net.rzdata.demo.encrypt.enumd.AlgorithmType;
|
||||
import net.rzdata.demo.encrypt.enumd.EncodeType;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 字段加密注解
|
||||
*
|
||||
* @author 老马
|
||||
*/
|
||||
@Documented
|
||||
@Inherited
|
||||
@Target({ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface EncryptField {
|
||||
|
||||
/**
|
||||
* 加密算法
|
||||
*/
|
||||
AlgorithmType algorithm() default AlgorithmType.DEFAULT;
|
||||
|
||||
/**
|
||||
* 秘钥。AES、SM4需要
|
||||
*/
|
||||
String password() default "";
|
||||
|
||||
/**
|
||||
* 公钥。RSA、SM2需要
|
||||
*/
|
||||
String publicKey() default "";
|
||||
|
||||
/**
|
||||
* 私钥。RSA、SM2需要
|
||||
*/
|
||||
String privateKey() default "";
|
||||
|
||||
/**
|
||||
* 编码方式。对加密算法为BASE64的不起作用
|
||||
*/
|
||||
EncodeType encode() default EncodeType.DEFAULT;
|
||||
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package net.rzdata.demo.encrypt.config;
|
||||
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import net.rzdata.demo.encrypt.filter.CryptoFilter;
|
||||
import net.rzdata.demo.encrypt.properties.ApiDecryptProperties;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* api 解密自动配置
|
||||
*
|
||||
* @author wdhcr
|
||||
*/
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(ApiDecryptProperties.class)
|
||||
@ConditionalOnProperty(value = "api-decrypt.enabled", havingValue = "true")
|
||||
public class ApiDecryptAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<CryptoFilter> cryptoFilterRegistration(ApiDecryptProperties properties) {
|
||||
FilterRegistrationBean<CryptoFilter> registration = new FilterRegistrationBean<>();
|
||||
registration.setDispatcherTypes(DispatcherType.REQUEST);
|
||||
registration.setFilter(new CryptoFilter(properties));
|
||||
registration.addUrlPatterns("/*");
|
||||
registration.setName("cryptoFilter");
|
||||
registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
|
||||
return registration;
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package net.rzdata.demo.encrypt.config;
|
||||
|
||||
import net.rzdata.demo.encrypt.core.EncryptorManager;
|
||||
import net.rzdata.demo.encrypt.interceptor.MybatisDecryptInterceptor;
|
||||
import net.rzdata.demo.encrypt.interceptor.MybatisEncryptInterceptor;
|
||||
import net.rzdata.demo.encrypt.properties.EncryptorProperties;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 加解密配置
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(EncryptorProperties.class)
|
||||
@ConditionalOnProperty(value = "mybatis-encryptor.enable", havingValue = "true")
|
||||
public class EncryptorAutoConfiguration {
|
||||
|
||||
@Autowired
|
||||
private EncryptorProperties properties;
|
||||
|
||||
@Bean
|
||||
public EncryptorManager encryptorManager() {
|
||||
return new EncryptorManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MybatisEncryptInterceptor mybatisEncryptInterceptor(EncryptorManager encryptorManager) {
|
||||
return new MybatisEncryptInterceptor(encryptorManager, properties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MybatisDecryptInterceptor mybatisDecryptInterceptor(EncryptorManager encryptorManager) {
|
||||
return new MybatisDecryptInterceptor(encryptorManager, properties);
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package net.rzdata.demo.encrypt.core;
|
||||
|
||||
import lombok.Data;
|
||||
import net.rzdata.demo.encrypt.enumd.AlgorithmType;
|
||||
import net.rzdata.demo.encrypt.enumd.EncodeType;
|
||||
|
||||
/**
|
||||
* 加密上下文 用于encryptor传递必要的参数。
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
@Data
|
||||
public class EncryptContext {
|
||||
|
||||
/**
|
||||
* 默认算法
|
||||
*/
|
||||
private AlgorithmType algorithm;
|
||||
|
||||
/**
|
||||
* 安全秘钥
|
||||
*/
|
||||
private String password;
|
||||
|
||||
/**
|
||||
* 公钥
|
||||
*/
|
||||
private String publicKey;
|
||||
|
||||
/**
|
||||
* 私钥
|
||||
*/
|
||||
private String privateKey;
|
||||
|
||||
/**
|
||||
* 编码方式,base64/hex
|
||||
*/
|
||||
private EncodeType encode;
|
||||
|
||||
}
|
@ -0,0 +1,100 @@
|
||||
package net.rzdata.demo.encrypt.core;
|
||||
|
||||
import cn.hutool.core.util.ReflectUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.rzdata.demo.encrypt.annotation.EncryptField;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 加密管理类
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
@Slf4j
|
||||
public class EncryptorManager {
|
||||
|
||||
/**
|
||||
* 缓存加密器
|
||||
*/
|
||||
Map<EncryptContext, IEncryptor> encryptorMap = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 类加密字段缓存
|
||||
*/
|
||||
Map<Class<?>, Set<Field>> fieldCache = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 获取类加密字段缓存
|
||||
*/
|
||||
public Set<Field> getFieldCache(Class<?> sourceClazz) {
|
||||
return fieldCache.computeIfAbsent(sourceClazz, clazz -> {
|
||||
Set<Field> fieldSet = new HashSet<>();
|
||||
while (clazz != null) {
|
||||
Field[] fields = clazz.getDeclaredFields();
|
||||
fieldSet.addAll(Arrays.asList(fields));
|
||||
clazz = clazz.getSuperclass();
|
||||
}
|
||||
fieldSet = fieldSet.stream().filter(field ->
|
||||
field.isAnnotationPresent(EncryptField.class) && field.getType() == String.class)
|
||||
.collect(Collectors.toSet());
|
||||
for (Field field : fieldSet) {
|
||||
field.setAccessible(true);
|
||||
}
|
||||
return fieldSet;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册加密执行者到缓存
|
||||
*
|
||||
* @param encryptContext 加密执行者需要的相关配置参数
|
||||
*/
|
||||
public IEncryptor registAndGetEncryptor(EncryptContext encryptContext) {
|
||||
if (encryptorMap.containsKey(encryptContext)) {
|
||||
return encryptorMap.get(encryptContext);
|
||||
}
|
||||
IEncryptor encryptor = ReflectUtil.newInstance(encryptContext.getAlgorithm().getClazz(), encryptContext);
|
||||
encryptorMap.put(encryptContext, encryptor);
|
||||
return encryptor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除缓存中的加密执行者
|
||||
*
|
||||
* @param encryptContext 加密执行者需要的相关配置参数
|
||||
*/
|
||||
public void removeEncryptor(EncryptContext encryptContext) {
|
||||
this.encryptorMap.remove(encryptContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据配置进行加密。会进行本地缓存对应的算法和对应的秘钥信息。
|
||||
*
|
||||
* @param value 待加密的值
|
||||
* @param encryptContext 加密相关的配置信息
|
||||
*/
|
||||
public String encrypt(String value, EncryptContext encryptContext) {
|
||||
IEncryptor encryptor = this.registAndGetEncryptor(encryptContext);
|
||||
return encryptor.encrypt(value, encryptContext.getEncode());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据配置进行解密
|
||||
*
|
||||
* @param value 待解密的值
|
||||
* @param encryptContext 加密相关的配置信息
|
||||
*/
|
||||
public String decrypt(String value, EncryptContext encryptContext) {
|
||||
IEncryptor encryptor = this.registAndGetEncryptor(encryptContext);
|
||||
return encryptor.decrypt(value);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package net.rzdata.demo.encrypt.core;
|
||||
|
||||
|
||||
import net.rzdata.demo.encrypt.enumd.AlgorithmType;
|
||||
import net.rzdata.demo.encrypt.enumd.EncodeType;
|
||||
|
||||
/**
|
||||
* 加解者
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
public interface IEncryptor {
|
||||
|
||||
/**
|
||||
* 获得当前算法
|
||||
*/
|
||||
AlgorithmType algorithm();
|
||||
|
||||
/**
|
||||
* 加密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
* @param encodeType 加密后的编码格式
|
||||
* @return 加密后的字符串
|
||||
*/
|
||||
String encrypt(String value, EncodeType encodeType);
|
||||
|
||||
/**
|
||||
* 解密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
* @return 解密后的字符串
|
||||
*/
|
||||
String decrypt(String value);
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package net.rzdata.demo.encrypt.core.encryptor;
|
||||
|
||||
|
||||
import net.rzdata.demo.encrypt.core.EncryptContext;
|
||||
import net.rzdata.demo.encrypt.core.IEncryptor;
|
||||
|
||||
/**
|
||||
* 所有加密执行者的基类
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
public abstract class AbstractEncryptor implements IEncryptor {
|
||||
|
||||
public AbstractEncryptor(EncryptContext context) {
|
||||
// 用户配置校验与配置注入
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package net.rzdata.demo.encrypt.core.encryptor;
|
||||
|
||||
|
||||
import net.rzdata.demo.encrypt.core.EncryptContext;
|
||||
import net.rzdata.demo.encrypt.enumd.AlgorithmType;
|
||||
import net.rzdata.demo.encrypt.enumd.EncodeType;
|
||||
import net.rzdata.demo.encrypt.utils.EncryptUtils;
|
||||
|
||||
/**
|
||||
* AES算法实现
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
public class AesEncryptor extends AbstractEncryptor {
|
||||
|
||||
private final EncryptContext context;
|
||||
|
||||
public AesEncryptor(EncryptContext context) {
|
||||
super(context);
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得当前算法
|
||||
*/
|
||||
@Override
|
||||
public AlgorithmType algorithm() {
|
||||
return AlgorithmType.AES;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
* @param encodeType 加密后的编码格式
|
||||
*/
|
||||
@Override
|
||||
public String encrypt(String value, EncodeType encodeType) {
|
||||
if (encodeType == EncodeType.HEX) {
|
||||
return EncryptUtils.encryptByAesHex(value, context.getPassword());
|
||||
} else {
|
||||
return EncryptUtils.encryptByAes(value, context.getPassword());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
*/
|
||||
@Override
|
||||
public String decrypt(String value) {
|
||||
return EncryptUtils.decryptByAes(value, context.getPassword());
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package net.rzdata.demo.encrypt.core.encryptor;
|
||||
|
||||
|
||||
import net.rzdata.demo.encrypt.core.EncryptContext;
|
||||
import net.rzdata.demo.encrypt.enumd.AlgorithmType;
|
||||
import net.rzdata.demo.encrypt.enumd.EncodeType;
|
||||
import net.rzdata.demo.encrypt.utils.EncryptUtils;
|
||||
|
||||
/**
|
||||
* Base64算法实现
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
public class Base64Encryptor extends AbstractEncryptor {
|
||||
|
||||
public Base64Encryptor(EncryptContext context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得当前算法
|
||||
*/
|
||||
@Override
|
||||
public AlgorithmType algorithm() {
|
||||
return AlgorithmType.BASE64;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
* @param encodeType 加密后的编码格式
|
||||
*/
|
||||
@Override
|
||||
public String encrypt(String value, EncodeType encodeType) {
|
||||
return EncryptUtils.encryptByBase64(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
*/
|
||||
@Override
|
||||
public String decrypt(String value) {
|
||||
return EncryptUtils.decryptByBase64(value);
|
||||
}
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package net.rzdata.demo.encrypt.core.encryptor;
|
||||
|
||||
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import net.rzdata.demo.encrypt.core.EncryptContext;
|
||||
import net.rzdata.demo.encrypt.enumd.AlgorithmType;
|
||||
import net.rzdata.demo.encrypt.enumd.EncodeType;
|
||||
import net.rzdata.demo.encrypt.utils.EncryptUtils;
|
||||
|
||||
/**
|
||||
* RSA算法实现
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
public class RsaEncryptor extends AbstractEncryptor {
|
||||
|
||||
private final EncryptContext context;
|
||||
|
||||
public RsaEncryptor(EncryptContext context) {
|
||||
super(context);
|
||||
String privateKey = context.getPrivateKey();
|
||||
String publicKey = context.getPublicKey();
|
||||
if (StringUtils.isAnyEmpty(privateKey, publicKey)) {
|
||||
throw new IllegalArgumentException("RSA公私钥均需要提供,公钥加密,私钥解密。");
|
||||
}
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得当前算法
|
||||
*/
|
||||
@Override
|
||||
public AlgorithmType algorithm() {
|
||||
return AlgorithmType.RSA;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
* @param encodeType 加密后的编码格式
|
||||
*/
|
||||
@Override
|
||||
public String encrypt(String value, EncodeType encodeType) {
|
||||
if (encodeType == EncodeType.HEX) {
|
||||
return EncryptUtils.encryptByRsaHex(value, context.getPublicKey());
|
||||
} else {
|
||||
return EncryptUtils.encryptByRsa(value, context.getPublicKey());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
*/
|
||||
@Override
|
||||
public String decrypt(String value) {
|
||||
return EncryptUtils.decryptByRsa(value, context.getPrivateKey());
|
||||
}
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package net.rzdata.demo.encrypt.core.encryptor;
|
||||
|
||||
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import net.rzdata.demo.encrypt.core.EncryptContext;
|
||||
import net.rzdata.demo.encrypt.enumd.AlgorithmType;
|
||||
import net.rzdata.demo.encrypt.enumd.EncodeType;
|
||||
import net.rzdata.demo.encrypt.utils.EncryptUtils;
|
||||
|
||||
/**
|
||||
* sm2算法实现
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
public class Sm2Encryptor extends AbstractEncryptor {
|
||||
|
||||
private final EncryptContext context;
|
||||
|
||||
public Sm2Encryptor(EncryptContext context) {
|
||||
super(context);
|
||||
String privateKey = context.getPrivateKey();
|
||||
String publicKey = context.getPublicKey();
|
||||
if (StringUtils.isAnyEmpty(privateKey, publicKey)) {
|
||||
throw new IllegalArgumentException("SM2公私钥均需要提供,公钥加密,私钥解密。");
|
||||
}
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得当前算法
|
||||
*/
|
||||
@Override
|
||||
public AlgorithmType algorithm() {
|
||||
return AlgorithmType.SM2;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
* @param encodeType 加密后的编码格式
|
||||
*/
|
||||
@Override
|
||||
public String encrypt(String value, EncodeType encodeType) {
|
||||
if (encodeType == EncodeType.HEX) {
|
||||
return EncryptUtils.encryptBySm2Hex(value, context.getPublicKey());
|
||||
} else {
|
||||
return EncryptUtils.encryptBySm2(value, context.getPublicKey());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
*/
|
||||
@Override
|
||||
public String decrypt(String value) {
|
||||
return EncryptUtils.decryptBySm2(value, context.getPrivateKey());
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package net.rzdata.demo.encrypt.core.encryptor;
|
||||
|
||||
|
||||
import net.rzdata.demo.encrypt.core.EncryptContext;
|
||||
import net.rzdata.demo.encrypt.enumd.AlgorithmType;
|
||||
import net.rzdata.demo.encrypt.enumd.EncodeType;
|
||||
import net.rzdata.demo.encrypt.utils.EncryptUtils;
|
||||
|
||||
/**
|
||||
* sm4算法实现
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
public class Sm4Encryptor extends AbstractEncryptor {
|
||||
|
||||
private final EncryptContext context;
|
||||
|
||||
public Sm4Encryptor(EncryptContext context) {
|
||||
super(context);
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得当前算法
|
||||
*/
|
||||
@Override
|
||||
public AlgorithmType algorithm() {
|
||||
return AlgorithmType.SM4;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
* @param encodeType 加密后的编码格式
|
||||
*/
|
||||
@Override
|
||||
public String encrypt(String value, EncodeType encodeType) {
|
||||
if (encodeType == EncodeType.HEX) {
|
||||
return EncryptUtils.encryptBySm4Hex(value, context.getPassword());
|
||||
} else {
|
||||
return EncryptUtils.encryptBySm4(value, context.getPassword());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密
|
||||
*
|
||||
* @param value 待加密字符串
|
||||
*/
|
||||
@Override
|
||||
public String decrypt(String value) {
|
||||
return EncryptUtils.decryptBySm4(value, context.getPassword());
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package net.rzdata.demo.encrypt.enumd;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import net.rzdata.demo.encrypt.core.encryptor.*;
|
||||
|
||||
/**
|
||||
* 算法名称
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum AlgorithmType {
|
||||
|
||||
/**
|
||||
* 默认走yml配置
|
||||
*/
|
||||
DEFAULT(null),
|
||||
|
||||
/**
|
||||
* base64
|
||||
*/
|
||||
BASE64(Base64Encryptor.class),
|
||||
|
||||
/**
|
||||
* aes
|
||||
*/
|
||||
AES(AesEncryptor.class),
|
||||
|
||||
/**
|
||||
* rsa
|
||||
*/
|
||||
RSA(RsaEncryptor.class),
|
||||
|
||||
/**
|
||||
* sm2
|
||||
*/
|
||||
SM2(Sm2Encryptor.class),
|
||||
|
||||
/**
|
||||
* sm4
|
||||
*/
|
||||
SM4(Sm4Encryptor.class);
|
||||
|
||||
private final Class<? extends AbstractEncryptor> clazz;
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package net.rzdata.demo.encrypt.enumd;
|
||||
|
||||
/**
|
||||
* 编码类型
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
public enum EncodeType {
|
||||
|
||||
/**
|
||||
* 默认使用yml配置
|
||||
*/
|
||||
DEFAULT,
|
||||
|
||||
/**
|
||||
* base64编码
|
||||
*/
|
||||
BASE64,
|
||||
|
||||
/**
|
||||
* 16进制编码
|
||||
*/
|
||||
HEX;
|
||||
|
||||
}
|
@ -0,0 +1,115 @@
|
||||
package net.rzdata.demo.encrypt.filter;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import jakarta.servlet.*;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import net.rzdata.demo.core.constant.HttpStatus;
|
||||
import net.rzdata.demo.core.exception.ServiceException;
|
||||
import net.rzdata.demo.core.utils.SpringUtils;
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import net.rzdata.demo.encrypt.annotation.ApiEncrypt;
|
||||
import net.rzdata.demo.encrypt.properties.ApiDecryptProperties;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.HandlerExecutionChain;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
/**
|
||||
* Crypto 过滤器
|
||||
*
|
||||
* @author wdhcr
|
||||
*/
|
||||
public class CryptoFilter implements Filter {
|
||||
private final ApiDecryptProperties properties;
|
||||
|
||||
public CryptoFilter(ApiDecryptProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletRequest servletRequest = (HttpServletRequest) request;
|
||||
HttpServletResponse servletResponse = (HttpServletResponse) response;
|
||||
|
||||
boolean responseFlag = false;
|
||||
ServletRequest requestWrapper = null;
|
||||
ServletResponse responseWrapper = null;
|
||||
EncryptResponseBodyWrapper responseBodyWrapper = null;
|
||||
|
||||
// 是否为 json 请求
|
||||
if (StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
|
||||
// 是否为 put 或者 post 请求
|
||||
if (HttpMethod.PUT.matches(servletRequest.getMethod()) || HttpMethod.POST.matches(servletRequest.getMethod())) {
|
||||
// 是否存在加密标头
|
||||
String headerValue = servletRequest.getHeader(properties.getHeaderFlag());
|
||||
// 获取加密注解
|
||||
ApiEncrypt apiEncrypt = this.getApiEncryptAnnotation(servletRequest);
|
||||
responseFlag = apiEncrypt != null && apiEncrypt.response();
|
||||
if (StringUtils.isNotBlank(headerValue)) {
|
||||
// 请求解密
|
||||
requestWrapper = new DecryptRequestBodyWrapper(servletRequest, properties.getPrivateKey(), properties.getHeaderFlag());
|
||||
} else {
|
||||
// 是否有注解,有就报错,没有放行
|
||||
if (ObjectUtil.isNotNull(apiEncrypt)) {
|
||||
HandlerExceptionResolver exceptionResolver = SpringUtils.getBean("handlerExceptionResolver", HandlerExceptionResolver.class);
|
||||
exceptionResolver.resolveException(
|
||||
servletRequest, servletResponse, null,
|
||||
new ServiceException("没有访问权限,请联系管理员授权", HttpStatus.FORBIDDEN));
|
||||
return;
|
||||
}
|
||||
}
|
||||
// 判断是否响应加密
|
||||
if (responseFlag) {
|
||||
responseBodyWrapper = new EncryptResponseBodyWrapper(servletResponse);
|
||||
responseWrapper = responseBodyWrapper;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
chain.doFilter(
|
||||
ObjectUtil.defaultIfNull(requestWrapper, request),
|
||||
ObjectUtil.defaultIfNull(responseWrapper, response));
|
||||
|
||||
if (responseFlag) {
|
||||
servletResponse.reset();
|
||||
// 对原始内容加密
|
||||
String encryptContent = responseBodyWrapper.getEncryptContent(
|
||||
servletResponse, properties.getPublicKey(), properties.getHeaderFlag());
|
||||
// 对加密后的内容写出
|
||||
servletResponse.getWriter().write(encryptContent);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 ApiEncrypt 注解
|
||||
*/
|
||||
private ApiEncrypt getApiEncryptAnnotation(HttpServletRequest servletRequest) {
|
||||
RequestMappingHandlerMapping handlerMapping = SpringUtils.getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
|
||||
// 获取注解
|
||||
try {
|
||||
HandlerExecutionChain mappingHandler = handlerMapping.getHandler(servletRequest);
|
||||
if (ObjectUtil.isNotNull(mappingHandler)) {
|
||||
Object handler = mappingHandler.getHandler();
|
||||
if (ObjectUtil.isNotNull(handler)) {
|
||||
// 从handler获取注解
|
||||
if (handler instanceof HandlerMethod handlerMethod) {
|
||||
return handlerMethod.getMethodAnnotation(ApiEncrypt.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
}
|
@ -0,0 +1,94 @@
|
||||
package net.rzdata.demo.encrypt.filter;
|
||||
|
||||
import cn.hutool.core.io.IoUtil;
|
||||
import jakarta.servlet.ReadListener;
|
||||
import jakarta.servlet.ServletInputStream;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequestWrapper;
|
||||
import net.rzdata.demo.core.constant.Constants;
|
||||
import net.rzdata.demo.encrypt.utils.EncryptUtils;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 解密请求参数工具类
|
||||
*
|
||||
* @author wdhcr
|
||||
*/
|
||||
public class DecryptRequestBodyWrapper extends HttpServletRequestWrapper {
|
||||
|
||||
private final byte[] body;
|
||||
|
||||
public DecryptRequestBodyWrapper(HttpServletRequest request, String privateKey, String headerFlag) throws IOException {
|
||||
super(request);
|
||||
// 获取 AES 密码 采用 RSA 加密
|
||||
String headerRsa = request.getHeader(headerFlag);
|
||||
String decryptAes = EncryptUtils.decryptByRsa(headerRsa, privateKey);
|
||||
// 解密 AES 密码
|
||||
String aesPassword = EncryptUtils.decryptByBase64(decryptAes);
|
||||
request.setCharacterEncoding(Constants.UTF8);
|
||||
byte[] readBytes = IoUtil.readBytes(request.getInputStream(), false);
|
||||
String requestBody = new String(readBytes, StandardCharsets.UTF_8);
|
||||
// 解密 body 采用 AES 加密
|
||||
String decryptBody = EncryptUtils.decryptByAes(requestBody, aesPassword);
|
||||
body = decryptBody.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BufferedReader getReader() {
|
||||
return new BufferedReader(new InputStreamReader(getInputStream()));
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int getContentLength() {
|
||||
return body.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getContentLengthLong() {
|
||||
return body.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContentType() {
|
||||
return MediaType.APPLICATION_JSON_VALUE;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ServletInputStream getInputStream() {
|
||||
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
|
||||
return new ServletInputStream() {
|
||||
@Override
|
||||
public int read() {
|
||||
return bais.read();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int available() {
|
||||
return body.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isFinished() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setReadListener(ReadListener readListener) {
|
||||
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
@ -0,0 +1,120 @@
|
||||
package net.rzdata.demo.encrypt.filter;
|
||||
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import jakarta.servlet.ServletOutputStream;
|
||||
import jakarta.servlet.WriteListener;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpServletResponseWrapper;
|
||||
import net.rzdata.demo.encrypt.utils.EncryptUtils;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 加密响应参数包装类
|
||||
*
|
||||
* @author Michelle.Chung
|
||||
*/
|
||||
public class EncryptResponseBodyWrapper extends HttpServletResponseWrapper {
|
||||
|
||||
private final ByteArrayOutputStream byteArrayOutputStream;
|
||||
private final ServletOutputStream servletOutputStream;
|
||||
private final PrintWriter printWriter;
|
||||
|
||||
public EncryptResponseBodyWrapper(HttpServletResponse response) throws IOException {
|
||||
super(response);
|
||||
this.byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
this.servletOutputStream = this.getOutputStream();
|
||||
this.printWriter = new PrintWriter(new OutputStreamWriter(byteArrayOutputStream));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PrintWriter getWriter() {
|
||||
return printWriter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flushBuffer() throws IOException {
|
||||
if (servletOutputStream != null) {
|
||||
servletOutputStream.flush();
|
||||
}
|
||||
if (printWriter != null) {
|
||||
printWriter.flush();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
byteArrayOutputStream.reset();
|
||||
}
|
||||
|
||||
public byte[] getResponseData() throws IOException {
|
||||
flushBuffer();
|
||||
return byteArrayOutputStream.toByteArray();
|
||||
}
|
||||
|
||||
public String getContent() throws IOException {
|
||||
flushBuffer();
|
||||
return byteArrayOutputStream.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取加密内容
|
||||
*
|
||||
* @param servletResponse response
|
||||
* @param publicKey RSA公钥 (用于加密 AES 秘钥)
|
||||
* @param headerFlag 请求头标志
|
||||
* @return 加密内容
|
||||
* @throws IOException
|
||||
*/
|
||||
public String getEncryptContent(HttpServletResponse servletResponse, String publicKey, String headerFlag) throws IOException {
|
||||
// 生成秘钥
|
||||
String aesPassword = RandomUtil.randomString(32);
|
||||
// 秘钥使用 Base64 编码
|
||||
String encryptAes = EncryptUtils.encryptByBase64(aesPassword);
|
||||
// Rsa 公钥加密 Base64 编码
|
||||
String encryptPassword = EncryptUtils.encryptByRsa(encryptAes, publicKey);
|
||||
|
||||
// 设置响应头
|
||||
servletResponse.setHeader(headerFlag, encryptPassword);
|
||||
servletResponse.setHeader("Access-Control-Allow-Origin", "*");
|
||||
servletResponse.setHeader("Access-Control-Allow-Methods", "*");
|
||||
servletResponse.setCharacterEncoding(StandardCharsets.UTF_8.toString());
|
||||
|
||||
// 获取原始内容
|
||||
String originalBody = this.getContent();
|
||||
// 对内容进行加密
|
||||
return EncryptUtils.encryptByAes(originalBody, aesPassword);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServletOutputStream getOutputStream() throws IOException {
|
||||
return new ServletOutputStream() {
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setWriteListener(WriteListener writeListener) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int b) throws IOException {
|
||||
byteArrayOutputStream.write(b);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] b) throws IOException {
|
||||
byteArrayOutputStream.write(b);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] b, int off, int len) throws IOException {
|
||||
byteArrayOutputStream.write(b, off, len);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,116 @@
|
||||
package net.rzdata.demo.encrypt.interceptor;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import net.rzdata.demo.encrypt.annotation.EncryptField;
|
||||
import net.rzdata.demo.encrypt.core.EncryptContext;
|
||||
import net.rzdata.demo.encrypt.core.EncryptorManager;
|
||||
import net.rzdata.demo.encrypt.enumd.AlgorithmType;
|
||||
import net.rzdata.demo.encrypt.enumd.EncodeType;
|
||||
import net.rzdata.demo.encrypt.properties.EncryptorProperties;
|
||||
import org.apache.ibatis.executor.resultset.ResultSetHandler;
|
||||
import org.apache.ibatis.plugin.*;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.sql.Statement;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 出参解密拦截器
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
@Slf4j
|
||||
@Intercepts({@Signature(
|
||||
type = ResultSetHandler.class,
|
||||
method = "handleResultSets",
|
||||
args = {Statement.class})
|
||||
})
|
||||
@AllArgsConstructor
|
||||
public class MybatisDecryptInterceptor implements Interceptor {
|
||||
|
||||
private final EncryptorManager encryptorManager;
|
||||
private final EncryptorProperties defaultProperties;
|
||||
|
||||
@Override
|
||||
public Object intercept(Invocation invocation) throws Throwable {
|
||||
// 获取执行mysql执行结果
|
||||
Object result = invocation.proceed();
|
||||
if (result == null) {
|
||||
return null;
|
||||
}
|
||||
decryptHandler(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密对象
|
||||
*
|
||||
* @param sourceObject 待加密对象
|
||||
*/
|
||||
private void decryptHandler(Object sourceObject) {
|
||||
if (ObjectUtil.isNull(sourceObject)) {
|
||||
return;
|
||||
}
|
||||
if (sourceObject instanceof Map<?, ?> map) {
|
||||
new HashSet<>(map.values()).forEach(this::decryptHandler);
|
||||
return;
|
||||
}
|
||||
if (sourceObject instanceof List<?> list) {
|
||||
if(CollUtil.isEmpty(list)) {
|
||||
return;
|
||||
}
|
||||
// 判断第一个元素是否含有注解。如果没有直接返回,提高效率
|
||||
Object firstItem = list.get(0);
|
||||
if (ObjectUtil.isNull(firstItem) || CollUtil.isEmpty(encryptorManager.getFieldCache(firstItem.getClass()))) {
|
||||
return;
|
||||
}
|
||||
list.forEach(this::decryptHandler);
|
||||
return;
|
||||
}
|
||||
Set<Field> fields = encryptorManager.getFieldCache(sourceObject.getClass());
|
||||
try {
|
||||
for (Field field : fields) {
|
||||
field.set(sourceObject, this.decryptField(Convert.toStr(field.get(sourceObject)), field));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("处理解密字段时出错", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 字段值进行加密。通过字段的批注注册新的加密算法
|
||||
*
|
||||
* @param value 待加密的值
|
||||
* @param field 待加密字段
|
||||
* @return 加密后结果
|
||||
*/
|
||||
private String decryptField(String value, Field field) {
|
||||
if (ObjectUtil.isNull(value)) {
|
||||
return null;
|
||||
}
|
||||
EncryptField encryptField = field.getAnnotation(EncryptField.class);
|
||||
EncryptContext encryptContext = new EncryptContext();
|
||||
encryptContext.setAlgorithm(encryptField.algorithm() == AlgorithmType.DEFAULT ? defaultProperties.getAlgorithm() : encryptField.algorithm());
|
||||
encryptContext.setEncode(encryptField.encode() == EncodeType.DEFAULT ? defaultProperties.getEncode() : encryptField.encode());
|
||||
encryptContext.setPassword(StringUtils.isBlank(encryptField.password()) ? defaultProperties.getPassword() : encryptField.password());
|
||||
encryptContext.setPrivateKey(StringUtils.isBlank(encryptField.privateKey()) ? defaultProperties.getPrivateKey() : encryptField.privateKey());
|
||||
encryptContext.setPublicKey(StringUtils.isBlank(encryptField.publicKey()) ? defaultProperties.getPublicKey() : encryptField.publicKey());
|
||||
return this.encryptorManager.decrypt(value, encryptContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object plugin(Object target) {
|
||||
return Plugin.wrap(target, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setProperties(Properties properties) {
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,120 @@
|
||||
package net.rzdata.demo.encrypt.interceptor;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import org.apache.ibatis.executor.parameter.ParameterHandler;
|
||||
import org.apache.ibatis.plugin.Interceptor;
|
||||
import org.apache.ibatis.plugin.Intercepts;
|
||||
import org.apache.ibatis.plugin.Invocation;
|
||||
import org.apache.ibatis.plugin.Signature;
|
||||
import net.rzdata.demo.encrypt.annotation.EncryptField;
|
||||
import net.rzdata.demo.encrypt.core.EncryptContext;
|
||||
import net.rzdata.demo.encrypt.core.EncryptorManager;
|
||||
import net.rzdata.demo.encrypt.enumd.AlgorithmType;
|
||||
import net.rzdata.demo.encrypt.enumd.EncodeType;
|
||||
import net.rzdata.demo.encrypt.properties.EncryptorProperties;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 入参加密拦截器
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
@Slf4j
|
||||
@Intercepts({@Signature(
|
||||
type = ParameterHandler.class,
|
||||
method = "setParameters",
|
||||
args = {PreparedStatement.class})
|
||||
})
|
||||
@AllArgsConstructor
|
||||
public class MybatisEncryptInterceptor implements Interceptor {
|
||||
|
||||
private final EncryptorManager encryptorManager;
|
||||
private final EncryptorProperties defaultProperties;
|
||||
|
||||
@Override
|
||||
public Object intercept(Invocation invocation) throws Throwable {
|
||||
return invocation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object plugin(Object target) {
|
||||
if (target instanceof ParameterHandler parameterHandler) {
|
||||
// 进行加密操作
|
||||
Object parameterObject = parameterHandler.getParameterObject();
|
||||
if (ObjectUtil.isNotNull(parameterObject) && !(parameterObject instanceof String)) {
|
||||
this.encryptHandler(parameterObject);
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密对象
|
||||
*
|
||||
* @param sourceObject 待加密对象
|
||||
*/
|
||||
private void encryptHandler(Object sourceObject) {
|
||||
if (ObjectUtil.isNull(sourceObject)) {
|
||||
return;
|
||||
}
|
||||
if (sourceObject instanceof Map<?, ?> map) {
|
||||
new HashSet<>(map.values()).forEach(this::encryptHandler);
|
||||
return;
|
||||
}
|
||||
if (sourceObject instanceof List<?> list) {
|
||||
if(CollUtil.isEmpty(list)) {
|
||||
return;
|
||||
}
|
||||
// 判断第一个元素是否含有注解。如果没有直接返回,提高效率
|
||||
Object firstItem = list.get(0);
|
||||
if (ObjectUtil.isNull(firstItem) || CollUtil.isEmpty(encryptorManager.getFieldCache(firstItem.getClass()))) {
|
||||
return;
|
||||
}
|
||||
list.forEach(this::encryptHandler);
|
||||
return;
|
||||
}
|
||||
Set<Field> fields = encryptorManager.getFieldCache(sourceObject.getClass());
|
||||
try {
|
||||
for (Field field : fields) {
|
||||
field.set(sourceObject, this.encryptField(Convert.toStr(field.get(sourceObject)), field));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("处理加密字段时出错", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 字段值进行加密。通过字段的批注注册新的加密算法
|
||||
*
|
||||
* @param value 待加密的值
|
||||
* @param field 待加密字段
|
||||
* @return 加密后结果
|
||||
*/
|
||||
private String encryptField(String value, Field field) {
|
||||
if (ObjectUtil.isNull(value)) {
|
||||
return null;
|
||||
}
|
||||
EncryptField encryptField = field.getAnnotation(EncryptField.class);
|
||||
EncryptContext encryptContext = new EncryptContext();
|
||||
encryptContext.setAlgorithm(encryptField.algorithm() == AlgorithmType.DEFAULT ? defaultProperties.getAlgorithm() : encryptField.algorithm());
|
||||
encryptContext.setEncode(encryptField.encode() == EncodeType.DEFAULT ? defaultProperties.getEncode() : encryptField.encode());
|
||||
encryptContext.setPassword(StringUtils.isBlank(encryptField.password()) ? defaultProperties.getPassword() : encryptField.password());
|
||||
encryptContext.setPrivateKey(StringUtils.isBlank(encryptField.privateKey()) ? defaultProperties.getPrivateKey() : encryptField.privateKey());
|
||||
encryptContext.setPublicKey(StringUtils.isBlank(encryptField.publicKey()) ? defaultProperties.getPublicKey() : encryptField.publicKey());
|
||||
return this.encryptorManager.encrypt(value, encryptContext);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void setProperties(Properties properties) {
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package net.rzdata.demo.encrypt.properties;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* api解密属性配置类
|
||||
* @author wdhcr
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "api-decrypt")
|
||||
public class ApiDecryptProperties {
|
||||
|
||||
/**
|
||||
* 加密开关
|
||||
*/
|
||||
private Boolean enabled;
|
||||
|
||||
/**
|
||||
* 头部标识
|
||||
*/
|
||||
private String headerFlag;
|
||||
|
||||
/**
|
||||
* 响应加密公钥
|
||||
*/
|
||||
private String publicKey;
|
||||
|
||||
/**
|
||||
* 请求解密私钥
|
||||
*/
|
||||
private String privateKey;
|
||||
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package net.rzdata.demo.encrypt.properties;
|
||||
|
||||
import lombok.Data;
|
||||
import net.rzdata.demo.encrypt.enumd.AlgorithmType;
|
||||
import net.rzdata.demo.encrypt.enumd.EncodeType;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* 加解密属性配置类
|
||||
*
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "mybatis-encryptor")
|
||||
public class EncryptorProperties {
|
||||
|
||||
/**
|
||||
* 过滤开关
|
||||
*/
|
||||
private Boolean enable;
|
||||
|
||||
/**
|
||||
* 默认算法
|
||||
*/
|
||||
private AlgorithmType algorithm;
|
||||
|
||||
/**
|
||||
* 安全秘钥
|
||||
*/
|
||||
private String password;
|
||||
|
||||
/**
|
||||
* 公钥
|
||||
*/
|
||||
private String publicKey;
|
||||
|
||||
/**
|
||||
* 私钥
|
||||
*/
|
||||
private String privateKey;
|
||||
|
||||
/**
|
||||
* 编码方式,base64/hex
|
||||
*/
|
||||
private EncodeType encode;
|
||||
|
||||
}
|
@ -0,0 +1,311 @@
|
||||
package net.rzdata.demo.encrypt.utils;
|
||||
|
||||
import cn.hutool.core.codec.Base64;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.crypto.SecureUtil;
|
||||
import cn.hutool.crypto.SmUtil;
|
||||
import cn.hutool.crypto.asymmetric.KeyType;
|
||||
import cn.hutool.crypto.asymmetric.RSA;
|
||||
import cn.hutool.crypto.asymmetric.SM2;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 安全相关工具类
|
||||
*
|
||||
* @author 老马
|
||||
*/
|
||||
public class EncryptUtils {
|
||||
/**
|
||||
* 公钥
|
||||
*/
|
||||
public static final String PUBLIC_KEY = "publicKey";
|
||||
/**
|
||||
* 私钥
|
||||
*/
|
||||
public static final String PRIVATE_KEY = "privateKey";
|
||||
|
||||
/**
|
||||
* Base64加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String encryptByBase64(String data) {
|
||||
return Base64.encode(data, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64解密
|
||||
*
|
||||
* @param data 待解密数据
|
||||
* @return 解密后字符串
|
||||
*/
|
||||
public static String decryptByBase64(String data) {
|
||||
return Base64.decodeStr(data, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* AES加密
|
||||
*
|
||||
* @param data 待解密数据
|
||||
* @param password 秘钥字符串
|
||||
* @return 加密后字符串, 采用Base64编码
|
||||
*/
|
||||
public static String encryptByAes(String data, String password) {
|
||||
if (StrUtil.isBlank(password)) {
|
||||
throw new IllegalArgumentException("AES需要传入秘钥信息");
|
||||
}
|
||||
// aes算法的秘钥要求是16位、24位、32位
|
||||
int[] array = {16, 24, 32};
|
||||
if (!ArrayUtil.contains(array, password.length())) {
|
||||
throw new IllegalArgumentException("AES秘钥长度要求为16位、24位、32位");
|
||||
}
|
||||
return SecureUtil.aes(password.getBytes(StandardCharsets.UTF_8)).encryptBase64(data, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* AES加密
|
||||
*
|
||||
* @param data 待解密数据
|
||||
* @param password 秘钥字符串
|
||||
* @return 加密后字符串, 采用Hex编码
|
||||
*/
|
||||
public static String encryptByAesHex(String data, String password) {
|
||||
if (StrUtil.isBlank(password)) {
|
||||
throw new IllegalArgumentException("AES需要传入秘钥信息");
|
||||
}
|
||||
// aes算法的秘钥要求是16位、24位、32位
|
||||
int[] array = {16, 24, 32};
|
||||
if (!ArrayUtil.contains(array, password.length())) {
|
||||
throw new IllegalArgumentException("AES秘钥长度要求为16位、24位、32位");
|
||||
}
|
||||
return SecureUtil.aes(password.getBytes(StandardCharsets.UTF_8)).encryptHex(data, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* AES解密
|
||||
*
|
||||
* @param data 待解密数据
|
||||
* @param password 秘钥字符串
|
||||
* @return 解密后字符串
|
||||
*/
|
||||
public static String decryptByAes(String data, String password) {
|
||||
if (StrUtil.isBlank(password)) {
|
||||
throw new IllegalArgumentException("AES需要传入秘钥信息");
|
||||
}
|
||||
// aes算法的秘钥要求是16位、24位、32位
|
||||
int[] array = {16, 24, 32};
|
||||
if (!ArrayUtil.contains(array, password.length())) {
|
||||
throw new IllegalArgumentException("AES秘钥长度要求为16位、24位、32位");
|
||||
}
|
||||
return SecureUtil.aes(password.getBytes(StandardCharsets.UTF_8)).decryptStr(data, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* sm4加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @param password 秘钥字符串
|
||||
* @return 加密后字符串, 采用Base64编码
|
||||
*/
|
||||
public static String encryptBySm4(String data, String password) {
|
||||
if (StrUtil.isBlank(password)) {
|
||||
throw new IllegalArgumentException("SM4需要传入秘钥信息");
|
||||
}
|
||||
// sm4算法的秘钥要求是16位长度
|
||||
int sm4PasswordLength = 16;
|
||||
if (sm4PasswordLength != password.length()) {
|
||||
throw new IllegalArgumentException("SM4秘钥长度要求为16位");
|
||||
}
|
||||
return SmUtil.sm4(password.getBytes(StandardCharsets.UTF_8)).encryptBase64(data, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* sm4加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @param password 秘钥字符串
|
||||
* @return 加密后字符串, 采用Base64编码
|
||||
*/
|
||||
public static String encryptBySm4Hex(String data, String password) {
|
||||
if (StrUtil.isBlank(password)) {
|
||||
throw new IllegalArgumentException("SM4需要传入秘钥信息");
|
||||
}
|
||||
// sm4算法的秘钥要求是16位长度
|
||||
int sm4PasswordLength = 16;
|
||||
if (sm4PasswordLength != password.length()) {
|
||||
throw new IllegalArgumentException("SM4秘钥长度要求为16位");
|
||||
}
|
||||
return SmUtil.sm4(password.getBytes(StandardCharsets.UTF_8)).encryptHex(data, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* sm4解密
|
||||
*
|
||||
* @param data 待解密数据
|
||||
* @param password 秘钥字符串
|
||||
* @return 解密后字符串
|
||||
*/
|
||||
public static String decryptBySm4(String data, String password) {
|
||||
if (StrUtil.isBlank(password)) {
|
||||
throw new IllegalArgumentException("SM4需要传入秘钥信息");
|
||||
}
|
||||
// sm4算法的秘钥要求是16位长度
|
||||
int sm4PasswordLength = 16;
|
||||
if (sm4PasswordLength != password.length()) {
|
||||
throw new IllegalArgumentException("SM4秘钥长度要求为16位");
|
||||
}
|
||||
return SmUtil.sm4(password.getBytes(StandardCharsets.UTF_8)).decryptStr(data, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* 产生sm2加解密需要的公钥和私钥
|
||||
*
|
||||
* @return 公私钥Map
|
||||
*/
|
||||
public static Map<String, String> generateSm2Key() {
|
||||
Map<String, String> keyMap = new HashMap<>(2);
|
||||
SM2 sm2 = SmUtil.sm2();
|
||||
keyMap.put(PRIVATE_KEY, sm2.getPrivateKeyBase64());
|
||||
keyMap.put(PUBLIC_KEY, sm2.getPublicKeyBase64());
|
||||
return keyMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* sm2公钥加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @param publicKey 公钥
|
||||
* @return 加密后字符串, 采用Base64编码
|
||||
*/
|
||||
public static String encryptBySm2(String data, String publicKey) {
|
||||
if (StrUtil.isBlank(publicKey)) {
|
||||
throw new IllegalArgumentException("SM2需要传入公钥进行加密");
|
||||
}
|
||||
SM2 sm2 = SmUtil.sm2(null, publicKey);
|
||||
return sm2.encryptBase64(data, StandardCharsets.UTF_8, KeyType.PublicKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* sm2公钥加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @param publicKey 公钥
|
||||
* @return 加密后字符串, 采用Hex编码
|
||||
*/
|
||||
public static String encryptBySm2Hex(String data, String publicKey) {
|
||||
if (StrUtil.isBlank(publicKey)) {
|
||||
throw new IllegalArgumentException("SM2需要传入公钥进行加密");
|
||||
}
|
||||
SM2 sm2 = SmUtil.sm2(null, publicKey);
|
||||
return sm2.encryptHex(data, StandardCharsets.UTF_8, KeyType.PublicKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* sm2私钥解密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @param privateKey 私钥
|
||||
* @return 解密后字符串
|
||||
*/
|
||||
public static String decryptBySm2(String data, String privateKey) {
|
||||
if (StrUtil.isBlank(privateKey)) {
|
||||
throw new IllegalArgumentException("SM2需要传入私钥进行解密");
|
||||
}
|
||||
SM2 sm2 = SmUtil.sm2(privateKey, null);
|
||||
return sm2.decryptStr(data, KeyType.PrivateKey, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* 产生RSA加解密需要的公钥和私钥
|
||||
*
|
||||
* @return 公私钥Map
|
||||
*/
|
||||
public static Map<String, String> generateRsaKey() {
|
||||
Map<String, String> keyMap = new HashMap<>(2);
|
||||
RSA rsa = SecureUtil.rsa();
|
||||
keyMap.put(PRIVATE_KEY, rsa.getPrivateKeyBase64());
|
||||
keyMap.put(PUBLIC_KEY, rsa.getPublicKeyBase64());
|
||||
return keyMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* rsa公钥加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @param publicKey 公钥
|
||||
* @return 加密后字符串, 采用Base64编码
|
||||
*/
|
||||
public static String encryptByRsa(String data, String publicKey) {
|
||||
if (StrUtil.isBlank(publicKey)) {
|
||||
throw new IllegalArgumentException("RSA需要传入公钥进行加密");
|
||||
}
|
||||
RSA rsa = SecureUtil.rsa(null, publicKey);
|
||||
return rsa.encryptBase64(data, StandardCharsets.UTF_8, KeyType.PublicKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* rsa公钥加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @param publicKey 公钥
|
||||
* @return 加密后字符串, 采用Hex编码
|
||||
*/
|
||||
public static String encryptByRsaHex(String data, String publicKey) {
|
||||
if (StrUtil.isBlank(publicKey)) {
|
||||
throw new IllegalArgumentException("RSA需要传入公钥进行加密");
|
||||
}
|
||||
RSA rsa = SecureUtil.rsa(null, publicKey);
|
||||
return rsa.encryptHex(data, StandardCharsets.UTF_8, KeyType.PublicKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* rsa私钥解密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @param privateKey 私钥
|
||||
* @return 解密后字符串
|
||||
*/
|
||||
public static String decryptByRsa(String data, String privateKey) {
|
||||
if (StrUtil.isBlank(privateKey)) {
|
||||
throw new IllegalArgumentException("RSA需要传入私钥进行解密");
|
||||
}
|
||||
RSA rsa = SecureUtil.rsa(privateKey, null);
|
||||
return rsa.decryptStr(data, KeyType.PrivateKey, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* md5加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @return 加密后字符串, 采用Hex编码
|
||||
*/
|
||||
public static String encryptByMd5(String data) {
|
||||
return SecureUtil.md5(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* sha256加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @return 加密后字符串, 采用Hex编码
|
||||
*/
|
||||
public static String encryptBySha256(String data) {
|
||||
return SecureUtil.sha256(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* sm3加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @return 加密后字符串, 采用Hex编码
|
||||
*/
|
||||
public static String encryptBySm3(String data) {
|
||||
return SmUtil.sm3(data);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
package net.rzdata.demo.event;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 登录事件
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
|
||||
@Data
|
||||
public class LogininforEvent implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 用户账号
|
||||
*/
|
||||
private String username;
|
||||
|
||||
/**
|
||||
* 登录状态 0成功 1失败
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 提示消息
|
||||
*/
|
||||
private String message;
|
||||
|
||||
/**
|
||||
* 请求体
|
||||
*/
|
||||
private HttpServletRequest request;
|
||||
|
||||
/**
|
||||
* 其他参数
|
||||
*/
|
||||
private Object[] args;
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package net.rzdata.demo.excel.annotation;
|
||||
|
||||
|
||||
import net.rzdata.demo.excel.core.CellMergeStrategy;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* excel 列单元格合并(合并列相同项)
|
||||
*
|
||||
* 需搭配 {@link CellMergeStrategy} 策略使用
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Target(ElementType.FIELD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
public @interface CellMerge {
|
||||
|
||||
/**
|
||||
* col index
|
||||
*/
|
||||
int index() default -1;
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package net.rzdata.demo.excel.annotation;
|
||||
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 字典格式化
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Target({ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
public @interface ExcelDictFormat {
|
||||
|
||||
/**
|
||||
* 读取内容转表达式 (如: 0=男,1=女,2=未知)
|
||||
*/
|
||||
String readConverterExp() default "";
|
||||
|
||||
/**
|
||||
* 分隔符,读取字符串组内容
|
||||
*/
|
||||
String separator() default StringUtils.SEPARATOR;
|
||||
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package net.rzdata.demo.excel.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 枚举格式化
|
||||
*
|
||||
* @author Liang
|
||||
*/
|
||||
@Target({ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
public @interface ExcelEnumFormat {
|
||||
|
||||
/**
|
||||
* 字典枚举类型
|
||||
*/
|
||||
Class<? extends Enum<?>> enumClass();
|
||||
|
||||
/**
|
||||
* 字典枚举类中对应的code属性名称,默认为code
|
||||
*/
|
||||
String codeField() default "code";
|
||||
|
||||
/**
|
||||
* 字典枚举类中对应的text属性名称,默认为text
|
||||
*/
|
||||
String textField() default "text";
|
||||
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
package net.rzdata.demo.excel.convert;
|
||||
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.alibaba.excel.converters.Converter;
|
||||
import com.alibaba.excel.enums.CellDataTypeEnum;
|
||||
import com.alibaba.excel.metadata.GlobalConfiguration;
|
||||
import com.alibaba.excel.metadata.data.ReadCellData;
|
||||
import com.alibaba.excel.metadata.data.WriteCellData;
|
||||
import com.alibaba.excel.metadata.property.ExcelContentProperty;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 大数值转换
|
||||
* Excel 数值长度位15位 大于15位的数值转换位字符串
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
public class ExcelBigNumberConvert implements Converter<Long> {
|
||||
|
||||
@Override
|
||||
public Class<Long> supportJavaTypeKey() {
|
||||
return Long.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CellDataTypeEnum supportExcelTypeKey() {
|
||||
return CellDataTypeEnum.STRING;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
|
||||
return Convert.toLong(cellData.getData());
|
||||
}
|
||||
|
||||
@Override
|
||||
public WriteCellData<Object> convertToExcelData(Long object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
|
||||
if (ObjectUtil.isNotNull(object)) {
|
||||
String str = Convert.toStr(object);
|
||||
if (str.length() > 15) {
|
||||
return new WriteCellData<>(str);
|
||||
}
|
||||
}
|
||||
WriteCellData<Object> cellData = new WriteCellData<>(new BigDecimal(object));
|
||||
cellData.setType(CellDataTypeEnum.NUMBER);
|
||||
return cellData;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,87 @@
|
||||
package net.rzdata.demo.excel.convert;
|
||||
|
||||
import cn.hutool.core.annotation.AnnotationUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.alibaba.excel.converters.Converter;
|
||||
import com.alibaba.excel.enums.CellDataTypeEnum;
|
||||
import com.alibaba.excel.metadata.GlobalConfiguration;
|
||||
import com.alibaba.excel.metadata.data.ReadCellData;
|
||||
import com.alibaba.excel.metadata.data.WriteCellData;
|
||||
import com.alibaba.excel.metadata.property.ExcelContentProperty;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.rzdata.demo.core.utils.reflect.ReflectUtils;
|
||||
import net.rzdata.demo.excel.annotation.ExcelEnumFormat;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 枚举格式化转换处理
|
||||
*
|
||||
* @author Liang
|
||||
*/
|
||||
@Slf4j
|
||||
public class ExcelEnumConvert implements Converter<Object> {
|
||||
|
||||
@Override
|
||||
public Class<Object> supportJavaTypeKey() {
|
||||
return Object.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CellDataTypeEnum supportExcelTypeKey() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
|
||||
cellData.checkEmpty();
|
||||
// Excel中填入的是枚举中指定的描述
|
||||
Object textValue = switch (cellData.getType()) {
|
||||
case STRING, DIRECT_STRING, RICH_TEXT_STRING -> cellData.getStringValue();
|
||||
case NUMBER -> cellData.getNumberValue();
|
||||
case BOOLEAN -> cellData.getBooleanValue();
|
||||
default -> throw new IllegalArgumentException("单元格类型异常!");
|
||||
};
|
||||
// 如果是空值
|
||||
if (ObjectUtil.isNull(textValue)) {
|
||||
return null;
|
||||
}
|
||||
Map<Object, String> enumCodeToTextMap = beforeConvert(contentProperty);
|
||||
// 从Java输出至Excel是code转text
|
||||
// 因此从Excel转Java应该将text与code对调
|
||||
Map<Object, Object> enumTextToCodeMap = new HashMap<>();
|
||||
enumCodeToTextMap.forEach((key, value) -> enumTextToCodeMap.put(value, key));
|
||||
// 应该从text -> code中查找
|
||||
Object codeValue = enumTextToCodeMap.get(textValue);
|
||||
return Convert.convert(contentProperty.getField().getType(), codeValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public WriteCellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
|
||||
if (ObjectUtil.isNull(object)) {
|
||||
return new WriteCellData<>("");
|
||||
}
|
||||
Map<Object, String> enumValueMap = beforeConvert(contentProperty);
|
||||
String value = Convert.toStr(enumValueMap.get(object), "");
|
||||
return new WriteCellData<>(value);
|
||||
}
|
||||
|
||||
private Map<Object, String> beforeConvert(ExcelContentProperty contentProperty) {
|
||||
ExcelEnumFormat anno = getAnnotation(contentProperty.getField());
|
||||
Map<Object, String> enumValueMap = new HashMap<>();
|
||||
Enum<?>[] enumConstants = anno.enumClass().getEnumConstants();
|
||||
for (Enum<?> enumConstant : enumConstants) {
|
||||
Object codeValue = ReflectUtils.invokeGetter(enumConstant, anno.codeField());
|
||||
String textValue = ReflectUtils.invokeGetter(enumConstant, anno.textField());
|
||||
enumValueMap.put(codeValue, textValue);
|
||||
}
|
||||
return enumValueMap;
|
||||
}
|
||||
|
||||
private ExcelEnumFormat getAnnotation(Field field) {
|
||||
return AnnotationUtil.getAnnotation(field, ExcelEnumFormat.class);
|
||||
}
|
||||
}
|
@ -0,0 +1,142 @@
|
||||
package net.rzdata.demo.excel.core;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import com.alibaba.excel.annotation.ExcelProperty;
|
||||
import com.alibaba.excel.metadata.Head;
|
||||
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.rzdata.demo.core.utils.reflect.ReflectUtils;
|
||||
import net.rzdata.demo.excel.annotation.CellMerge;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 列值重复合并策略
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
public class CellMergeStrategy extends AbstractMergeStrategy {
|
||||
|
||||
private final List<CellRangeAddress> cellList;
|
||||
private final boolean hasTitle;
|
||||
private int rowIndex;
|
||||
|
||||
public CellMergeStrategy(List<?> list, boolean hasTitle) {
|
||||
this.hasTitle = hasTitle;
|
||||
// 行合并开始下标
|
||||
this.rowIndex = hasTitle ? 1 : 0;
|
||||
this.cellList = handle(list, hasTitle);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
|
||||
// judge the list is not null
|
||||
if (CollUtil.isNotEmpty(cellList)) {
|
||||
// the judge is necessary
|
||||
if (cell.getRowIndex() == rowIndex && cell.getColumnIndex() == 0) {
|
||||
for (CellRangeAddress item : cellList) {
|
||||
sheet.addMergedRegion(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private List<CellRangeAddress> handle(List<?> list, boolean hasTitle) {
|
||||
List<CellRangeAddress> cellList = new ArrayList<>();
|
||||
if (CollUtil.isEmpty(list)) {
|
||||
return cellList;
|
||||
}
|
||||
Field[] fields = ReflectUtils.getFields(list.get(0).getClass(), field -> !"serialVersionUID".equals(field.getName()));
|
||||
|
||||
// 有注解的字段
|
||||
List<Field> mergeFields = new ArrayList<>();
|
||||
List<Integer> mergeFieldsIndex = new ArrayList<>();
|
||||
for (int i = 0; i < fields.length; i++) {
|
||||
Field field = fields[i];
|
||||
if (field.isAnnotationPresent(CellMerge.class)) {
|
||||
CellMerge cm = field.getAnnotation(CellMerge.class);
|
||||
mergeFields.add(field);
|
||||
mergeFieldsIndex.add(cm.index() == -1 ? i : cm.index());
|
||||
if (hasTitle) {
|
||||
ExcelProperty property = field.getAnnotation(ExcelProperty.class);
|
||||
rowIndex = Math.max(rowIndex, property.value().length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Map<Field, RepeatCell> map = new HashMap<>();
|
||||
// 生成两两合并单元格
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
for (int j = 0; j < mergeFields.size(); j++) {
|
||||
Field field = mergeFields.get(j);
|
||||
Object val = ReflectUtils.invokeGetter(list.get(i), field.getName());
|
||||
|
||||
int colNum = mergeFieldsIndex.get(j);
|
||||
if (!map.containsKey(field)) {
|
||||
map.put(field, new RepeatCell(val, i));
|
||||
} else {
|
||||
RepeatCell repeatCell = map.get(field);
|
||||
Object cellValue = repeatCell.getValue();
|
||||
if (cellValue == null || "".equals(cellValue)) {
|
||||
// 空值跳过不合并
|
||||
continue;
|
||||
}
|
||||
if (!cellValue.equals(val)) {
|
||||
if (i - repeatCell.getCurrent() > 1) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex - 1, colNum, colNum));
|
||||
}
|
||||
map.put(field, new RepeatCell(val, i));
|
||||
} else if (j == 0) {
|
||||
if (i == list.size() - 1) {
|
||||
if (i > repeatCell.getCurrent()) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex, colNum, colNum));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 判断前面的是否合并了
|
||||
RepeatCell firstCell = map.get(mergeFields.get(0));
|
||||
if (repeatCell.getCurrent() != firstCell.getCurrent()) {
|
||||
if (i == list.size() - 1) {
|
||||
if (i > repeatCell.getCurrent()) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex, colNum, colNum));
|
||||
}
|
||||
} else if (repeatCell.getCurrent() < firstCell.getCurrent()) {
|
||||
if (i - repeatCell.getCurrent() > 1) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex - 1, colNum, colNum));
|
||||
}
|
||||
map.put(field, new RepeatCell(val, i));
|
||||
}
|
||||
} else if (i == list.size() - 1) {
|
||||
if (i > repeatCell.getCurrent()) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex, colNum, colNum));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return cellList;
|
||||
}
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
static class RepeatCell {
|
||||
|
||||
private Object value;
|
||||
|
||||
private int current;
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,104 @@
|
||||
package net.rzdata.demo.excel.core;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.excel.context.AnalysisContext;
|
||||
import com.alibaba.excel.event.AnalysisEventListener;
|
||||
import com.alibaba.excel.exception.ExcelAnalysisException;
|
||||
import com.alibaba.excel.exception.ExcelDataConvertException;
|
||||
import net.rzdata.demo.core.utils.StreamUtils;
|
||||
import net.rzdata.demo.core.utils.ValidatorUtils;
|
||||
import net.rzdata.demo.json.utils.JsonUtils;
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Excel 导入监听
|
||||
*
|
||||
* @author Yjoioooo
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@NoArgsConstructor
|
||||
public class DefaultExcelListener<T> extends AnalysisEventListener<T> implements ExcelListener<T> {
|
||||
|
||||
/**
|
||||
* 是否Validator检验,默认为是
|
||||
*/
|
||||
private Boolean isValidate = Boolean.TRUE;
|
||||
|
||||
/**
|
||||
* excel 表头数据
|
||||
*/
|
||||
private Map<Integer, String> headMap;
|
||||
|
||||
/**
|
||||
* 导入回执
|
||||
*/
|
||||
private ExcelResult<T> excelResult;
|
||||
|
||||
public DefaultExcelListener(boolean isValidate) {
|
||||
this.excelResult = new DefaultExcelResult<>();
|
||||
this.isValidate = isValidate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理异常
|
||||
*
|
||||
* @param exception ExcelDataConvertException
|
||||
* @param context Excel 上下文
|
||||
*/
|
||||
@Override
|
||||
public void onException(Exception exception, AnalysisContext context) throws Exception {
|
||||
String errMsg = null;
|
||||
if (exception instanceof ExcelDataConvertException excelDataConvertException) {
|
||||
// 如果是某一个单元格的转换异常 能获取到具体行号
|
||||
Integer rowIndex = excelDataConvertException.getRowIndex();
|
||||
Integer columnIndex = excelDataConvertException.getColumnIndex();
|
||||
errMsg = StrUtil.format("第{}行-第{}列-表头{}: 解析异常<br/>",
|
||||
rowIndex + 1, columnIndex + 1, headMap.get(columnIndex));
|
||||
if (log.isDebugEnabled()) {
|
||||
log.error(errMsg);
|
||||
}
|
||||
}
|
||||
if (exception instanceof ConstraintViolationException constraintViolationException) {
|
||||
Set<ConstraintViolation<?>> constraintViolations = constraintViolationException.getConstraintViolations();
|
||||
String constraintViolationsMsg = StreamUtils.join(constraintViolations, ConstraintViolation::getMessage, ", ");
|
||||
errMsg = StrUtil.format("第{}行数据校验异常: {}", context.readRowHolder().getRowIndex() + 1, constraintViolationsMsg);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.error(errMsg);
|
||||
}
|
||||
}
|
||||
excelResult.getErrorList().add(errMsg);
|
||||
throw new ExcelAnalysisException(errMsg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
|
||||
this.headMap = headMap;
|
||||
log.debug("解析到一条表头数据: {}", JsonUtils.toJsonString(headMap));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(T data, AnalysisContext context) {
|
||||
if (isValidate) {
|
||||
ValidatorUtils.validate(data);
|
||||
}
|
||||
excelResult.getList().add(data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doAfterAllAnalysed(AnalysisContext context) {
|
||||
log.debug("所有数据解析完成!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ExcelResult<T> getExcelResult() {
|
||||
return excelResult;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
package net.rzdata.demo.excel.core;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 默认excel返回对象
|
||||
*
|
||||
* @author Yjoioooo
|
||||
* @author Lion Li
|
||||
*/
|
||||
public class DefaultExcelResult<T> implements ExcelResult<T> {
|
||||
|
||||
/**
|
||||
* 数据对象list
|
||||
*/
|
||||
@Setter
|
||||
private List<T> list;
|
||||
|
||||
/**
|
||||
* 错误信息列表
|
||||
*/
|
||||
@Setter
|
||||
private List<String> errorList;
|
||||
|
||||
public DefaultExcelResult() {
|
||||
this.list = new ArrayList<>();
|
||||
this.errorList = new ArrayList<>();
|
||||
}
|
||||
|
||||
public DefaultExcelResult(List<T> list, List<String> errorList) {
|
||||
this.list = list;
|
||||
this.errorList = errorList;
|
||||
}
|
||||
|
||||
public DefaultExcelResult(ExcelResult<T> excelResult) {
|
||||
this.list = excelResult.getList();
|
||||
this.errorList = excelResult.getErrorList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<T> getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getErrorList() {
|
||||
return errorList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取导入回执
|
||||
*
|
||||
* @return 导入回执
|
||||
*/
|
||||
@Override
|
||||
public String getAnalysis() {
|
||||
int successCount = list.size();
|
||||
int errorCount = errorList.size();
|
||||
if (successCount == 0) {
|
||||
return "读取失败,未解析到数据";
|
||||
} else {
|
||||
if (errorCount == 0) {
|
||||
return StrUtil.format("恭喜您,全部读取成功!共{}条", successCount);
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,149 @@
|
||||
package net.rzdata.demo.excel.core;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import net.rzdata.demo.core.exception.ServiceException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* <h1>Excel下拉可选项</h1>
|
||||
* 注意:为确保下拉框解析正确,传值务必使用createOptionValue()做为值的拼接
|
||||
*
|
||||
* @author Emil.Zhang
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@SuppressWarnings("unused")
|
||||
public class DropDownOptions {
|
||||
/**
|
||||
* 一级下拉所在列index,从0开始算
|
||||
*/
|
||||
private int index = 0;
|
||||
/**
|
||||
* 二级下拉所在的index,从0开始算,不能与一级相同
|
||||
*/
|
||||
private int nextIndex = 0;
|
||||
/**
|
||||
* 一级下拉所包含的数据
|
||||
*/
|
||||
private List<String> options = new ArrayList<>();
|
||||
/**
|
||||
* 二级下拉所包含的数据Map
|
||||
* <p>以每一个一级选项值为Key,每个一级选项对应的二级数据为Value</p>
|
||||
*/
|
||||
private Map<String, List<String>> nextOptions = new HashMap<>();
|
||||
/**
|
||||
* 分隔符
|
||||
*/
|
||||
private static final String DELIMITER = "_";
|
||||
|
||||
/**
|
||||
* 创建只有一级的下拉选
|
||||
*/
|
||||
public DropDownOptions(int index, List<String> options) {
|
||||
this.index = index;
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
/**
|
||||
* <h2>创建每个选项可选值</h2>
|
||||
* <p>注意:不能以数字,特殊符号开头,选项中不可以包含任何运算符号</p>
|
||||
*
|
||||
* @param vars 可选值内包含的参数
|
||||
* @return 合规的可选值
|
||||
*/
|
||||
public static String createOptionValue(Object... vars) {
|
||||
StringBuilder stringBuffer = new StringBuilder();
|
||||
String regex = "^[\\S\\d\\u4e00-\\u9fa5]+$";
|
||||
for (int i = 0; i < vars.length; i++) {
|
||||
String var = StrUtil.trimToEmpty(String.valueOf(vars[i]));
|
||||
if (!var.matches(regex)) {
|
||||
throw new ServiceException("选项数据不符合规则,仅允许使用中英文字符以及数字");
|
||||
}
|
||||
stringBuffer.append(var);
|
||||
if (i < vars.length - 1) {
|
||||
// 直至最后一个前,都以_作为切割线
|
||||
stringBuffer.append(DELIMITER);
|
||||
}
|
||||
}
|
||||
if (stringBuffer.toString().matches("^\\d_*$")) {
|
||||
throw new ServiceException("禁止以数字开头");
|
||||
}
|
||||
return stringBuffer.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将处理后合理的可选值解析为原始的参数
|
||||
*
|
||||
* @param option 经过处理后的合理的可选项
|
||||
* @return 原始的参数
|
||||
*/
|
||||
public static List<String> analyzeOptionValue(String option) {
|
||||
return StrUtil.split(option, DELIMITER, true, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建级联下拉选项
|
||||
*
|
||||
* @param parentList 父实体可选项原始数据
|
||||
* @param parentIndex 父下拉选位置
|
||||
* @param sonList 子实体可选项原始数据
|
||||
* @param sonIndex 子下拉选位置
|
||||
* @param parentHowToGetIdFunction 父类如何获取唯一标识
|
||||
* @param sonHowToGetParentIdFunction 子类如何获取父类的唯一标识
|
||||
* @param howToBuildEveryOption 如何生成下拉选内容
|
||||
* @return 级联下拉选项
|
||||
*/
|
||||
public static <T> DropDownOptions buildLinkedOptions(List<T> parentList,
|
||||
int parentIndex,
|
||||
List<T> sonList,
|
||||
int sonIndex,
|
||||
Function<T, Number> parentHowToGetIdFunction,
|
||||
Function<T, Number> sonHowToGetParentIdFunction,
|
||||
Function<T, String> howToBuildEveryOption) {
|
||||
DropDownOptions parentLinkSonOptions = new DropDownOptions();
|
||||
// 先创建父类的下拉
|
||||
parentLinkSonOptions.setIndex(parentIndex);
|
||||
parentLinkSonOptions.setOptions(
|
||||
parentList.stream()
|
||||
.map(howToBuildEveryOption)
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
// 提取父-子级联下拉
|
||||
Map<String, List<String>> sonOptions = new HashMap<>();
|
||||
// 父级依据自己的ID分组
|
||||
Map<Number, List<T>> parentGroupByIdMap =
|
||||
parentList.stream().collect(Collectors.groupingBy(parentHowToGetIdFunction));
|
||||
// 遍历每个子集,提取到Map中
|
||||
sonList.forEach(everySon -> {
|
||||
if (parentGroupByIdMap.containsKey(sonHowToGetParentIdFunction.apply(everySon))) {
|
||||
// 找到对应的上级
|
||||
T parentObj = parentGroupByIdMap.get(sonHowToGetParentIdFunction.apply(everySon)).get(0);
|
||||
// 提取名称和ID作为Key
|
||||
String key = howToBuildEveryOption.apply(parentObj);
|
||||
// Key对应的Value
|
||||
List<String> thisParentSonOptionList;
|
||||
if (sonOptions.containsKey(key)) {
|
||||
thisParentSonOptionList = sonOptions.get(key);
|
||||
} else {
|
||||
thisParentSonOptionList = new ArrayList<>();
|
||||
sonOptions.put(key, thisParentSonOptionList);
|
||||
}
|
||||
// 往Value中添加当前子集选项
|
||||
thisParentSonOptionList.add(howToBuildEveryOption.apply(everySon));
|
||||
}
|
||||
});
|
||||
parentLinkSonOptions.setNextIndex(sonIndex);
|
||||
parentLinkSonOptions.setNextOptions(sonOptions);
|
||||
return parentLinkSonOptions;
|
||||
}
|
||||
}
|
@ -0,0 +1,357 @@
|
||||
package net.rzdata.demo.excel.core;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.EnumUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.excel.metadata.FieldCache;
|
||||
import com.alibaba.excel.metadata.FieldWrapper;
|
||||
import com.alibaba.excel.util.ClassUtils;
|
||||
import com.alibaba.excel.write.handler.SheetWriteHandler;
|
||||
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
|
||||
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.rzdata.demo.core.utils.StreamUtils;
|
||||
import net.rzdata.demo.excel.annotation.ExcelDictFormat;
|
||||
import net.rzdata.demo.excel.annotation.ExcelEnumFormat;
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.ss.util.CellRangeAddressList;
|
||||
import org.apache.poi.ss.util.WorkbookUtil;
|
||||
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* <h1>Excel表格下拉选操作</h1>
|
||||
* 考虑到下拉选过多可能导致Excel打开缓慢的问题,只校验前1000行
|
||||
* <p>
|
||||
* 即只有前1000行的数据可以用下拉框,超出的自行通过限制数据量的形式,第二次输出
|
||||
*
|
||||
* @author Emil.Zhang
|
||||
*/
|
||||
@Slf4j
|
||||
public class ExcelDownHandler implements SheetWriteHandler {
|
||||
|
||||
/**
|
||||
* Excel表格中的列名英文
|
||||
* 仅为了解析列英文,禁止修改
|
||||
*/
|
||||
private static final String EXCEL_COLUMN_NAME = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
/**
|
||||
* 单选数据Sheet名
|
||||
*/
|
||||
private static final String OPTIONS_SHEET_NAME = "options";
|
||||
/**
|
||||
* 联动选择数据Sheet名的头
|
||||
*/
|
||||
private static final String LINKED_OPTIONS_SHEET_NAME = "linkedOptions";
|
||||
/**
|
||||
* 下拉可选项
|
||||
*/
|
||||
private final List<DropDownOptions> dropDownOptions;
|
||||
/**
|
||||
* 当前单选进度
|
||||
*/
|
||||
private int currentOptionsColumnIndex;
|
||||
/**
|
||||
* 当前联动选择进度
|
||||
*/
|
||||
private int currentLinkedOptionsSheetIndex;
|
||||
|
||||
public ExcelDownHandler(List<DropDownOptions> options) {
|
||||
this.dropDownOptions = options;
|
||||
this.currentOptionsColumnIndex = 0;
|
||||
this.currentLinkedOptionsSheetIndex = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* <h2>开始创建下拉数据</h2>
|
||||
* 1.通过解析传入的@ExcelProperty同级是否标注有@DropDown选项
|
||||
* 如果有且设置了value值,则将其直接置为下拉可选项
|
||||
* <p>
|
||||
* 2.或者在调用ExcelUtil时指定了可选项,将依据传入的可选项做下拉
|
||||
* <p>
|
||||
* 3.二者并存,注意调用方式
|
||||
*/
|
||||
@Override
|
||||
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
|
||||
Sheet sheet = writeSheetHolder.getSheet();
|
||||
// 开始设置下拉框 HSSFWorkbook
|
||||
DataValidationHelper helper = sheet.getDataValidationHelper();
|
||||
Workbook workbook = writeWorkbookHolder.getWorkbook();
|
||||
FieldCache fieldCache = ClassUtils.declaredFields(writeWorkbookHolder.getClazz(), writeWorkbookHolder);
|
||||
for (Map.Entry<Integer, FieldWrapper> entry : fieldCache.getSortedFieldMap().entrySet()) {
|
||||
Integer index = entry.getKey();
|
||||
FieldWrapper wrapper = entry.getValue();
|
||||
Field field = wrapper.getField();
|
||||
// 循环实体中的每个属性
|
||||
// 可选的下拉值
|
||||
List<String> options = new ArrayList<>();
|
||||
if (field.isAnnotationPresent(ExcelDictFormat.class)) {
|
||||
// 如果指定了@ExcelDictFormat,则使用字典的逻辑
|
||||
ExcelDictFormat format = field.getDeclaredAnnotation(ExcelDictFormat.class);
|
||||
String converterExp = format.readConverterExp();
|
||||
// 如果指定了确切的值,则直接解析确切的值
|
||||
options = StrUtil.split(converterExp, format.separator(), true, true);
|
||||
} else if (field.isAnnotationPresent(ExcelEnumFormat.class)) {
|
||||
// 否则如果指定了@ExcelEnumFormat,则使用枚举的逻辑
|
||||
ExcelEnumFormat format = field.getDeclaredAnnotation(ExcelEnumFormat.class);
|
||||
List<Object> values = EnumUtil.getFieldValues(format.enumClass(), format.textField());
|
||||
options = StreamUtils.toList(values, String::valueOf);
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(options)) {
|
||||
// 仅当下拉可选项不为空时执行
|
||||
if (options.size() > 20) {
|
||||
// 这里限制如果可选项大于20,则使用额外表形式
|
||||
dropDownWithSheet(helper, workbook, sheet, index, options);
|
||||
} else {
|
||||
// 否则使用固定值形式
|
||||
dropDownWithSimple(helper, sheet, index, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (CollUtil.isEmpty(dropDownOptions)) {
|
||||
return;
|
||||
}
|
||||
dropDownOptions.forEach(everyOptions -> {
|
||||
// 如果传递了下拉框选择器参数
|
||||
if (!everyOptions.getNextOptions().isEmpty()) {
|
||||
// 当二级选项不为空时,使用额外关联表的形式
|
||||
dropDownLinkedOptions(helper, workbook, sheet, everyOptions);
|
||||
} else if (everyOptions.getOptions().size() > 10) {
|
||||
// 当一级选项参数个数大于10,使用额外表的形式
|
||||
dropDownWithSheet(helper, workbook, sheet, everyOptions.getIndex(), everyOptions.getOptions());
|
||||
} else if (everyOptions.getOptions().size() != 0) {
|
||||
// 当一级选项个数不为空,使用默认形式
|
||||
dropDownWithSimple(helper, sheet, everyOptions.getIndex(), everyOptions.getOptions());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* <h2>简单下拉框</h2>
|
||||
* 直接将可选项拼接为指定列的数据校验值
|
||||
*
|
||||
* @param celIndex 列index
|
||||
* @param value 下拉选可选值
|
||||
*/
|
||||
private void dropDownWithSimple(DataValidationHelper helper, Sheet sheet, Integer celIndex, List<String> value) {
|
||||
if (ObjectUtil.isEmpty(value)) {
|
||||
return;
|
||||
}
|
||||
this.markOptionsToSheet(helper, sheet, celIndex, helper.createExplicitListConstraint(ArrayUtil.toArray(value, String.class)));
|
||||
}
|
||||
|
||||
/**
|
||||
* <h2>额外表格形式的级联下拉框</h2>
|
||||
*
|
||||
* @param options 额外表格形式存储的下拉可选项
|
||||
*/
|
||||
private void dropDownLinkedOptions(DataValidationHelper helper, Workbook workbook, Sheet sheet, DropDownOptions options) {
|
||||
String linkedOptionsSheetName = String.format("%s_%d", LINKED_OPTIONS_SHEET_NAME, currentLinkedOptionsSheetIndex);
|
||||
// 创建联动下拉数据表
|
||||
Sheet linkedOptionsDataSheet = workbook.createSheet(WorkbookUtil.createSafeSheetName(linkedOptionsSheetName));
|
||||
// 将下拉表隐藏
|
||||
workbook.setSheetHidden(workbook.getSheetIndex(linkedOptionsDataSheet), true);
|
||||
// 完善横向的一级选项数据表
|
||||
List<String> firstOptions = options.getOptions();
|
||||
Map<String, List<String>> secoundOptionsMap = options.getNextOptions();
|
||||
|
||||
// 创建名称管理器
|
||||
Name name = workbook.createName();
|
||||
// 设置名称管理器的别名
|
||||
name.setNameName(linkedOptionsSheetName);
|
||||
// 以横向第一行创建一级下拉拼接引用位置
|
||||
String firstOptionsFunction = String.format("%s!$%s$1:$%s$1",
|
||||
linkedOptionsSheetName,
|
||||
getExcelColumnName(0),
|
||||
getExcelColumnName(firstOptions.size())
|
||||
);
|
||||
// 设置名称管理器的引用位置
|
||||
name.setRefersToFormula(firstOptionsFunction);
|
||||
// 设置数据校验为序列模式,引用的是名称管理器中的别名
|
||||
this.markOptionsToSheet(helper, sheet, options.getIndex(), helper.createFormulaListConstraint(linkedOptionsSheetName));
|
||||
|
||||
for (int columIndex = 0; columIndex < firstOptions.size(); columIndex++) {
|
||||
// 先提取主表中一级下拉的列名
|
||||
String firstOptionsColumnName = getExcelColumnName(columIndex);
|
||||
// 一次循环是每一个一级选项
|
||||
int finalI = columIndex;
|
||||
// 本次循环的一级选项值
|
||||
String thisFirstOptionsValue = firstOptions.get(columIndex);
|
||||
// 创建第一行的数据
|
||||
Optional.ofNullable(linkedOptionsDataSheet.getRow(0))
|
||||
// 如果不存在则创建第一行
|
||||
.orElseGet(() -> linkedOptionsDataSheet.createRow(finalI))
|
||||
// 第一行当前列
|
||||
.createCell(columIndex)
|
||||
// 设置值为当前一级选项值
|
||||
.setCellValue(thisFirstOptionsValue);
|
||||
|
||||
// 第二行开始,设置第二级别选项参数
|
||||
List<String> secondOptions = secoundOptionsMap.get(thisFirstOptionsValue);
|
||||
if (CollUtil.isEmpty(secondOptions)) {
|
||||
// 必须保证至少有一个关联选项,否则将导致Excel解析错误
|
||||
secondOptions = Collections.singletonList("暂无_0");
|
||||
}
|
||||
|
||||
// 以该一级选项值创建子名称管理器
|
||||
Name sonName = workbook.createName();
|
||||
// 设置名称管理器的别名
|
||||
sonName.setNameName(thisFirstOptionsValue);
|
||||
// 以第二行该列数据拼接引用位置
|
||||
String sonFunction = String.format("%s!$%s$2:$%s$%d",
|
||||
linkedOptionsSheetName,
|
||||
firstOptionsColumnName,
|
||||
firstOptionsColumnName,
|
||||
secondOptions.size() + 1
|
||||
);
|
||||
// 设置名称管理器的引用位置
|
||||
sonName.setRefersToFormula(sonFunction);
|
||||
// 数据验证为序列模式,引用到每一个主表中的二级选项位置
|
||||
// 创建子项的名称管理器,只是为了使得Excel可以识别到数据
|
||||
String mainSheetFirstOptionsColumnName = getExcelColumnName(options.getIndex());
|
||||
for (int i = 0; i < 100; i++) {
|
||||
// 以一级选项对应的主体所在位置创建二级下拉
|
||||
String secondOptionsFunction = String.format("=INDIRECT(%s%d)", mainSheetFirstOptionsColumnName, i + 1);
|
||||
// 二级只能主表每一行的每一列添加二级校验
|
||||
markLinkedOptionsToSheet(helper, sheet, i, options.getNextIndex(), helper.createFormulaListConstraint(secondOptionsFunction));
|
||||
}
|
||||
|
||||
for (int rowIndex = 0; rowIndex < secondOptions.size(); rowIndex++) {
|
||||
// 从第二行开始填充二级选项
|
||||
int finalRowIndex = rowIndex + 1;
|
||||
int finalColumIndex = columIndex;
|
||||
|
||||
Row row = Optional.ofNullable(linkedOptionsDataSheet.getRow(finalRowIndex))
|
||||
// 没有则创建
|
||||
.orElseGet(() -> linkedOptionsDataSheet.createRow(finalRowIndex));
|
||||
Optional
|
||||
// 在本级一级选项所在的列
|
||||
.ofNullable(row.getCell(finalColumIndex))
|
||||
// 不存在则创建
|
||||
.orElseGet(() -> row.createCell(finalColumIndex))
|
||||
// 设置二级选项值
|
||||
.setCellValue(secondOptions.get(rowIndex));
|
||||
}
|
||||
}
|
||||
|
||||
currentLinkedOptionsSheetIndex++;
|
||||
}
|
||||
|
||||
/**
|
||||
* <h2>额外表格形式的普通下拉框</h2>
|
||||
* 由于下拉框可选值数量过多,为提升Excel打开效率,使用额外表格形式做下拉
|
||||
*
|
||||
* @param celIndex 下拉选
|
||||
* @param value 下拉选可选值
|
||||
*/
|
||||
private void dropDownWithSheet(DataValidationHelper helper, Workbook workbook, Sheet sheet, Integer celIndex, List<String> value) {
|
||||
// 创建下拉数据表
|
||||
Sheet simpleDataSheet = Optional.ofNullable(workbook.getSheet(WorkbookUtil.createSafeSheetName(OPTIONS_SHEET_NAME)))
|
||||
.orElseGet(() -> workbook.createSheet(WorkbookUtil.createSafeSheetName(OPTIONS_SHEET_NAME)));
|
||||
// 将下拉表隐藏
|
||||
workbook.setSheetHidden(workbook.getSheetIndex(simpleDataSheet), true);
|
||||
// 完善纵向的一级选项数据表
|
||||
for (int i = 0; i < value.size(); i++) {
|
||||
int finalI = i;
|
||||
// 获取每一选项行,如果没有则创建
|
||||
Row row = Optional.ofNullable(simpleDataSheet.getRow(i))
|
||||
.orElseGet(() -> simpleDataSheet.createRow(finalI));
|
||||
// 获取本级选项对应的选项列,如果没有则创建
|
||||
Cell cell = Optional.ofNullable(row.getCell(currentOptionsColumnIndex))
|
||||
.orElseGet(() -> row.createCell(currentOptionsColumnIndex));
|
||||
// 设置值
|
||||
cell.setCellValue(value.get(i));
|
||||
}
|
||||
|
||||
// 创建名称管理器
|
||||
Name name = workbook.createName();
|
||||
// 设置名称管理器的别名
|
||||
String nameName = String.format("%s_%d", OPTIONS_SHEET_NAME, celIndex);
|
||||
name.setNameName(nameName);
|
||||
// 以纵向第一列创建一级下拉拼接引用位置
|
||||
String function = String.format("%s!$%s$1:$%s$%d",
|
||||
OPTIONS_SHEET_NAME,
|
||||
getExcelColumnName(currentOptionsColumnIndex),
|
||||
getExcelColumnName(currentOptionsColumnIndex),
|
||||
value.size());
|
||||
// 设置名称管理器的引用位置
|
||||
name.setRefersToFormula(function);
|
||||
// 设置数据校验为序列模式,引用的是名称管理器中的别名
|
||||
this.markOptionsToSheet(helper, sheet, celIndex, helper.createFormulaListConstraint(nameName));
|
||||
currentOptionsColumnIndex++;
|
||||
}
|
||||
|
||||
/**
|
||||
* 挂载下拉的列,仅限一级选项
|
||||
*/
|
||||
private void markOptionsToSheet(DataValidationHelper helper, Sheet sheet, Integer celIndex,
|
||||
DataValidationConstraint constraint) {
|
||||
// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
|
||||
CellRangeAddressList addressList = new CellRangeAddressList(1, 1000, celIndex, celIndex);
|
||||
markDataValidationToSheet(helper, sheet, constraint, addressList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 挂载下拉的列,仅限二级选项
|
||||
*/
|
||||
private void markLinkedOptionsToSheet(DataValidationHelper helper, Sheet sheet, Integer rowIndex,
|
||||
Integer celIndex, DataValidationConstraint constraint) {
|
||||
// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
|
||||
CellRangeAddressList addressList = new CellRangeAddressList(rowIndex, rowIndex, celIndex, celIndex);
|
||||
markDataValidationToSheet(helper, sheet, constraint, addressList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用数据校验
|
||||
*/
|
||||
private void markDataValidationToSheet(DataValidationHelper helper, Sheet sheet,
|
||||
DataValidationConstraint constraint, CellRangeAddressList addressList) {
|
||||
// 数据有效性对象
|
||||
DataValidation dataValidation = helper.createValidation(constraint, addressList);
|
||||
// 处理Excel兼容性问题
|
||||
if (dataValidation instanceof XSSFDataValidation) {
|
||||
//数据校验
|
||||
dataValidation.setSuppressDropDownArrow(true);
|
||||
//错误提示
|
||||
dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP);
|
||||
dataValidation.createErrorBox("提示", "此值与单元格定义数据不一致");
|
||||
dataValidation.setShowErrorBox(true);
|
||||
//选定提示
|
||||
dataValidation.createPromptBox("填写说明:", "填写内容只能为下拉中数据,其他数据将导致导入失败");
|
||||
dataValidation.setShowPromptBox(true);
|
||||
sheet.addValidationData(dataValidation);
|
||||
} else {
|
||||
dataValidation.setSuppressDropDownArrow(false);
|
||||
}
|
||||
sheet.addValidationData(dataValidation);
|
||||
}
|
||||
|
||||
/**
|
||||
* <h2>依据列index获取列名英文</h2>
|
||||
* 依据列index转换为Excel中的列名英文
|
||||
* <p>例如第1列,index为0,解析出来为A列</p>
|
||||
* 第27列,index为26,解析为AA列
|
||||
* <p>第28列,index为27,解析为AB列</p>
|
||||
*
|
||||
* @param columnIndex 列index
|
||||
* @return 列index所在得英文名
|
||||
*/
|
||||
private String getExcelColumnName(int columnIndex) {
|
||||
// 26一循环的次数
|
||||
int columnCircleCount = columnIndex / 26;
|
||||
// 26一循环内的位置
|
||||
int thisCircleColumnIndex = columnIndex % 26;
|
||||
// 26一循环的次数大于0,则视为栏名至少两位
|
||||
String columnPrefix = columnCircleCount == 0
|
||||
? StrUtil.EMPTY
|
||||
: StrUtil.subWithLength(EXCEL_COLUMN_NAME, columnCircleCount - 1, 1);
|
||||
// 从26一循环内取对应的栏位名
|
||||
String columnNext = StrUtil.subWithLength(EXCEL_COLUMN_NAME, thisCircleColumnIndex, 1);
|
||||
// 将二者拼接即为最终的栏位名
|
||||
return columnPrefix + columnNext;
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package net.rzdata.demo.excel.core;
|
||||
|
||||
import com.alibaba.excel.read.listener.ReadListener;
|
||||
|
||||
/**
|
||||
* Excel 导入监听
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface ExcelListener<T> extends ReadListener<T> {
|
||||
|
||||
ExcelResult<T> getExcelResult();
|
||||
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package net.rzdata.demo.excel.core;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* excel返回对象
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface ExcelResult<T> {
|
||||
|
||||
/**
|
||||
* 对象列表
|
||||
*/
|
||||
List<T> getList();
|
||||
|
||||
/**
|
||||
* 错误列表
|
||||
*/
|
||||
List<String> getErrorList();
|
||||
|
||||
/**
|
||||
* 导入回执
|
||||
*/
|
||||
String getAnalysis();
|
||||
}
|
436
common/src/main/java/net/rzdata/demo/excel/utils/ExcelUtil.java
Normal file
436
common/src/main/java/net/rzdata/demo/excel/utils/ExcelUtil.java
Normal file
@ -0,0 +1,436 @@
|
||||
package net.rzdata.demo.excel.utils;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.io.resource.ClassPathResource;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.alibaba.excel.EasyExcel;
|
||||
import com.alibaba.excel.ExcelWriter;
|
||||
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
|
||||
import com.alibaba.excel.write.metadata.WriteSheet;
|
||||
import com.alibaba.excel.write.metadata.fill.FillConfig;
|
||||
import com.alibaba.excel.write.metadata.fill.FillWrapper;
|
||||
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
|
||||
import jakarta.servlet.ServletOutputStream;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import net.rzdata.demo.core.utils.file.FileUtils;
|
||||
import net.rzdata.demo.excel.convert.ExcelBigNumberConvert;
|
||||
import net.rzdata.demo.excel.core.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Excel相关处理
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class ExcelUtil {
|
||||
|
||||
/**
|
||||
* 同步导入(适用于小数据量)
|
||||
*
|
||||
* @param is 输入流
|
||||
* @return 转换后集合
|
||||
*/
|
||||
public static <T> List<T> importExcel(InputStream is, Class<T> clazz) {
|
||||
return EasyExcel.read(is).head(clazz).autoCloseStream(false).sheet().doReadSync();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 使用校验监听器 异步导入 同步返回
|
||||
*
|
||||
* @param is 输入流
|
||||
* @param clazz 对象类型
|
||||
* @param isValidate 是否 Validator 检验 默认为是
|
||||
* @return 转换后集合
|
||||
*/
|
||||
public static <T> ExcelResult<T> importExcel(InputStream is, Class<T> clazz, boolean isValidate) {
|
||||
DefaultExcelListener<T> listener = new DefaultExcelListener<>(isValidate);
|
||||
EasyExcel.read(is, clazz, listener).sheet().doRead();
|
||||
return listener.getExcelResult();
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用自定义监听器 异步导入 自定义返回
|
||||
*
|
||||
* @param is 输入流
|
||||
* @param clazz 对象类型
|
||||
* @param listener 自定义监听器
|
||||
* @return 转换后集合
|
||||
*/
|
||||
public static <T> ExcelResult<T> importExcel(InputStream is, Class<T> clazz, ExcelListener<T> listener) {
|
||||
EasyExcel.read(is, clazz, listener).sheet().doRead();
|
||||
return listener.getExcelResult();
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出excel
|
||||
*
|
||||
* @param list 导出数据集合
|
||||
* @param sheetName 工作表的名称
|
||||
* @param clazz 实体类
|
||||
* @param response 响应体
|
||||
*/
|
||||
public static <T> void exportExcel(List<T> list, String sheetName, Class<T> clazz, HttpServletResponse response) {
|
||||
try {
|
||||
resetResponse(sheetName, response);
|
||||
ServletOutputStream os = response.getOutputStream();
|
||||
exportExcel(list, sheetName, clazz, false, os, null);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("导出Excel异常");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出excel
|
||||
*
|
||||
* @param list 导出数据集合
|
||||
* @param sheetName 工作表的名称
|
||||
* @param clazz 实体类
|
||||
* @param response 响应体
|
||||
* @param options 级联下拉选
|
||||
*/
|
||||
public static <T> void exportExcel(List<T> list, String sheetName, Class<T> clazz, HttpServletResponse response, List<DropDownOptions> options) {
|
||||
try {
|
||||
resetResponse(sheetName, response);
|
||||
ServletOutputStream os = response.getOutputStream();
|
||||
exportExcel(list, sheetName, clazz, false, os, options);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("导出Excel异常");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出excel
|
||||
*
|
||||
* @param list 导出数据集合
|
||||
* @param sheetName 工作表的名称
|
||||
* @param clazz 实体类
|
||||
* @param merge 是否合并单元格
|
||||
* @param response 响应体
|
||||
*/
|
||||
public static <T> void exportExcel(List<T> list, String sheetName, Class<T> clazz, boolean merge, HttpServletResponse response) {
|
||||
try {
|
||||
resetResponse(sheetName, response);
|
||||
ServletOutputStream os = response.getOutputStream();
|
||||
exportExcel(list, sheetName, clazz, merge, os, null);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("导出Excel异常");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出excel
|
||||
*
|
||||
* @param list 导出数据集合
|
||||
* @param sheetName 工作表的名称
|
||||
* @param clazz 实体类
|
||||
* @param merge 是否合并单元格
|
||||
* @param response 响应体
|
||||
* @param options 级联下拉选
|
||||
*/
|
||||
public static <T> void exportExcel(List<T> list, String sheetName, Class<T> clazz, boolean merge, HttpServletResponse response, List<DropDownOptions> options) {
|
||||
try {
|
||||
resetResponse(sheetName, response);
|
||||
ServletOutputStream os = response.getOutputStream();
|
||||
exportExcel(list, sheetName, clazz, merge, os, options);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("导出Excel异常");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出excel
|
||||
*
|
||||
* @param list 导出数据集合
|
||||
* @param sheetName 工作表的名称
|
||||
* @param clazz 实体类
|
||||
* @param os 输出流
|
||||
*/
|
||||
public static <T> void exportExcel(List<T> list, String sheetName, Class<T> clazz, OutputStream os) {
|
||||
exportExcel(list, sheetName, clazz, false, os, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出excel
|
||||
*
|
||||
* @param list 导出数据集合
|
||||
* @param sheetName 工作表的名称
|
||||
* @param clazz 实体类
|
||||
* @param os 输出流
|
||||
* @param options 级联下拉选内容
|
||||
*/
|
||||
public static <T> void exportExcel(List<T> list, String sheetName, Class<T> clazz, OutputStream os, List<DropDownOptions> options) {
|
||||
exportExcel(list, sheetName, clazz, false, os, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出excel
|
||||
*
|
||||
* @param list 导出数据集合
|
||||
* @param sheetName 工作表的名称
|
||||
* @param clazz 实体类
|
||||
* @param merge 是否合并单元格
|
||||
* @param os 输出流
|
||||
*/
|
||||
public static <T> void exportExcel(List<T> list, String sheetName, Class<T> clazz, boolean merge,
|
||||
OutputStream os, List<DropDownOptions> options) {
|
||||
ExcelWriterSheetBuilder builder = EasyExcel.write(os, clazz)
|
||||
.autoCloseStream(false)
|
||||
// 自动适配
|
||||
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
|
||||
// 大数值自动转换 防止失真
|
||||
.registerConverter(new ExcelBigNumberConvert())
|
||||
.sheet(sheetName);
|
||||
if (merge) {
|
||||
// 合并处理器
|
||||
builder.registerWriteHandler(new CellMergeStrategy(list, true));
|
||||
}
|
||||
// 添加下拉框操作
|
||||
builder.registerWriteHandler(new ExcelDownHandler(options));
|
||||
builder.doWrite(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* 单表多数据模板导出 模板格式为 {.属性}
|
||||
*
|
||||
* @param filename 文件名
|
||||
* @param templatePath 模板路径 resource 目录下的路径包括模板文件名
|
||||
* 例如: excel/temp.xlsx
|
||||
* 重点: 模板文件必须放置到启动类对应的 resource 目录下
|
||||
* @param data 模板需要的数据
|
||||
* @param response 响应体
|
||||
*/
|
||||
public static void exportTemplate(List<Object> data, String filename, String templatePath, HttpServletResponse response) {
|
||||
try {
|
||||
resetResponse(filename, response);
|
||||
ServletOutputStream os = response.getOutputStream();
|
||||
exportTemplate(data, templatePath, os);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("导出Excel异常");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 单表多数据模板导出 模板格式为 {.属性}
|
||||
*
|
||||
* @param templatePath 模板路径 resource 目录下的路径包括模板文件名
|
||||
* 例如: excel/temp.xlsx
|
||||
* 重点: 模板文件必须放置到启动类对应的 resource 目录下
|
||||
* @param data 模板需要的数据
|
||||
* @param os 输出流
|
||||
*/
|
||||
public static void exportTemplate(List<Object> data, String templatePath, OutputStream os) {
|
||||
ClassPathResource templateResource = new ClassPathResource(templatePath);
|
||||
ExcelWriter excelWriter = EasyExcel.write(os)
|
||||
.withTemplate(templateResource.getStream())
|
||||
.autoCloseStream(false)
|
||||
// 大数值自动转换 防止失真
|
||||
.registerConverter(new ExcelBigNumberConvert())
|
||||
.build();
|
||||
WriteSheet writeSheet = EasyExcel.writerSheet().build();
|
||||
if (CollUtil.isEmpty(data)) {
|
||||
throw new IllegalArgumentException("数据为空");
|
||||
}
|
||||
// 单表多数据导出 模板格式为 {.属性}
|
||||
for (Object d : data) {
|
||||
excelWriter.fill(d, writeSheet);
|
||||
}
|
||||
excelWriter.finish();
|
||||
}
|
||||
|
||||
/**
|
||||
* 多表多数据模板导出 模板格式为 {key.属性}
|
||||
*
|
||||
* @param filename 文件名
|
||||
* @param templatePath 模板路径 resource 目录下的路径包括模板文件名
|
||||
* 例如: excel/temp.xlsx
|
||||
* 重点: 模板文件必须放置到启动类对应的 resource 目录下
|
||||
* @param data 模板需要的数据
|
||||
* @param response 响应体
|
||||
*/
|
||||
public static void exportTemplateMultiList(Map<String, Object> data, String filename, String templatePath, HttpServletResponse response) {
|
||||
try {
|
||||
resetResponse(filename, response);
|
||||
ServletOutputStream os = response.getOutputStream();
|
||||
exportTemplateMultiList(data, templatePath, os);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("导出Excel异常");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 多sheet模板导出 模板格式为 {key.属性}
|
||||
*
|
||||
* @param filename 文件名
|
||||
* @param templatePath 模板路径 resource 目录下的路径包括模板文件名
|
||||
* 例如: excel/temp.xlsx
|
||||
* 重点: 模板文件必须放置到启动类对应的 resource 目录下
|
||||
* @param data 模板需要的数据
|
||||
* @param response 响应体
|
||||
*/
|
||||
public static void exportTemplateMultiSheet(List<Map<String, Object>> data, String filename, String templatePath, HttpServletResponse response) {
|
||||
try {
|
||||
resetResponse(filename, response);
|
||||
ServletOutputStream os = response.getOutputStream();
|
||||
exportTemplateMultiSheet(data, templatePath, os);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("导出Excel异常");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 多表多数据模板导出 模板格式为 {key.属性}
|
||||
*
|
||||
* @param templatePath 模板路径 resource 目录下的路径包括模板文件名
|
||||
* 例如: excel/temp.xlsx
|
||||
* 重点: 模板文件必须放置到启动类对应的 resource 目录下
|
||||
* @param data 模板需要的数据
|
||||
* @param os 输出流
|
||||
*/
|
||||
public static void exportTemplateMultiList(Map<String, Object> data, String templatePath, OutputStream os) {
|
||||
ClassPathResource templateResource = new ClassPathResource(templatePath);
|
||||
ExcelWriter excelWriter = EasyExcel.write(os)
|
||||
.withTemplate(templateResource.getStream())
|
||||
.autoCloseStream(false)
|
||||
// 大数值自动转换 防止失真
|
||||
.registerConverter(new ExcelBigNumberConvert())
|
||||
.build();
|
||||
WriteSheet writeSheet = EasyExcel.writerSheet().build();
|
||||
if (CollUtil.isEmpty(data)) {
|
||||
throw new IllegalArgumentException("数据为空");
|
||||
}
|
||||
for (Map.Entry<String, Object> map : data.entrySet()) {
|
||||
// 设置列表后续还有数据
|
||||
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
|
||||
if (map.getValue() instanceof Collection) {
|
||||
// 多表导出必须使用 FillWrapper
|
||||
excelWriter.fill(new FillWrapper(map.getKey(), (Collection<?>) map.getValue()), fillConfig, writeSheet);
|
||||
} else {
|
||||
excelWriter.fill(map.getValue(), writeSheet);
|
||||
}
|
||||
}
|
||||
excelWriter.finish();
|
||||
}
|
||||
|
||||
/**
|
||||
* 多sheet模板导出 模板格式为 {key.属性}
|
||||
*
|
||||
* @param templatePath 模板路径 resource 目录下的路径包括模板文件名
|
||||
* 例如: excel/temp.xlsx
|
||||
* 重点: 模板文件必须放置到启动类对应的 resource 目录下
|
||||
* @param data 模板需要的数据
|
||||
* @param os 输出流
|
||||
*/
|
||||
public static void exportTemplateMultiSheet(List<Map<String, Object>> data, String templatePath, OutputStream os) {
|
||||
ClassPathResource templateResource = new ClassPathResource(templatePath);
|
||||
ExcelWriter excelWriter = EasyExcel.write(os)
|
||||
.withTemplate(templateResource.getStream())
|
||||
.autoCloseStream(false)
|
||||
// 大数值自动转换 防止失真
|
||||
.registerConverter(new ExcelBigNumberConvert())
|
||||
.build();
|
||||
if (CollUtil.isEmpty(data)) {
|
||||
throw new IllegalArgumentException("数据为空");
|
||||
}
|
||||
for (int i = 0; i < data.size(); i++) {
|
||||
WriteSheet writeSheet = EasyExcel.writerSheet(i).build();
|
||||
for (Map.Entry<String, Object> map : data.get(i).entrySet()) {
|
||||
// 设置列表后续还有数据
|
||||
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
|
||||
if (map.getValue() instanceof Collection) {
|
||||
// 多表导出必须使用 FillWrapper
|
||||
excelWriter.fill(new FillWrapper(map.getKey(), (Collection<?>) map.getValue()), fillConfig, writeSheet);
|
||||
} else {
|
||||
excelWriter.fill(map.getValue(), writeSheet);
|
||||
}
|
||||
}
|
||||
}
|
||||
excelWriter.finish();
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置响应体
|
||||
*/
|
||||
private static void resetResponse(String sheetName, HttpServletResponse response) throws UnsupportedEncodingException {
|
||||
String filename = encodingFilename(sheetName);
|
||||
FileUtils.setAttachmentResponseHeader(response, filename);
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析导出值 0=男,1=女,2=未知
|
||||
*
|
||||
* @param propertyValue 参数值
|
||||
* @param converterExp 翻译注解
|
||||
* @param separator 分隔符
|
||||
* @return 解析后值
|
||||
*/
|
||||
public static String convertByExp(String propertyValue, String converterExp, String separator) {
|
||||
StringBuilder propertyString = new StringBuilder();
|
||||
String[] convertSource = converterExp.split(StringUtils.SEPARATOR);
|
||||
for (String item : convertSource) {
|
||||
String[] itemArray = item.split("=");
|
||||
if (StringUtils.containsAny(propertyValue, separator)) {
|
||||
for (String value : propertyValue.split(separator)) {
|
||||
if (itemArray[0].equals(value)) {
|
||||
propertyString.append(itemArray[1] + separator);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (itemArray[0].equals(propertyValue)) {
|
||||
return itemArray[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
return StringUtils.stripEnd(propertyString.toString(), separator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 反向解析值 男=0,女=1,未知=2
|
||||
*
|
||||
* @param propertyValue 参数值
|
||||
* @param converterExp 翻译注解
|
||||
* @param separator 分隔符
|
||||
* @return 解析后值
|
||||
*/
|
||||
public static String reverseByExp(String propertyValue, String converterExp, String separator) {
|
||||
StringBuilder propertyString = new StringBuilder();
|
||||
String[] convertSource = converterExp.split(StringUtils.SEPARATOR);
|
||||
for (String item : convertSource) {
|
||||
String[] itemArray = item.split("=");
|
||||
if (StringUtils.containsAny(propertyValue, separator)) {
|
||||
for (String value : propertyValue.split(separator)) {
|
||||
if (itemArray[1].equals(value)) {
|
||||
propertyString.append(itemArray[0] + separator);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (itemArray[1].equals(propertyValue)) {
|
||||
return itemArray[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
return StringUtils.stripEnd(propertyString.toString(), separator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 编码文件名
|
||||
*/
|
||||
public static String encodingFilename(String filename) {
|
||||
return IdUtil.fastSimpleUUID() + "_" + filename + ".xlsx";
|
||||
}
|
||||
|
||||
}
|
@ -3,162 +3,161 @@ package net.rzdata.demo.exception;
|
||||
import cn.dev33.satoken.exception.NotLoginException;
|
||||
import cn.dev33.satoken.exception.NotPermissionException;
|
||||
import cn.dev33.satoken.exception.NotRoleException;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.http.HttpStatus;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.rzdata.domain.Result;
|
||||
import net.rzdata.exception.ClientException;
|
||||
import net.rzdata.exception.ServerException;
|
||||
import net.rzdata.exception.ThirdPartyException;
|
||||
import net.rzdata.demo.core.domain.R;
|
||||
import net.rzdata.demo.core.exception.ServiceException;
|
||||
import net.rzdata.demo.core.exception.base.BaseException;
|
||||
import net.rzdata.demo.core.utils.StreamUtils;
|
||||
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingPathVariableException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
|
||||
/**
|
||||
* 全局异常处理
|
||||
* 全局异常处理器
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
protected final transient String errorMessage = "系统错误,请联系系统管理员";
|
||||
|
||||
/**
|
||||
* 权限码异常
|
||||
*/
|
||||
@ExceptionHandler(NotPermissionException.class)
|
||||
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||
public Result<Void> handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
|
||||
public R<Void> handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
|
||||
String requestURI = request.getRequestURI();
|
||||
log.error("请求地址'{}',权限码校验失败'{}'", requestURI, e.getMessage());
|
||||
ClientException ce = new ClientException("没有访问权限,请联系管理员授权", e);
|
||||
return Result.fail(ce);
|
||||
return R.fail(HttpStatus.HTTP_FORBIDDEN, "没有访问权限,请联系管理员授权");
|
||||
}
|
||||
|
||||
/**
|
||||
* 角色权限异常
|
||||
*/
|
||||
@ExceptionHandler(NotRoleException.class)
|
||||
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||
public Result<Void> handleNotRoleException(NotRoleException e, HttpServletRequest request) {
|
||||
public R<Void> handleNotRoleException(NotRoleException e, HttpServletRequest request) {
|
||||
String requestURI = request.getRequestURI();
|
||||
log.error("请求地址'{}',角色权限校验失败'{}'", requestURI, e.getMessage());
|
||||
ClientException ce = new ClientException("没有访问权限,请联系管理员授权", e);
|
||||
return Result.fail(ce);
|
||||
return R.fail(HttpStatus.HTTP_FORBIDDEN, "没有访问权限,请联系管理员授权");
|
||||
}
|
||||
|
||||
/**
|
||||
* 认证失败
|
||||
*/
|
||||
@ExceptionHandler(NotLoginException.class)
|
||||
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||
public Result<Void> handleNotLoginException(NotLoginException e, HttpServletRequest request) {
|
||||
public R<Void> handleNotLoginException(NotLoginException e, HttpServletRequest request) {
|
||||
String requestURI = request.getRequestURI();
|
||||
log.error("请求地址'{}',认证失败'{}',无法访问系统资源", requestURI, e.getMessage());
|
||||
ClientException ce = new ClientException("没有访问权限,请联系管理员授权", e);
|
||||
return Result.fail(ce);
|
||||
return R.fail(HttpStatus.HTTP_UNAUTHORIZED, "认证失败,无法访问系统资源");
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求方式不支持
|
||||
*/
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public Result<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
|
||||
public R<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
|
||||
HttpServletRequest request) {
|
||||
String requestURI = request.getRequestURI();
|
||||
log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
|
||||
ServerException se = new ServerException("请求方式不支持", e);
|
||||
return Result.fail(se, errorMessage);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(ClientException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public Result<Void> handleClientException(ClientException e) {
|
||||
log.error("客户端异常: {}", e.getMessage(), e);
|
||||
return Result.fail(e);
|
||||
/**
|
||||
* 业务异常
|
||||
*/
|
||||
@ExceptionHandler(ServiceException.class)
|
||||
public R<Void> handleServiceException(ServiceException e, HttpServletRequest request) {
|
||||
log.error(e.getMessage());
|
||||
Integer code = e.getCode();
|
||||
return ObjectUtil.isNotNull(code) ? R.fail(code, e.getMessage()) : R.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(ServerException.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public Result<Void> handleServerException(ServerException e) {
|
||||
log.error("服务端异常: {}", e.getMessage(), e);
|
||||
return Result.fail(e, errorMessage);
|
||||
/**
|
||||
* 业务异常
|
||||
*/
|
||||
@ExceptionHandler(BaseException.class)
|
||||
public R<Void> handleBaseException(BaseException e, HttpServletRequest request) {
|
||||
log.error(e.getMessage());
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(ThirdPartyException.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public Result<Void> handleThirdPartyException(ThirdPartyException e) {
|
||||
log.error("第三方服务异常: {}", e.getMessage(), e);
|
||||
return Result.fail(e, errorMessage);
|
||||
/**
|
||||
* 请求路径中缺少必需的路径变量
|
||||
*/
|
||||
@ExceptionHandler(MissingPathVariableException.class)
|
||||
public R<Void> handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
|
||||
String requestURI = request.getRequestURI();
|
||||
log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI);
|
||||
return R.fail(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求参数类型不匹配
|
||||
*/
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||
public R<Void> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
|
||||
String requestURI = request.getRequestURI();
|
||||
log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI);
|
||||
return R.fail(String.format("请求参数类型不匹配,参数[%s]要求类型为:'%s',但输入值为:'%s'", e.getName(), e.getRequiredType().getName(), e.getValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截未知的运行时异常
|
||||
*/
|
||||
@ExceptionHandler(RuntimeException.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public Result<String> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
|
||||
public R<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
|
||||
String requestURI = request.getRequestURI();
|
||||
log.error("请求地址'{}',发生未知异常.", requestURI, e);
|
||||
ServerException se = new ServerException(errorMessage, e);
|
||||
return Result.fail(se);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 系统异常
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public Result<String> handleException(Exception e, HttpServletRequest request) {
|
||||
public R<Void> handleException(Exception e, HttpServletRequest request) {
|
||||
String requestURI = request.getRequestURI();
|
||||
log.error("请求地址'{}',发生系统异常.", requestURI, e);
|
||||
ServerException se = new ServerException(errorMessage, e);
|
||||
return Result.fail(se);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义验证异常
|
||||
*/
|
||||
@ExceptionHandler(BindException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public Result<Void> handleBindException(BindException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
String message = e.getAllErrors().parallelStream()
|
||||
.map(DefaultMessageSourceResolvable::getDefaultMessage)
|
||||
.collect(Collectors.joining(", "));
|
||||
ClientException ce = new ClientException(message, e);
|
||||
return Result.fail(ce);
|
||||
public R<Void> handleBindException(BindException e) {
|
||||
log.error(e.getMessage());
|
||||
String message = StreamUtils.join(e.getAllErrors(), DefaultMessageSourceResolvable::getDefaultMessage, ", ");
|
||||
return R.fail(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义验证异常
|
||||
*/
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public Result<Void> constraintViolationException(ConstraintViolationException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
String message = e.getConstraintViolations().parallelStream()
|
||||
.map(ConstraintViolation::getMessage)
|
||||
.collect(Collectors.joining(", "));
|
||||
ClientException ce = new ClientException(message, e);
|
||||
return Result.fail(ce);
|
||||
public R<Void> constraintViolationException(ConstraintViolationException e) {
|
||||
log.error(e.getMessage());
|
||||
String message = StreamUtils.join(e.getConstraintViolations(), ConstraintViolation::getMessage, ", ");
|
||||
return R.fail(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义验证异常
|
||||
*/
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
public R<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
|
||||
log.error(e.getMessage());
|
||||
String message = e.getBindingResult().getFieldError().getDefaultMessage();
|
||||
ClientException ce = new ClientException(message, e);
|
||||
return Result.fail(ce);
|
||||
return R.fail(message);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,29 @@
|
||||
package net.rzdata.demo.idempotent.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 自定义注解防止表单重复提交
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Inherited
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface RepeatSubmit {
|
||||
|
||||
/**
|
||||
* 间隔时间(ms),小于此时间视为重复提交
|
||||
*/
|
||||
int interval() default 5000;
|
||||
|
||||
TimeUnit timeUnit() default TimeUnit.MILLISECONDS;
|
||||
|
||||
/**
|
||||
* 提示消息 支持国际化 格式为 {code}
|
||||
*/
|
||||
String message() default "{repeat.submit.message}";
|
||||
|
||||
}
|
@ -0,0 +1,146 @@
|
||||
package net.rzdata.demo.idempotent.aspectj;
|
||||
|
||||
import cn.dev33.satoken.SaManager;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.crypto.SecureUtil;
|
||||
import net.rzdata.demo.core.constant.GlobalConstants;
|
||||
import net.rzdata.demo.core.domain.R;
|
||||
import net.rzdata.demo.core.exception.ServiceException;
|
||||
import net.rzdata.demo.core.utils.MessageUtils;
|
||||
import net.rzdata.demo.core.utils.ServletUtils;
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import net.rzdata.demo.idempotent.annotation.RepeatSubmit;
|
||||
import net.rzdata.demo.json.utils.JsonUtils;
|
||||
import net.rzdata.demo.redis.utils.RedisUtils;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.AfterReturning;
|
||||
import org.aspectj.lang.annotation.AfterThrowing;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
/**
|
||||
* 防止重复提交(参考美团GTIS防重系统)
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Aspect
|
||||
public class RepeatSubmitAspect {
|
||||
|
||||
private static final ThreadLocal<String> KEY_CACHE = new ThreadLocal<>();
|
||||
|
||||
@Before("@annotation(repeatSubmit)")
|
||||
public void doBefore(JoinPoint point, RepeatSubmit repeatSubmit) throws Throwable {
|
||||
// 如果注解不为0 则使用注解数值
|
||||
long interval = repeatSubmit.timeUnit().toMillis(repeatSubmit.interval());
|
||||
|
||||
if (interval < 1000) {
|
||||
throw new ServiceException("重复提交间隔时间不能小于'1'秒");
|
||||
}
|
||||
HttpServletRequest request = ServletUtils.getRequest();
|
||||
String nowParams = argsArrayToString(point.getArgs());
|
||||
|
||||
// 请求地址(作为存放cache的key值)
|
||||
String url = request.getRequestURI();
|
||||
|
||||
// 唯一值(没有消息头则使用请求地址)
|
||||
String submitKey = StringUtils.trimToEmpty(request.getHeader(SaManager.getConfig().getTokenName()));
|
||||
|
||||
submitKey = SecureUtil.md5(submitKey + ":" + nowParams);
|
||||
// 唯一标识(指定key + url + 消息头)
|
||||
String cacheRepeatKey = GlobalConstants.REPEAT_SUBMIT_KEY + url + submitKey;
|
||||
if (RedisUtils.setObjectIfAbsent(cacheRepeatKey, "", Duration.ofMillis(interval))) {
|
||||
KEY_CACHE.set(cacheRepeatKey);
|
||||
} else {
|
||||
String message = repeatSubmit.message();
|
||||
if (StringUtils.startsWith(message, "{") && StringUtils.endsWith(message, "}")) {
|
||||
message = MessageUtils.message(StringUtils.substring(message, 1, message.length() - 1));
|
||||
}
|
||||
throw new ServiceException(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理完请求后执行
|
||||
*
|
||||
* @param joinPoint 切点
|
||||
*/
|
||||
@AfterReturning(pointcut = "@annotation(repeatSubmit)", returning = "jsonResult")
|
||||
public void doAfterReturning(JoinPoint joinPoint, RepeatSubmit repeatSubmit, Object jsonResult) {
|
||||
if (jsonResult instanceof R<?> r) {
|
||||
try {
|
||||
// 成功则不删除redis数据 保证在有效时间内无法重复提交
|
||||
if (r.getCode() == R.SUCCESS) {
|
||||
return;
|
||||
}
|
||||
RedisUtils.deleteObject(KEY_CACHE.get());
|
||||
} finally {
|
||||
KEY_CACHE.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截异常操作
|
||||
*
|
||||
* @param joinPoint 切点
|
||||
* @param e 异常
|
||||
*/
|
||||
@AfterThrowing(value = "@annotation(repeatSubmit)", throwing = "e")
|
||||
public void doAfterThrowing(JoinPoint joinPoint, RepeatSubmit repeatSubmit, Exception e) {
|
||||
RedisUtils.deleteObject(KEY_CACHE.get());
|
||||
KEY_CACHE.remove();
|
||||
}
|
||||
|
||||
/**
|
||||
* 参数拼装
|
||||
*/
|
||||
private String argsArrayToString(Object[] paramsArray) {
|
||||
StringJoiner params = new StringJoiner(" ");
|
||||
if (ArrayUtil.isEmpty(paramsArray)) {
|
||||
return params.toString();
|
||||
}
|
||||
for (Object o : paramsArray) {
|
||||
if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
|
||||
params.add(JsonUtils.toJsonString(o));
|
||||
}
|
||||
}
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否需要过滤的对象。
|
||||
*
|
||||
* @param o 对象信息。
|
||||
* @return 如果是需要过滤的对象,则返回true;否则返回false。
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public boolean isFilterObject(final Object o) {
|
||||
Class<?> clazz = o.getClass();
|
||||
if (clazz.isArray()) {
|
||||
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
|
||||
} else if (Collection.class.isAssignableFrom(clazz)) {
|
||||
Collection collection = (Collection) o;
|
||||
for (Object value : collection) {
|
||||
return value instanceof MultipartFile;
|
||||
}
|
||||
} else if (Map.class.isAssignableFrom(clazz)) {
|
||||
Map map = (Map) o;
|
||||
for (Object value : map.values()) {
|
||||
return value instanceof MultipartFile;
|
||||
}
|
||||
}
|
||||
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
|
||||
|| o instanceof BindingResult;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package net.rzdata.demo.idempotent.config;
|
||||
|
||||
import net.rzdata.demo.idempotent.aspectj.RepeatSubmitAspect;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 幂等功能配置
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Configuration
|
||||
public class IdempotentConfig {
|
||||
|
||||
@Bean
|
||||
public RepeatSubmitAspect repeatSubmitAspect() {
|
||||
return new RepeatSubmitAspect();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package net.rzdata.demo.json.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||
import net.rzdata.demo.json.handler.BigNumberSerializer;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.TimeZone;
|
||||
|
||||
/**
|
||||
* jackson 配置
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
public class JacksonConfig {
|
||||
|
||||
@Bean
|
||||
public Jackson2ObjectMapperBuilderCustomizer customizer() {
|
||||
return builder -> {
|
||||
// 全局配置序列化返回 JSON 处理
|
||||
JavaTimeModule javaTimeModule = new JavaTimeModule();
|
||||
javaTimeModule.addSerializer(Long.class, BigNumberSerializer.INSTANCE);
|
||||
javaTimeModule.addSerializer(Long.TYPE, BigNumberSerializer.INSTANCE);
|
||||
javaTimeModule.addSerializer(BigInteger.class, BigNumberSerializer.INSTANCE);
|
||||
javaTimeModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
|
||||
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
|
||||
builder.modules(javaTimeModule);
|
||||
builder.timeZone(TimeZone.getDefault());
|
||||
log.info("初始化 jackson 配置");
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
package net.rzdata.demo.json.handler;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
|
||||
import com.fasterxml.jackson.databind.ser.std.NumberSerializer;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 超出 JS 最大最小值 处理
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@JacksonStdImpl
|
||||
public class BigNumberSerializer extends NumberSerializer {
|
||||
|
||||
/**
|
||||
* 根据 JS Number.MAX_SAFE_INTEGER 与 Number.MIN_SAFE_INTEGER 得来
|
||||
*/
|
||||
private static final long MAX_SAFE_INTEGER = 9007199254740991L;
|
||||
private static final long MIN_SAFE_INTEGER = -9007199254740991L;
|
||||
|
||||
/**
|
||||
* 提供实例
|
||||
*/
|
||||
public static final BigNumberSerializer INSTANCE = new BigNumberSerializer(Number.class);
|
||||
|
||||
public BigNumberSerializer(Class<? extends Number> rawType) {
|
||||
super(rawType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(Number value, JsonGenerator gen, SerializerProvider provider) throws IOException {
|
||||
// 超出范围 序列化位字符串
|
||||
if (value.longValue() > MIN_SAFE_INTEGER && value.longValue() < MAX_SAFE_INTEGER) {
|
||||
super.serialize(value, gen, provider);
|
||||
} else {
|
||||
gen.writeString(value.toString());
|
||||
}
|
||||
}
|
||||
}
|
113
common/src/main/java/net/rzdata/demo/json/utils/JsonUtils.java
Normal file
113
common/src/main/java/net/rzdata/demo/json/utils/JsonUtils.java
Normal file
@ -0,0 +1,113 @@
|
||||
package net.rzdata.demo.json.utils;
|
||||
|
||||
import cn.hutool.core.lang.Dict;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
|
||||
import net.rzdata.demo.core.utils.SpringUtils;
|
||||
import net.rzdata.demo.core.utils.StringUtils;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* JSON 工具类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class JsonUtils {
|
||||
|
||||
private static final ObjectMapper OBJECT_MAPPER = SpringUtils.getBean(ObjectMapper.class);
|
||||
|
||||
public static ObjectMapper getObjectMapper() {
|
||||
return OBJECT_MAPPER;
|
||||
}
|
||||
|
||||
public static String toJsonString(Object object) {
|
||||
if (ObjectUtil.isNull(object)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return OBJECT_MAPPER.writeValueAsString(object);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T parseObject(String text, Class<T> clazz) {
|
||||
if (StringUtils.isEmpty(text)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(text, clazz);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
|
||||
if (ArrayUtil.isEmpty(bytes)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(bytes, clazz);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T parseObject(String text, TypeReference<T> typeReference) {
|
||||
if (StringUtils.isBlank(text)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(text, typeReference);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Dict parseMap(String text) {
|
||||
if (StringUtils.isBlank(text)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructType(Dict.class));
|
||||
} catch (MismatchedInputException e) {
|
||||
// 类型不匹配说明不是json
|
||||
return null;
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Dict> parseArrayMap(String text) {
|
||||
if (StringUtils.isBlank(text)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, Dict.class));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> List<T> parseArray(String text, Class<T> clazz) {
|
||||
if (StringUtils.isEmpty(text)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package net.rzdata.demo.mybatis.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 数据权限
|
||||
*
|
||||
* 一个注解只能对应一个模板
|
||||
*
|
||||
* @author Lion Li
|
||||
* @version 3.5.0
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface DataColumn {
|
||||
|
||||
/**
|
||||
* 占位符关键字
|
||||
*/
|
||||
String[] key() default "deptName";
|
||||
|
||||
/**
|
||||
* 占位符替换值
|
||||
*/
|
||||
String[] value() default "dept_id";
|
||||
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package net.rzdata.demo.mybatis.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 数据权限组
|
||||
*
|
||||
* @author Lion Li
|
||||
* @version 3.5.0
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface DataPermission {
|
||||
|
||||
DataColumn[] value();
|
||||
|
||||
}
|
@ -0,0 +1,104 @@
|
||||
package net.rzdata.demo.mybatis.config;
|
||||
|
||||
import cn.hutool.core.net.NetUtil;
|
||||
import com.baomidou.mybatisplus.autoconfigure.DdlApplicationRunner;
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
|
||||
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
|
||||
import com.baomidou.mybatisplus.extension.ddl.IDdl;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import net.rzdata.demo.mybatis.handler.InjectionMetaObjectHandler;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* mybatis-plus配置类(下方注释有插件介绍)
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@EnableTransactionManagement(proxyTargetClass = true)
|
||||
@Configuration
|
||||
@MapperScan("${mybatis-plus.mapperPackage}")
|
||||
@ConfigurationProperties(prefix = "mybatis-plus")
|
||||
public class MybatisPlusConfig {
|
||||
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
// 分页插件
|
||||
interceptor.addInnerInterceptor(paginationInnerInterceptor());
|
||||
// 乐观锁插件
|
||||
interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
|
||||
return interceptor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页插件,自动识别数据库类型
|
||||
*/
|
||||
public PaginationInnerInterceptor paginationInnerInterceptor() {
|
||||
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
|
||||
// 设置最大单页限制数量,默认 500 条,-1 不受限制
|
||||
paginationInnerInterceptor.setMaxLimit(-1L);
|
||||
// 分页合理化
|
||||
paginationInnerInterceptor.setOverflow(true);
|
||||
return paginationInnerInterceptor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 乐观锁插件
|
||||
*/
|
||||
public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {
|
||||
return new OptimisticLockerInnerInterceptor();
|
||||
}
|
||||
|
||||
/**
|
||||
* 元对象字段填充控制器
|
||||
*/
|
||||
@Bean
|
||||
public MetaObjectHandler metaObjectHandler() {
|
||||
return new InjectionMetaObjectHandler();
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用网卡信息绑定雪花生成器
|
||||
* 防止集群雪花ID重复
|
||||
*/
|
||||
@Bean
|
||||
public IdentifierGenerator idGenerator() {
|
||||
return new DefaultIdentifierGenerator(NetUtil.getLocalhost());
|
||||
}
|
||||
|
||||
/**
|
||||
* PaginationInnerInterceptor 分页插件,自动识别数据库类型
|
||||
* https://baomidou.com/pages/97710a/
|
||||
* OptimisticLockerInnerInterceptor 乐观锁插件
|
||||
* https://baomidou.com/pages/0d93c0/
|
||||
* MetaObjectHandler 元对象字段填充控制器
|
||||
* https://baomidou.com/pages/4c6bcf/
|
||||
* ISqlInjector sql注入器
|
||||
* https://baomidou.com/pages/42ea4a/
|
||||
* BlockAttackInnerInterceptor 如果是对全表的删除或更新操作,就会终止该操作
|
||||
* https://baomidou.com/pages/f9a237/
|
||||
* IllegalSQLInnerInterceptor sql性能规范插件(垃圾SQL拦截)
|
||||
* IdentifierGenerator 自定义主键策略
|
||||
* https://baomidou.com/pages/568eb2/
|
||||
* TenantLineInnerInterceptor 多租户插件
|
||||
* https://baomidou.com/pages/aef2f2/
|
||||
* DynamicTableNameInnerInterceptor 动态表名插件
|
||||
* https://baomidou.com/pages/2a45ff/
|
||||
*/
|
||||
|
||||
@Bean
|
||||
public DdlApplicationRunner ddlApplicationRunner(@Autowired(required = false) List<IDdl> ddlList) {
|
||||
return new DdlApplicationRunner(ddlList);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package net.rzdata.demo.mybatis.core.domain;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Entity基类
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
|
||||
@Data
|
||||
public class BaseEntity implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 搜索值
|
||||
*/
|
||||
@JsonIgnore
|
||||
@TableField(exist = false)
|
||||
private String searchValue;
|
||||
|
||||
/**
|
||||
* 创建者
|
||||
*/
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private Long createBy;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private Date createTime;
|
||||
|
||||
/**
|
||||
* 更新者
|
||||
*/
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
private Long updateBy;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
private Date updateTime;
|
||||
|
||||
/**
|
||||
* 请求参数
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_EMPTY)
|
||||
@TableField(exist = false)
|
||||
private Map<String, Object> params = new HashMap<>();
|
||||
|
||||
}
|
@ -0,0 +1,199 @@
|
||||
package net.rzdata.demo.mybatis.core.mapper;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.core.toolkit.reflect.GenericTypeUtils;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.toolkit.Db;
|
||||
import net.rzdata.demo.core.utils.MapstructUtils;
|
||||
import org.apache.ibatis.logging.Log;
|
||||
import org.apache.ibatis.logging.LogFactory;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 自定义 Mapper 接口, 实现 自定义扩展
|
||||
*
|
||||
* @param <T> table 泛型
|
||||
* @param <V> vo 泛型
|
||||
* @author Lion Li
|
||||
* @since 2021-05-13
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public interface BaseMapperPlus<T, V> extends BaseMapper<T> {
|
||||
|
||||
Log log = LogFactory.getLog(BaseMapperPlus.class);
|
||||
|
||||
default Class<V> currentVoClass() {
|
||||
GenericTypeUtils.resolveTypeArguments(this.getClass(), BaseMapperPlus.class);
|
||||
return (Class<V>) GenericTypeUtils.resolveTypeArguments(this.getClass(), BaseMapperPlus.class)[1];
|
||||
}
|
||||
|
||||
default Class<T> currentModelClass() {
|
||||
return (Class<T>) GenericTypeUtils.resolveTypeArguments(this.getClass(), BaseMapperPlus.class)[0];
|
||||
}
|
||||
|
||||
default List<T> selectList() {
|
||||
return this.selectList(new QueryWrapper<>());
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入
|
||||
*/
|
||||
default boolean insertBatch(Collection<T> entityList) {
|
||||
return Db.saveBatch(entityList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新
|
||||
*/
|
||||
default boolean updateBatchById(Collection<T> entityList) {
|
||||
return Db.updateBatchById(entityList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入或更新
|
||||
*/
|
||||
default boolean insertOrUpdateBatch(Collection<T> entityList) {
|
||||
return Db.saveOrUpdateBatch(entityList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入(包含限制条数)
|
||||
*/
|
||||
default boolean insertBatch(Collection<T> entityList, int batchSize) {
|
||||
return Db.saveBatch(entityList, batchSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新(包含限制条数)
|
||||
*/
|
||||
default boolean updateBatchById(Collection<T> entityList, int batchSize) {
|
||||
return Db.updateBatchById(entityList, batchSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入或更新(包含限制条数)
|
||||
*/
|
||||
default boolean insertOrUpdateBatch(Collection<T> entityList, int batchSize) {
|
||||
return Db.saveOrUpdateBatch(entityList, batchSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入或更新(包含限制条数)
|
||||
*/
|
||||
default boolean insertOrUpdate(T entity) {
|
||||
return Db.saveOrUpdate(entity);
|
||||
}
|
||||
|
||||
default V selectVoById(Serializable id) {
|
||||
return selectVoById(id, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 ID 查询
|
||||
*/
|
||||
default <C> C selectVoById(Serializable id, Class<C> voClass) {
|
||||
T obj = this.selectById(id);
|
||||
if (ObjectUtil.isNull(obj)) {
|
||||
return null;
|
||||
}
|
||||
return MapstructUtils.convert(obj, voClass);
|
||||
}
|
||||
|
||||
default List<V> selectVoBatchIds(Collection<? extends Serializable> idList) {
|
||||
return selectVoBatchIds(idList, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询(根据ID 批量查询)
|
||||
*/
|
||||
default <C> List<C> selectVoBatchIds(Collection<? extends Serializable> idList, Class<C> voClass) {
|
||||
List<T> list = this.selectBatchIds(idList);
|
||||
if (CollUtil.isEmpty(list)) {
|
||||
return CollUtil.newArrayList();
|
||||
}
|
||||
return MapstructUtils.convert(list, voClass);
|
||||
}
|
||||
|
||||
default List<V> selectVoByMap(Map<String, Object> map) {
|
||||
return selectVoByMap(map, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询(根据 columnMap 条件)
|
||||
*/
|
||||
default <C> List<C> selectVoByMap(Map<String, Object> map, Class<C> voClass) {
|
||||
List<T> list = this.selectByMap(map);
|
||||
if (CollUtil.isEmpty(list)) {
|
||||
return CollUtil.newArrayList();
|
||||
}
|
||||
return MapstructUtils.convert(list, voClass);
|
||||
}
|
||||
|
||||
default V selectVoOne(Wrapper<T> wrapper) {
|
||||
return selectVoOne(wrapper, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 entity 条件,查询一条记录
|
||||
*/
|
||||
default <C> C selectVoOne(Wrapper<T> wrapper, Class<C> voClass) {
|
||||
T obj = this.selectOne(wrapper);
|
||||
if (ObjectUtil.isNull(obj)) {
|
||||
return null;
|
||||
}
|
||||
return MapstructUtils.convert(obj, voClass);
|
||||
}
|
||||
|
||||
default List<V> selectVoList() {
|
||||
return selectVoList(new QueryWrapper<>(), this.currentVoClass());
|
||||
}
|
||||
|
||||
default List<V> selectVoList(Wrapper<T> wrapper) {
|
||||
return selectVoList(wrapper, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 entity 条件,查询全部记录
|
||||
*/
|
||||
default <C> List<C> selectVoList(Wrapper<T> wrapper, Class<C> voClass) {
|
||||
List<T> list = this.selectList(wrapper);
|
||||
if (CollUtil.isEmpty(list)) {
|
||||
return CollUtil.newArrayList();
|
||||
}
|
||||
return MapstructUtils.convert(list, voClass);
|
||||
}
|
||||
|
||||
default <P extends IPage<V>> P selectVoPage(IPage<T> page, Wrapper<T> wrapper) {
|
||||
return selectVoPage(page, wrapper, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询VO
|
||||
*/
|
||||
default <C, P extends IPage<C>> P selectVoPage(IPage<T> page, Wrapper<T> wrapper, Class<C> voClass) {
|
||||
IPage<T> list = this.selectPage(page, wrapper);
|
||||
IPage<C> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
|
||||
if (CollUtil.isEmpty(list.getRecords())) {
|
||||
return (P) voPage;
|
||||
}
|
||||
voPage.setRecords(MapstructUtils.convert(list.getRecords(), voClass));
|
||||
return (P) voPage;
|
||||
}
|
||||
|
||||
default <C> List<C> selectObjs(Wrapper<T> wrapper, Function<? super Object, C> mapper) {
|
||||
return this.selectObjs(wrapper).stream().filter(Objects::nonNull).map(mapper).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user