Pre Merge pull request !183 from 1332987/master

pull/183/MERGE
1332987 3 years ago committed by Gitee
commit b6ae297424
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F

@ -1 +0,0 @@
custom: http://doc.ruoyi.vip/ruoyi-cloud/other/donate.html

@ -57,15 +57,15 @@ com.ruoyi
## 内置功能 ## 内置功能
1. 用户管理:用户是系统操作者,该功能主要完成系统用户配置。 1. 用户管理:用户是系统操作者,该功能主要完成系统用户配置。
2. 部门管理:配置系统组织机构(公司、部门、小组),树结构展现支持数据权限。 2. 部门管理:配置系统组织机构(公司、部门、小组),树结构展现支持数据权限。
3. 岗位管理:配置系统用户所属担任职务。 3. 岗位管理:配置系统用户所属担任职务。
4. 菜单管理:配置系统菜单,操作权限,按钮权限标识等。 4. 菜单管理:配置系统菜单,操作权限,按钮权限标识等。
5. 角色管理:角色菜单权限分配、设置角色按机构进行数据范围权限划分。 5. 角色管理:角色菜单权限分配、设置角色按机构进行数据范围权限划分。
6. 字典管理:对系统中经常使用的一些较为固定的数据进行维护。 6. 字典管理:对系统中经常使用的一些较为固定的数据进行维护。
7. 参数管理:对系统动态配置常用参数。 7. 参数管理:对系统动态配置常用参数。
8. 通知公告:系统通知公告信息发布维护。 8. 通知公告:系统通知公告信息发布维护。
9. 操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。 9. 操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。
10. 登录日志:系统登录日志记录查询包含登录异常。 10. 登录日志:系统登录日志记录查询包含登录异常。
11. 在线用户:当前系统中活跃用户状态监控。 11. 在线用户:当前系统中活跃用户状态监控。
12. 定时任务:在线(添加、修改、删除)任务调度包含执行结果日志。 12. 定时任务:在线(添加、修改、删除)任务调度包含执行结果日志。
@ -75,6 +75,16 @@ com.ruoyi
16. 在线构建器拖动表单元素生成相应的HTML代码。 16. 在线构建器拖动表单元素生成相应的HTML代码。
17. 连接池监视监视当前系统数据库连接池状态可进行分析SQL找出系统性能瓶颈。 17. 连接池监视监视当前系统数据库连接池状态可进行分析SQL找出系统性能瓶颈。
## TODO
- 添加lombok
- 通过代码规约扫描
- 用smart-doc + Torna 替换掉swagger
- 引入mybatis-plus
- 日志使用ELK
## 在线体验 ## 在线体验
- admin/admin123 - admin/admin123

@ -1,12 +0,0 @@
@echo off
echo.
echo [信息] 清理工程target生成路径。
echo.
%~d0
cd %~dp0
cd ..
call mvn clean
pause

@ -1,12 +0,0 @@
@echo off
echo.
echo [信息] 打包Web工程生成war/jar包文件。
echo.
%~d0
cd %~dp0
cd ..
call mvn clean package -Dmaven.test.skip=true
pause

@ -1,14 +0,0 @@
@echo off
echo.
echo [信息] 使用Jar命令运行Auth工程。
echo.
cd %~dp0
cd ../ruoyi-auth/target
set JAVA_OPTS=-Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m
java -Dfile.encoding=utf-8 %JAVA_OPTS% -jar ruoyi-auth.jar
cd bin
pause

@ -1,14 +0,0 @@
@echo off
echo.
echo [信息] 使用Jar命令运行Gateway工程。
echo.
cd %~dp0
cd ../ruoyi-gateway/target
set JAVA_OPTS=-Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m
java -Dfile.encoding=utf-8 %JAVA_OPTS% -jar ruoyi-gateway.jar
cd bin
pause

@ -1,14 +0,0 @@
@echo off
echo.
echo [信息] 使用Jar命令运行Modules-File工程。
echo.
cd %~dp0
cd ../ruoyi-modules/ruoyi-file/target
set JAVA_OPTS=-Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m
java -Dfile.encoding=utf-8 %JAVA_OPTS% -jar ruoyi-modules-file.jar
cd bin
pause

@ -1,14 +0,0 @@
@echo off
echo.
echo [信息] 使用Jar命令运行Modules-Gen工程。
echo.
cd %~dp0
cd ../ruoyi-modules/ruoyi-gen/target
set JAVA_OPTS=-Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m
java -Dfile.encoding=utf-8 %JAVA_OPTS% -jar ruoyi-modules-gen.jar
cd bin
pause

@ -1,14 +0,0 @@
@echo off
echo.
echo [信息] 使用Jar命令运行Modules-Job工程。
echo.
cd %~dp0
cd ../ruoyi-modules/ruoyi-job/target
set JAVA_OPTS=-Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m
java -Dfile.encoding=utf-8 %JAVA_OPTS% -jar ruoyi-modules-job.jar
cd bin
pause

@ -1,14 +0,0 @@
@echo off
echo.
echo [信息] 使用Jar命令运行Modules-System工程。
echo.
cd %~dp0
cd ../ruoyi-modules/ruoyi-system/target
set JAVA_OPTS=-Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m
java -Dfile.encoding=utf-8 %JAVA_OPTS% -jar ruoyi-modules-system.jar
cd bin
pause

@ -1,14 +0,0 @@
@echo off
echo.
echo [信息] 使用Jar命令运行Monitor工程。
echo.
cd %~dp0
cd ../ruoyi-visual/ruoyi-monitor/target
set JAVA_OPTS=-Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m
java -Dfile.encoding=utf-8 %JAVA_OPTS% -jar ruoyi-visual-monitor.jar
cd bin
pause

@ -29,13 +29,13 @@
<kaptcha.version>2.3.2</kaptcha.version> <kaptcha.version>2.3.2</kaptcha.version>
<pagehelper.boot.version>1.4.1</pagehelper.boot.version> <pagehelper.boot.version>1.4.1</pagehelper.boot.version>
<druid.version>1.2.8</druid.version> <druid.version>1.2.8</druid.version>
<dynamic-ds.version>3.5.0</dynamic-ds.version> <dynamic-ds.version>3.5.1</dynamic-ds.version>
<commons.io.version>2.11.0</commons.io.version> <commons.io.version>2.11.0</commons.io.version>
<commons.fileupload.version>1.4</commons.fileupload.version> <commons.fileupload.version>1.4</commons.fileupload.version>
<velocity.version>2.3</velocity.version> <velocity.version>2.3</velocity.version>
<fastjson.version>1.2.80</fastjson.version> <fastjson.version>1.2.80</fastjson.version>
<jjwt.version>0.9.1</jjwt.version> <jjwt.version>0.9.1</jjwt.version>
<minio.version>8.2.2</minio.version> <minio.version>8.3.7</minio.version>
<poi.version>4.1.2</poi.version> <poi.version>4.1.2</poi.version>
<commons-collections.version>3.2.2</commons-collections.version> <commons-collections.version>3.2.2</commons-collections.version>
<transmittable-thread-local.version>2.12.2</transmittable-thread-local.version> <transmittable-thread-local.version>2.12.2</transmittable-thread-local.version>
@ -264,6 +264,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration> <configuration>
<source>${java.version}</source> <source>${java.version}</source>
<target>${java.version}</target> <target>${java.version}</target>

@ -1,23 +1,22 @@
package com.ruoyi.system.api; package com.ruoyi.system.api;
import com.ruoyi.common.core.constant.ServiceNameConstants;
import com.ruoyi.common.core.domain.Rust;
import com.ruoyi.system.api.domain.SysFile;
import com.ruoyi.system.api.factory.RemoteFileFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.constant.ServiceNameConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.domain.SysFile;
import com.ruoyi.system.api.factory.RemoteFileFallbackFactory;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@FeignClient(contextId = "remoteFileService", value = ServiceNameConstants.FILE_SERVICE, fallbackFactory = RemoteFileFallbackFactory.class) @FeignClient(contextId = "remoteFileService", value = ServiceNameConstants.FILE_SERVICE, fallbackFactory = RemoteFileFallbackFactory.class)
public interface RemoteFileService public interface RemoteFileService {
{
/** /**
* *
* *
@ -25,5 +24,5 @@ public interface RemoteFileService
* @return * @return
*/ */
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R<SysFile> upload(@RequestPart(value = "file") MultipartFile file); public Rust<SysFile> upload(@RequestPart(value = "file") MultipartFile file);
} }

@ -1,41 +1,40 @@
package com.ruoyi.system.api; package com.ruoyi.system.api;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import com.ruoyi.common.core.constant.SecurityConstants; import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.ServiceNameConstants; import com.ruoyi.common.core.constant.ServiceNameConstants;
import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.Rust;
import com.ruoyi.system.api.domain.SysLogininfor; import com.ruoyi.system.api.domain.SysLogininfor;
import com.ruoyi.system.api.domain.SysOperLog; import com.ruoyi.system.api.domain.SysOperLog;
import com.ruoyi.system.api.factory.RemoteLogFallbackFactory; import com.ruoyi.system.api.factory.RemoteLogFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@FeignClient(contextId = "remoteLogService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteLogFallbackFactory.class) @FeignClient(contextId = "remoteLogService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteLogFallbackFactory.class)
public interface RemoteLogService public interface RemoteLogService {
{
/** /**
* *
* *
* @param sysOperLog * @param sysOperLog
* @param source * @param source
* @return * @return
*/ */
@PostMapping("/operlog") @PostMapping("/operlog")
public R<Boolean> saveLog(@RequestBody SysOperLog sysOperLog, @RequestHeader(SecurityConstants.FROM_SOURCE) String source); public Rust<Boolean> saveLog(@RequestBody SysOperLog sysOperLog, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
/** /**
* 访 * 访
* *
* @param sysLogininfor 访 * @param sysLogininfor 访
* @param source * @param source
* @return * @return
*/ */
@PostMapping("/logininfor") @PostMapping("/logininfor")
public R<Boolean> saveLogininfor(@RequestBody SysLogininfor sysLogininfor, @RequestHeader(SecurityConstants.FROM_SOURCE) String source); public Rust<Boolean> saveLogininfor(@RequestBody SysLogininfor sysLogininfor, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
} }

@ -1,43 +1,38 @@
package com.ruoyi.system.api; package com.ruoyi.system.api;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import com.ruoyi.common.core.constant.SecurityConstants; import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.ServiceNameConstants; import com.ruoyi.common.core.constant.ServiceNameConstants;
import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.Rust;
import com.ruoyi.system.api.domain.SysUser; import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.factory.RemoteUserFallbackFactory; import com.ruoyi.system.api.factory.RemoteUserFallbackFactory;
import com.ruoyi.system.api.model.LoginUser; import com.ruoyi.system.api.model.LoginUser;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@FeignClient(contextId = "remoteUserService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteUserFallbackFactory.class) @FeignClient(contextId = "remoteUserService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteUserFallbackFactory.class)
public interface RemoteUserService public interface RemoteUserService {
{
/** /**
* *
* *
* @param username * @param username
* @param source * @param source
* @return * @return
*/ */
@GetMapping("/user/info/{username}") @GetMapping("/user/info/{username}")
public R<LoginUser> getUserInfo(@PathVariable("username") String username, @RequestHeader(SecurityConstants.FROM_SOURCE) String source); public Rust<LoginUser> getUserInfo(@PathVariable("username") String username, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
/** /**
* *
* *
* @param sysUser * @param sysUser
* @param source * @param source
* @return * @return
*/ */
@PostMapping("/user/register") @PostMapping("/user/register")
public R<Boolean> registerUserInfo(@RequestBody SysUser sysUser, @RequestHeader(SecurityConstants.FROM_SOURCE) String source); public Rust<Boolean> registerUserInfo(@RequestBody SysUser sysUser, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
} }

@ -1,202 +1,202 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import java.util.ArrayList; import com.ruoyi.common.core.web.domain.BaseEntity;
import java.util.List; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.Email; import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.ArrayList;
import org.apache.commons.lang3.builder.ToStringStyle; import java.util.List;
import com.ruoyi.common.core.web.domain.BaseEntity;
/** /**
* sys_dept * sys_dept
* *
* @author ruoyi * @author ruoyi
*/ */
public class SysDept extends BaseEntity public class SysDept extends BaseEntity {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 部门ID */ /**
* ID
*/
private Long deptId; private Long deptId;
/** 父部门ID */ /**
* ID
*/
private Long parentId; private Long parentId;
/** 祖级列表 */ /**
*
*/
private String ancestors; private String ancestors;
/** 部门名称 */ /**
*
*/
private String deptName; private String deptName;
/** 显示顺序 */ /**
*
*/
private String orderNum; private String orderNum;
/** 负责人 */ /**
*
*/
private String leader; private String leader;
/** 联系电话 */ /**
*
*/
private String phone; private String phone;
/** 邮箱 */ /**
*
*/
private String email; private String email;
/** 部门状态:0正常,1停用 */ /**
* :0,1
*/
private String status; private String status;
/** 删除标志0代表存在 2代表删除 */ /**
* 0 2
*/
private String delFlag; private String delFlag;
/** 父部门名称 */ /**
*
*/
private String parentName; private String parentName;
/** 子部门 */ /**
*
*/
private List<SysDept> children = new ArrayList<SysDept>(); private List<SysDept> children = new ArrayList<SysDept>();
public Long getDeptId() public Long getDeptId() {
{
return deptId; return deptId;
} }
public void setDeptId(Long deptId) public void setDeptId(Long deptId) {
{
this.deptId = deptId; this.deptId = deptId;
} }
public Long getParentId() public Long getParentId() {
{
return parentId; return parentId;
} }
public void setParentId(Long parentId) public void setParentId(Long parentId) {
{
this.parentId = parentId; this.parentId = parentId;
} }
public String getAncestors() public String getAncestors() {
{
return ancestors; return ancestors;
} }
public void setAncestors(String ancestors) public void setAncestors(String ancestors) {
{
this.ancestors = ancestors; this.ancestors = ancestors;
} }
@NotBlank(message = "部门名称不能为空") @NotBlank(message = "部门名称不能为空")
@Size(min = 0, max = 30, message = "部门名称长度不能超过30个字符") @Size(min = 0, max = 30, message = "部门名称长度不能超过30个字符")
public String getDeptName() public String getDeptName() {
{
return deptName; return deptName;
} }
public void setDeptName(String deptName) public void setDeptName(String deptName) {
{
this.deptName = deptName; this.deptName = deptName;
} }
@NotBlank(message = "显示顺序不能为空") @NotBlank(message = "显示顺序不能为空")
public String getOrderNum() public String getOrderNum() {
{
return orderNum; return orderNum;
} }
public void setOrderNum(String orderNum) public void setOrderNum(String orderNum) {
{
this.orderNum = orderNum; this.orderNum = orderNum;
} }
public String getLeader() public String getLeader() {
{
return leader; return leader;
} }
public void setLeader(String leader) public void setLeader(String leader) {
{
this.leader = leader; this.leader = leader;
} }
@Size(min = 0, max = 11, message = "联系电话长度不能超过11个字符") @Size(min = 0, max = 11, message = "联系电话长度不能超过11个字符")
public String getPhone() public String getPhone() {
{
return phone; return phone;
} }
public void setPhone(String phone) public void setPhone(String phone) {
{
this.phone = phone; this.phone = phone;
} }
@Email(message = "邮箱格式不正确") @Email(message = "邮箱格式不正确")
@Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符") @Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
public String getEmail() public String getEmail() {
{
return email; return email;
} }
public void setEmail(String email) public void setEmail(String email) {
{
this.email = email; this.email = email;
} }
public String getStatus() public String getStatus() {
{
return status; return status;
} }
public void setStatus(String status) public void setStatus(String status) {
{
this.status = status; this.status = status;
} }
public String getDelFlag() public String getDelFlag() {
{
return delFlag; return delFlag;
} }
public void setDelFlag(String delFlag) public void setDelFlag(String delFlag) {
{
this.delFlag = delFlag; this.delFlag = delFlag;
} }
public String getParentName() public String getParentName() {
{
return parentName; return parentName;
} }
public void setParentName(String parentName) public void setParentName(String parentName) {
{
this.parentName = parentName; this.parentName = parentName;
} }
public List<SysDept> getChildren() public List<SysDept> getChildren() {
{
return children; return children;
} }
public void setChildren(List<SysDept> children) public void setChildren(List<SysDept> children) {
{
this.children = children; this.children = children;
} }
@Override @Override
public String toString() { public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("deptId", getDeptId()) .append("deptId", getDeptId())
.append("parentId", getParentId()) .append("parentId", getParentId())
.append("ancestors", getAncestors()) .append("ancestors", getAncestors())
.append("deptName", getDeptName()) .append("deptName", getDeptName())
.append("orderNum", getOrderNum()) .append("orderNum", getOrderNum())
.append("leader", getLeader()) .append("leader", getLeader())
.append("phone", getPhone()) .append("phone", getPhone())
.append("email", getEmail()) .append("email", getEmail())
.append("status", getStatus()) .append("status", getStatus())
.append("delFlag", getDelFlag()) .append("delFlag", getDelFlag())
.append("createBy", getCreateBy()) .append("createBy", getCreateBy())
.append("createTime", getCreateTime()) .append("createTime", getCreateTime())
.append("updateBy", getUpdateBy()) .append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime()) .append("updateTime", getUpdateTime())
.toString(); .toString();
} }
} }

@ -1,176 +1,175 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
import com.ruoyi.common.core.constant.UserConstants; import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
/** /**
* sys_dict_data * sys_dict_data
* *
* @author ruoyi * @author ruoyi
*/ */
public class SysDictData extends BaseEntity public class SysDictData extends BaseEntity {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 字典编码 */ /**
*
*/
@Excel(name = "字典编码", cellType = ColumnType.NUMERIC) @Excel(name = "字典编码", cellType = ColumnType.NUMERIC)
private Long dictCode; private Long dictCode;
/** 字典排序 */ /**
*
*/
@Excel(name = "字典排序", cellType = ColumnType.NUMERIC) @Excel(name = "字典排序", cellType = ColumnType.NUMERIC)
private Long dictSort; private Long dictSort;
/** 字典标签 */ /**
*
*/
@Excel(name = "字典标签") @Excel(name = "字典标签")
private String dictLabel; private String dictLabel;
/** 字典键值 */ /**
*
*/
@Excel(name = "字典键值") @Excel(name = "字典键值")
private String dictValue; private String dictValue;
/** 字典类型 */ /**
*
*/
@Excel(name = "字典类型") @Excel(name = "字典类型")
private String dictType; private String dictType;
/** 样式属性(其他样式扩展) */ /**
*
*/
private String cssClass; private String cssClass;
/** 表格字典样式 */ /**
*
*/
private String listClass; private String listClass;
/** 是否默认Y是 N否 */ /**
* Y N
*/
@Excel(name = "是否默认", readConverterExp = "Y=是,N=否") @Excel(name = "是否默认", readConverterExp = "Y=是,N=否")
private String isDefault; private String isDefault;
/** 状态0正常 1停用 */ /**
* 0 1
*/
@Excel(name = "状态", readConverterExp = "0=正常,1=停用") @Excel(name = "状态", readConverterExp = "0=正常,1=停用")
private String status; private String status;
public Long getDictCode() public Long getDictCode() {
{
return dictCode; return dictCode;
} }
public void setDictCode(Long dictCode) public void setDictCode(Long dictCode) {
{
this.dictCode = dictCode; this.dictCode = dictCode;
} }
public Long getDictSort() public Long getDictSort() {
{
return dictSort; return dictSort;
} }
public void setDictSort(Long dictSort) public void setDictSort(Long dictSort) {
{
this.dictSort = dictSort; this.dictSort = dictSort;
} }
@NotBlank(message = "字典标签不能为空") @NotBlank(message = "字典标签不能为空")
@Size(min = 0, max = 100, message = "字典标签长度不能超过100个字符") @Size(min = 0, max = 100, message = "字典标签长度不能超过100个字符")
public String getDictLabel() public String getDictLabel() {
{
return dictLabel; return dictLabel;
} }
public void setDictLabel(String dictLabel) public void setDictLabel(String dictLabel) {
{
this.dictLabel = dictLabel; this.dictLabel = dictLabel;
} }
@NotBlank(message = "字典键值不能为空") @NotBlank(message = "字典键值不能为空")
@Size(min = 0, max = 100, message = "字典键值长度不能超过100个字符") @Size(min = 0, max = 100, message = "字典键值长度不能超过100个字符")
public String getDictValue() public String getDictValue() {
{
return dictValue; return dictValue;
} }
public void setDictValue(String dictValue) public void setDictValue(String dictValue) {
{
this.dictValue = dictValue; this.dictValue = dictValue;
} }
@NotBlank(message = "字典类型不能为空") @NotBlank(message = "字典类型不能为空")
@Size(min = 0, max = 100, message = "字典类型长度不能超过100个字符") @Size(min = 0, max = 100, message = "字典类型长度不能超过100个字符")
public String getDictType() public String getDictType() {
{
return dictType; return dictType;
} }
public void setDictType(String dictType) public void setDictType(String dictType) {
{
this.dictType = dictType; this.dictType = dictType;
} }
@Size(min = 0, max = 100, message = "样式属性长度不能超过100个字符") @Size(min = 0, max = 100, message = "样式属性长度不能超过100个字符")
public String getCssClass() public String getCssClass() {
{
return cssClass; return cssClass;
} }
public void setCssClass(String cssClass) public void setCssClass(String cssClass) {
{
this.cssClass = cssClass; this.cssClass = cssClass;
} }
public String getListClass() public String getListClass() {
{
return listClass; return listClass;
} }
public void setListClass(String listClass) public void setListClass(String listClass) {
{
this.listClass = listClass; this.listClass = listClass;
} }
public boolean getDefault() public boolean getDefault() {
{
return UserConstants.YES.equals(this.isDefault) ? true : false; return UserConstants.YES.equals(this.isDefault) ? true : false;
} }
public String getIsDefault() public String getIsDefault() {
{
return isDefault; return isDefault;
} }
public void setIsDefault(String isDefault) public void setIsDefault(String isDefault) {
{
this.isDefault = isDefault; this.isDefault = isDefault;
} }
public String getStatus() public String getStatus() {
{
return status; return status;
} }
public void setStatus(String status) public void setStatus(String status) {
{
this.status = status; this.status = status;
} }
@Override @Override
public String toString() { public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("dictCode", getDictCode()) .append("dictCode", getDictCode())
.append("dictSort", getDictSort()) .append("dictSort", getDictSort())
.append("dictLabel", getDictLabel()) .append("dictLabel", getDictLabel())
.append("dictValue", getDictValue()) .append("dictValue", getDictValue())
.append("dictType", getDictType()) .append("dictType", getDictType())
.append("cssClass", getCssClass()) .append("cssClass", getCssClass())
.append("listClass", getListClass()) .append("listClass", getListClass())
.append("isDefault", getIsDefault()) .append("isDefault", getIsDefault())
.append("status", getStatus()) .append("status", getStatus())
.append("createBy", getCreateBy()) .append("createBy", getCreateBy())
.append("createTime", getCreateTime()) .append("createTime", getCreateTime())
.append("updateBy", getUpdateBy()) .append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime()) .append("updateTime", getUpdateTime())
.append("remark", getRemark()) .append("remark", getRemark())
.toString(); .toString();
} }
} }

@ -1,96 +1,96 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
/** /**
* sys_dict_type * sys_dict_type
* *
* @author ruoyi * @author ruoyi
*/ */
public class SysDictType extends BaseEntity public class SysDictType extends BaseEntity {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 字典主键 */ /**
*
*/
@Excel(name = "字典主键", cellType = ColumnType.NUMERIC) @Excel(name = "字典主键", cellType = ColumnType.NUMERIC)
private Long dictId; private Long dictId;
/** 字典名称 */ /**
*
*/
@Excel(name = "字典名称") @Excel(name = "字典名称")
private String dictName; private String dictName;
/** 字典类型 */ /**
*
*/
@Excel(name = "字典类型") @Excel(name = "字典类型")
private String dictType; private String dictType;
/** 状态0正常 1停用 */ /**
* 0 1
*/
@Excel(name = "状态", readConverterExp = "0=正常,1=停用") @Excel(name = "状态", readConverterExp = "0=正常,1=停用")
private String status; private String status;
public Long getDictId() public Long getDictId() {
{
return dictId; return dictId;
} }
public void setDictId(Long dictId) public void setDictId(Long dictId) {
{
this.dictId = dictId; this.dictId = dictId;
} }
@NotBlank(message = "字典名称不能为空") @NotBlank(message = "字典名称不能为空")
@Size(min = 0, max = 100, message = "字典类型名称长度不能超过100个字符") @Size(min = 0, max = 100, message = "字典类型名称长度不能超过100个字符")
public String getDictName() public String getDictName() {
{
return dictName; return dictName;
} }
public void setDictName(String dictName) public void setDictName(String dictName) {
{
this.dictName = dictName; this.dictName = dictName;
} }
@NotBlank(message = "字典类型不能为空") @NotBlank(message = "字典类型不能为空")
@Size(min = 0, max = 100, message = "字典类型类型长度不能超过100个字符") @Size(min = 0, max = 100, message = "字典类型类型长度不能超过100个字符")
@Pattern(regexp = "^[a-z][a-z0-9_]*$", message = "字典类型必须以字母开头,且只能为(小写字母,数字,下滑线)") @Pattern(regexp = "^[a-z][a-z0-9_]*$", message = "字典类型必须以字母开头,且只能为(小写字母,数字,下滑线)")
public String getDictType() public String getDictType() {
{
return dictType; return dictType;
} }
public void setDictType(String dictType) public void setDictType(String dictType) {
{
this.dictType = dictType; this.dictType = dictType;
} }
public String getStatus() public String getStatus() {
{
return status; return status;
} }
public void setStatus(String status) public void setStatus(String status) {
{
this.status = status; this.status = status;
} }
@Override @Override
public String toString() { public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("dictId", getDictId()) .append("dictId", getDictId())
.append("dictName", getDictName()) .append("dictName", getDictName())
.append("dictType", getDictType()) .append("dictType", getDictType())
.append("status", getStatus()) .append("status", getStatus())
.append("createBy", getCreateBy()) .append("createBy", getCreateBy())
.append("createTime", getCreateTime()) .append("createTime", getCreateTime())
.append("updateBy", getUpdateBy()) .append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime()) .append("updateTime", getUpdateTime())
.append("remark", getRemark()) .append("remark", getRemark())
.toString(); .toString();
} }
} }

@ -5,11 +5,10 @@ import org.apache.commons.lang3.builder.ToStringStyle;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class SysFile public class SysFile {
{
/** /**
* *
*/ */
@ -20,31 +19,27 @@ public class SysFile
*/ */
private String url; private String url;
public String getName() public String getName() {
{
return name; return name;
} }
public void setName(String name) public void setName(String name) {
{
this.name = name; this.name = name;
} }
public String getUrl() public String getUrl() {
{
return url; return url;
} }
public void setUrl(String url) public void setUrl(String url) {
{
this.url = url; this.url = url;
} }
@Override @Override
public String toString() { public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("name", getName()) .append("name", getName())
.append("url", getUrl()) .append("url", getUrl())
.toString(); .toString();
} }
} }

@ -1,102 +1,102 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import java.util.Date;
/** /**
* 访 sys_logininfor * 访 sys_logininfor
* *
* @author ruoyi * @author ruoyi
*/ */
public class SysLogininfor extends BaseEntity public class SysLogininfor extends BaseEntity {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** ID */ /**
* ID
*/
@Excel(name = "序号", cellType = ColumnType.NUMERIC) @Excel(name = "序号", cellType = ColumnType.NUMERIC)
private Long infoId; private Long infoId;
/** 用户账号 */ /**
*
*/
@Excel(name = "用户账号") @Excel(name = "用户账号")
private String userName; private String userName;
/** 状态 0成功 1失败 */ /**
* 0 1
*/
@Excel(name = "状态", readConverterExp = "0=成功,1=失败") @Excel(name = "状态", readConverterExp = "0=成功,1=失败")
private String status; private String status;
/** 地址 */ /**
*
*/
@Excel(name = "地址") @Excel(name = "地址")
private String ipaddr; private String ipaddr;
/** 描述 */ /**
*
*/
@Excel(name = "描述") @Excel(name = "描述")
private String msg; private String msg;
/** 访问时间 */ /**
* 访
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Excel(name = "访问时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") @Excel(name = "访问时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
private Date accessTime; private Date accessTime;
public Long getInfoId() public Long getInfoId() {
{
return infoId; return infoId;
} }
public void setInfoId(Long infoId) public void setInfoId(Long infoId) {
{
this.infoId = infoId; this.infoId = infoId;
} }
public String getUserName() public String getUserName() {
{
return userName; return userName;
} }
public void setUserName(String userName) public void setUserName(String userName) {
{
this.userName = userName; this.userName = userName;
} }
public String getStatus() public String getStatus() {
{
return status; return status;
} }
public void setStatus(String status) public void setStatus(String status) {
{
this.status = status; this.status = status;
} }
public String getIpaddr() public String getIpaddr() {
{
return ipaddr; return ipaddr;
} }
public void setIpaddr(String ipaddr) public void setIpaddr(String ipaddr) {
{
this.ipaddr = ipaddr; this.ipaddr = ipaddr;
} }
public String getMsg() public String getMsg() {
{
return msg; return msg;
} }
public void setMsg(String msg) public void setMsg(String msg) {
{
this.msg = msg; this.msg = msg;
} }
public Date getAccessTime() public Date getAccessTime() {
{
return accessTime; return accessTime;
} }
public void setAccessTime(Date accessTime) public void setAccessTime(Date accessTime) {
{
this.accessTime = accessTime; this.accessTime = accessTime;
} }
} }

@ -1,241 +1,241 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import java.util.Date;
/** /**
* oper_log * oper_log
* *
* @author ruoyi * @author ruoyi
*/ */
public class SysOperLog extends BaseEntity public class SysOperLog extends BaseEntity {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 日志主键 */ /**
*
*/
@Excel(name = "操作序号", cellType = ColumnType.NUMERIC) @Excel(name = "操作序号", cellType = ColumnType.NUMERIC)
private Long operId; private Long operId;
/** 操作模块 */ /**
*
*/
@Excel(name = "操作模块") @Excel(name = "操作模块")
private String title; private String title;
/** 业务类型0其它 1新增 2修改 3删除 */ /**
* 0 1 2 3
*/
@Excel(name = "业务类型", readConverterExp = "0=其它,1=新增,2=修改,3=删除,4=授权,5=导出,6=导入,7=强退,8=生成代码,9=清空数据") @Excel(name = "业务类型", readConverterExp = "0=其它,1=新增,2=修改,3=删除,4=授权,5=导出,6=导入,7=强退,8=生成代码,9=清空数据")
private Integer businessType; private Integer businessType;
/** 业务类型数组 */ /**
*
*/
private Integer[] businessTypes; private Integer[] businessTypes;
/** 请求方法 */ /**
*
*/
@Excel(name = "请求方法") @Excel(name = "请求方法")
private String method; private String method;
/** 请求方式 */ /**
*
*/
@Excel(name = "请求方式") @Excel(name = "请求方式")
private String requestMethod; private String requestMethod;
/** 操作类别0其它 1后台用户 2手机端用户 */ /**
* 0 1 2
*/
@Excel(name = "操作类别", readConverterExp = "0=其它,1=后台用户,2=手机端用户") @Excel(name = "操作类别", readConverterExp = "0=其它,1=后台用户,2=手机端用户")
private Integer operatorType; private Integer operatorType;
/** 操作人员 */ /**
*
*/
@Excel(name = "操作人员") @Excel(name = "操作人员")
private String operName; private String operName;
/** 部门名称 */ /**
*
*/
@Excel(name = "部门名称") @Excel(name = "部门名称")
private String deptName; private String deptName;
/** 请求url */ /**
* url
*/
@Excel(name = "请求地址") @Excel(name = "请求地址")
private String operUrl; private String operUrl;
/** 操作地址 */ /**
*
*/
@Excel(name = "操作地址") @Excel(name = "操作地址")
private String operIp; private String operIp;
/** 请求参数 */ /**
*
*/
@Excel(name = "请求参数") @Excel(name = "请求参数")
private String operParam; private String operParam;
/** 返回参数 */ /**
*
*/
@Excel(name = "返回参数") @Excel(name = "返回参数")
private String jsonResult; private String jsonResult;
/** 操作状态0正常 1异常 */ /**
* 0 1
*/
@Excel(name = "状态", readConverterExp = "0=正常,1=异常") @Excel(name = "状态", readConverterExp = "0=正常,1=异常")
private Integer status; private Integer status;
/** 错误消息 */ /**
*
*/
@Excel(name = "错误消息") @Excel(name = "错误消息")
private String errorMsg; private String errorMsg;
/** 操作时间 */ /**
*
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Excel(name = "操作时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") @Excel(name = "操作时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
private Date operTime; private Date operTime;
public Long getOperId() public Long getOperId() {
{
return operId; return operId;
} }
public void setOperId(Long operId) public void setOperId(Long operId) {
{
this.operId = operId; this.operId = operId;
} }
public String getTitle() public String getTitle() {
{
return title; return title;
} }
public void setTitle(String title) public void setTitle(String title) {
{
this.title = title; this.title = title;
} }
public Integer getBusinessType() public Integer getBusinessType() {
{
return businessType; return businessType;
} }
public void setBusinessType(Integer businessType) public void setBusinessType(Integer businessType) {
{
this.businessType = businessType; this.businessType = businessType;
} }
public Integer[] getBusinessTypes() public Integer[] getBusinessTypes() {
{
return businessTypes; return businessTypes;
} }
public void setBusinessTypes(Integer[] businessTypes) public void setBusinessTypes(Integer[] businessTypes) {
{
this.businessTypes = businessTypes; this.businessTypes = businessTypes;
} }
public String getMethod() public String getMethod() {
{
return method; return method;
} }
public void setMethod(String method) public void setMethod(String method) {
{
this.method = method; this.method = method;
} }
public String getRequestMethod() public String getRequestMethod() {
{
return requestMethod; return requestMethod;
} }
public void setRequestMethod(String requestMethod) public void setRequestMethod(String requestMethod) {
{
this.requestMethod = requestMethod; this.requestMethod = requestMethod;
} }
public Integer getOperatorType() public Integer getOperatorType() {
{
return operatorType; return operatorType;
} }
public void setOperatorType(Integer operatorType) public void setOperatorType(Integer operatorType) {
{
this.operatorType = operatorType; this.operatorType = operatorType;
} }
public String getOperName() public String getOperName() {
{
return operName; return operName;
} }
public void setOperName(String operName) public void setOperName(String operName) {
{
this.operName = operName; this.operName = operName;
} }
public String getDeptName() public String getDeptName() {
{
return deptName; return deptName;
} }
public void setDeptName(String deptName) public void setDeptName(String deptName) {
{
this.deptName = deptName; this.deptName = deptName;
} }
public String getOperUrl() public String getOperUrl() {
{
return operUrl; return operUrl;
} }
public void setOperUrl(String operUrl) public void setOperUrl(String operUrl) {
{
this.operUrl = operUrl; this.operUrl = operUrl;
} }
public String getOperIp() public String getOperIp() {
{
return operIp; return operIp;
} }
public void setOperIp(String operIp) public void setOperIp(String operIp) {
{
this.operIp = operIp; this.operIp = operIp;
} }
public String getOperParam() public String getOperParam() {
{
return operParam; return operParam;
} }
public void setOperParam(String operParam) public void setOperParam(String operParam) {
{
this.operParam = operParam; this.operParam = operParam;
} }
public String getJsonResult() public String getJsonResult() {
{
return jsonResult; return jsonResult;
} }
public void setJsonResult(String jsonResult) public void setJsonResult(String jsonResult) {
{
this.jsonResult = jsonResult; this.jsonResult = jsonResult;
} }
public Integer getStatus() public Integer getStatus() {
{
return status; return status;
} }
public void setStatus(Integer status) public void setStatus(Integer status) {
{
this.status = status; this.status = status;
} }
public String getErrorMsg() public String getErrorMsg() {
{
return errorMsg; return errorMsg;
} }
public void setErrorMsg(String errorMsg) public void setErrorMsg(String errorMsg) {
{
this.errorMsg = errorMsg; this.errorMsg = errorMsg;
} }
public Date getOperTime() public Date getOperTime() {
{
return operTime; return operTime;
} }
public void setOperTime(Date operTime) public void setOperTime(Date operTime) {
{
this.operTime = operTime; this.operTime = operTime;
} }
} }

@ -1,226 +1,222 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
/** /**
* sys_role * sys_role
* *
* @author ruoyi * @author ruoyi
*/ */
public class SysRole extends BaseEntity public class SysRole extends BaseEntity {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 角色ID */ /**
* ID
*/
@Excel(name = "角色序号", cellType = ColumnType.NUMERIC) @Excel(name = "角色序号", cellType = ColumnType.NUMERIC)
private Long roleId; private Long roleId;
/** 角色名称 */ /**
*
*/
@Excel(name = "角色名称") @Excel(name = "角色名称")
private String roleName; private String roleName;
/** 角色权限 */ /**
*
*/
@Excel(name = "角色权限") @Excel(name = "角色权限")
private String roleKey; private String roleKey;
/** 角色排序 */ /**
*
*/
@Excel(name = "角色排序") @Excel(name = "角色排序")
private String roleSort; private String roleSort;
/** 数据范围1所有数据权限2自定义数据权限3本部门数据权限4本部门及以下数据权限5仅本人数据权限 */ /**
* 12345
*/
@Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限,5=仅本人数据权限") @Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限,5=仅本人数据权限")
private String dataScope; private String dataScope;
/** 菜单树选择项是否关联显示( 0父子不互相关联显示 1父子互相关联显示 */ /**
* 0 1
*/
private boolean menuCheckStrictly; private boolean menuCheckStrictly;
/** 部门树选择项是否关联显示0父子不互相关联显示 1父子互相关联显示 */ /**
* 0 1
*/
private boolean deptCheckStrictly; private boolean deptCheckStrictly;
/** 角色状态0正常 1停用 */ /**
* 0 1
*/
@Excel(name = "角色状态", readConverterExp = "0=正常,1=停用") @Excel(name = "角色状态", readConverterExp = "0=正常,1=停用")
private String status; private String status;
/** 删除标志0代表存在 2代表删除 */ /**
* 0 2
*/
private String delFlag; private String delFlag;
/** 用户是否存在此角色标识 默认不存在 */ /**
*
*/
private boolean flag = false; private boolean flag = false;
/** 菜单组 */ /**
*
*/
private Long[] menuIds; private Long[] menuIds;
/** 部门组(数据权限) */ /**
*
*/
private Long[] deptIds; private Long[] deptIds;
public SysRole() public SysRole() {
{
} }
public SysRole(Long roleId) public SysRole(Long roleId) {
{
this.roleId = roleId; this.roleId = roleId;
} }
public Long getRoleId() public static boolean isAdmin(Long roleId) {
{ return roleId != null && 1L == roleId;
}
public Long getRoleId() {
return roleId; return roleId;
} }
public void setRoleId(Long roleId) public void setRoleId(Long roleId) {
{
this.roleId = roleId; this.roleId = roleId;
} }
public boolean isAdmin() public boolean isAdmin() {
{
return isAdmin(this.roleId); return isAdmin(this.roleId);
} }
public static boolean isAdmin(Long roleId)
{
return roleId != null && 1L == roleId;
}
@NotBlank(message = "角色名称不能为空") @NotBlank(message = "角色名称不能为空")
@Size(min = 0, max = 30, message = "角色名称长度不能超过30个字符") @Size(min = 0, max = 30, message = "角色名称长度不能超过30个字符")
public String getRoleName() public String getRoleName() {
{
return roleName; return roleName;
} }
public void setRoleName(String roleName) public void setRoleName(String roleName) {
{
this.roleName = roleName; this.roleName = roleName;
} }
@NotBlank(message = "权限字符不能为空") @NotBlank(message = "权限字符不能为空")
@Size(min = 0, max = 100, message = "权限字符长度不能超过100个字符") @Size(min = 0, max = 100, message = "权限字符长度不能超过100个字符")
public String getRoleKey() public String getRoleKey() {
{
return roleKey; return roleKey;
} }
public void setRoleKey(String roleKey) public void setRoleKey(String roleKey) {
{
this.roleKey = roleKey; this.roleKey = roleKey;
} }
@NotBlank(message = "显示顺序不能为空") @NotBlank(message = "显示顺序不能为空")
public String getRoleSort() public String getRoleSort() {
{
return roleSort; return roleSort;
} }
public void setRoleSort(String roleSort) public void setRoleSort(String roleSort) {
{
this.roleSort = roleSort; this.roleSort = roleSort;
} }
public String getDataScope() public String getDataScope() {
{
return dataScope; return dataScope;
} }
public void setDataScope(String dataScope) public void setDataScope(String dataScope) {
{
this.dataScope = dataScope; this.dataScope = dataScope;
} }
public boolean isMenuCheckStrictly() public boolean isMenuCheckStrictly() {
{
return menuCheckStrictly; return menuCheckStrictly;
} }
public void setMenuCheckStrictly(boolean menuCheckStrictly) public void setMenuCheckStrictly(boolean menuCheckStrictly) {
{
this.menuCheckStrictly = menuCheckStrictly; this.menuCheckStrictly = menuCheckStrictly;
} }
public boolean isDeptCheckStrictly() public boolean isDeptCheckStrictly() {
{
return deptCheckStrictly; return deptCheckStrictly;
} }
public void setDeptCheckStrictly(boolean deptCheckStrictly) public void setDeptCheckStrictly(boolean deptCheckStrictly) {
{
this.deptCheckStrictly = deptCheckStrictly; this.deptCheckStrictly = deptCheckStrictly;
} }
public String getStatus() public String getStatus() {
{
return status; return status;
} }
public void setStatus(String status) public void setStatus(String status) {
{
this.status = status; this.status = status;
} }
public String getDelFlag() public String getDelFlag() {
{
return delFlag; return delFlag;
} }
public void setDelFlag(String delFlag) public void setDelFlag(String delFlag) {
{
this.delFlag = delFlag; this.delFlag = delFlag;
} }
public boolean isFlag() public boolean isFlag() {
{
return flag; return flag;
} }
public void setFlag(boolean flag) public void setFlag(boolean flag) {
{
this.flag = flag; this.flag = flag;
} }
public Long[] getMenuIds() public Long[] getMenuIds() {
{
return menuIds; return menuIds;
} }
public void setMenuIds(Long[] menuIds) public void setMenuIds(Long[] menuIds) {
{
this.menuIds = menuIds; this.menuIds = menuIds;
} }
public Long[] getDeptIds() public Long[] getDeptIds() {
{
return deptIds; return deptIds;
} }
public void setDeptIds(Long[] deptIds) public void setDeptIds(Long[] deptIds) {
{
this.deptIds = deptIds; this.deptIds = deptIds;
} }
@Override @Override
public String toString() { public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("roleId", getRoleId()) .append("roleId", getRoleId())
.append("roleName", getRoleName()) .append("roleName", getRoleName())
.append("roleKey", getRoleKey()) .append("roleKey", getRoleKey())
.append("roleSort", getRoleSort()) .append("roleSort", getRoleSort())
.append("dataScope", getDataScope()) .append("dataScope", getDataScope())
.append("menuCheckStrictly", isMenuCheckStrictly()) .append("menuCheckStrictly", isMenuCheckStrictly())
.append("deptCheckStrictly", isDeptCheckStrictly()) .append("deptCheckStrictly", isDeptCheckStrictly())
.append("status", getStatus()) .append("status", getStatus())
.append("delFlag", getDelFlag()) .append("delFlag", getDelFlag())
.append("createBy", getCreateBy()) .append("createBy", getCreateBy())
.append("createTime", getCreateTime()) .append("createTime", getCreateTime())
.append("updateBy", getUpdateBy()) .append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime()) .append("updateTime", getUpdateTime())
.append("remark", getRemark()) .append("remark", getRemark())
.toString(); .toString();
} }
} }

@ -1,10 +1,5 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.*;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
@ -12,314 +7,318 @@ import com.ruoyi.common.core.annotation.Excel.Type;
import com.ruoyi.common.core.annotation.Excels; import com.ruoyi.common.core.annotation.Excels;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import com.ruoyi.common.core.xss.Xss; import com.ruoyi.common.core.xss.Xss;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.List;
/** /**
* sys_user * sys_user
* *
* @author ruoyi * @author ruoyi
*/ */
public class SysUser extends BaseEntity public class SysUser extends BaseEntity {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 用户ID */ /**
* ID
*/
@Excel(name = "用户序号", cellType = ColumnType.NUMERIC, prompt = "用户编号") @Excel(name = "用户序号", cellType = ColumnType.NUMERIC, prompt = "用户编号")
private Long userId; private Long userId;
/** 部门ID */ /**
* ID
*/
@Excel(name = "部门编号", type = Type.IMPORT) @Excel(name = "部门编号", type = Type.IMPORT)
private Long deptId; private Long deptId;
/** 用户账号 */ /**
*
*/
@Excel(name = "登录名称") @Excel(name = "登录名称")
private String userName; private String userName;
/** 用户昵称 */ /**
*
*/
@Excel(name = "用户名称") @Excel(name = "用户名称")
private String nickName; private String nickName;
/** 用户邮箱 */ /**
*
*/
@Excel(name = "用户邮箱") @Excel(name = "用户邮箱")
private String email; private String email;
/** 手机号码 */ /**
*
*/
@Excel(name = "手机号码") @Excel(name = "手机号码")
private String phonenumber; private String phonenumber;
/** 用户性别 */ /**
*
*/
@Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知") @Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知")
private String sex; private String sex;
/** 用户头像 */ /**
*
*/
private String avatar; private String avatar;
/** 密码 */ /**
*
*/
private String password; private String password;
/** 帐号状态0正常 1停用 */ /**
* 0 1
*/
@Excel(name = "帐号状态", readConverterExp = "0=正常,1=停用") @Excel(name = "帐号状态", readConverterExp = "0=正常,1=停用")
private String status; private String status;
/** 删除标志0代表存在 2代表删除 */ /**
* 0 2
*/
private String delFlag; private String delFlag;
/** 最后登录IP */ /**
* IP
*/
@Excel(name = "最后登录IP", type = Type.EXPORT) @Excel(name = "最后登录IP", type = Type.EXPORT)
private String loginIp; private String loginIp;
/** 最后登录时间 */ /**
*
*/
@Excel(name = "最后登录时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Type.EXPORT) @Excel(name = "最后登录时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Type.EXPORT)
private Date loginDate; private Date loginDate;
/** 部门对象 */ /**
*
*/
@Excels({ @Excels({
@Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT), @Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT),
@Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT) @Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT)
}) })
private SysDept dept; private SysDept dept;
/** 角色对象 */ /**
*
*/
private List<SysRole> roles; private List<SysRole> roles;
/** 角色组 */ /**
*
*/
private Long[] roleIds; private Long[] roleIds;
/** 岗位组 */ /**
*
*/
private Long[] postIds; private Long[] postIds;
/** 角色ID */ /**
* ID
*/
private Long roleId; private Long roleId;
public SysUser() public SysUser() {
{
} }
public SysUser(Long userId) public SysUser(Long userId) {
{
this.userId = userId; this.userId = userId;
} }
public Long getUserId() public static boolean isAdmin(Long userId) {
{ return userId != null && 1L == userId;
}
public Long getUserId() {
return userId; return userId;
} }
public void setUserId(Long userId) public void setUserId(Long userId) {
{
this.userId = userId; this.userId = userId;
} }
public boolean isAdmin() public boolean isAdmin() {
{
return isAdmin(this.userId); return isAdmin(this.userId);
} }
public static boolean isAdmin(Long userId) public Long getDeptId() {
{
return userId != null && 1L == userId;
}
public Long getDeptId()
{
return deptId; return deptId;
} }
public void setDeptId(Long deptId) public void setDeptId(Long deptId) {
{
this.deptId = deptId; this.deptId = deptId;
} }
@Xss(message = "用户昵称不能包含脚本字符") @Xss(message = "用户昵称不能包含脚本字符")
@Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符") @Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符")
public String getNickName() public String getNickName() {
{
return nickName; return nickName;
} }
public void setNickName(String nickName) public void setNickName(String nickName) {
{
this.nickName = nickName; this.nickName = nickName;
} }
@Xss(message = "用户账号不能包含脚本字符") @Xss(message = "用户账号不能包含脚本字符")
@NotBlank(message = "用户账号不能为空") @NotBlank(message = "用户账号不能为空")
@Size(min = 0, max = 30, message = "用户账号长度不能超过30个字符") @Size(min = 0, max = 30, message = "用户账号长度不能超过30个字符")
public String getUserName() public String getUserName() {
{
return userName; return userName;
} }
public void setUserName(String userName) public void setUserName(String userName) {
{
this.userName = userName; this.userName = userName;
} }
@Email(message = "邮箱格式不正确") @Email(message = "邮箱格式不正确")
@Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符") @Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
public String getEmail() public String getEmail() {
{
return email; return email;
} }
public void setEmail(String email) public void setEmail(String email) {
{
this.email = email; this.email = email;
} }
@Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符") @Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符")
public String getPhonenumber() public String getPhonenumber() {
{
return phonenumber; return phonenumber;
} }
public void setPhonenumber(String phonenumber) public void setPhonenumber(String phonenumber) {
{
this.phonenumber = phonenumber; this.phonenumber = phonenumber;
} }
public String getSex() public String getSex() {
{
return sex; return sex;
} }
public void setSex(String sex) public void setSex(String sex) {
{
this.sex = sex; this.sex = sex;
} }
public String getAvatar() public String getAvatar() {
{
return avatar; return avatar;
} }
public void setAvatar(String avatar) public void setAvatar(String avatar) {
{
this.avatar = avatar; this.avatar = avatar;
} }
@JsonProperty @JsonProperty
public String getPassword() public String getPassword() {
{
return password; return password;
} }
public void setPassword(String password) public void setPassword(String password) {
{
this.password = password; this.password = password;
} }
public String getStatus() public String getStatus() {
{
return status; return status;
} }
public void setStatus(String status) public void setStatus(String status) {
{
this.status = status; this.status = status;
} }
public String getDelFlag() public String getDelFlag() {
{
return delFlag; return delFlag;
} }
public void setDelFlag(String delFlag) public void setDelFlag(String delFlag) {
{
this.delFlag = delFlag; this.delFlag = delFlag;
} }
public String getLoginIp() public String getLoginIp() {
{
return loginIp; return loginIp;
} }
public void setLoginIp(String loginIp) public void setLoginIp(String loginIp) {
{
this.loginIp = loginIp; this.loginIp = loginIp;
} }
public Date getLoginDate() public Date getLoginDate() {
{
return loginDate; return loginDate;
} }
public void setLoginDate(Date loginDate) public void setLoginDate(Date loginDate) {
{
this.loginDate = loginDate; this.loginDate = loginDate;
} }
public SysDept getDept() public SysDept getDept() {
{
return dept; return dept;
} }
public void setDept(SysDept dept) public void setDept(SysDept dept) {
{
this.dept = dept; this.dept = dept;
} }
public List<SysRole> getRoles() public List<SysRole> getRoles() {
{
return roles; return roles;
} }
public void setRoles(List<SysRole> roles) public void setRoles(List<SysRole> roles) {
{
this.roles = roles; this.roles = roles;
} }
public Long[] getRoleIds() public Long[] getRoleIds() {
{
return roleIds; return roleIds;
} }
public void setRoleIds(Long[] roleIds) public void setRoleIds(Long[] roleIds) {
{
this.roleIds = roleIds; this.roleIds = roleIds;
} }
public Long[] getPostIds() public Long[] getPostIds() {
{
return postIds; return postIds;
} }
public void setPostIds(Long[] postIds) public void setPostIds(Long[] postIds) {
{
this.postIds = postIds; this.postIds = postIds;
} }
public Long getRoleId() public Long getRoleId() {
{
return roleId; return roleId;
} }
public void setRoleId(Long roleId) public void setRoleId(Long roleId) {
{
this.roleId = roleId; this.roleId = roleId;
} }
@Override @Override
public String toString() { public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("userId", getUserId()) .append("userId", getUserId())
.append("deptId", getDeptId()) .append("deptId", getDeptId())
.append("userName", getUserName()) .append("userName", getUserName())
.append("nickName", getNickName()) .append("nickName", getNickName())
.append("email", getEmail()) .append("email", getEmail())
.append("phonenumber", getPhonenumber()) .append("phonenumber", getPhonenumber())
.append("sex", getSex()) .append("sex", getSex())
.append("avatar", getAvatar()) .append("avatar", getAvatar())
.append("password", getPassword()) .append("password", getPassword())
.append("status", getStatus()) .append("status", getStatus())
.append("delFlag", getDelFlag()) .append("delFlag", getDelFlag())
.append("loginIp", getLoginIp()) .append("loginIp", getLoginIp())
.append("loginDate", getLoginDate()) .append("loginDate", getLoginDate())
.append("createBy", getCreateBy()) .append("createBy", getCreateBy())
.append("createTime", getCreateTime()) .append("createTime", getCreateTime())
.append("updateBy", getUpdateBy()) .append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime()) .append("updateTime", getUpdateTime())
.append("remark", getRemark()) .append("remark", getRemark())
.append("dept", getDept()) .append("dept", getDept())
.toString(); .toString();
} }
} }

@ -1,34 +1,30 @@
package com.ruoyi.system.api.factory; package com.ruoyi.system.api.factory;
import com.ruoyi.common.core.domain.Rust;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.SysFile;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.SysFile;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@Component @Component
public class RemoteFileFallbackFactory implements FallbackFactory<RemoteFileService> public class RemoteFileFallbackFactory implements FallbackFactory<RemoteFileService> {
{
private static final Logger log = LoggerFactory.getLogger(RemoteFileFallbackFactory.class); private static final Logger log = LoggerFactory.getLogger(RemoteFileFallbackFactory.class);
@Override @Override
public RemoteFileService create(Throwable throwable) public RemoteFileService create(Throwable throwable) {
{
log.error("文件服务调用失败:{}", throwable.getMessage()); log.error("文件服务调用失败:{}", throwable.getMessage());
return new RemoteFileService() return new RemoteFileService() {
{
@Override @Override
public R<SysFile> upload(MultipartFile file) public Rust<SysFile> upload(MultipartFile file) {
{ return Rust.fail("上传文件失败:" + throwable.getMessage());
return R.fail("上传文件失败:" + throwable.getMessage());
} }
}; };
} }

@ -1,39 +1,34 @@
package com.ruoyi.system.api.factory; package com.ruoyi.system.api.factory;
import com.ruoyi.common.core.domain.Rust;
import com.ruoyi.system.api.RemoteLogService;
import com.ruoyi.system.api.domain.SysLogininfor;
import com.ruoyi.system.api.domain.SysOperLog;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.RemoteLogService;
import com.ruoyi.system.api.domain.SysLogininfor;
import com.ruoyi.system.api.domain.SysOperLog;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@Component @Component
public class RemoteLogFallbackFactory implements FallbackFactory<RemoteLogService> public class RemoteLogFallbackFactory implements FallbackFactory<RemoteLogService> {
{
private static final Logger log = LoggerFactory.getLogger(RemoteLogFallbackFactory.class); private static final Logger log = LoggerFactory.getLogger(RemoteLogFallbackFactory.class);
@Override @Override
public RemoteLogService create(Throwable throwable) public RemoteLogService create(Throwable throwable) {
{
log.error("日志服务调用失败:{}", throwable.getMessage()); log.error("日志服务调用失败:{}", throwable.getMessage());
return new RemoteLogService() return new RemoteLogService() {
{
@Override @Override
public R<Boolean> saveLog(SysOperLog sysOperLog, String source) public Rust<Boolean> saveLog(SysOperLog sysOperLog, String source) {
{
return null; return null;
} }
@Override @Override
public R<Boolean> saveLogininfor(SysLogininfor sysLogininfor, String source) public Rust<Boolean> saveLogininfor(SysLogininfor sysLogininfor, String source) {
{
return null; return null;
} }
}; };

@ -1,40 +1,35 @@
package com.ruoyi.system.api.factory; package com.ruoyi.system.api.factory;
import com.ruoyi.common.core.domain.Rust;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@Component @Component
public class RemoteUserFallbackFactory implements FallbackFactory<RemoteUserService> public class RemoteUserFallbackFactory implements FallbackFactory<RemoteUserService> {
{
private static final Logger log = LoggerFactory.getLogger(RemoteUserFallbackFactory.class); private static final Logger log = LoggerFactory.getLogger(RemoteUserFallbackFactory.class);
@Override @Override
public RemoteUserService create(Throwable throwable) public RemoteUserService create(Throwable throwable) {
{
log.error("用户服务调用失败:{}", throwable.getMessage()); log.error("用户服务调用失败:{}", throwable.getMessage());
return new RemoteUserService() return new RemoteUserService() {
{
@Override @Override
public R<LoginUser> getUserInfo(String username, String source) public Rust<LoginUser> getUserInfo(String username, String source) {
{ return Rust.fail("获取用户失败:" + throwable.getMessage());
return R.fail("获取用户失败:" + throwable.getMessage());
} }
@Override @Override
public R<Boolean> registerUserInfo(SysUser sysUser, String source) public Rust<Boolean> registerUserInfo(SysUser sysUser, String source) {
{ return Rust.fail("注册用户失败:" + throwable.getMessage());
return R.fail("注册用户失败:" + throwable.getMessage());
} }
}; };
} }

@ -1,16 +1,16 @@
package com.ruoyi.system.api.model; package com.ruoyi.system.api.model;
import com.ruoyi.system.api.domain.SysUser;
import java.io.Serializable; import java.io.Serializable;
import java.util.Set; import java.util.Set;
import com.ruoyi.system.api.domain.SysUser;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class LoginUser implements Serializable public class LoginUser implements Serializable {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
@ -58,93 +58,75 @@ public class LoginUser implements Serializable
*/ */
private SysUser sysUser; private SysUser sysUser;
public String getToken() public String getToken() {
{
return token; return token;
} }
public void setToken(String token) public void setToken(String token) {
{
this.token = token; this.token = token;
} }
public Long getUserid() public Long getUserid() {
{
return userid; return userid;
} }
public void setUserid(Long userid) public void setUserid(Long userid) {
{
this.userid = userid; this.userid = userid;
} }
public String getUsername() public String getUsername() {
{
return username; return username;
} }
public void setUsername(String username) public void setUsername(String username) {
{
this.username = username; this.username = username;
} }
public Long getLoginTime() public Long getLoginTime() {
{
return loginTime; return loginTime;
} }
public void setLoginTime(Long loginTime) public void setLoginTime(Long loginTime) {
{
this.loginTime = loginTime; this.loginTime = loginTime;
} }
public Long getExpireTime() public Long getExpireTime() {
{
return expireTime; return expireTime;
} }
public void setExpireTime(Long expireTime) public void setExpireTime(Long expireTime) {
{
this.expireTime = expireTime; this.expireTime = expireTime;
} }
public String getIpaddr() public String getIpaddr() {
{
return ipaddr; return ipaddr;
} }
public void setIpaddr(String ipaddr) public void setIpaddr(String ipaddr) {
{
this.ipaddr = ipaddr; this.ipaddr = ipaddr;
} }
public Set<String> getPermissions() public Set<String> getPermissions() {
{
return permissions; return permissions;
} }
public void setPermissions(Set<String> permissions) public void setPermissions(Set<String> permissions) {
{
this.permissions = permissions; this.permissions = permissions;
} }
public Set<String> getRoles() public Set<String> getRoles() {
{
return roles; return roles;
} }
public void setRoles(Set<String> roles) public void setRoles(Set<String> roles) {
{
this.roles = roles; this.roles = roles;
} }
public SysUser getSysUser() public SysUser getSysUser() {
{
return sysUser; return sysUser;
} }
public void setSysUser(SysUser sysUser) public void setSysUser(SysUser sysUser) {
{
this.sysUser = sysUser; this.sysUser = sysUser;
} }
} }

@ -60,6 +60,7 @@
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.6</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>

@ -1,21 +1,19 @@
package com.ruoyi.auth; package com.ruoyi.auth;
import com.ruoyi.common.security.annotation.EnableRyFeignClients;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import com.ruoyi.common.security.annotation.EnableRyFeignClients;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@EnableRyFeignClients @EnableRyFeignClients
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class }) @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class RuoYiAuthApplication public class RuoYiAuthApplication {
{ public static void main(String[] args) {
public static void main(String[] args)
{
SpringApplication.run(RuoYiAuthApplication.class, args); SpringApplication.run(RuoYiAuthApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 认证授权中心启动成功 ლ(´ڡ`ლ)゙ \n" + System.out.println("(♥◠‿◠)ノ゙ 认证授权中心启动成功 ლ(´ڡ`ლ)゙ \n" +
" .-------. ____ __ \n" + " .-------. ____ __ \n" +

@ -1,30 +1,30 @@
package com.ruoyi.auth.controller; package com.ruoyi.auth.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.auth.form.LoginBody; import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.RegisterBody; import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.service.SysLoginService; import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.Rust;
import com.ruoyi.common.core.utils.JwtUtils; import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils; import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil; import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService; import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils; import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser; import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/** /**
* token * token
* *
* @author ruoyi * @author ruoyi
*/ */
@RestController @RestController
public class TokenController public class TokenController {
{
@Autowired @Autowired
private TokenService tokenService; private TokenService tokenService;
@ -32,47 +32,41 @@ public class TokenController
private SysLoginService sysLoginService; private SysLoginService sysLoginService;
@PostMapping("login") @PostMapping("login")
public R<?> login(@RequestBody LoginBody form) public Rust<?> login(@RequestBody LoginBody form) {
{
// 用户登录 // 用户登录
LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword()); LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
// 获取登录token // 获取登录token
return R.ok(tokenService.createToken(userInfo)); return Rust.ok(tokenService.createToken(userInfo));
} }
@DeleteMapping("logout") @DeleteMapping("logout")
public R<?> logout(HttpServletRequest request) public Rust<?> logout(HttpServletRequest request) {
{
String token = SecurityUtils.getToken(request); String token = SecurityUtils.getToken(request);
if (StringUtils.isNotEmpty(token)) if (StringUtils.isNotEmpty(token)) {
{
String username = JwtUtils.getUserName(token); String username = JwtUtils.getUserName(token);
// 删除用户缓存记录 // 删除用户缓存记录
AuthUtil.logoutByToken(token); AuthUtil.logoutByToken(token);
// 记录用户退出日志 // 记录用户退出日志
sysLoginService.logout(username); sysLoginService.logout(username);
} }
return R.ok(); return Rust.ok();
} }
@PostMapping("refresh") @PostMapping("refresh")
public R<?> refresh(HttpServletRequest request) public Rust<?> refresh(HttpServletRequest request) {
{
LoginUser loginUser = tokenService.getLoginUser(request); LoginUser loginUser = tokenService.getLoginUser(request);
if (StringUtils.isNotNull(loginUser)) if (StringUtils.isNotNull(loginUser)) {
{
// 刷新令牌有效期 // 刷新令牌有效期
tokenService.refreshToken(loginUser); tokenService.refreshToken(loginUser);
return R.ok(); return Rust.ok();
} }
return R.ok(); return Rust.ok();
} }
@PostMapping("register") @PostMapping("register")
public R<?> register(@RequestBody RegisterBody registerBody) public Rust<?> register(@RequestBody RegisterBody registerBody) {
{
// 用户注册 // 用户注册
sysLoginService.register(registerBody.getUsername(), registerBody.getPassword()); sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
return R.ok(); return Rust.ok();
} }
} }

@ -2,11 +2,10 @@ package com.ruoyi.auth.form;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class LoginBody public class LoginBody {
{
/** /**
* *
*/ */
@ -17,23 +16,19 @@ public class LoginBody
*/ */
private String password; private String password;
public String getUsername() public String getUsername() {
{
return username; return username;
} }
public void setUsername(String username) public void setUsername(String username) {
{
this.username = username; this.username = username;
} }
public String getPassword() public String getPassword() {
{
return password; return password;
} }
public void setPassword(String password) public void setPassword(String password) {
{
this.password = password; this.password = password;
} }
} }

@ -2,10 +2,9 @@ package com.ruoyi.auth.form;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class RegisterBody extends LoginBody public class RegisterBody extends LoginBody {
{
} }

@ -1,11 +1,9 @@
package com.ruoyi.auth.service; package com.ruoyi.auth.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.constant.Constants; import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.SecurityConstants; import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.UserConstants; import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.Rust;
import com.ruoyi.common.core.enums.UserStatus; import com.ruoyi.common.core.enums.UserStatus;
import com.ruoyi.common.core.exception.ServiceException; import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.ServletUtils; import com.ruoyi.common.core.utils.ServletUtils;
@ -17,73 +15,66 @@ import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysLogininfor; import com.ruoyi.system.api.domain.SysLogininfor;
import com.ruoyi.system.api.domain.SysUser; import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser; import com.ruoyi.system.api.model.LoginUser;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@Component @Component
public class SysLoginService public class SysLoginService {
{ @Resource
@Autowired
private RemoteLogService remoteLogService; private RemoteLogService remoteLogService;
@Autowired @Resource
private RemoteUserService remoteUserService; private RemoteUserService remoteUserService;
/** /**
* *
*/ */
public LoginUser login(String username, String password) public LoginUser login(String username, String password) {
{
// 用户名或密码为空 错误 // 用户名或密码为空 错误
if (StringUtils.isAnyBlank(username, password)) if (StringUtils.isAnyBlank(username, password)) {
{
recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写"); recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
throw new ServiceException("用户/密码必须填写"); throw new ServiceException("用户/密码必须填写");
} }
// 密码如果不在指定范围内 错误 // 密码如果不在指定范围内 错误
if (password.length() < UserConstants.PASSWORD_MIN_LENGTH if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH) || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
{
recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围"); recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
throw new ServiceException("用户密码不在指定范围"); throw new ServiceException("用户密码不在指定范围");
} }
// 用户名不在指定范围内 错误 // 用户名不在指定范围内 错误
if (username.length() < UserConstants.USERNAME_MIN_LENGTH if (username.length() < UserConstants.USERNAME_MIN_LENGTH
|| username.length() > UserConstants.USERNAME_MAX_LENGTH) || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
{
recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围"); recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
throw new ServiceException("用户名不在指定范围"); throw new ServiceException("用户名不在指定范围");
} }
// 查询用户信息 // 查询用户信息
R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER); Rust<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
if (R.FAIL == userResult.getCode()) if (Rust.FAIL == userResult.getCode()) {
{
throw new ServiceException(userResult.getMsg()); throw new ServiceException(userResult.getMsg());
} }
if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
{
recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在"); recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
throw new ServiceException("登录用户:" + username + " 不存在"); throw new ServiceException("登录用户:" + username + " 不存在");
} }
LoginUser userInfo = userResult.getData(); LoginUser userInfo = userResult.getData();
SysUser user = userResult.getData().getSysUser(); SysUser user = userResult.getData().getSysUser();
if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
{
recordLogininfor(username, Constants.LOGIN_FAIL, "对不起,您的账号已被删除"); recordLogininfor(username, Constants.LOGIN_FAIL, "对不起,您的账号已被删除");
throw new ServiceException("对不起,您的账号:" + username + " 已被删除"); throw new ServiceException("对不起,您的账号:" + username + " 已被删除");
} }
if (UserStatus.DISABLE.getCode().equals(user.getStatus())) if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
{
recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用,请联系管理员"); recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用,请联系管理员");
throw new ServiceException("对不起,您的账号:" + username + " 已停用"); throw new ServiceException("对不起,您的账号:" + username + " 已停用");
} }
if (!SecurityUtils.matchesPassword(password, user.getPassword())) if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
{
recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码错误"); recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码错误");
throw new ServiceException("用户不存在/密码错误"); throw new ServiceException("用户不存在/密码错误");
} }
@ -91,29 +82,24 @@ public class SysLoginService
return userInfo; return userInfo;
} }
public void logout(String loginName) public void logout(String loginName) {
{
recordLogininfor(loginName, Constants.LOGOUT, "退出成功"); recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
} }
/** /**
* *
*/ */
public void register(String username, String password) public void register(String username, String password) {
{
// 用户名或密码为空 错误 // 用户名或密码为空 错误
if (StringUtils.isAnyBlank(username, password)) if (StringUtils.isAnyBlank(username, password)) {
{
throw new ServiceException("用户/密码必须填写"); throw new ServiceException("用户/密码必须填写");
} }
if (username.length() < UserConstants.USERNAME_MIN_LENGTH if (username.length() < UserConstants.USERNAME_MIN_LENGTH
|| username.length() > UserConstants.USERNAME_MAX_LENGTH) || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
{
throw new ServiceException("账户长度必须在2到20个字符之间"); throw new ServiceException("账户长度必须在2到20个字符之间");
} }
if (password.length() < UserConstants.PASSWORD_MIN_LENGTH if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH) || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
{
throw new ServiceException("密码长度必须在5到20个字符之间"); throw new ServiceException("密码长度必须在5到20个字符之间");
} }
@ -122,10 +108,9 @@ public class SysLoginService
sysUser.setUserName(username); sysUser.setUserName(username);
sysUser.setNickName(username); sysUser.setNickName(username);
sysUser.setPassword(SecurityUtils.encryptPassword(password)); sysUser.setPassword(SecurityUtils.encryptPassword(password));
R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER); Rust<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);
if (R.FAIL == registerResult.getCode()) if (Rust.FAIL == registerResult.getCode()) {
{
throw new ServiceException(registerResult.getMsg()); throw new ServiceException(registerResult.getMsg());
} }
recordLogininfor(username, Constants.REGISTER, "注册成功"); recordLogininfor(username, Constants.REGISTER, "注册成功");
@ -133,27 +118,23 @@ public class SysLoginService
/** /**
* *
* *
* @param username * @param username
* @param status * @param status
* @param message * @param message
* @return * @return
*/ */
public void recordLogininfor(String username, String status, String message) public void recordLogininfor(String username, String status, String message) {
{
SysLogininfor logininfor = new SysLogininfor(); SysLogininfor logininfor = new SysLogininfor();
logininfor.setUserName(username); logininfor.setUserName(username);
logininfor.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest())); logininfor.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
logininfor.setMsg(message); logininfor.setMsg(message);
// 日志状态 // 日志状态
if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
{
logininfor.setStatus(Constants.LOGIN_SUCCESS_STATUS); logininfor.setStatus(Constants.LOGIN_SUCCESS_STATUS);
} } else if (Constants.LOGIN_FAIL.equals(status)) {
else if (Constants.LOGIN_FAIL.equals(status))
{
logininfor.setStatus(Constants.LOGIN_FAIL_STATUS); logininfor.setStatus(Constants.LOGIN_FAIL_STATUS);
} }
remoteLogService.saveLogininfor(logininfor, SecurityConstants.INNER); remoteLogService.saveLogininfor(logininfor, SecurityConstants.INNER);
} }
} }

@ -118,6 +118,11 @@
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>

@ -1,23 +1,21 @@
package com.ruoyi.common.core.annotation; package com.ruoyi.common.core.annotation;
import com.ruoyi.common.core.utils.poi.ExcelHandlerAdapter;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import java.math.BigDecimal; import java.math.BigDecimal;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import com.ruoyi.common.core.utils.poi.ExcelHandlerAdapter;
/** /**
* Excel * Excel
* *
* @author ruoyi * @author ruoyi
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD) @Target(ElementType.FIELD)
public @interface Excel public @interface Excel {
{
/** /**
* excel * excel
*/ */
@ -128,34 +126,66 @@ public @interface Excel
*/ */
Type type() default Type.ALL; Type type() default Type.ALL;
public enum Type public enum Align { //AUTO(
{ AUTO(0),
ALL(0), EXPORT(1), IMPORT(2); LEFT(1),
CENTER(2),
RIGHT(3);
private final int value;
Align(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}
public enum Type {
/**
* ALL
*/
ALL(0),
/**
* EXPORT
*/
EXPORT(1),
/**
* IMPORT
*/
IMPORT(2);
private final int value; private final int value;
Type(int value) Type(int value) {
{
this.value = value; this.value = value;
} }
public int value() public int value() {
{
return this.value; return this.value;
} }
} }
public enum ColumnType public enum ColumnType {
{ /**
NUMERIC(0), STRING(1), IMAGE(2); * EXPORT
*/
NUMERIC(0),
/**
* EXPORT
*/
STRING(1),
/**
* EXPORT
*/
IMAGE(2);
private final int value; private final int value;
ColumnType(int value) ColumnType(int value) {
{
this.value = value; this.value = value;
} }
public int value() public int value() {
{
return this.value; return this.value;
} }
} }

@ -7,12 +7,11 @@ import java.lang.annotation.Target;
/** /**
* Excel * Excel
* *
* @author ruoyi * @author ruoyi
*/ */
@Target(ElementType.FIELD) @Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface Excels public @interface Excels {
{
Excel[] value(); Excel[] value();
} }

@ -2,11 +2,10 @@ package com.ruoyi.common.core.constant;
/** /**
* key * key
* *
* @author ruoyi * @author ruoyi
*/ */
public class CacheConstants public class CacheConstants {
{
/** /**
* 720 * 720
*/ */

@ -2,11 +2,10 @@ package com.ruoyi.common.core.constant;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class Constants public class Constants {
{
/** /**
* UTF-8 * UTF-8
*/ */
@ -131,11 +130,11 @@ public class Constants
/** /**
* 访 * 访
*/ */
public static final String[] JOB_WHITELIST_STR = { "com.ruoyi" }; public static final String[] JOB_WHITELIST_STR = {"com.ruoyi"};
/** /**
* *
*/ */
public static final String[] JOB_ERROR_STR = { "java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml", public static final String[] JOB_ERROR_STR = {"java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml",
"org.springframework", "org.apache", "com.ruoyi.common.core.utils.file" }; "org.springframework", "org.apache", "com.ruoyi.common.core.utils.file"};
} }

@ -2,116 +2,185 @@ package com.ruoyi.common.core.constant;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class GenConstants public class GenConstants {
{ /**
/** 单表(增删改查) */ *
*/
public static final String TPL_CRUD = "crud"; public static final String TPL_CRUD = "crud";
/** 树表(增删改查) */ /**
*
*/
public static final String TPL_TREE = "tree"; public static final String TPL_TREE = "tree";
/** 主子表(增删改查) */ /**
*
*/
public static final String TPL_SUB = "sub"; public static final String TPL_SUB = "sub";
/** 树编码字段 */ /**
*
*/
public static final String TREE_CODE = "treeCode"; public static final String TREE_CODE = "treeCode";
/** 树父编码字段 */ /**
*
*/
public static final String TREE_PARENT_CODE = "treeParentCode"; public static final String TREE_PARENT_CODE = "treeParentCode";
/** 树名称字段 */ /**
*
*/
public static final String TREE_NAME = "treeName"; public static final String TREE_NAME = "treeName";
/** 上级菜单ID字段 */ /**
* ID
*/
public static final String PARENT_MENU_ID = "parentMenuId"; public static final String PARENT_MENU_ID = "parentMenuId";
/** 上级菜单名称字段 */ /**
*
*/
public static final String PARENT_MENU_NAME = "parentMenuName"; public static final String PARENT_MENU_NAME = "parentMenuName";
/** 数据库字符串类型 */ /**
public static final String[] COLUMNTYPE_STR = { "char", "varchar", "nvarchar", "varchar2" }; *
*/
/** 数据库文本类型 */ public static final String[] COLUMNTYPE_STR = {"char", "varchar", "nvarchar", "varchar2"};
public static final String[] COLUMNTYPE_TEXT = { "tinytext", "text", "mediumtext", "longtext" };
/**
/** 数据库时间类型 */ *
public static final String[] COLUMNTYPE_TIME = { "datetime", "time", "date", "timestamp" }; */
public static final String[] COLUMNTYPE_TEXT = {"tinytext", "text", "mediumtext", "longtext"};
/** 数据库数字类型 */
public static final String[] COLUMNTYPE_NUMBER = { "tinyint", "smallint", "mediumint", "int", "number", "integer", /**
"bigint", "float", "double", "decimal" }; *
*/
/** 页面不需要编辑字段 */ public static final String[] COLUMNTYPE_TIME = {"datetime", "time", "date", "timestamp"};
public static final String[] COLUMNNAME_NOT_EDIT = { "id", "create_by", "create_time", "del_flag" };
/**
/** 页面不需要显示的列表字段 */ *
public static final String[] COLUMNNAME_NOT_LIST = { "id", "create_by", "create_time", "del_flag", "update_by", */
"update_time" }; public static final String[] COLUMNTYPE_NUMBER = {"tinyint", "smallint", "mediumint", "int", "number", "integer",
"bigint", "float", "double", "decimal"};
/** 页面不需要查询字段 */
public static final String[] COLUMNNAME_NOT_QUERY = { "id", "create_by", "create_time", "del_flag", "update_by", /**
"update_time", "remark" }; *
*/
/** Entity基类字段 */ public static final String[] COLUMNNAME_NOT_EDIT = {"id", "create_by", "create_time", "del_flag"};
public static final String[] BASE_ENTITY = { "createBy", "createTime", "updateBy", "updateTime", "remark" };
/**
/** Tree基类字段 */ *
public static final String[] TREE_ENTITY = { "parentName", "parentId", "orderNum", "ancestors" }; */
public static final String[] COLUMNNAME_NOT_LIST = {"id", "create_by", "create_time", "del_flag", "update_by",
/** 文本框 */ "update_time"};
/**
*
*/
public static final String[] COLUMNNAME_NOT_QUERY = {"id", "create_by", "create_time", "del_flag", "update_by",
"update_time", "remark"};
/**
* Entity
*/
public static final String[] BASE_ENTITY = {"createBy", "createTime", "updateBy", "updateTime", "remark"};
/**
* Tree
*/
public static final String[] TREE_ENTITY = {"parentName", "parentId", "orderNum", "ancestors"};
/**
*
*/
public static final String HTML_INPUT = "input"; public static final String HTML_INPUT = "input";
/** 文本域 */ /**
*
*/
public static final String HTML_TEXTAREA = "textarea"; public static final String HTML_TEXTAREA = "textarea";
/** 下拉框 */ /**
*
*/
public static final String HTML_SELECT = "select"; public static final String HTML_SELECT = "select";
/** 单选框 */ /**
*
*/
public static final String HTML_RADIO = "radio"; public static final String HTML_RADIO = "radio";
/** 复选框 */ /**
*
*/
public static final String HTML_CHECKBOX = "checkbox"; public static final String HTML_CHECKBOX = "checkbox";
/** 日期控件 */ /**
*
*/
public static final String HTML_DATETIME = "datetime"; public static final String HTML_DATETIME = "datetime";
/** 图片上传控件 */ /**
*
*/
public static final String HTML_IMAGE_UPLOAD = "imageUpload"; public static final String HTML_IMAGE_UPLOAD = "imageUpload";
/** 文件上传控件 */ /**
*
*/
public static final String HTML_FILE_UPLOAD = "fileUpload"; public static final String HTML_FILE_UPLOAD = "fileUpload";
/** 富文本控件 */ /**
*
*/
public static final String HTML_EDITOR = "editor"; public static final String HTML_EDITOR = "editor";
/** 字符串类型 */ /**
*
*/
public static final String TYPE_STRING = "String"; public static final String TYPE_STRING = "String";
/** 整型 */ /**
*
*/
public static final String TYPE_INTEGER = "Integer"; public static final String TYPE_INTEGER = "Integer";
/** 长整型 */ /**
*
*/
public static final String TYPE_LONG = "Long"; public static final String TYPE_LONG = "Long";
/** 浮点型 */ /**
*
*/
public static final String TYPE_DOUBLE = "Double"; public static final String TYPE_DOUBLE = "Double";
/** 高精度计算类型 */ /**
*
*/
public static final String TYPE_BIGDECIMAL = "BigDecimal"; public static final String TYPE_BIGDECIMAL = "BigDecimal";
/** 时间类型 */ /**
*
*/
public static final String TYPE_DATE = "Date"; public static final String TYPE_DATE = "Date";
/** 模糊查询 */ /**
*
*/
public static final String QUERY_LIKE = "LIKE"; public static final String QUERY_LIKE = "LIKE";
/** 相等查询 */ /**
*
*/
public static final String QUERY_EQ = "EQ"; public static final String QUERY_EQ = "EQ";
/** 需要 */ /**
*
*/
public static final String REQUIRE = "1"; public static final String REQUIRE = "1";
} }

@ -2,11 +2,10 @@ package com.ruoyi.common.core.constant;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class HttpStatus public class HttpStatus {
{
/** /**
* *
*/ */

@ -2,30 +2,38 @@ package com.ruoyi.common.core.constant;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class ScheduleConstants public class ScheduleConstants {
{
public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME"; public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME";
/** 执行目标key */ /**
* key
*/
public static final String TASK_PROPERTIES = "TASK_PROPERTIES"; public static final String TASK_PROPERTIES = "TASK_PROPERTIES";
/** 默认 */ /**
*
*/
public static final String MISFIRE_DEFAULT = "0"; public static final String MISFIRE_DEFAULT = "0";
/** 立即触发执行 */ /**
*
*/
public static final String MISFIRE_IGNORE_MISFIRES = "1"; public static final String MISFIRE_IGNORE_MISFIRES = "1";
/** 触发一次执行 */ /**
*
*/
public static final String MISFIRE_FIRE_AND_PROCEED = "2"; public static final String MISFIRE_FIRE_AND_PROCEED = "2";
/** 不触发立即执行 */ /**
*
*/
public static final String MISFIRE_DO_NOTHING = "3"; public static final String MISFIRE_DO_NOTHING = "3";
public enum Status public enum Status {
{
/** /**
* *
*/ */
@ -37,13 +45,11 @@ public class ScheduleConstants
private String value; private String value;
private Status(String value) private Status(String value) {
{
this.value = value; this.value = value;
} }
public String getValue() public String getValue() {
{
return value; return value;
} }
} }

@ -2,11 +2,10 @@ package com.ruoyi.common.core.constant;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class SecurityConstants public class SecurityConstants {
{
/** /**
* ID * ID
*/ */

@ -2,11 +2,10 @@ package com.ruoyi.common.core.constant;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class ServiceNameConstants public class ServiceNameConstants {
{
/** /**
* serviceid * serviceid
*/ */

@ -2,11 +2,10 @@ package com.ruoyi.common.core.constant;
/** /**
* TokenKey * TokenKey
* *
* @author ruoyi * @author ruoyi
*/ */
public class TokenConstants public class TokenConstants {
{
/** /**
* *
*/ */

@ -2,65 +2,98 @@ package com.ruoyi.common.core.constant;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class UserConstants public class UserConstants {
{
/** /**
* *
*/ */
public static final String SYS_USER = "SYS_USER"; public static final String SYS_USER = "SYS_USER";
/** 正常状态 */ /**
*
*/
public static final String NORMAL = "0"; public static final String NORMAL = "0";
/** 异常状态 */ /**
*
*/
public static final String EXCEPTION = "1"; public static final String EXCEPTION = "1";
/** 用户封禁状态 */ /**
*
*/
public static final String USER_DISABLE = "1"; public static final String USER_DISABLE = "1";
/** 角色封禁状态 */ /**
*
*/
public static final String ROLE_DISABLE = "1"; public static final String ROLE_DISABLE = "1";
/** 部门正常状态 */ /**
*
*/
public static final String DEPT_NORMAL = "0"; public static final String DEPT_NORMAL = "0";
/** 部门停用状态 */ /**
*
*/
public static final String DEPT_DISABLE = "1"; public static final String DEPT_DISABLE = "1";
/** 字典正常状态 */ /**
*
*/
public static final String DICT_NORMAL = "0"; public static final String DICT_NORMAL = "0";
/** 是否为系统默认(是) */ /**
*
*/
public static final String YES = "Y"; public static final String YES = "Y";
/** 是否菜单外链(是) */ /**
*
*/
public static final String YES_FRAME = "0"; public static final String YES_FRAME = "0";
/** 是否菜单外链(否) */ /**
*
*/
public static final String NO_FRAME = "1"; public static final String NO_FRAME = "1";
/** 菜单类型(目录) */ /**
*
*/
public static final String TYPE_DIR = "M"; public static final String TYPE_DIR = "M";
/** 菜单类型(菜单) */ /**
*
*/
public static final String TYPE_MENU = "C"; public static final String TYPE_MENU = "C";
/** 菜单类型(按钮) */ /**
*
*/
public static final String TYPE_BUTTON = "F"; public static final String TYPE_BUTTON = "F";
/** Layout组件标识 */ /**
* Layout
*/
public final static String LAYOUT = "Layout"; public final static String LAYOUT = "Layout";
/** ParentView组件标识 */ /**
* ParentView
*/
public final static String PARENT_VIEW = "ParentView"; public final static String PARENT_VIEW = "ParentView";
/** InnerLink组件标识 */ /**
* InnerLink
*/
public final static String INNER_LINK = "InnerLink"; public final static String INNER_LINK = "InnerLink";
/** 校验返回结果码 */ /**
*
*/
public final static String UNIQUE = "0"; public final static String UNIQUE = "0";
public final static String NOT_UNIQUE = "1"; public final static String NOT_UNIQUE = "1";

@ -1,88 +1,75 @@
package com.ruoyi.common.core.context; package com.ruoyi.common.core.context;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.ttl.TransmittableThreadLocal; import com.alibaba.ttl.TransmittableThreadLocal;
import com.ruoyi.common.core.constant.SecurityConstants; import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.StringUtils; import com.ruoyi.common.core.utils.StringUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* 线 idToken * 线 idToken
* HeaderInterceptor * HeaderInterceptor
* *
* @author ruoyi * @author ruoyi
*/ */
public class SecurityContextHolder public class SecurityContextHolder {
{
private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>(); private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();
public static void set(String key, Object value) public static void set(String key, Object value) {
{
Map<String, Object> map = getLocalMap(); Map<String, Object> map = getLocalMap();
map.put(key, value == null ? StringUtils.EMPTY : value); map.put(key, value == null ? StringUtils.EMPTY : value);
} }
public static String get(String key) public static String get(String key) {
{
Map<String, Object> map = getLocalMap(); Map<String, Object> map = getLocalMap();
return Convert.toStr(map.getOrDefault(key, StringUtils.EMPTY)); return Convert.toStr(map.getOrDefault(key, StringUtils.EMPTY));
} }
public static <T> T get(String key, Class<T> clazz) public static <T> T get(String key, Class<T> clazz) {
{
Map<String, Object> map = getLocalMap(); Map<String, Object> map = getLocalMap();
return StringUtils.cast(map.getOrDefault(key, null)); return StringUtils.cast(map.getOrDefault(key, null));
} }
public static Map<String, Object> getLocalMap() public static Map<String, Object> getLocalMap() {
{
Map<String, Object> map = THREAD_LOCAL.get(); Map<String, Object> map = THREAD_LOCAL.get();
if (map == null) if (map == null) {
{ map = new ConcurrentHashMap<String, Object>(2);
map = new ConcurrentHashMap<String, Object>();
THREAD_LOCAL.set(map); THREAD_LOCAL.set(map);
} }
return map; return map;
} }
public static void setLocalMap(Map<String, Object> threadLocalMap) public static void setLocalMap(Map<String, Object> threadLocalMap) {
{
THREAD_LOCAL.set(threadLocalMap); THREAD_LOCAL.set(threadLocalMap);
} }
public static Long getUserId() public static Long getUserId() {
{
return Convert.toLong(get(SecurityConstants.DETAILS_USER_ID), 0L); return Convert.toLong(get(SecurityConstants.DETAILS_USER_ID), 0L);
} }
public static void setUserId(String account) public static void setUserId(String account) {
{
set(SecurityConstants.DETAILS_USER_ID, account); set(SecurityConstants.DETAILS_USER_ID, account);
} }
public static String getUserName() public static String getUserName() {
{
return get(SecurityConstants.DETAILS_USERNAME); return get(SecurityConstants.DETAILS_USERNAME);
} }
public static void setUserName(String username) public static void setUserName(String username) {
{
set(SecurityConstants.DETAILS_USERNAME, username); set(SecurityConstants.DETAILS_USERNAME, username);
} }
public static String getUserKey() public static String getUserKey() {
{
return get(SecurityConstants.USER_KEY); return get(SecurityConstants.USER_KEY);
} }
public static void setUserKey(String userKey) public static void setUserKey(String userKey) {
{
set(SecurityConstants.USER_KEY, userKey); set(SecurityConstants.USER_KEY, userKey);
} }
public static void remove() public static void remove() {
{
THREAD_LOCAL.remove(); THREAD_LOCAL.remove();
} }
} }

@ -1,105 +1,91 @@
package com.ruoyi.common.core.domain; package com.ruoyi.common.core.domain;
import java.io.Serializable; import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.Constants;
import java.io.Serializable;
/**
* /**
* *
* @author ruoyi *
*/ * @author ruoyi
public class R<T> implements Serializable */
{ public class Rust<T> implements Serializable {
private static final long serialVersionUID = 1L; /**
*
/** 成功 */ */
public static final int SUCCESS = Constants.SUCCESS; public static final int SUCCESS = Constants.SUCCESS;
/**
/** 失败 */ *
public static final int FAIL = Constants.FAIL; */
public static final int FAIL = Constants.FAIL;
private int code; private static final long serialVersionUID = 1L;
private int code;
private String msg;
private String msg;
private T data;
private T data;
public static <T> R<T> ok()
{ public static <T> Rust<T> ok() {
return restResult(null, SUCCESS, null); return restResult(null, SUCCESS, null);
} }
public static <T> R<T> ok(T data) public static <T> Rust<T> ok(T data) {
{ return restResult(data, SUCCESS, null);
return restResult(data, SUCCESS, null); }
}
public static <T> Rust<T> ok(T data, String msg) {
public static <T> R<T> ok(T data, String msg) return restResult(data, SUCCESS, msg);
{ }
return restResult(data, SUCCESS, msg);
} public static <T> Rust<T> fail() {
return restResult(null, FAIL, null);
public static <T> R<T> fail() }
{
return restResult(null, FAIL, null); public static <T> Rust<T> fail(String msg) {
} return restResult(null, FAIL, msg);
}
public static <T> R<T> fail(String msg)
{ public static <T> Rust<T> fail(T data) {
return restResult(null, FAIL, msg); return restResult(data, FAIL, null);
} }
public static <T> R<T> fail(T data) public static <T> Rust<T> fail(T data, String msg) {
{ return restResult(data, FAIL, msg);
return restResult(data, FAIL, null); }
}
public static <T> Rust<T> fail(int code, String msg) {
public static <T> R<T> fail(T data, String msg) return restResult(null, code, msg);
{ }
return restResult(data, FAIL, msg);
} private static <T> Rust<T> restResult(T data, int code, String msg) {
Rust<T> apiResult = new Rust<>();
public static <T> R<T> fail(int code, String msg) apiResult.setCode(code);
{ apiResult.setData(data);
return restResult(null, code, msg); apiResult.setMsg(msg);
} return apiResult;
}
private static <T> R<T> restResult(T data, int code, String msg)
{ public int getCode() {
R<T> apiResult = new R<>(); return code;
apiResult.setCode(code); }
apiResult.setData(data);
apiResult.setMsg(msg); public void setCode(int code) {
return apiResult; this.code = code;
} }
public int getCode() public String getMsg() {
{ return msg;
return code; }
}
public void setMsg(String msg) {
public void setCode(int code) this.msg = msg;
{ }
this.code = code;
} public T getData() {
return data;
public String getMsg() }
{
return msg; public void setData(T data) {
} this.data = data;
}
public void setMsg(String msg) }
{
this.msg = msg;
}
public T getData()
{
return data;
}
public void setData(T data)
{
this.data = data;
}
}

@ -2,29 +2,36 @@ package com.ruoyi.common.core.enums;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public enum UserStatus public enum UserStatus {
{ /**
OK("0", "正常"), DISABLE("1", "停用"), DELETED("2", "删除"); * EXPORT
*/
OK("0", "正常"),
/**
* EXPORT
*/
DISABLE("1", "停用"),
/**
* EXPORT
*/
DELETED("2", "删除");
private final String code; private final String code;
private final String info; private final String info;
UserStatus(String code, String info) UserStatus(String code, String info) {
{
this.code = code; this.code = code;
this.info = info; this.info = info;
} }
public String getCode() public String getCode() {
{
return code; return code;
} }
public String getInfo() public String getInfo() {
{
return info; return info;
} }
} }

@ -2,15 +2,13 @@ package com.ruoyi.common.core.exception;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class CaptchaException extends RuntimeException public class CaptchaException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public CaptchaException(String msg) public CaptchaException(String msg) {
{
super(msg); super(msg);
} }
} }

@ -2,30 +2,25 @@ package com.ruoyi.common.core.exception;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class CheckedException extends RuntimeException public class CheckedException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public CheckedException(String message) public CheckedException(String message) {
{
super(message); super(message);
} }
public CheckedException(Throwable cause) public CheckedException(Throwable cause) {
{
super(cause); super(cause);
} }
public CheckedException(String message, Throwable cause) public CheckedException(String message, Throwable cause) {
{
super(message, cause); super(message, cause);
} }
public CheckedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) public CheckedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
{
super(message, cause, enableSuppression, writableStackTrace); super(message, cause, enableSuppression, writableStackTrace);
} }
} }

@ -2,14 +2,12 @@ package com.ruoyi.common.core.exception;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class DemoModeException extends RuntimeException public class DemoModeException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public DemoModeException() public DemoModeException() {
{
} }
} }

@ -2,11 +2,10 @@ package com.ruoyi.common.core.exception;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class GlobalException extends RuntimeException public class GlobalException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -17,41 +16,36 @@ public class GlobalException extends RuntimeException
/** /**
* *
* * <p>
* {@link CommonResult#getDetailMessage()} * CommonResult#getDetailMessage()
*/ */
private String detailMessage; private String detailMessage;
/** /**
* *
*/ */
public GlobalException() public GlobalException() {
{
} }
public GlobalException(String message) public GlobalException(String message) {
{
this.message = message; this.message = message;
} }
public String getDetailMessage() public String getDetailMessage() {
{
return detailMessage; return detailMessage;
} }
public GlobalException setDetailMessage(String detailMessage) public GlobalException setDetailMessage(String detailMessage) {
{
this.detailMessage = detailMessage; this.detailMessage = detailMessage;
return this; return this;
} }
public String getMessage() @Override
{ public String getMessage() {
return message; return message;
} }
public GlobalException setMessage(String message) public GlobalException setMessage(String message) {
{
this.message = message; this.message = message;
return this; return this;
} }

@ -2,15 +2,13 @@ package com.ruoyi.common.core.exception;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class InnerAuthException extends RuntimeException public class InnerAuthException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public InnerAuthException(String message) public InnerAuthException(String message) {
{
super(message); super(message);
} }
} }

@ -2,14 +2,12 @@ package com.ruoyi.common.core.exception;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class PreAuthorizeException extends RuntimeException public class PreAuthorizeException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public PreAuthorizeException() public PreAuthorizeException() {
{
} }
} }

@ -2,11 +2,10 @@ package com.ruoyi.common.core.exception;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public final class ServiceException extends RuntimeException public final class ServiceException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
@ -21,53 +20,46 @@ public final class ServiceException extends RuntimeException
/** /**
* *
* * <p>
* {@link CommonResult#getDetailMessage()} * CommonResult#getDetailMessage()
*/ */
private String detailMessage; private String detailMessage;
/** /**
* *
*/ */
public ServiceException() public ServiceException() {
{
} }
public ServiceException(String message) public ServiceException(String message) {
{
this.message = message; this.message = message;
} }
public ServiceException(String message, Integer code) public ServiceException(String message, Integer code) {
{
this.message = message; this.message = message;
this.code = code; this.code = code;
} }
public String getDetailMessage() public String getDetailMessage() {
{
return detailMessage; return detailMessage;
} }
public String getMessage() public ServiceException setDetailMessage(String detailMessage) {
{ this.detailMessage = detailMessage;
return message; return this;
} }
public Integer getCode() @Override
{ public String getMessage() {
return code; return message;
} }
public ServiceException setMessage(String message) public ServiceException setMessage(String message) {
{
this.message = message; this.message = message;
return this; return this;
} }
public ServiceException setDetailMessage(String detailMessage) public Integer getCode() {
{ return code;
this.detailMessage = detailMessage;
return this;
} }
} }

@ -2,25 +2,21 @@ package com.ruoyi.common.core.exception;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class UtilException extends RuntimeException public class UtilException extends RuntimeException {
{
private static final long serialVersionUID = 8247610319171014183L; private static final long serialVersionUID = 8247610319171014183L;
public UtilException(Throwable e) public UtilException(Throwable e) {
{
super(e.getMessage(), e); super(e.getMessage(), e);
} }
public UtilException(String message) public UtilException(String message) {
{
super(message); super(message);
} }
public UtilException(String message, Throwable throwable) public UtilException(String message, Throwable throwable) {
{
super(message, throwable); super(message, throwable);
} }
} }

@ -2,15 +2,13 @@ package com.ruoyi.common.core.exception.auth;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class NotLoginException extends RuntimeException public class NotLoginException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public NotLoginException(String message) public NotLoginException(String message) {
{
super(message); super(message);
} }
} }

@ -4,20 +4,17 @@ import org.apache.commons.lang3.StringUtils;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class NotPermissionException extends RuntimeException public class NotPermissionException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public NotPermissionException(String permission) public NotPermissionException(String permission) {
{
super(permission); super(permission);
} }
public NotPermissionException(String[] permissions) public NotPermissionException(String[] permissions) {
{
super(StringUtils.join(permissions, ",")); super(StringUtils.join(permissions, ","));
} }
} }

@ -4,20 +4,17 @@ import org.apache.commons.lang3.StringUtils;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class NotRoleException extends RuntimeException public class NotRoleException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public NotRoleException(String role) public NotRoleException(String role) {
{
super(role); super(role);
} }
public NotRoleException(String[] roles) public NotRoleException(String[] roles) {
{
super(StringUtils.join(roles, ",")); super(StringUtils.join(roles, ","));
} }
} }

@ -2,11 +2,10 @@ package com.ruoyi.common.core.exception.base;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class BaseException extends RuntimeException public class BaseException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
@ -29,51 +28,42 @@ public class BaseException extends RuntimeException
*/ */
private String defaultMessage; private String defaultMessage;
public BaseException(String module, String code, Object[] args, String defaultMessage) public BaseException(String module, String code, Object[] args, String defaultMessage) {
{
this.module = module; this.module = module;
this.code = code; this.code = code;
this.args = args; this.args = args;
this.defaultMessage = defaultMessage; this.defaultMessage = defaultMessage;
} }
public BaseException(String module, String code, Object[] args) public BaseException(String module, String code, Object[] args) {
{
this(module, code, args, null); this(module, code, args, null);
} }
public BaseException(String module, String defaultMessage) public BaseException(String module, String defaultMessage) {
{
this(module, null, null, defaultMessage); this(module, null, null, defaultMessage);
} }
public BaseException(String code, Object[] args) public BaseException(String code, Object[] args) {
{
this(null, code, args, null); this(null, code, args, null);
} }
public BaseException(String defaultMessage) public BaseException(String defaultMessage) {
{
this(null, null, null, defaultMessage); this(null, null, null, defaultMessage);
} }
public String getModule() public String getModule() {
{
return module; return module;
} }
public String getCode() public String getCode() {
{
return code; return code;
} }
public Object[] getArgs() public Object[] getArgs() {
{
return args; return args;
} }
public String getDefaultMessage() public String getDefaultMessage() {
{
return defaultMessage; return defaultMessage;
} }
} }

@ -4,15 +4,13 @@ import com.ruoyi.common.core.exception.base.BaseException;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class FileException extends BaseException public class FileException extends BaseException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public FileException(String code, Object[] args) public FileException(String code, Object[] args) {
{
super("file", code, args, null); super("file", code, args, null);
} }

@ -2,15 +2,13 @@ package com.ruoyi.common.core.exception.file;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class FileNameLengthLimitExceededException extends FileException public class FileNameLengthLimitExceededException extends FileException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public FileNameLengthLimitExceededException(int defaultFileNameLength) public FileNameLengthLimitExceededException(int defaultFileNameLength) {
{ super("upload.filename.exceed.length", new Object[]{defaultFileNameLength});
super("upload.filename.exceed.length", new Object[] { defaultFileNameLength });
} }
} }

@ -2,15 +2,13 @@ package com.ruoyi.common.core.exception.file;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class FileSizeLimitExceededException extends FileException public class FileSizeLimitExceededException extends FileException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public FileSizeLimitExceededException(long defaultMaxSize) public FileSizeLimitExceededException(long defaultMaxSize) {
{ super("upload.exceed.maxSize", new Object[]{defaultMaxSize});
super("upload.exceed.maxSize", new Object[] { defaultMaxSize });
} }
} }

@ -1,80 +1,68 @@
package com.ruoyi.common.core.exception.file; package com.ruoyi.common.core.exception.file;
import java.util.Arrays;
import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.FileUploadException;
import java.util.Arrays;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class InvalidExtensionException extends FileUploadException public class InvalidExtensionException extends FileUploadException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private String[] allowedExtension; private String[] allowedExtension;
private String extension; private String extension;
private String filename; private String filename;
public InvalidExtensionException(String[] allowedExtension, String extension, String filename) public InvalidExtensionException(String[] allowedExtension, String extension, String filename) {
{
super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]"); super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
this.allowedExtension = allowedExtension; this.allowedExtension = allowedExtension;
this.extension = extension; this.extension = extension;
this.filename = filename; this.filename = filename;
} }
public String[] getAllowedExtension() public String[] getAllowedExtension() {
{
return allowedExtension; return allowedExtension;
} }
public String getExtension() public String getExtension() {
{
return extension; return extension;
} }
public String getFilename() public String getFilename() {
{
return filename; return filename;
} }
public static class InvalidImageExtensionException extends InvalidExtensionException public static class InvalidImageExtensionException extends InvalidExtensionException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename) public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename) {
{
super(allowedExtension, extension, filename); super(allowedExtension, extension, filename);
} }
} }
public static class InvalidFlashExtensionException extends InvalidExtensionException public static class InvalidFlashExtensionException extends InvalidExtensionException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename) public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename) {
{
super(allowedExtension, extension, filename); super(allowedExtension, extension, filename);
} }
} }
public static class InvalidMediaExtensionException extends InvalidExtensionException public static class InvalidMediaExtensionException extends InvalidExtensionException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename) public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename) {
{
super(allowedExtension, extension, filename); super(allowedExtension, extension, filename);
} }
} }
public static class InvalidVideoExtensionException extends InvalidExtensionException public static class InvalidVideoExtensionException extends InvalidExtensionException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename) public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename) {
{
super(allowedExtension, extension, filename); super(allowedExtension, extension, filename);
} }
} }

@ -2,33 +2,47 @@ package com.ruoyi.common.core.exception.job;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class TaskException extends Exception public class TaskException extends Exception {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Code code; private Code code;
public TaskException(String msg, Code code) public TaskException(String msg, Code code) {
{
this(msg, code, null); this(msg, code, null);
} }
public TaskException(String msg, Code code, Exception nestedEx) public TaskException(String msg, Code code, Exception nestedEx) {
{
super(msg, nestedEx); super(msg, nestedEx);
this.code = code; this.code = code;
} }
public Code getCode() public Code getCode() {
{
return code; return code;
} }
public enum Code public enum Code {
{ /**
TASK_EXISTS, NO_TASK_EXISTS, TASK_ALREADY_STARTED, UNKNOWN, CONFIG_ERROR, TASK_NODE_NOT_AVAILABLE * EXPORT
*/
TASK_EXISTS,
/**
* EXPORT
*/
NO_TASK_EXISTS,
/**
* EXPORT
*/
TASK_ALREADY_STARTED,
/**
* EXPORT
*/
UNKNOWN, CONFIG_ERROR,
/**
* EXPORT
*/
TASK_NODE_NOT_AVAILABLE
} }
} }

@ -2,15 +2,13 @@ package com.ruoyi.common.core.exception.user;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class CaptchaExpireException extends UserException public class CaptchaExpireException extends UserException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public CaptchaExpireException() public CaptchaExpireException() {
{
super("user.jcaptcha.expire", null); super("user.jcaptcha.expire", null);
} }
} }

@ -4,15 +4,13 @@ import com.ruoyi.common.core.exception.base.BaseException;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class UserException extends BaseException public class UserException extends BaseException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public UserException(String code, Object[] args) public UserException(String code, Object[] args) {
{
super("user", code, args, null); super("user", code, args, null);
} }
} }

@ -2,15 +2,13 @@ package com.ruoyi.common.core.exception.user;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class UserPasswordNotMatchException extends UserException public class UserPasswordNotMatchException extends UserException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public UserPasswordNotMatchException() public UserPasswordNotMatchException() {
{
super("user.password.not.match", null); super("user.password.not.match", null);
} }
} }

@ -1,76 +1,82 @@
package com.ruoyi.common.core.text; package com.ruoyi.common.core.text;
import com.ruoyi.common.core.utils.StringUtils;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import com.ruoyi.common.core.utils.StringUtils;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class CharsetKit public class CharsetKit {
{ /**
/** ISO-8859-1 */ * ISO-8859-1
*/
public static final String ISO_8859_1 = "ISO-8859-1"; public static final String ISO_8859_1 = "ISO-8859-1";
/** UTF-8 */ /**
* UTF-8
*/
public static final String UTF_8 = "UTF-8"; public static final String UTF_8 = "UTF-8";
/** GBK */ /**
* GBK
*/
public static final String GBK = "GBK"; public static final String GBK = "GBK";
/** ISO-8859-1 */ /**
* ISO-8859-1
*/
public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1); public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1);
/** UTF-8 */ /**
* UTF-8
*/
public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8); public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8);
/** GBK */ /**
* GBK
*/
public static final Charset CHARSET_GBK = Charset.forName(GBK); public static final Charset CHARSET_GBK = Charset.forName(GBK);
/** /**
* Charset * Charset
* *
* @param charset * @param charset
* @return Charset * @return Charset
*/ */
public static Charset charset(String charset) public static Charset charset(String charset) {
{
return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset); return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset);
} }
/** /**
* *
* *
* @param source * @param source
* @param srcCharset ISO-8859-1 * @param srcCharset ISO-8859-1
* @param destCharset UTF-8 * @param destCharset UTF-8
* @return * @return
*/ */
public static String convert(String source, String srcCharset, String destCharset) public static String convert(String source, String srcCharset, String destCharset) {
{
return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset)); return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset));
} }
/** /**
* *
* *
* @param source * @param source
* @param srcCharset ISO-8859-1 * @param srcCharset ISO-8859-1
* @param destCharset UTF-8 * @param destCharset UTF-8
* @return * @return
*/ */
public static String convert(String source, Charset srcCharset, Charset destCharset) public static String convert(String source, Charset srcCharset, Charset destCharset) {
{ if (null == srcCharset) {
if (null == srcCharset)
{
srcCharset = StandardCharsets.ISO_8859_1; srcCharset = StandardCharsets.ISO_8859_1;
} }
if (null == destCharset) if (null == destCharset) {
{
destCharset = StandardCharsets.UTF_8; destCharset = StandardCharsets.UTF_8;
} }
if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) {
{
return source; return source;
} }
return new String(source.getBytes(srcCharset), destCharset); return new String(source.getBytes(srcCharset), destCharset);
@ -79,8 +85,7 @@ public class CharsetKit
/** /**
* @return * @return
*/ */
public static String systemCharset() public static String systemCharset() {
{
return Charset.defaultCharset().name(); return Charset.defaultCharset().name();
} }
} }

@ -4,11 +4,10 @@ import com.ruoyi.common.core.utils.StringUtils;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class StrFormatter public class StrFormatter {
{
public static final String EMPTY_JSON = "{}"; public static final String EMPTY_JSON = "{}";
public static final char C_BACKSLASH = '\\'; public static final char C_BACKSLASH = '\\';
public static final char C_DELIM_START = '{'; public static final char C_DELIM_START = '{';
@ -22,15 +21,13 @@ public class StrFormatter
* 使format("this is {} for {}", "a", "b") -> this is a for b<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 \{} for a<br>
* \ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br> * \ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
* *
* @param strPattern * @param strPattern
* @param argArray * @param argArray
* @return * @return
*/ */
public static String format(final String strPattern, final Object... argArray) public static String format(final String strPattern, final Object... argArray) {
{ if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray)) {
if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray))
{
return strPattern; return strPattern;
} }
final int strPatternLength = strPattern.length(); final int strPatternLength = strPattern.length();
@ -40,43 +37,30 @@ public class StrFormatter
int handledPosition = 0; int handledPosition = 0;
int delimIndex;// 占位符所在位置 int delimIndex;// 占位符所在位置
for (int argIndex = 0; argIndex < argArray.length; argIndex++) for (int argIndex = 0; argIndex < argArray.length; argIndex++) {
{
delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition); delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
if (delimIndex == -1) if (delimIndex == -1) {
{ if (handledPosition == 0) {
if (handledPosition == 0)
{
return strPattern; return strPattern;
} } else { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
else
{ // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
sbuf.append(strPattern, handledPosition, strPatternLength); sbuf.append(strPattern, handledPosition, strPatternLength);
return sbuf.toString(); return sbuf.toString();
} }
} } else {
else if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) {
{ if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) {
if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH)
{
if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH)
{
// 转义符之前还有一个转义符,占位符依旧有效 // 转义符之前还有一个转义符,占位符依旧有效
sbuf.append(strPattern, handledPosition, delimIndex - 1); sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(Convert.utf8Str(argArray[argIndex])); sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2; handledPosition = delimIndex + 2;
} } else {
else
{
// 占位符被转义 // 占位符被转义
argIndex--; argIndex--;
sbuf.append(strPattern, handledPosition, delimIndex - 1); sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(C_DELIM_START); sbuf.append(C_DELIM_START);
handledPosition = delimIndex + 1; handledPosition = delimIndex + 1;
} }
} } else {
else
{
// 正常占位符 // 正常占位符
sbuf.append(strPattern, handledPosition, delimIndex); sbuf.append(strPattern, handledPosition, delimIndex);
sbuf.append(Convert.utf8Str(argArray[argIndex])); sbuf.append(Convert.utf8Str(argArray[argIndex]));

@ -1,23 +1,19 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.LocalDate; import java.time.*;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date; import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
{
public static String YYYY = "yyyy"; public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM"; public static String YYYY_MM = "yyyy-MM";
@ -38,8 +34,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
* *
* @return Date() * @return Date()
*/ */
public static Date getNowDate() public static Date getNowDate() {
{
return new Date(); return new Date();
} }
@ -48,44 +43,34 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
* *
* @return String * @return String
*/ */
public static String getDate() public static String getDate() {
{
return dateTimeNow(YYYY_MM_DD); return dateTimeNow(YYYY_MM_DD);
} }
public static final String getTime() public static final String getTime() {
{
return dateTimeNow(YYYY_MM_DD_HH_MM_SS); return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
} }
public static final String dateTimeNow() public static final String dateTimeNow() {
{
return dateTimeNow(YYYYMMDDHHMMSS); return dateTimeNow(YYYYMMDDHHMMSS);
} }
public static final String dateTimeNow(final String format) public static final String dateTimeNow(final String format) {
{
return parseDateToStr(format, new Date()); return parseDateToStr(format, new Date());
} }
public static final String dateTime(final Date date) public static final String dateTime(final Date date) {
{
return parseDateToStr(YYYY_MM_DD, date); return parseDateToStr(YYYY_MM_DD, date);
} }
public static final String parseDateToStr(final String format, final Date date) public static final String parseDateToStr(final String format, final Date date) {
{
return new SimpleDateFormat(format).format(date); return new SimpleDateFormat(format).format(date);
} }
public static final Date dateTime(final String format, final String ts) public static final Date dateTime(final String format, final String ts) {
{ try {
try
{
return new SimpleDateFormat(format).parse(ts); return new SimpleDateFormat(format).parse(ts);
} } catch (ParseException e) {
catch (ParseException e)
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -93,8 +78,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* // 2018/08/08 * // 2018/08/08
*/ */
public static final String datePath() public static final String datePath() {
{
Date now = new Date(); Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd"); return DateFormatUtils.format(now, "yyyy/MM/dd");
} }
@ -102,8 +86,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* // 20180808 * // 20180808
*/ */
public static final String dateTime() public static final String dateTime() {
{
Date now = new Date(); Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd"); return DateFormatUtils.format(now, "yyyyMMdd");
} }
@ -111,18 +94,13 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* *
*/ */
public static Date parseDate(Object str) public static Date parseDate(Object str) {
{ if (str == null) {
if (str == null)
{
return null; return null;
} }
try try {
{
return parseDate(str.toString(), parsePatterns); return parseDate(str.toString(), parsePatterns);
} } catch (ParseException e) {
catch (ParseException e)
{
return null; return null;
} }
} }
@ -130,8 +108,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* *
*/ */
public static Date getServerStartDate() public static Date getServerStartDate() {
{
long time = ManagementFactory.getRuntimeMXBean().getStartTime(); long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time); return new Date(time);
} }
@ -139,8 +116,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* *
*/ */
public static String getDatePoor(Date endDate, Date nowDate) public static String getDatePoor(Date endDate, Date nowDate) {
{
long nd = 1000 * 24 * 60 * 60; long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60; long nh = 1000 * 60 * 60;
long nm = 1000 * 60; long nm = 1000 * 60;
@ -161,8 +137,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* LocalDateTime ==> Date * LocalDateTime ==> Date
*/ */
public static Date toDate(LocalDateTime temporalAccessor) public static Date toDate(LocalDateTime temporalAccessor) {
{
ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault()); ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
return Date.from(zdt.toInstant()); return Date.from(zdt.toInstant());
} }
@ -170,8 +145,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* LocalDate ==> Date * LocalDate ==> Date
*/ */
public static Date toDate(LocalDate temporalAccessor) public static Date toDate(LocalDate temporalAccessor) {
{
LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0)); LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault()); ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
return Date.from(zdt.toInstant()); return Date.from(zdt.toInstant());

@ -1,37 +1,33 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import org.apache.commons.lang3.exception.ExceptionUtils;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class ExceptionUtil public class ExceptionUtil {
{
/** /**
* exception * exception
*/ */
public static String getExceptionMessage(Throwable e) public static String getExceptionMessage(Throwable e) {
{
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true)); e.printStackTrace(new PrintWriter(sw, true));
return sw.toString(); return sw.toString();
} }
public static String getRootErrorMessage(Exception e) public static String getRootErrorMessage(Exception e) {
{
Throwable root = ExceptionUtils.getRootCause(e); Throwable root = ExceptionUtils.getRootCause(e);
root = (root == null ? e : root); root = (root == null ? e : root);
if (root == null) if (root == null) {
{
return ""; return "";
} }
String msg = root.getMessage(); String msg = root.getMessage();
if (msg == null) if (msg == null) {
{
return "null"; return "null";
} }
return StringUtils.defaultString(msg); return StringUtils.defaultString(msg);

@ -1,6 +1,5 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import java.util.Map;
import com.ruoyi.common.core.constant.SecurityConstants; import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.TokenConstants; import com.ruoyi.common.core.constant.TokenConstants;
import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.core.text.Convert;
@ -8,13 +7,14 @@ import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Map;
/** /**
* Jwt * Jwt
* *
* @author ruoyi * @author ruoyi
*/ */
public class JwtUtils public class JwtUtils {
{
public static String secret = TokenConstants.SECRET; public static String secret = TokenConstants.SECRET;
/** /**
@ -23,8 +23,7 @@ public class JwtUtils
* @param claims * @param claims
* @return * @return
*/ */
public static String createToken(Map<String, Object> claims) public static String createToken(Map<String, Object> claims) {
{
String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact(); String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
return token; return token;
} }
@ -35,89 +34,81 @@ public class JwtUtils
* @param token * @param token
* @return * @return
*/ */
public static Claims parseToken(String token) public static Claims parseToken(String token) {
{
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
} }
/** /**
* *
* *
* @param token * @param token
* @return ID * @return ID
*/ */
public static String getUserKey(String token) public static String getUserKey(String token) {
{
Claims claims = parseToken(token); Claims claims = parseToken(token);
return getValue(claims, SecurityConstants.USER_KEY); return getValue(claims, SecurityConstants.USER_KEY);
} }
/** /**
* *
* *
* @param claims * @param claims
* @return ID * @return ID
*/ */
public static String getUserKey(Claims claims) public static String getUserKey(Claims claims) {
{
return getValue(claims, SecurityConstants.USER_KEY); return getValue(claims, SecurityConstants.USER_KEY);
} }
/** /**
* ID * ID
* *
* @param token * @param token
* @return ID * @return ID
*/ */
public static String getUserId(String token) public static String getUserId(String token) {
{
Claims claims = parseToken(token); Claims claims = parseToken(token);
return getValue(claims, SecurityConstants.DETAILS_USER_ID); return getValue(claims, SecurityConstants.DETAILS_USER_ID);
} }
/** /**
* ID * ID
* *
* @param claims * @param claims
* @return ID * @return ID
*/ */
public static String getUserId(Claims claims) public static String getUserId(Claims claims) {
{
return getValue(claims, SecurityConstants.DETAILS_USER_ID); return getValue(claims, SecurityConstants.DETAILS_USER_ID);
} }
/** /**
* *
* *
* @param token * @param token
* @return * @return
*/ */
public static String getUserName(String token) public static String getUserName(String token) {
{
Claims claims = parseToken(token); Claims claims = parseToken(token);
return getValue(claims, SecurityConstants.DETAILS_USERNAME); return getValue(claims, SecurityConstants.DETAILS_USERNAME);
} }
/** /**
* *
* *
* @param claims * @param claims
* @return * @return
*/ */
public static String getUserName(Claims claims) public static String getUserName(Claims claims) {
{
return getValue(claims, SecurityConstants.DETAILS_USERNAME); return getValue(claims, SecurityConstants.DETAILS_USERNAME);
} }
/** /**
* *
* *
* @param claims * @param claims
* @param key * @param key
* @return * @return
*/ */
public static String getValue(Claims claims, String key) public static String getValue(Claims claims, String key) {
{
return Convert.toStr(claims.get(key), ""); return Convert.toStr(claims.get(key), "");
} }
} }

@ -7,16 +7,14 @@ import com.ruoyi.common.core.web.page.TableSupport;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class PageUtils extends PageHelper public class PageUtils extends PageHelper {
{
/** /**
* *
*/ */
public static void startPage() public static void startPage() {
{
PageDomain pageDomain = TableSupport.buildPageRequest(); PageDomain pageDomain = TableSupport.buildPageRequest();
Integer pageNum = pageDomain.getPageNum(); Integer pageNum = pageDomain.getPageNum();
Integer pageSize = pageDomain.getPageSize(); Integer pageSize = pageDomain.getPageSize();
@ -28,8 +26,7 @@ public class PageUtils extends PageHelper
/** /**
* 线 * 线
*/ */
public static void clearPage() public static void clearPage() {
{
PageHelper.clearPage(); PageHelper.clearPage();
} }
} }

@ -1,5 +1,7 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import com.ruoyi.common.core.text.Convert;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
@ -7,18 +9,18 @@ import java.util.Set;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import com.ruoyi.common.core.text.Convert; /**
import com.ruoyi.common.core.utils.StringUtils; * @author pan
*/
public class ReUtil public class ReUtil {
{
public final static Pattern GROUP_VAR = Pattern.compile("\\$(\\d+)"); public final static Pattern GROUP_VAR = Pattern.compile("\\$(\\d+)");
/** /**
* *
*/ */
public final static Set<Character> RE_KEYS = new HashSet<>( public final static Set<Character> RE_KEYS = new HashSet<>(
Arrays.asList('$', '(', ')', '*', '+', '.', '[', ']', '?', '\\', '^', '{', '}', '|'));; Arrays.asList('$', '(', ')', '*', '+', '.', '[', ']', '?', '\\', '^', '{', '}', '|'));
;
/** /**
* <br> * <br>
@ -33,13 +35,12 @@ public class ReUtil
* (1234) * (1234)
* </pre> * </pre>
* *
* @param content * @param content
* @param regex * @param regex
* @param replacementTemplate 使$1 * @param replacementTemplate 使$1
* @return * @return
*/ */
public static String replaceAll(CharSequence content, String regex, String replacementTemplate) public static String replaceAll(CharSequence content, String regex, String replacementTemplate) {
{
final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL); final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
return replaceAll(content, pattern, replacementTemplate); return replaceAll(content, pattern, replacementTemplate);
} }
@ -48,30 +49,25 @@ public class ReUtil
* <br> * <br>
* replacementTemplate$11 * replacementTemplate$11
* *
* @param content * @param content
* @param pattern {@link Pattern} * @param pattern {@link Pattern}
* @param replacementTemplate 使$1 * @param replacementTemplate 使$1
* @return * @return
* @since 3.0.4 * @since 3.0.4
*/ */
public static String replaceAll(CharSequence content, Pattern pattern, String replacementTemplate) public static String replaceAll(CharSequence content, Pattern pattern, String replacementTemplate) {
{ if (StringUtils.isEmpty(content)) {
if (StringUtils.isEmpty(content))
{
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
final Matcher matcher = pattern.matcher(content); final Matcher matcher = pattern.matcher(content);
boolean result = matcher.find(); boolean result = matcher.find();
if (result) if (result) {
{
final Set<String> varNums = findAll(GROUP_VAR, replacementTemplate, 1, new HashSet<>()); final Set<String> varNums = findAll(GROUP_VAR, replacementTemplate, 1, new HashSet<>());
final StringBuffer sb = new StringBuffer(); final StringBuffer sb = new StringBuffer();
do do {
{
String replacement = replacementTemplate; String replacement = replacementTemplate;
for (String var : varNums) for (String var : varNums) {
{
int group = Integer.parseInt(var); int group = Integer.parseInt(var);
replacement = replacement.replace("$" + var, matcher.group(group)); replacement = replacement.replace("$" + var, matcher.group(group));
} }
@ -84,33 +80,29 @@ public class ReUtil
} }
return Convert.toStr(content); return Convert.toStr(content);
} }
/** /**
* *
* *
* @param <T> * @param <T>
* @param pattern * @param pattern
* @param content * @param content
* @param group * @param group
* @param collection * @param collection
* @return * @return
*/ */
public static <T extends Collection<String>> T findAll(Pattern pattern, CharSequence content, int group, public static <T extends Collection<String>> T findAll(Pattern pattern, CharSequence content, int group,
T collection) T collection) {
{ if (null == pattern || null == content) {
if (null == pattern || null == content)
{
return null; return null;
} }
if (null == collection) if (null == collection) {
{
throw new NullPointerException("Null collection param provided!"); throw new NullPointerException("Null collection param provided!");
} }
final Matcher matcher = pattern.matcher(content); final Matcher matcher = pattern.matcher(content);
while (matcher.find()) while (matcher.find()) {
{
collection.add(matcher.group(group)); collection.add(matcher.group(group));
} }
return collection; return collection;
@ -122,11 +114,9 @@ public class ReUtil
* @param c * @param c
* @return * @return
*/ */
public static String escape(char c) public static String escape(char c) {
{
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
if (RE_KEYS.contains(c)) if (RE_KEYS.contains(c)) {
{
builder.append('\\'); builder.append('\\');
} }
builder.append(c); builder.append(c);
@ -139,21 +129,17 @@ public class ReUtil
* @param content * @param content
* @return * @return
*/ */
public static String escape(CharSequence content) public static String escape(CharSequence content) {
{ if (StringUtils.isBlank(content)) {
if (StringUtils.isBlank(content))
{
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
int len = content.length(); int len = content.length();
char current; char current;
for (int i = 0; i < len; i++) for (int i = 0; i < len; i++) {
{
current = content.charAt(i); current = content.charAt(i);
if (RE_KEYS.contains(current)) if (RE_KEYS.contains(current)) {
{
builder.append('\\'); builder.append('\\');
} }
builder.append(current); builder.append(current);

@ -1,15 +1,9 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import java.io.IOException; import com.alibaba.fastjson.JSONObject;
import java.io.UnsupportedEncodingException; import com.ruoyi.common.core.constant.Constants;
import java.net.URLDecoder; import com.ruoyi.common.core.domain.Rust;
import java.net.URLEncoder; import com.ruoyi.common.core.text.Convert;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@ -18,78 +12,74 @@ import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.text.Convert;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class ServletUtils public class ServletUtils {
{
/** /**
* String * String
*/ */
public static String getParameter(String name) public static String getParameter(String name) {
{
return getRequest().getParameter(name); return getRequest().getParameter(name);
} }
/** /**
* String * String
*/ */
public static String getParameter(String name, String defaultValue) public static String getParameter(String name, String defaultValue) {
{
return Convert.toStr(getRequest().getParameter(name), defaultValue); return Convert.toStr(getRequest().getParameter(name), defaultValue);
} }
/** /**
* Integer * Integer
*/ */
public static Integer getParameterToInt(String name) public static Integer getParameterToInt(String name) {
{
return Convert.toInt(getRequest().getParameter(name)); return Convert.toInt(getRequest().getParameter(name));
} }
/** /**
* Integer * Integer
*/ */
public static Integer getParameterToInt(String name, Integer defaultValue) public static Integer getParameterToInt(String name, Integer defaultValue) {
{
return Convert.toInt(getRequest().getParameter(name), defaultValue); return Convert.toInt(getRequest().getParameter(name), defaultValue);
} }
/** /**
* Boolean * Boolean
*/ */
public static Boolean getParameterToBool(String name) public static Boolean getParameterToBool(String name) {
{
return Convert.toBool(getRequest().getParameter(name)); return Convert.toBool(getRequest().getParameter(name));
} }
/** /**
* Boolean * Boolean
*/ */
public static Boolean getParameterToBool(String name, Boolean defaultValue) public static Boolean getParameterToBool(String name, Boolean defaultValue) {
{
return Convert.toBool(getRequest().getParameter(name), defaultValue); return Convert.toBool(getRequest().getParameter(name), defaultValue);
} }
/** /**
* request * request
*/ */
public static HttpServletRequest getRequest() public static HttpServletRequest getRequest() {
{ try {
try
{
return getRequestAttributes().getRequest(); return getRequestAttributes().getRequest();
} } catch (Exception e) {
catch (Exception e)
{
return null; return null;
} }
} }
@ -97,14 +87,10 @@ public class ServletUtils
/** /**
* response * response
*/ */
public static HttpServletResponse getResponse() public static HttpServletResponse getResponse() {
{ try {
try
{
return getRequestAttributes().getResponse(); return getRequestAttributes().getResponse();
} } catch (Exception e) {
catch (Exception e)
{
return null; return null;
} }
} }
@ -112,42 +98,32 @@ public class ServletUtils
/** /**
* session * session
*/ */
public static HttpSession getSession() public static HttpSession getSession() {
{
return getRequest().getSession(); return getRequest().getSession();
} }
public static ServletRequestAttributes getRequestAttributes() public static ServletRequestAttributes getRequestAttributes() {
{ try {
try
{
RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes; return (ServletRequestAttributes) attributes;
} } catch (Exception e) {
catch (Exception e)
{
return null; return null;
} }
} }
public static String getHeader(HttpServletRequest request, String name) public static String getHeader(HttpServletRequest request, String name) {
{
String value = request.getHeader(name); String value = request.getHeader(name);
if (StringUtils.isEmpty(value)) if (StringUtils.isEmpty(value)) {
{
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
return urlDecode(value); return urlDecode(value);
} }
public static Map<String, String> getHeaders(HttpServletRequest request) public static Map<String, String> getHeaders(HttpServletRequest request) {
{
Map<String, String> map = new LinkedHashMap<>(); Map<String, String> map = new LinkedHashMap<>();
Enumeration<String> enumeration = request.getHeaderNames(); Enumeration<String> enumeration = request.getHeaderNames();
if (enumeration != null) if (enumeration != null) {
{ while (enumeration.hasMoreElements()) {
while (enumeration.hasMoreElements())
{
String key = enumeration.nextElement(); String key = enumeration.nextElement();
String value = request.getHeader(key); String value = request.getHeader(key);
map.put(key, value); map.put(key, value);
@ -158,47 +134,39 @@ public class ServletUtils
/** /**
* *
* *
* @param response * @param response
* @param string * @param string
*/ */
public static void renderString(HttpServletResponse response, String string) public static void renderString(HttpServletResponse response, String string) {
{ try {
try
{
response.setStatus(200); response.setStatus(200);
response.setContentType("application/json"); response.setContentType("application/json");
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.getWriter().print(string); response.getWriter().print(string);
} } catch (IOException e) {
catch (IOException e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Ajax * Ajax
* *
* @param request * @param request
*/ */
public static boolean isAjaxRequest(HttpServletRequest request) public static boolean isAjaxRequest(HttpServletRequest request) {
{
String accept = request.getHeader("accept"); String accept = request.getHeader("accept");
if (accept != null && accept.contains("application/json")) if (accept != null && accept.contains(StringUtils.ACCEPT_JSON)) {
{
return true; return true;
} }
String xRequestedWith = request.getHeader("X-Requested-With"); String xRequestedWith = request.getHeader("X-Requested-With");
if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) if (xRequestedWith != null && xRequestedWith.contains(StringUtils.XML_HTTP)) {
{
return true; return true;
} }
String uri = request.getRequestURI(); String uri = request.getRequestURI();
if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) if (StringUtils.inStringIgnoreCase(uri, StringUtils.DOT + StringUtils.JSON, StringUtils.DOT + StringUtils.XML)) {
{
return true; return true;
} }
@ -208,36 +176,28 @@ public class ServletUtils
/** /**
* *
* *
* @param str * @param str
* @return * @return
*/ */
public static String urlEncode(String str) public static String urlEncode(String str) {
{ try {
try
{
return URLEncoder.encode(str, Constants.UTF8); return URLEncoder.encode(str, Constants.UTF8);
} } catch (UnsupportedEncodingException e) {
catch (UnsupportedEncodingException e)
{
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
} }
/** /**
* *
* *
* @param str * @param str
* @return * @return
*/ */
public static String urlDecode(String str) public static String urlDecode(String str) {
{ try {
try
{
return URLDecoder.decode(str, Constants.UTF8); return URLDecoder.decode(str, Constants.UTF8);
} } catch (UnsupportedEncodingException e) {
catch (UnsupportedEncodingException e)
{
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
} }
@ -246,24 +206,22 @@ public class ServletUtils
* webflux * webflux
* *
* @param response ServerHttpResponse * @param response ServerHttpResponse
* @param value * @param value
* @return Mono<Void> * @return Mono<Void>
*/ */
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value) public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value) {
{ return webFluxResponseWriter(response, HttpStatus.OK, value, Rust.FAIL);
return webFluxResponseWriter(response, HttpStatus.OK, value, R.FAIL);
} }
/** /**
* webflux * webflux
* *
* @param response ServerHttpResponse * @param response ServerHttpResponse
* @param code * @param code
* @param value * @param value
* @return Mono<Void> * @return Mono<Void>
*/ */
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value, int code) public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value, int code) {
{
return webFluxResponseWriter(response, HttpStatus.OK, value, code); return webFluxResponseWriter(response, HttpStatus.OK, value, code);
} }
@ -271,31 +229,29 @@ public class ServletUtils
* webflux * webflux
* *
* @param response ServerHttpResponse * @param response ServerHttpResponse
* @param status http * @param status http
* @param code * @param code
* @param value * @param value
* @return Mono<Void> * @return Mono<Void>
*/ */
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, HttpStatus status, Object value, int code) public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, HttpStatus status, Object value, int code) {
{
return webFluxResponseWriter(response, MediaType.APPLICATION_JSON_VALUE, status, value, code); return webFluxResponseWriter(response, MediaType.APPLICATION_JSON_VALUE, status, value, code);
} }
/** /**
* webflux * webflux
* *
* @param response ServerHttpResponse * @param response ServerHttpResponse
* @param contentType content-type * @param contentType content-type
* @param status http * @param status http
* @param code * @param code
* @param value * @param value
* @return Mono<Void> * @return Mono<Void>
*/ */
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, HttpStatus status, Object value, int code) public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, HttpStatus status, Object value, int code) {
{
response.setStatusCode(status); response.setStatusCode(status);
response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType); response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
R<?> result = R.fail(code, value.toString()); Rust<?> result = Rust.fail(code, value.toString());
DataBuffer dataBuffer = response.bufferFactory().wrap(JSONObject.toJSONString(result).getBytes()); DataBuffer dataBuffer = response.bufferFactory().wrap(JSONObject.toJSONString(result).getBytes());
return response.writeWith(Mono.just(dataBuffer)); return response.writeWith(Mono.just(dataBuffer));
} }

@ -9,32 +9,25 @@ import org.springframework.stereotype.Component;
/** /**
* spring 便springbean * spring 便springbean
* *
* @author ruoyi * @author ruoyi
*/ */
@Component @Component
public final class SpringUtils implements BeanFactoryPostProcessor public final class SpringUtils implements BeanFactoryPostProcessor {
{ /**
/** Spring应用上下文环境 */ * Spring
*/
private static ConfigurableListableBeanFactory beanFactory; private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
SpringUtils.beanFactory = beanFactory;
}
/** /**
* *
* *
* @param name * @param name
* @return Object bean * @return Object bean
* @throws org.springframework.beans.BeansException * @throws org.springframework.beans.BeansException
*
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException public static <T> T getBean(String name) throws BeansException {
{
return (T) beanFactory.getBean(name); return (T) beanFactory.getBean(name);
} }
@ -44,10 +37,8 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param clz * @param clz
* @return * @return
* @throws org.springframework.beans.BeansException * @throws org.springframework.beans.BeansException
*
*/ */
public static <T> T getBean(Class<T> clz) throws BeansException public static <T> T getBean(Class<T> clz) throws BeansException {
{
T result = (T) beanFactory.getBean(clz); T result = (T) beanFactory.getBean(clz);
return result; return result;
} }
@ -58,8 +49,7 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param name * @param name
* @return boolean * @return boolean
*/ */
public static boolean containsBean(String name) public static boolean containsBean(String name) {
{
return beanFactory.containsBean(name); return beanFactory.containsBean(name);
} }
@ -69,10 +59,8 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param name * @param name
* @return boolean * @return boolean
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/ */
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
{
return beanFactory.isSingleton(name); return beanFactory.isSingleton(name);
} }
@ -80,10 +68,8 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param name * @param name
* @return Class * @return Class
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/ */
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
{
return beanFactory.getType(name); return beanFactory.getType(name);
} }
@ -93,22 +79,24 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param name * @param name
* @return * @return
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/ */
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
{
return beanFactory.getAliases(name); return beanFactory.getAliases(name);
} }
/** /**
* aop * aop
* *
* @param invoker * @param invoker
* @return * @return
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T getAopProxy(T invoker) public static <T> T getAopProxy(T invoker) {
{
return (T) AopContext.currentProxy(); return (T) AopContext.currentProxy();
} }
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtils.beanFactory = beanFactory;
}
} }

@ -1,190 +1,276 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.text.StrFormatter;
import org.springframework.util.AntPathMatcher;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.springframework.util.AntPathMatcher;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.text.StrFormatter;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class StringUtils extends org.apache.commons.lang3.StringUtils public class StringUtils extends org.apache.commons.lang3.StringUtils {
{ /**
/** 空字符串 */ *
private static final String NULLSTR = ""; */
public static final String NULLSTR = "";
/**
*
*/
public static final String BLANK_SPACE = " ";
/**
*
*/
public static final String SLASH = "/";
/**
*
*/
public static final String WELL_NO = "#";
/**
*
*/
public static final String DOT = ".";
/**
*
*/
public static final String COMMA = ",";
/**
* (
*/
public static final String LEFT_BRACKETS = "(";
/**
* get
*/
public static final String GET = "GET";
/**
* POST
*/
public static final String POST = "POST";
/**
* DELETE
*/
public static final String DELETE = "DELETE";
/**
*
*/
public static final String ASC_ENDING = "ascending";
/**
*
*/
public static final String DESC_ENDING = "descending";
/**
* true
*/
public static final String TRUE = "true";
/**
* registerUser
*/
public static final String SYS_ACCOUNT_USER = "sys.account.registerUser";
/**
* char
*/
public static final String CHAR = "char";
/**
* math
*/
public static final String MATH = "math";
/**
* JPG
*/
public static final String JPG = "JPG";
/**
* PNG
*/
public static final String PNG = "PNG";
/**
*
*/
public static final String NOTE = "注:";
/**
* MSIE
*/
public static final String MSIE = "MSIE";
/**
* Firefox
*/
public static final String FIREFOX = "Firefox";
/**
* Chrome
*/
public static final String CHROME = "Chrome";
/**
* json
*/
public static final String ACCEPT_JSON = "application/json";
/**
* XMLHttpRequest
*/
public static final String XML_HTTP = "XMLHttpRequest";
/**
* json
*/
public static final String JSON = "json";
/**
* xml
*/
public static final String XML = "xml";
/** 下划线 */ /**
private static final char SEPARATOR = '_'; * 线
*/
public static final char SEPARATOR = '_';
/** /**
* *
* *
* @param value defaultValue value * @param value defaultValue value
* @return value * @return value
*/ */
public static <T> T nvl(T value, T defaultValue) public static <T> T nvl(T value, T defaultValue) {
{
return value != null ? value : defaultValue; return value != null ? value : defaultValue;
} }
/** /**
* * Collection ListSetQueue * * Collection ListSetQueue
* *
* @param coll Collection * @param coll Collection
* @return true false * @return true false
*/ */
public static boolean isEmpty(Collection<?> coll) public static boolean isEmpty(Collection<?> coll) {
{
return isNull(coll) || coll.isEmpty(); return isNull(coll) || coll.isEmpty();
} }
/** /**
* * CollectionListSetQueue * * CollectionListSetQueue
* *
* @param coll Collection * @param coll Collection
* @return true false * @return true false
*/ */
public static boolean isNotEmpty(Collection<?> coll) public static boolean isNotEmpty(Collection<?> coll) {
{
return !isEmpty(coll); return !isEmpty(coll);
} }
/** /**
* * * *
* *
* @param objects * @param objects
** @return true false * * @return true false
*/ */
public static boolean isEmpty(Object[] objects) public static boolean isEmpty(Object[] objects) {
{
return isNull(objects) || (objects.length == 0); return isNull(objects) || (objects.length == 0);
} }
/** /**
* * * *
* *
* @param objects * @param objects
* @return true false * @return true false
*/ */
public static boolean isNotEmpty(Object[] objects) public static boolean isNotEmpty(Object[] objects) {
{
return !isEmpty(objects); return !isEmpty(objects);
} }
/** /**
* * Map * * Map
* *
* @param map Map * @param map Map
* @return true false * @return true false
*/ */
public static boolean isEmpty(Map<?, ?> map) public static boolean isEmpty(Map<?, ?> map) {
{
return isNull(map) || map.isEmpty(); return isNull(map) || map.isEmpty();
} }
/** /**
* * Map * * Map
* *
* @param map Map * @param map Map
* @return true false * @return true false
*/ */
public static boolean isNotEmpty(Map<?, ?> map) public static boolean isNotEmpty(Map<?, ?> map) {
{
return !isEmpty(map); return !isEmpty(map);
} }
/** /**
* * * *
* *
* @param str String * @param str String
* @return true false * @return true false
*/ */
public static boolean isEmpty(String str) public static boolean isEmpty(String str) {
{
return isNull(str) || NULLSTR.equals(str.trim()); return isNull(str) || NULLSTR.equals(str.trim());
} }
/** /**
* * * *
* *
* @param str String * @param str String
* @return true false * @return true false
*/ */
public static boolean isNotEmpty(String str) public static boolean isNotEmpty(String str) {
{
return !isEmpty(str); return !isEmpty(str);
} }
/** /**
* * * *
* *
* @param object Object * @param object Object
* @return true false * @return true false
*/ */
public static boolean isNull(Object object) public static boolean isNull(Object object) {
{
return object == null; return object == null;
} }
/** /**
* * * *
* *
* @param object Object * @param object Object
* @return true false * @return true false
*/ */
public static boolean isNotNull(Object object) public static boolean isNotNull(Object object) {
{
return !isNull(object); return !isNull(object);
} }
/** /**
* * Java * * Java
* *
* @param object * @param object
* @return true false * @return true false
*/ */
public static boolean isArray(Object object) public static boolean isArray(Object object) {
{
return isNotNull(object) && object.getClass().isArray(); return isNotNull(object) && object.getClass().isArray();
} }
/** /**
* *
*/ */
public static String trim(String str) public static String trim(String str) {
{
return (str == null ? "" : str.trim()); return (str == null ? "" : str.trim());
} }
/** /**
* *
* *
* @param str * @param str
* @param start * @param start
* @return * @return
*/ */
public static String substring(final String str, int start) public static String substring(final String str, int start) {
{ if (str == null) {
if (str == null)
{
return NULLSTR; return NULLSTR;
} }
if (start < 0) if (start < 0) {
{
start = str.length() + start; start = str.length() + start;
} }
if (start < 0) if (start < 0) {
{
start = 0; start = 0;
} }
if (start > str.length()) if (start > str.length()) {
{
return NULLSTR; return NULLSTR;
} }
@ -193,44 +279,36 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* *
* *
* @param str * @param str
* @param start * @param start
* @param end * @param end
* @return * @return
*/ */
public static String substring(final String str, int start, int end) public static String substring(final String str, int start, int end) {
{ if (str == null) {
if (str == null)
{
return NULLSTR; return NULLSTR;
} }
if (end < 0) if (end < 0) {
{
end = str.length() + end; end = str.length() + end;
} }
if (start < 0) if (start < 0) {
{
start = str.length() + start; start = str.length() + start;
} }
if (end > str.length()) if (end > str.length()) {
{
end = str.length(); end = str.length();
} }
if (start > end) if (start > end) {
{
return NULLSTR; return NULLSTR;
} }
if (start < 0) if (start < 0) {
{
start = 0; start = 0;
} }
if (end < 0) if (end < 0) {
{
end = 0; end = 0;
} }
@ -239,22 +317,18 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* *
* *
* @param str value * @param str value
* @return * @return
*/ */
public static boolean hasText(String str) public static boolean hasText(String str) {
{
return (str != null && !str.isEmpty() && containsText(str)); return (str != null && !str.isEmpty() && containsText(str));
} }
private static boolean containsText(CharSequence str) private static boolean containsText(CharSequence str) {
{
int strLen = str.length(); int strLen = str.length();
for (int i = 0; i < strLen; i++) for (int i = 0; i < strLen; i++) {
{ if (!Character.isWhitespace(str.charAt(i))) {
if (!Character.isWhitespace(str.charAt(i)))
{
return true; return true;
} }
} }
@ -269,15 +343,13 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* 使format("this is {} for {}", "a", "b") -> this is a for b<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 \{} for a<br>
* \ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br> * \ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
* *
* @param template {} * @param template {}
* @param params * @param params
* @return * @return
*/ */
public static String format(String template, Object... params) public static String format(String template, Object... params) {
{ if (isEmpty(params) || isEmpty(template)) {
if (isEmpty(params) || isEmpty(template))
{
return template; return template;
} }
return StrFormatter.format(template, params); return StrFormatter.format(template, params);
@ -285,22 +357,19 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* http(s)://开头 * http(s)://开头
* *
* @param link * @param link
* @return * @return
*/ */
public static boolean ishttp(String link) public static boolean ishttp(String link) {
{
return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS); return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS);
} }
/** /**
* 线 * 线
*/ */
public static String toUnderScoreCase(String str) public static String toUnderScoreCase(String str) {
{ if (str == null) {
if (str == null)
{
return null; return null;
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -310,31 +379,23 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
boolean curreCharIsUpperCase = true; boolean curreCharIsUpperCase = true;
// 下一字符是否大写 // 下一字符是否大写
boolean nexteCharIsUpperCase = true; boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++) for (int i = 0; i < str.length(); i++) {
{
char c = str.charAt(i); char c = str.charAt(i);
if (i > 0) if (i > 0) {
{
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1)); preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
} } else {
else
{
preCharIsUpperCase = false; preCharIsUpperCase = false;
} }
curreCharIsUpperCase = Character.isUpperCase(c); curreCharIsUpperCase = Character.isUpperCase(c);
if (i < (str.length() - 1)) if (i < (str.length() - 1)) {
{
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1)); nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
} }
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
{
sb.append(SEPARATOR); sb.append(SEPARATOR);
} } else if (i != 0 && !preCharIsUpperCase && curreCharIsUpperCase) {
else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)
{
sb.append(SEPARATOR); sb.append(SEPARATOR);
} }
sb.append(Character.toLowerCase(c)); sb.append(Character.toLowerCase(c));
@ -345,19 +406,15 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* *
* *
* @param str * @param str
* @param strs * @param strs
* @return true * @return true
*/ */
public static boolean inStringIgnoreCase(String str, String... strs) public static boolean inStringIgnoreCase(String str, String... strs) {
{ if (str != null && strs != null) {
if (str != null && strs != null) for (String s : strs) {
{ if (str.equalsIgnoreCase(trim(s))) {
for (String s : strs)
{
if (str.equalsIgnoreCase(trim(s)))
{
return true; return true;
} }
} }
@ -367,31 +424,26 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* 线线 HELLO_WORLD->HelloWorld * 线线 HELLO_WORLD->HelloWorld
* *
* @param name 线 * @param name 线
* @return * @return
*/ */
public static String convertToCamelCase(String name) public static String convertToCamelCase(String name) {
{
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
String underline = "_";
// 快速检查 // 快速检查
if (name == null || name.isEmpty()) if (name == null || name.isEmpty()) {
{
// 没必要转换 // 没必要转换
return ""; return "";
} } else if (!name.contains(underline)) {
else if (!name.contains("_"))
{
// 不含下划线,仅将首字母大写 // 不含下划线,仅将首字母大写
return name.substring(0, 1).toUpperCase() + name.substring(1); return name.substring(0, 1).toUpperCase() + name.substring(1);
} }
// 用下划线将原始字符串分割 // 用下划线将原始字符串分割
String[] camels = name.split("_"); String[] camels = name.split(underline);
for (String camel : camels) for (String camel : camels) {
{
// 跳过原始字符串中开头、结尾的下换线或双重下划线 // 跳过原始字符串中开头、结尾的下换线或双重下划线
if (camel.isEmpty()) if (camel.isEmpty()) {
{
continue; continue;
} }
// 首字母大写 // 首字母大写
@ -404,30 +456,22 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* user_name->userName * user_name->userName
*/ */
public static String toCamelCase(String s) public static String toCamelCase(String s) {
{ if (s == null) {
if (s == null)
{
return null; return null;
} }
s = s.toLowerCase(); s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length()); StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false; boolean upperCase = false;
for (int i = 0; i < s.length(); i++) for (int i = 0; i < s.length(); i++) {
{
char c = s.charAt(i); char c = s.charAt(i);
if (c == SEPARATOR) if (c == SEPARATOR) {
{
upperCase = true; upperCase = true;
} } else if (upperCase) {
else if (upperCase)
{
sb.append(Character.toUpperCase(c)); sb.append(Character.toUpperCase(c));
upperCase = false; upperCase = false;
} } else {
else
{
sb.append(c); sb.append(c);
} }
} }
@ -436,21 +480,17 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/** /**
* *
* *
* @param str * @param str
* @param strs * @param strs
* @return * @return
*/ */
public static boolean matches(String str, List<String> strs) public static boolean matches(String str, List<String> strs) {
{ if (isEmpty(str) || isEmpty(strs)) {
if (isEmpty(str) || isEmpty(strs))
{
return false; return false;
} }
for (String pattern : strs) for (String pattern : strs) {
{ if (isMatch(pattern, str)) {
if (isMatch(pattern, str))
{
return true; return true;
} }
} }
@ -458,70 +498,58 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
} }
/** /**
* url: * url:
* ? ; * ? ;
* * ; * * ;
* ** ; * ** ;
* *
* @param pattern * @param pattern
* @param url url * @param url url
* @return * @return
*/ */
public static boolean isMatch(String pattern, String url) public static boolean isMatch(String pattern, String url) {
{
AntPathMatcher matcher = new AntPathMatcher(); AntPathMatcher matcher = new AntPathMatcher();
return matcher.match(pattern, url); return matcher.match(pattern, url);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T cast(Object obj) public static <T> T cast(Object obj) {
{
return (T) obj; return (T) obj;
} }
/** /**
* 0使size size * 0使size size
* *
* @param num * @param num
* @param size * @param size
* @return * @return
*/ */
public static final String padl(final Number num, final int size) public static final String padl(final Number num, final int size) {
{
return padl(num.toString(), size, '0'); return padl(num.toString(), size, '0');
} }
/** /**
* ssizesize * ssizesize
* *
* @param s * @param s
* @param size * @param size
* @param c * @param c
* @return * @return
*/ */
public static final String padl(final String s, final int size, final char c) public static final String padl(final String s, final int size, final char c) {
{
final StringBuilder sb = new StringBuilder(size); final StringBuilder sb = new StringBuilder(size);
if (s != null) if (s != null) {
{
final int len = s.length(); final int len = s.length();
if (s.length() <= size) if (s.length() <= size) {
{ for (int i = size - len; i > 0; i--) {
for (int i = size - len; i > 0; i--)
{
sb.append(c); sb.append(c);
} }
sb.append(s); sb.append(s);
} } else {
else
{
return s.substring(len - size, len); return s.substring(len - size, len);
} }
} } else {
else for (int i = size; i > 0; i--) {
{
for (int i = size; i > 0; i--)
{
sb.append(c); sb.append(c);
} }
} }

@ -8,46 +8,46 @@ import java.util.regex.Pattern;
/** /**
* Bean * Bean
* *
* @author ruoyi * @author ruoyi
*/ */
public class BeanUtils extends org.springframework.beans.BeanUtils public class BeanUtils extends org.springframework.beans.BeanUtils {
{ /**
/** Bean方法名中属性名开始的下标 */ * Bean
*/
private static final int BEAN_METHOD_PROP_INDEX = 3; private static final int BEAN_METHOD_PROP_INDEX = 3;
/** * 匹配getter方法的正则表达式 */ /**
* getter
*/
private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)"); private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)");
/** * 匹配setter方法的正则表达式 */ /**
* setter
*/
private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)"); private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)");
/** /**
* Bean * Bean
* *
* @param dest * @param dest
* @param src * @param src
*/ */
public static void copyBeanProp(Object dest, Object src) public static void copyBeanProp(Object dest, Object src) {
{ try {
try
{
copyProperties(src, dest); copyProperties(src, dest);
} } catch (Exception e) {
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* setter * setter
* *
* @param obj * @param obj
* @return setter * @return setter
*/ */
public static List<Method> getSetterMethods(Object obj) public static List<Method> getSetterMethods(Object obj) {
{
// setter方法列表 // setter方法列表
List<Method> setterMethods = new ArrayList<Method>(); List<Method> setterMethods = new ArrayList<Method>();
@ -56,11 +56,9 @@ public class BeanUtils extends org.springframework.beans.BeanUtils
// 查找setter方法 // 查找setter方法
for (Method method : methods) for (Method method : methods) {
{
Matcher m = SET_PATTERN.matcher(method.getName()); Matcher m = SET_PATTERN.matcher(method.getName());
if (m.matches() && (method.getParameterTypes().length == 1)) if (m.matches() && (method.getParameterTypes().length == 1)) {
{
setterMethods.add(method); setterMethods.add(method);
} }
} }
@ -70,23 +68,20 @@ public class BeanUtils extends org.springframework.beans.BeanUtils
/** /**
* getter * getter
* *
* @param obj * @param obj
* @return getter * @return getter
*/ */
public static List<Method> getGetterMethods(Object obj) public static List<Method> getGetterMethods(Object obj) {
{
// getter方法列表 // getter方法列表
List<Method> getterMethods = new ArrayList<Method>(); List<Method> getterMethods = new ArrayList<Method>();
// 获取所有方法 // 获取所有方法
Method[] methods = obj.getClass().getMethods(); Method[] methods = obj.getClass().getMethods();
// 查找getter方法 // 查找getter方法
for (Method method : methods) for (Method method : methods) {
{
Matcher m = GET_PATTERN.matcher(method.getName()); Matcher m = GET_PATTERN.matcher(method.getName());
if (m.matches() && (method.getParameterTypes().length == 0)) if (m.matches() && (method.getParameterTypes().length == 0)) {
{
getterMethods.add(method); getterMethods.add(method);
} }
} }
@ -97,14 +92,13 @@ public class BeanUtils extends org.springframework.beans.BeanUtils
/** /**
* Bean<br> * Bean<br>
* getName()setName()getName()setAge() * getName()setName()getName()setAge()
* *
* @param m1 1 * @param m1 1
* @param m2 2 * @param m2 2
* @return truefalse * @return truefalse
*/ */
public static boolean isMethodPropEquals(String m1, String m2) public static boolean isMethodPropEquals(String m1, String m2) {
{
return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX)); return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX));
} }
} }

@ -1,23 +1,20 @@
package com.ruoyi.common.core.utils.bean; package com.ruoyi.common.core.utils.bean;
import java.util.Set;
import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException; import javax.validation.ConstraintViolationException;
import javax.validation.Validator; import javax.validation.Validator;
import java.util.Set;
/** /**
* bean * bean
* *
* @author ruoyi * @author ruoyi
*/ */
public class BeanValidators public class BeanValidators {
{
public static void validateWithException(Validator validator, Object object, Class<?>... groups) public static void validateWithException(Validator validator, Object object, Class<?>... groups)
throws ConstraintViolationException throws ConstraintViolationException {
{
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups); Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) if (!constraintViolations.isEmpty()) {
{
throw new ConstraintViolationException(constraintViolations); throw new ConstraintViolationException(constraintViolations);
} }
} }

@ -1,27 +1,25 @@
package com.ruoyi.common.core.utils.file; package com.ruoyi.common.core.utils.file;
import java.io.File;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import java.io.File;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class FileTypeUtils public class FileTypeUtils {
{
/** /**
* *
* <p> * <p>
* : ruoyi.txt, : txt * : ruoyi.txt, : txt
* *
* @param file * @param file
* @return ".") * @return ".")
*/ */
public static String getFileType(File file) public static String getFileType(File file) {
{ if (null == file) {
if (null == file)
{
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
return getFileType(file.getName()); return getFileType(file.getName());
@ -35,11 +33,9 @@ public class FileTypeUtils
* @param fileName * @param fileName
* @return ".") * @return ".")
*/ */
public static String getFileType(String fileName) public static String getFileType(String fileName) {
{
int separatorIndex = fileName.lastIndexOf("."); int separatorIndex = fileName.lastIndexOf(".");
if (separatorIndex < 0) if (separatorIndex < 0) {
{
return ""; return "";
} }
return fileName.substring(separatorIndex + 1).toLowerCase(); return fileName.substring(separatorIndex + 1).toLowerCase();
@ -47,30 +43,43 @@ public class FileTypeUtils
/** /**
* *
* *
* @param photoByte * @param photoByte
* @return ".") * @return ".")
*/ */
public static String getFileExtendName(byte[] photoByte) public static String getFileExtendName(byte[] photoByte) {
{
String strFileExtendName = "JPG"; String strFileExtendName = "JPG";
if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56) int i71 = 71;
&& ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) int i73 = 73;
{ int i2 = 2;
strFileExtendName = "GIF"; int i70 = 70;
} int i3 = 3;
else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) int i56 = 56;
{ int i5 = 5;
int i97 = 97;
int i4 = 4;
int i55 = 55;
int i57 = 57;
int i6 = 6;
int i74 = 74;
int i7 = 7;
int i8 = 8;
int i9 = 9;
int i66 = 66;
int i77 = 77;
int i80 = 80;
int i78 = 78;
if ((photoByte[0] == i71) && (photoByte[1] == i73) && (photoByte[i2] == i70) && (photoByte[i3] == i56) && (photoByte[i5] == i97)) {
if ((photoByte[i4] == i55) || (photoByte[i4] == i57)) {
strFileExtendName = "GIF";
}
} else if ((photoByte[i6] == i74) && (photoByte[i7] == i70) && (photoByte[i8] == i73) && (photoByte[i9] == i70)) {
strFileExtendName = "JPG"; strFileExtendName = "JPG";
} } else if ((photoByte[0] == i66) && (photoByte[1] == i77)) {
else if ((photoByte[0] == 66) && (photoByte[1] == 77))
{
strFileExtendName = "BMP"; strFileExtendName = "BMP";
} } else if ((photoByte[1] == i80) && (photoByte[i2] == i78) && (photoByte[i3] == i71)) {
else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71))
{
strFileExtendName = "PNG"; strFileExtendName = "PNG";
} }
return strFileExtendName; return strFileExtendName;
} }
} }

@ -1,83 +1,64 @@
package com.ruoyi.common.core.utils.file; package com.ruoyi.common.core.utils.file;
import java.io.File; import com.ruoyi.common.core.utils.StringUtils;
import java.io.FileInputStream; import org.apache.commons.lang3.ArrayUtils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils; import java.io.*;
import com.ruoyi.common.core.utils.StringUtils; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class FileUtils public class FileUtils {
{ /**
/** 字符常量:斜杠 {@code '/'} */ * {@code '/'}
*/
public static final char SLASH = '/'; public static final char SLASH = '/';
/** 字符常量:反斜杠 {@code '\\'} */ /**
* {@code '\\'}
*/
public static final char BACKSLASH = '\\'; public static final char BACKSLASH = '\\';
public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-|.\\u4e00-\\u9fa5]+";
/** /**
* byte * byte
* *
* @param filePath * @param filePath
* @param os * @param os
* @return * @return
*/ */
public static void writeBytes(String filePath, OutputStream os) throws IOException public static void writeBytes(String filePath, OutputStream os) throws IOException {
{
FileInputStream fis = null; FileInputStream fis = null;
try try {
{
File file = new File(filePath); File file = new File(filePath);
if (!file.exists()) if (!file.exists()) {
{
throw new FileNotFoundException(filePath); throw new FileNotFoundException(filePath);
} }
fis = new FileInputStream(file); fis = new FileInputStream(file);
byte[] b = new byte[1024]; byte[] b = new byte[1024];
int length; int length;
while ((length = fis.read(b)) > 0) while ((length = fis.read(b)) > 0) {
{
os.write(b, 0, length); os.write(b, 0, length);
} }
} } finally {
catch (IOException e) if (os != null) {
{ try {
throw e;
}
finally
{
if (os != null)
{
try
{
os.close(); os.close();
} } catch (IOException e1) {
catch (IOException e1)
{
e1.printStackTrace(); e1.printStackTrace();
} }
} }
if (fis != null) if (fis != null) {
{ try {
try
{
fis.close(); fis.close();
} } catch (IOException e1) {
catch (IOException e1)
{
e1.printStackTrace(); e1.printStackTrace();
} }
} }
@ -86,17 +67,15 @@ public class FileUtils
/** /**
* *
* *
* @param filePath * @param filePath
* @return * @return
*/ */
public static boolean deleteFile(String filePath) public static boolean deleteFile(String filePath) {
{
boolean flag = false; boolean flag = false;
File file = new File(filePath); File file = new File(filePath);
// 路径为文件且不为空则进行删除 // 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) if (file.isFile() && file.exists()) {
{
file.delete(); file.delete();
flag = true; flag = true;
} }
@ -105,32 +84,28 @@ public class FileUtils
/** /**
* *
* *
* @param filename * @param filename
* @return true false * @return true false
*/ */
public static boolean isValidFilename(String filename) public static boolean isValidFilename(String filename) {
{
return filename.matches(FILENAME_PATTERN); return filename.matches(FILENAME_PATTERN);
} }
/** /**
* *
* *
* @param resource * @param resource
* @return true false * @return true false
*/ */
public static boolean checkAllowDownload(String resource) public static boolean checkAllowDownload(String resource) {
{
// 禁止目录上跳级别 // 禁止目录上跳级别
if (StringUtils.contains(resource, "..")) if (StringUtils.contains(resource, StringUtils.DOT + StringUtils.DOT)) {
{
return false; return false;
} }
// 检查允许下载的文件规则 // 检查允许下载的文件规则
if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource))) if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource))) {
{
return true; return true;
} }
@ -140,33 +115,25 @@ public class FileUtils
/** /**
* *
* *
* @param request * @param request
* @param fileName * @param fileName
* @return * @return
*/ */
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
{
final String agent = request.getHeader("USER-AGENT"); final String agent = request.getHeader("USER-AGENT");
String filename = fileName; String filename = fileName;
if (agent.contains("MSIE")) if (agent.contains(StringUtils.MSIE)) {
{
// IE浏览器 // IE浏览器
filename = URLEncoder.encode(filename, "utf-8"); filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " "); filename = filename.replace("+", " ");
} } else if (agent.contains(StringUtils.FIREFOX)) {
else if (agent.contains("Firefox"))
{
// 火狐浏览器 // 火狐浏览器
filename = new String(fileName.getBytes(), "ISO8859-1"); filename = new String(fileName.getBytes(), "ISO8859-1");
} } else if (agent.contains(StringUtils.CHROME)) {
else if (agent.contains("Chrome"))
{
// google浏览器 // google浏览器
filename = URLEncoder.encode(filename, "utf-8"); filename = URLEncoder.encode(filename, "utf-8");
} } else {
else
{
// 其它浏览器 // 其它浏览器
filename = URLEncoder.encode(filename, "utf-8"); filename = URLEncoder.encode(filename, "utf-8");
} }
@ -179,30 +146,24 @@ public class FileUtils
* @param filePath * @param filePath
* @return * @return
*/ */
public static String getName(String filePath) public static String getName(String filePath) {
{ if (null == filePath) {
if (null == filePath)
{
return null; return null;
} }
int len = filePath.length(); int len = filePath.length();
if (0 == len) if (0 == len) {
{
return filePath; return filePath;
} }
if (isFileSeparator(filePath.charAt(len - 1))) if (isFileSeparator(filePath.charAt(len - 1))) {
{
// 以分隔符结尾的去掉结尾分隔符 // 以分隔符结尾的去掉结尾分隔符
len--; len--;
} }
int begin = 0; int begin = 0;
char c; char c;
for (int i = len - 1; i > -1; i--) for (int i = len - 1; i > -1; i--) {
{
c = filePath.charAt(i); c = filePath.charAt(i);
if (isFileSeparator(c)) if (isFileSeparator(c)) {
{
// 查找最后一个路径分隔符(/或者\ // 查找最后一个路径分隔符(/或者\
begin = i + 1; begin = i + 1;
break; break;
@ -219,20 +180,18 @@ public class FileUtils
* @param c * @param c
* @return WindowsLinuxUnix * @return WindowsLinuxUnix
*/ */
public static boolean isFileSeparator(char c) public static boolean isFileSeparator(char c) {
{
return SLASH == c || BACKSLASH == c; return SLASH == c || BACKSLASH == c;
} }
/** /**
* *
* *
* @param response * @param response
* @param realFileName * @param realFileName
* @return * @return
*/ */
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
{
String percentEncodedFileName = percentEncode(realFileName); String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder(); StringBuilder contentDispositionValue = new StringBuilder();
@ -253,8 +212,7 @@ public class FileUtils
* @param s * @param s
* @return * @return
*/ */
public static String percentEncode(String s) throws UnsupportedEncodingException public static String percentEncode(String s) throws UnsupportedEncodingException {
{
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString()); String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\\+", "%20"); return encode.replaceAll("\\+", "%20");
} }

@ -1,67 +1,55 @@
package com.ruoyi.common.core.utils.file; package com.ruoyi.common.core.utils.file;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.Arrays; import java.util.Arrays;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class ImageUtils public class ImageUtils {
{
private static final Logger log = LoggerFactory.getLogger(ImageUtils.class); private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
public static byte[] getImage(String imagePath) public static byte[] getImage(String imagePath) {
{
InputStream is = getFile(imagePath); InputStream is = getFile(imagePath);
try try {
{
return IOUtils.toByteArray(is); return IOUtils.toByteArray(is);
} } catch (Exception e) {
catch (Exception e) log.error("图片加载异常 ", e);
{
log.error("图片加载异常 {}", e);
return null; return null;
} } finally {
finally
{
IOUtils.closeQuietly(is); IOUtils.closeQuietly(is);
} }
} }
public static InputStream getFile(String imagePath) public static InputStream getFile(String imagePath) {
{ try {
try
{
byte[] result = readFile(imagePath); byte[] result = readFile(imagePath);
result = Arrays.copyOf(result, result.length); result = Arrays.copyOf(result, result.length);
return new ByteArrayInputStream(result); return new ByteArrayInputStream(result);
} } catch (Exception e) {
catch (Exception e) log.error("获取图片异常 ", e);
{
log.error("获取图片异常 {}", e);
} }
return null; return null;
} }
/** /**
* *
* *
* @param url * @param url
* @return * @return
*/ */
public static byte[] readFile(String url) public static byte[] readFile(String url) {
{
InputStream in = null; InputStream in = null;
try try {
{
// 网络地址 // 网络地址
URL urlObj = new URL(url); URL urlObj = new URL(url);
URLConnection urlConnection = urlObj.openConnection(); URLConnection urlConnection = urlObj.openConnection();
@ -70,14 +58,10 @@ public class ImageUtils
urlConnection.setDoInput(true); urlConnection.setDoInput(true);
in = urlConnection.getInputStream(); in = urlConnection.getInputStream();
return IOUtils.toByteArray(in); return IOUtils.toByteArray(in);
} } catch (Exception e) {
catch (Exception e) log.error("访问文件异常 ", e);
{
log.error("访问文件异常 {}", e);
return null; return null;
} } finally {
finally
{
IOUtils.closeQuietly(in); IOUtils.closeQuietly(in);
} }
} }

@ -2,11 +2,10 @@ package com.ruoyi.common.core.utils.file;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class MimeTypeUtils public class MimeTypeUtils {
{
public static final String IMAGE_PNG = "image/png"; public static final String IMAGE_PNG = "image/png";
public static final String IMAGE_JPG = "image/jpg"; public static final String IMAGE_JPG = "image/jpg";
@ -17,14 +16,14 @@ public class MimeTypeUtils
public static final String IMAGE_GIF = "image/gif"; public static final String IMAGE_GIF = "image/gif";
public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" }; public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};
public static final String[] FLASH_EXTENSION = { "swf", "flv" }; public static final String[] FLASH_EXTENSION = {"swf", "flv"};
public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
"asf", "rm", "rmvb" }; "asf", "rm", "rmvb"};
public static final String[] VIDEO_EXTENSION = { "mp4", "avi", "rmvb" }; public static final String[] VIDEO_EXTENSION = {"mp4", "avi", "rmvb"};
public static final String[] DEFAULT_ALLOWED_EXTENSION = { public static final String[] DEFAULT_ALLOWED_EXTENSION = {
// 图片 // 图片
@ -36,12 +35,10 @@ public class MimeTypeUtils
// 视频格式 // 视频格式
"mp4", "avi", "rmvb", "mp4", "avi", "rmvb",
// pdf // pdf
"pdf" }; "pdf"};
public static String getExtension(String prefix) public static String getExtension(String prefix) {
{ switch (prefix) {
switch (prefix)
{
case IMAGE_PNG: case IMAGE_PNG:
return "png"; return "png";
case IMAGE_JPG: case IMAGE_JPG:

@ -4,95 +4,82 @@ import com.ruoyi.common.core.utils.StringUtils;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class EscapeUtil public class EscapeUtil {
{
public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)"; public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)";
private static final char[][] TEXT = new char[64][]; private static final char[][] TEXT = new char[64][];
static static {
{ int baseSize = 64;
for (int i = 0; i < 64; i++) for (int i = 0; i < baseSize; i++) {
{ TEXT[i] = new char[]{(char) i};
TEXT[i] = new char[] { (char) i };
} }
// special HTML characters // special HTML characters
TEXT['\''] = "&#039;".toCharArray(); // 单引号 TEXT['\''] = "&#039;".toCharArray();
TEXT['"'] = "&#34;".toCharArray(); // 双引号 TEXT['"'] = "&#34;".toCharArray();
TEXT['&'] = "&#38;".toCharArray(); // &符 TEXT['&'] = "&#38;".toCharArray();
TEXT['<'] = "&#60;".toCharArray(); // 小于号 TEXT['<'] = "&#60;".toCharArray();
TEXT['>'] = "&#62;".toCharArray(); // 大于号 TEXT['>'] = "&#62;".toCharArray();
} }
/** /**
* HTML * HTML
* *
* @param text * @param text
* @return * @return
*/ */
public static String escape(String text) public static String escape(String text) {
{
return encode(text); return encode(text);
} }
/** /**
* HTML * HTML
* *
* @param content HTML * @param content HTML
* @return * @return
*/ */
public static String unescape(String content) public static String unescape(String content) {
{
return decode(content); return decode(content);
} }
/** /**
* HTML * HTML
* *
* @param content * @param content
* @return * @return
*/ */
public static String clean(String content) public static String clean(String content) {
{ return new HtmlFilter().filter(content);
return new HTMLFilter().filter(content);
} }
/** /**
* Escape * Escape
* *
* @param text * @param text
* @return * @return
*/ */
private static String encode(String text) private static String encode(String text) {
{ if (StringUtils.isEmpty(text)) {
if (StringUtils.isEmpty(text))
{
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
final StringBuilder tmp = new StringBuilder(text.length() * 6); final StringBuilder tmp = new StringBuilder(text.length() * 6);
char c; char c;
for (int i = 0; i < text.length(); i++) for (int i = 0; i < text.length(); i++) {
{
c = text.charAt(i); c = text.charAt(i);
if (c < 256) if (c < 256) {
{
tmp.append("%"); tmp.append("%");
if (c < 16) if (c < 16) {
{
tmp.append("0"); tmp.append("0");
} }
tmp.append(Integer.toString(c, 16)); tmp.append(Integer.toString(c, 16));
} } else {
else
{
tmp.append("%u"); tmp.append("%u");
if (c <= 0xfff) if (c <= 0xfff) {
{
// issue#I49JU8@Gitee // issue#I49JU8@Gitee
tmp.append("0"); tmp.append("0");
} }
@ -104,48 +91,36 @@ public class EscapeUtil
/** /**
* Escape * Escape
* *
* @param content * @param content
* @return * @return
*/ */
public static String decode(String content) public static String decode(String content) {
{ if (StringUtils.isEmpty(content)) {
if (StringUtils.isEmpty(content))
{
return content; return content;
} }
StringBuilder tmp = new StringBuilder(content.length()); StringBuilder tmp = new StringBuilder(content.length());
int lastPos = 0, pos = 0; int lastPos = 0, pos = 0;
char ch; char ch;
while (lastPos < content.length()) while (lastPos < content.length()) {
{
pos = content.indexOf("%", lastPos); pos = content.indexOf("%", lastPos);
if (pos == lastPos) if (pos == lastPos) {
{ if (content.charAt(pos + 1) == 'u') {
if (content.charAt(pos + 1) == 'u')
{
ch = (char) Integer.parseInt(content.substring(pos + 2, pos + 6), 16); ch = (char) Integer.parseInt(content.substring(pos + 2, pos + 6), 16);
tmp.append(ch); tmp.append(ch);
lastPos = pos + 6; lastPos = pos + 6;
} } else {
else
{
ch = (char) Integer.parseInt(content.substring(pos + 1, pos + 3), 16); ch = (char) Integer.parseInt(content.substring(pos + 1, pos + 3), 16);
tmp.append(ch); tmp.append(ch);
lastPos = pos + 3; lastPos = pos + 3;
} }
} } else {
else if (pos == -1) {
{
if (pos == -1)
{
tmp.append(content.substring(lastPos)); tmp.append(content.substring(lastPos));
lastPos = content.length(); lastPos = content.length();
} } else {
else tmp.append(content, lastPos, pos);
{
tmp.append(content.substring(lastPos, pos));
lastPos = pos; lastPos = pos;
} }
} }
@ -153,8 +128,7 @@ public class EscapeUtil
return tmp.toString(); return tmp.toString();
} }
public static void main(String[] args) public static void main(String[] args) {
{
String html = "<script>alert(1);</script>"; String html = "<script>alert(1);</script>";
String escape = EscapeUtil.escape(html); String escape = EscapeUtil.escape(html);
// String html = "<scr<script>ipt>alert(\"XSS\")</scr<script>ipt>"; // String html = "<scr<script>ipt>alert(\"XSS\")</scr<script>ipt>";

@ -1,10 +1,8 @@
package com.ruoyi.common.core.utils.html; package com.ruoyi.common.core.utils.html;
import java.util.ArrayList; import com.ruoyi.common.core.utils.StringUtils;
import java.util.Collections;
import java.util.HashMap; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -15,8 +13,7 @@ import java.util.regex.Pattern;
* *
* @author ruoyi * @author ruoyi
*/ */
public final class HTMLFilter public final class HtmlFilter {
{
/** /**
* regex flag union representing /si modifiers in php * regex flag union representing /si modifiers in php
**/ **/
@ -45,7 +42,9 @@ public final class HTMLFilter
private static final Pattern P_RIGHT_ARROW = Pattern.compile(">"); private static final Pattern P_RIGHT_ARROW = Pattern.compile(">");
private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>"); private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>");
// @xxx could grow large... maybe use sesat's ReferenceMap /**
* @xxx could grow large... maybe use sesat's ReferenceMap
*/
private static final ConcurrentMap<String, Pattern> P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<>(); private static final ConcurrentMap<String, Pattern> P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, Pattern> P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<>(); private static final ConcurrentMap<String, Pattern> P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<>();
@ -100,35 +99,34 @@ public final class HTMLFilter
/** /**
* Default constructor. * Default constructor.
*/ */
public HTMLFilter() public HtmlFilter() {
{
vAllowed = new HashMap<>(); vAllowed = new HashMap<>();
final ArrayList<String> a_atts = new ArrayList<>(); final ArrayList<String> aAtos = new ArrayList<>();
a_atts.add("href"); aAtos.add("href");
a_atts.add("target"); aAtos.add("target");
vAllowed.put("a", a_atts); vAllowed.put("a", aAtos);
final ArrayList<String> img_atts = new ArrayList<>(); final ArrayList<String> imgAtts = new ArrayList<>();
img_atts.add("src"); imgAtts.add("src");
img_atts.add("width"); imgAtts.add("width");
img_atts.add("height"); imgAtts.add("height");
img_atts.add("alt"); imgAtts.add("alt");
vAllowed.put("img", img_atts); vAllowed.put("img", imgAtts);
final ArrayList<String> no_atts = new ArrayList<>(); final ArrayList<String> noAtts = new ArrayList<>();
vAllowed.put("b", no_atts); vAllowed.put("b", noAtts);
vAllowed.put("strong", no_atts); vAllowed.put("strong", noAtts);
vAllowed.put("i", no_atts); vAllowed.put("i", noAtts);
vAllowed.put("em", no_atts); vAllowed.put("em", noAtts);
vSelfClosingTags = new String[] { "img" }; vSelfClosingTags = new String[]{"img"};
vNeedClosingTags = new String[] { "a", "b", "strong", "i", "em" }; vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"};
vDisallowed = new String[] {}; vDisallowed = new String[]{};
vAllowedProtocols = new String[] { "http", "mailto", "https" }; // no ftp. vAllowedProtocols = new String[]{"http", "mailto", "https"};
vProtocolAtts = new String[] { "src", "href" }; vProtocolAtts = new String[]{"src", "href"};
vRemoveBlanks = new String[] { "a", "b", "strong", "i", "em" }; vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"};
vAllowedEntities = new String[] { "amp", "gt", "lt", "quot" }; vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"};
stripComment = true; stripComment = true;
encodeQuotes = true; encodeQuotes = true;
alwaysMakeTags = false; alwaysMakeTags = false;
@ -140,8 +138,7 @@ public final class HTMLFilter
* @param conf map containing configuration. keys match field names. * @param conf map containing configuration. keys match field names.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public HTMLFilter(final Map<String, Object> conf) public HtmlFilter(final Map<String, Object> conf) {
{
assert conf.containsKey("vAllowed") : "configuration requires vAllowed"; assert conf.containsKey("vAllowed") : "configuration requires vAllowed";
assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags"; assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags";
@ -165,20 +162,19 @@ public final class HTMLFilter
alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true; alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true;
} }
private void reset() /**
{ * my versions of some PHP library functions
vTagCounts.clear(); *
* @param decimal /
* @return /
*/
public static String chr(final int decimal) {
return String.valueOf((char) decimal);
} }
// --------------------------------------------------------------- // ---------------------------------------------------------------
// my versions of some PHP library functions
public static String chr(final int decimal)
{
return String.valueOf((char) decimal);
}
public static String htmlSpecialChars(final String s) public static String htmlSpecialChars(final String s) {
{
String result = s; String result = s;
result = regexReplace(P_AMP, "&amp;", result); result = regexReplace(P_AMP, "&amp;", result);
result = regexReplace(P_QUOTE, "&quot;", result); result = regexReplace(P_QUOTE, "&quot;", result);
@ -187,22 +183,39 @@ public final class HTMLFilter
return result; return result;
} }
private static String regexReplace(final Pattern regexPattern, final String replacement, final String s) {
Matcher m = regexPattern.matcher(s);
return m.replaceAll(replacement);
}
// --------------------------------------------------------------- // ---------------------------------------------------------------
private static boolean inArray(final String s, final String[] array) {
for (String item : array) {
if (item != null && item.equals(s)) {
return true;
}
}
return false;
}
private void reset() {
vTagCounts.clear();
}
/** /**
* given a user submitted input String, filter out any invalid or restricted html. * given a user submitted input String, filter out any invalid or restricted html.
* *
* @param input text (i.e. submitted by a user) than may contain html * @param input text (i.e. submitted by a user) than may contain html
* @return "clean" version of input, with only valid, whitelisted html elements allowed * @return "clean" version of input, with only valid, whitelisted html elements allowed
*/ */
public String filter(final String input) public String filter(final String input) {
{
reset(); reset();
String s = input; String s = input;
s = escapeComments(s); s = escapeComments(s);
s = balanceHTML(s); s = balancehtml(s);
s = checkTags(s); s = checkTags(s);
@ -213,23 +226,19 @@ public final class HTMLFilter
return s; return s;
} }
public boolean isAlwaysMakeTags() public boolean isAlwaysMakeTags() {
{
return alwaysMakeTags; return alwaysMakeTags;
} }
public boolean isStripComments() public boolean isStripComments() {
{
return stripComment; return stripComment;
} }
private String escapeComments(final String s) private String escapeComments(final String s) {
{
final Matcher m = P_COMMENTS.matcher(s); final Matcher m = P_COMMENTS.matcher(s);
final StringBuffer buf = new StringBuffer(); final StringBuffer buf = new StringBuffer();
if (m.find()) if (m.find()) {
{ final String match = m.group(1);
final String match = m.group(1); // (.*?)
m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->")); m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->"));
} }
m.appendTail(buf); m.appendTail(buf);
@ -237,10 +246,8 @@ public final class HTMLFilter
return buf.toString(); return buf.toString();
} }
private String balanceHTML(String s) private String balancehtml(String s) {
{ if (alwaysMakeTags) {
if (alwaysMakeTags)
{
// //
// try and form html // try and form html
// //
@ -249,9 +256,7 @@ public final class HTMLFilter
s = regexReplace(P_BODY_TO_END, "<$1>", s); s = regexReplace(P_BODY_TO_END, "<$1>", s);
s = regexReplace(P_XML_CONTENT, "$1<$2", s); s = regexReplace(P_XML_CONTENT, "$1<$2", s);
} } else {
else
{
// //
// escape stray brackets // escape stray brackets
// //
@ -269,13 +274,11 @@ public final class HTMLFilter
return s; return s;
} }
private String checkTags(String s) private String checkTags(String s) {
{
Matcher m = P_TAGS.matcher(s); Matcher m = P_TAGS.matcher(s);
final StringBuffer buf = new StringBuffer(); final StringBuffer buf = new StringBuffer();
while (m.find()) while (m.find()) {
{
String replaceStr = m.group(1); String replaceStr = m.group(1);
replaceStr = processTag(replaceStr); replaceStr = processTag(replaceStr);
m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr)); m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr));
@ -285,10 +288,8 @@ public final class HTMLFilter
// these get tallied in processTag // these get tallied in processTag
// (remember to reset before subsequent calls to filter method) // (remember to reset before subsequent calls to filter method)
final StringBuilder sBuilder = new StringBuilder(buf.toString()); final StringBuilder sBuilder = new StringBuilder(buf.toString());
for (String key : vTagCounts.keySet()) for (String key : vTagCounts.keySet()) {
{ for (int ii = 0; ii < vTagCounts.get(key); ii++) {
for (int ii = 0; ii < vTagCounts.get(key); ii++)
{
sBuilder.append("</").append(key).append(">"); sBuilder.append("</").append(key).append(">");
} }
} }
@ -297,18 +298,14 @@ public final class HTMLFilter
return s; return s;
} }
private String processRemoveBlanks(final String s) private String processRemoveBlanks(final String s) {
{
String result = s; String result = s;
for (String tag : vRemoveBlanks) for (String tag : vRemoveBlanks) {
{ if (!P_REMOVE_PAIR_BLANKS.containsKey(tag)) {
if (!P_REMOVE_PAIR_BLANKS.containsKey(tag))
{
P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">")); P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
} }
result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result); result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result);
if (!P_REMOVE_SELF_BLANKS.containsKey(tag)) if (!P_REMOVE_SELF_BLANKS.containsKey(tag)) {
{
P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>")); P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
} }
result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result); result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result);
@ -317,136 +314,88 @@ public final class HTMLFilter
return result; return result;
} }
private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) private String processTag(final String s) {
{
Matcher m = regex_pattern.matcher(s);
return m.replaceAll(replacement);
}
private String processTag(final String s)
{
// ending tags
Matcher m = P_END_TAG.matcher(s); Matcher m = P_END_TAG.matcher(s);
if (m.find()) if (m.find()) {
{
final String name = m.group(1).toLowerCase(); final String name = m.group(1).toLowerCase();
if (allowed(name)) if (allowed(name)) {
{ if (false == inArray(name, vSelfClosingTags)) {
if (false == inArray(name, vSelfClosingTags)) if (vTagCounts.containsKey(name)) {
{
if (vTagCounts.containsKey(name))
{
vTagCounts.put(name, vTagCounts.get(name) - 1); vTagCounts.put(name, vTagCounts.get(name) - 1);
return "</" + name + ">"; return "</" + name + ">";
} }
} }
} }
} }
// starting tags // starting tags
m = P_START_TAG.matcher(s); m = P_START_TAG.matcher(s);
if (m.find()) if (m.find()) {
{
final String name = m.group(1).toLowerCase(); final String name = m.group(1).toLowerCase();
final String body = m.group(2); final String body = m.group(2);
String ending = m.group(3); String ending = m.group(3);
// debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" ); // debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" );
if (allowed(name)) if (allowed(name)) {
{
final StringBuilder params = new StringBuilder(); final StringBuilder params = new StringBuilder();
final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body); final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body);
final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body); final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body);
final List<String> paramNames = new ArrayList<>(); final List<String> paramNames = new ArrayList<>();
final List<String> paramValues = new ArrayList<>(); final List<String> paramValues = new ArrayList<>();
while (m2.find()) while (m2.find()) {
{ paramNames.add(m2.group(1));
paramNames.add(m2.group(1)); // ([a-z0-9]+) paramValues.add(m2.group(3));
paramValues.add(m2.group(3)); // (.*?)
} }
while (m3.find()) while (m3.find()) {
{ paramNames.add(m3.group(1));
paramNames.add(m3.group(1)); // ([a-z0-9]+) paramValues.add(m3.group(3));
paramValues.add(m3.group(3)); // ([^\"\\s']+)
} }
String paramName, paramValue; String paramName, paramValue;
for (int ii = 0; ii < paramNames.size(); ii++) for (int ii = 0; ii < paramNames.size(); ii++) {
{
paramName = paramNames.get(ii).toLowerCase(); paramName = paramNames.get(ii).toLowerCase();
paramValue = paramValues.get(ii); paramValue = paramValues.get(ii);
if (allowedAttribute(name, paramName)) {
// debug( "paramName='" + paramName + "'" ); if (inArray(paramName, vProtocolAtts)) {
// debug( "paramValue='" + paramValue + "'" );
// debug( "allowed? " + vAllowed.get( name ).contains( paramName ) );
if (allowedAttribute(name, paramName))
{
if (inArray(paramName, vProtocolAtts))
{
paramValue = processParamProtocol(paramValue); paramValue = processParamProtocol(paramValue);
} }
params.append(' ').append(paramName).append("=\\\"").append(paramValue).append("\""); params.append(' ').append(paramName).append("=\\\"").append(paramValue).append("\"");
} }
} }
if (inArray(name, vSelfClosingTags)) {
if (inArray(name, vSelfClosingTags))
{
ending = " /"; ending = " /";
} }
if (inArray(name, vNeedClosingTags)) {
if (inArray(name, vNeedClosingTags))
{
ending = ""; ending = "";
} }
if (ending == null || ending.length() < 1) {
if (ending == null || ending.length() < 1) if (vTagCounts.containsKey(name)) {
{
if (vTagCounts.containsKey(name))
{
vTagCounts.put(name, vTagCounts.get(name) + 1); vTagCounts.put(name, vTagCounts.get(name) + 1);
} } else {
else
{
vTagCounts.put(name, 1); vTagCounts.put(name, 1);
} }
} } else {
else
{
ending = " /"; ending = " /";
} }
return "<" + name + params + ending + ">"; return "<" + name + params + ending + ">";
} } else {
else
{
return ""; return "";
} }
} }
// comments // comments
m = P_COMMENT.matcher(s); m = P_COMMENT.matcher(s);
if (!stripComment && m.find()) if (!stripComment && m.find()) {
{
return "<" + m.group() + ">"; return "<" + m.group() + ">";
} }
return ""; return "";
} }
private String processParamProtocol(String s) private String processParamProtocol(String s) {
{
s = decodeEntities(s); s = decodeEntities(s);
final Matcher m = P_PROTOCOL.matcher(s); final Matcher m = P_PROTOCOL.matcher(s);
if (m.find()) if (m.find()) {
{
final String protocol = m.group(1); final String protocol = m.group(1);
if (!inArray(protocol, vAllowedProtocols)) if (!inArray(protocol, vAllowedProtocols)) {
{
// bad protocol, turn into local anchor link instead // bad protocol, turn into local anchor link instead
s = "#" + s.substring(protocol.length() + 1); s = "#" + s.substring(protocol.length() + 1);
if (s.startsWith("#//")) if (s.startsWith(StringUtils.WELL_NO + StringUtils.SLASH + StringUtils.SLASH)) {
{
s = "#" + s.substring(3); s = "#" + s.substring(3);
} }
} }
@ -455,13 +404,11 @@ public final class HTMLFilter
return s; return s;
} }
private String decodeEntities(String s) private String decodeEntities(String s) {
{
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
Matcher m = P_ENTITY.matcher(s); Matcher m = P_ENTITY.matcher(s);
while (m.find()) while (m.find()) {
{
final String match = m.group(1); final String match = m.group(1);
final int decimal = Integer.decode(match).intValue(); final int decimal = Integer.decode(match).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
@ -471,8 +418,7 @@ public final class HTMLFilter
buf = new StringBuffer(); buf = new StringBuffer();
m = P_ENTITY_UNICODE.matcher(s); m = P_ENTITY_UNICODE.matcher(s);
while (m.find()) while (m.find()) {
{
final String match = m.group(1); final String match = m.group(1);
final int decimal = Integer.valueOf(match, 16).intValue(); final int decimal = Integer.valueOf(match, 16).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
@ -482,8 +428,7 @@ public final class HTMLFilter
buf = new StringBuffer(); buf = new StringBuffer();
m = P_ENCODE.matcher(s); m = P_ENCODE.matcher(s);
while (m.find()) while (m.find()) {
{
final String match = m.group(1); final String match = m.group(1);
final int decimal = Integer.valueOf(match, 16).intValue(); final int decimal = Integer.valueOf(match, 16).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
@ -495,16 +440,14 @@ public final class HTMLFilter
return s; return s;
} }
private String validateEntities(final String s) private String validateEntities(final String s) {
{
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
// validate entities throughout the string // validate entities throughout the string
Matcher m = P_VALID_ENTITIES.matcher(s); Matcher m = P_VALID_ENTITIES.matcher(s);
while (m.find()) while (m.find()) {
{ final String one = m.group(1);
final String one = m.group(1); // ([^&;]*) final String two = m.group(2);
final String two = m.group(2); // (?=(;|&|$))
m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two)));
} }
m.appendTail(buf); m.appendTail(buf);
@ -512,59 +455,38 @@ public final class HTMLFilter
return encodeQuotes(buf.toString()); return encodeQuotes(buf.toString());
} }
private String encodeQuotes(final String s) private String encodeQuotes(final String s) {
{ if (encodeQuotes) {
if (encodeQuotes)
{
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
Matcher m = P_VALID_QUOTES.matcher(s); Matcher m = P_VALID_QUOTES.matcher(s);
while (m.find()) while (m.find()) {
{ final String one = m.group(1);
final String one = m.group(1); // (>|^) final String two = m.group(2);
final String two = m.group(2); // ([^<]+?) final String three = m.group(3);
final String three = m.group(3); // (<|$) /*不替换双引号为&quot;防止json格式无效 regexReplace(P_QUOTE, "&quot;", two)*/
// 不替换双引号为&quot;防止json格式无效 regexReplace(P_QUOTE, "&quot;", two)
m.appendReplacement(buf, Matcher.quoteReplacement(one + two + three)); m.appendReplacement(buf, Matcher.quoteReplacement(one + two + three));
} }
m.appendTail(buf); m.appendTail(buf);
return buf.toString(); return buf.toString();
} } else {
else
{
return s; return s;
} }
} }
private String checkEntity(final String preamble, final String term) private String checkEntity(final String preamble, final String term) {
{
return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&amp;" + preamble; return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&amp;" + preamble;
} }
private boolean isValidEntity(final String entity) private boolean isValidEntity(final String entity) {
{
return inArray(entity, vAllowedEntities); return inArray(entity, vAllowedEntities);
} }
private static boolean inArray(final String s, final String[] array) private boolean allowed(final String name) {
{
for (String item : array)
{
if (item != null && item.equals(s))
{
return true;
}
}
return false;
}
private boolean allowed(final String name)
{
return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed); return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed);
} }
private boolean allowedAttribute(final String name, final String paramName) private boolean allowedAttribute(final String name, final String paramName) {
{
return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName)); return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName));
} }
} }

@ -1,49 +1,43 @@
package com.ruoyi.common.core.utils.ip; package com.ruoyi.common.core.utils.ip;
import com.ruoyi.common.core.utils.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
import com.ruoyi.common.core.utils.StringUtils;
/** /**
* IP * IP
* *
* @author ruoyi * @author ruoyi
*/ */
public class IpUtils public class IpUtils {
{
/** /**
* IP * IP
* *
* @param request * @param request
* @return IP * @return IP
*/ */
public static String getIpAddr(HttpServletRequest request) public static String getIpAddr(HttpServletRequest request) {
{ String unknown = "unknown";
if (request == null) if (request == null) {
{ return unknown;
return "unknown";
} }
String ip = request.getHeader("x-forwarded-for"); String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
{
ip = request.getHeader("Proxy-Client-IP"); ip = request.getHeader("Proxy-Client-IP");
} }
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
{
ip = request.getHeader("X-Forwarded-For"); ip = request.getHeader("X-Forwarded-For");
} }
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
{
ip = request.getHeader("WL-Proxy-Client-IP"); ip = request.getHeader("WL-Proxy-Client-IP");
} }
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
{
ip = request.getHeader("X-Real-IP"); ip = request.getHeader("X-Real-IP");
} }
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
{
ip = request.getRemoteAddr(); ip = request.getRemoteAddr();
} }
@ -52,84 +46,81 @@ public class IpUtils
/** /**
* IP * IP
* *
* @param ip IP * @param ip IP
* @return * @return
*/ */
public static boolean internalIp(String ip) public static boolean internalIp(String ip) {
{
byte[] addr = textToNumericFormatV4(ip); byte[] addr = textToNumericFormatV4(ip);
return internalIp(addr) || "127.0.0.1".equals(ip); return internalIp(addr) || "127.0.0.1".equals(ip);
} }
/** /**
* IP * IP
* *
* @param addr byte * @param addr byte
* @return * @return
*/ */
private static boolean internalIp(byte[] addr) private static boolean internalIp(byte[] addr) {
{ int tow = 2;
if (StringUtils.isNull(addr) || addr.length < 2) if (StringUtils.isNull(addr) || addr.length < tow) {
{
return true; return true;
} }
final byte b0 = addr[0]; final byte b0 = addr[0];
final byte b1 = addr[1]; final byte b1 = addr[1];
// 10.x.x.x/8 // 10.x.x.x/8
final byte SECTION_1 = 0x0A; final byte section1 = 0x0A;
// 172.16.x.x/12 // 172.16.x.x/12
final byte SECTION_2 = (byte) 0xAC; final byte section2 = (byte) 0xAC;
final byte SECTION_3 = (byte) 0x10; final byte section3 = (byte) 0x10;
final byte SECTION_4 = (byte) 0x1F; final byte section4 = (byte) 0x1F;
// 192.168.x.x/16 // 192.168.x.x/16
final byte SECTION_5 = (byte) 0xC0; final byte section5 = (byte) 0xC0;
final byte SECTION_6 = (byte) 0xA8; final byte section6 = (byte) 0xA8;
switch (b0) switch (b0) {
{ case section1:
case SECTION_1:
return true; return true;
case SECTION_2: case section2:
if (b1 >= SECTION_3 && b1 <= SECTION_4) if (b1 >= section3 && b1 <= section4) {
{
return true; return true;
} }
case SECTION_5: case section5:
switch (b1) switch (b1) {
{ case section6: {
case SECTION_6:
return true; return true;
}
default: {
break;
}
} }
default: default: {
return false; return false;
}
} }
} }
/** /**
* IPv4 * IPv4
* *
* @param text IPv4 * @param text IPv4
* @return byte * @return byte
*/ */
public static byte[] textToNumericFormatV4(String text) public static byte[] textToNumericFormatV4(String text) {
{ if (text.length() == 0) {
if (text.length() == 0)
{
return null; return null;
} }
byte[] bytes = new byte[4]; byte[] bytes = new byte[4];
String[] elements = text.split("\\.", -1); String[] elements = text.split("\\.", -1);
try try {
{
long l; long l;
int i; int i;
switch (elements.length) switch (elements.length) {
{
case 1: case 1:
l = Long.parseLong(elements[0]); l = Long.parseLong(elements[0]);
if ((l < 0L) || (l > 4294967295L)) long l1 = 4294967295L;
{ if ((l < 0L) || (l > l1)) {
return null; return null;
} }
bytes[0] = (byte) (int) (l >> 24 & 0xFF); bytes[0] = (byte) (int) (l >> 24 & 0xFF);
@ -139,14 +130,14 @@ public class IpUtils
break; break;
case 2: case 2:
l = Integer.parseInt(elements[0]); l = Integer.parseInt(elements[0]);
if ((l < 0L) || (l > 255L)) long l2 = 255L;
{ if ((l < 0L) || (l > l2)) {
return null; return null;
} }
bytes[0] = (byte) (int) (l & 0xFF); bytes[0] = (byte) (int) (l & 0xFF);
l = Integer.parseInt(elements[1]); l = Integer.parseInt(elements[1]);
if ((l < 0L) || (l > 16777215L)) long l3 = 16777215L;
{ if ((l < 0L) || (l > l3)) {
return null; return null;
} }
bytes[1] = (byte) (int) (l >> 16 & 0xFF); bytes[1] = (byte) (int) (l >> 16 & 0xFF);
@ -154,29 +145,27 @@ public class IpUtils
bytes[3] = (byte) (int) (l & 0xFF); bytes[3] = (byte) (int) (l & 0xFF);
break; break;
case 3: case 3:
for (i = 0; i < 2; ++i) int i1 = 2;
{ for (i = 0; i < i1; ++i) {
l = Integer.parseInt(elements[i]); l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L)) if ((l < 0L) || (l > 255L)) {
{
return null; return null;
} }
bytes[i] = (byte) (int) (l & 0xFF); bytes[i] = (byte) (int) (l & 0xFF);
} }
l = Integer.parseInt(elements[2]); l = Integer.parseInt(elements[2]);
if ((l < 0L) || (l > 65535L)) long l4 = 65535L;
{ if ((l < 0L) || (l > l4)) {
return null; return null;
} }
bytes[2] = (byte) (int) (l >> 8 & 0xFF); bytes[2] = (byte) (int) (l >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF); bytes[3] = (byte) (int) (l & 0xFF);
break; break;
case 4: case 4:
for (i = 0; i < 4; ++i) int i2 = 4;
{ for (i = 0; i < i2; ++i) {
l = Integer.parseInt(elements[i]); l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L)) if ((l < 0L) || (l > 255L)) {
{
return null; return null;
} }
bytes[i] = (byte) (int) (l & 0xFF); bytes[i] = (byte) (int) (l & 0xFF);
@ -185,9 +174,7 @@ public class IpUtils
default: default:
return null; return null;
} }
} } catch (NumberFormatException e) {
catch (NumberFormatException e)
{
return null; return null;
} }
return bytes; return bytes;
@ -195,34 +182,28 @@ public class IpUtils
/** /**
* IP * IP
* *
* @return IP * @return IP
*/ */
public static String getHostIp() public static String getHostIp() {
{ try {
try
{
return InetAddress.getLocalHost().getHostAddress(); return InetAddress.getLocalHost().getHostAddress();
} } catch (UnknownHostException e) {
catch (UnknownHostException e) e.printStackTrace();
{
} }
return "127.0.0.1"; return "127.0.0.1";
} }
/** /**
* *
* *
* @return * @return
*/ */
public static String getHostName() public static String getHostName() {
{ try {
try
{
return InetAddress.getLocalHost().getHostName(); return InetAddress.getLocalHost().getHostName();
} } catch (UnknownHostException e) {
catch (UnknownHostException e) e.printStackTrace();
{
} }
return "未知"; return "未知";
} }
@ -233,16 +214,12 @@ public class IpUtils
* @param ip IP * @param ip IP
* @return unknown IP * @return unknown IP
*/ */
public static String getMultistageReverseProxyIp(String ip) public static String getMultistageReverseProxyIp(String ip) {
{
// 多级反向代理检测 // 多级反向代理检测
if (ip != null && ip.indexOf(",") > 0) if (ip != null && ip.indexOf(StringUtils.COMMA) > 0) {
{
final String[] ips = ip.trim().split(","); final String[] ips = ip.trim().split(",");
for (String subIp : ips) for (String subIp : ips) {
{ if (false == isUnknown(subIp)) {
if (false == isUnknown(subIp))
{
ip = subIp; ip = subIp;
break; break;
} }
@ -257,8 +234,7 @@ public class IpUtils
* @param checkString * @param checkString
* @return * @return
*/ */
public static boolean isUnknown(String checkString) public static boolean isUnknown(String checkString) {
{
return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString); return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
} }
} }

@ -2,17 +2,15 @@ package com.ruoyi.common.core.utils.poi;
/** /**
* Excel * Excel
* *
* @author ruoyi * @author ruoyi
*/ */
public interface ExcelHandlerAdapter public interface ExcelHandlerAdapter {
{
/** /**
* *
*
* @param value
* @param args excelargs
* *
* @param value
* @param args excelargs
* @return * @return
*/ */
Object format(Object value, String[] args); Object format(Object value, String[] args);

@ -1,28 +1,23 @@
package com.ruoyi.common.core.utils.reflect; package com.ruoyi.common.core.utils.reflect;
import java.lang.reflect.Field; import com.ruoyi.common.core.text.Convert;
import java.lang.reflect.InvocationTargetException; import com.ruoyi.common.core.utils.DateUtils;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Date;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.Validate;
import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.DateUtils; import java.lang.reflect.*;
import java.util.Date;
/** /**
* . getter/setter, 访, , Class, AOP. * . getter/setter, 访, , Class, AOP.
* *
* @author ruoyi * @author ruoyi
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class ReflectUtils public class ReflectUtils {
{
private static final String SETTER_PREFIX = "set"; private static final String SETTER_PREFIX = "set";
private static final String GETTER_PREFIX = "get"; private static final String GETTER_PREFIX = "get";
@ -36,13 +31,12 @@ public class ReflectUtils
* .. * ..
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <E> E invokeGetter(Object obj, String propertyName) public static <E> E invokeGetter(Object obj, String propertyName) {
{
Object object = obj; Object object = obj;
for (String name : StringUtils.split(propertyName, ".")) String point = ".";
{ for (String name : StringUtils.split(propertyName, point)) {
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name); String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
} }
return (E) object; return (E) object;
} }
@ -51,21 +45,16 @@ public class ReflectUtils
* Setter, * Setter,
* .. * ..
*/ */
public static <E> void invokeSetter(Object obj, String propertyName, E value) public static <E> void invokeSetter(Object obj, String propertyName, E value) {
{
Object object = obj; Object object = obj;
String[] names = StringUtils.split(propertyName, "."); String[] names = StringUtils.split(propertyName, ".");
for (int i = 0; i < names.length; i++) for (int i = 0; i < names.length; i++) {
{ if (i < names.length - 1) {
if (i < names.length - 1)
{
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]); String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
} } else {
else
{
String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]); String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
invokeMethodByName(object, setterMethodName, new Object[] { value }); invokeMethodByName(object, setterMethodName, new Object[]{value});
} }
} }
} }
@ -74,21 +63,16 @@ public class ReflectUtils
* , private/protected, getter. * , private/protected, getter.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <E> E getFieldValue(final Object obj, final String fieldName) public static <E> E getFieldValue(final Object obj, final String fieldName) {
{
Field field = getAccessibleField(obj, fieldName); Field field = getAccessibleField(obj, fieldName);
if (field == null) if (field == null) {
{
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
return null; return null;
} }
E result = null; E result = null;
try try {
{
result = (E) field.get(obj); result = (E) field.get(obj);
} } catch (IllegalAccessException e) {
catch (IllegalAccessException e)
{
logger.error("不可能抛出的异常{}", e.getMessage()); logger.error("不可能抛出的异常{}", e.getMessage());
} }
return result; return result;
@ -97,21 +81,15 @@ public class ReflectUtils
/** /**
* , private/protected, setter. * , private/protected, setter.
*/ */
public static <E> void setFieldValue(final Object obj, final String fieldName, final E value) public static <E> void setFieldValue(final Object obj, final String fieldName, final E value) {
{
Field field = getAccessibleField(obj, fieldName); Field field = getAccessibleField(obj, fieldName);
if (field == null) if (field == null) {
{
// throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
return; return;
} }
try try {
{
field.set(obj, value); field.set(obj, value);
} } catch (IllegalAccessException e) {
catch (IllegalAccessException e)
{
logger.error("不可能抛出的异常: {}", e.getMessage()); logger.error("不可能抛出的异常: {}", e.getMessage());
} }
} }
@ -123,24 +101,18 @@ public class ReflectUtils
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <E> E invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes, public static <E> E invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
final Object[] args) final Object[] args) {
{ if (obj == null || methodName == null) {
if (obj == null || methodName == null)
{
return null; return null;
} }
Method method = getAccessibleMethod(obj, methodName, parameterTypes); Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null) if (method == null) {
{
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
return null; return null;
} }
try try {
{
return (E) method.invoke(obj, args); return (E) method.invoke(obj, args);
} } catch (Exception e) {
catch (Exception e)
{
String msg = "method: " + method + ", obj: " + obj + ", args: " + args + ""; String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
throw convertReflectionExceptionToUnchecked(msg, e); throw convertReflectionExceptionToUnchecked(msg, e);
} }
@ -152,68 +124,44 @@ public class ReflectUtils
* *
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args) public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
{
Method method = getAccessibleMethodByName(obj, methodName, args.length); Method method = getAccessibleMethodByName(obj, methodName, args.length);
if (method == null) if (method == null) {
{
// 如果为空不报错,直接返回空。 // 如果为空不报错,直接返回空。
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
return null; return null;
} }
try try {
{
// 类型转换(将参数数据类型转换为目标方法参数类型) // 类型转换(将参数数据类型转换为目标方法参数类型)
Class<?>[] cs = method.getParameterTypes(); Class<?>[] cs = method.getParameterTypes();
for (int i = 0; i < cs.length; i++) for (int i = 0; i < cs.length; i++) {
{ if (args[i] != null && !args[i].getClass().equals(cs[i])) {
if (args[i] != null && !args[i].getClass().equals(cs[i])) if (cs[i] == String.class) {
{
if (cs[i] == String.class)
{
args[i] = Convert.toStr(args[i]); args[i] = Convert.toStr(args[i]);
if (StringUtils.endsWith((String) args[i], ".0")) if (StringUtils.endsWith((String) args[i], ".0")) {
{
args[i] = StringUtils.substringBefore((String) args[i], ".0"); args[i] = StringUtils.substringBefore((String) args[i], ".0");
} }
} } else if (cs[i] == Integer.class) {
else if (cs[i] == Integer.class)
{
args[i] = Convert.toInt(args[i]); args[i] = Convert.toInt(args[i]);
} } else if (cs[i] == Long.class) {
else if (cs[i] == Long.class)
{
args[i] = Convert.toLong(args[i]); args[i] = Convert.toLong(args[i]);
} } else if (cs[i] == Double.class) {
else if (cs[i] == Double.class)
{
args[i] = Convert.toDouble(args[i]); args[i] = Convert.toDouble(args[i]);
} } else if (cs[i] == Float.class) {
else if (cs[i] == Float.class)
{
args[i] = Convert.toFloat(args[i]); args[i] = Convert.toFloat(args[i]);
} } else if (cs[i] == Date.class) {
else if (cs[i] == Date.class) if (args[i] instanceof String) {
{
if (args[i] instanceof String)
{
args[i] = DateUtils.parseDate(args[i]); args[i] = DateUtils.parseDate(args[i]);
} } else {
else
{
args[i] = DateUtil.getJavaDate((Double) args[i]); args[i] = DateUtil.getJavaDate((Double) args[i]);
} }
} } else if (cs[i] == boolean.class || cs[i] == Boolean.class) {
else if (cs[i] == boolean.class || cs[i] == Boolean.class)
{
args[i] = Convert.toBool(args[i]); args[i] = Convert.toBool(args[i]);
} }
} }
} }
return (E) method.invoke(obj, args); return (E) method.invoke(obj, args);
} } catch (Exception e) {
catch (Exception e)
{
String msg = "method: " + method + ", obj: " + obj + ", args: " + args + ""; String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
throw convertReflectionExceptionToUnchecked(msg, e); throw convertReflectionExceptionToUnchecked(msg, e);
} }
@ -223,24 +171,18 @@ public class ReflectUtils
* , DeclaredField, 访. * , DeclaredField, 访.
* Object, null. * Object, null.
*/ */
public static Field getAccessibleField(final Object obj, final String fieldName) public static Field getAccessibleField(final Object obj, final String fieldName) {
{
// 为空不报错。直接返回 null // 为空不报错。直接返回 null
if (obj == null) if (obj == null) {
{
return null; return null;
} }
Validate.notBlank(fieldName, "fieldName can't be blank"); Validate.notBlank(fieldName, "fieldName can't be blank");
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
{ try {
try
{
Field field = superClass.getDeclaredField(fieldName); Field field = superClass.getDeclaredField(fieldName);
makeAccessible(field); makeAccessible(field);
return field; return field;
} } catch (NoSuchFieldException e) {
catch (NoSuchFieldException e)
{
continue; continue;
} }
} }
@ -254,24 +196,18 @@ public class ReflectUtils
* . 使Method,Method.invoke(Object obj, Object... args) * . 使Method,Method.invoke(Object obj, Object... args)
*/ */
public static Method getAccessibleMethod(final Object obj, final String methodName, public static Method getAccessibleMethod(final Object obj, final String methodName,
final Class<?>... parameterTypes) final Class<?>... parameterTypes) {
{
// 为空不报错。直接返回 null // 为空不报错。直接返回 null
if (obj == null) if (obj == null) {
{
return null; return null;
} }
Validate.notBlank(methodName, "methodName can't be blank"); Validate.notBlank(methodName, "methodName can't be blank");
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
{ try {
try
{
Method method = searchType.getDeclaredMethod(methodName, parameterTypes); Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
makeAccessible(method); makeAccessible(method);
return method; return method;
} } catch (NoSuchMethodException e) {
catch (NoSuchMethodException e)
{
continue; continue;
} }
} }
@ -284,21 +220,16 @@ public class ReflectUtils
* *
* . 使Method,Method.invoke(Object obj, Object... args) * . 使Method,Method.invoke(Object obj, Object... args)
*/ */
public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum) public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum) {
{
// 为空不报错。直接返回 null // 为空不报错。直接返回 null
if (obj == null) if (obj == null) {
{
return null; return null;
} }
Validate.notBlank(methodName, "methodName can't be blank"); Validate.notBlank(methodName, "methodName can't be blank");
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
{
Method[] methods = searchType.getDeclaredMethods(); Method[] methods = searchType.getDeclaredMethods();
for (Method method : methods) for (Method method : methods) {
{ if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum) {
if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum)
{
makeAccessible(method); makeAccessible(method);
return method; return method;
} }
@ -310,24 +241,23 @@ public class ReflectUtils
/** /**
* private/protectedpublicJDKSecurityManager * private/protectedpublicJDKSecurityManager
*/ */
public static void makeAccessible(Method method) public static void makeAccessible(Method method) {
{ if (!method.isAccessible()) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) if (!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
&& !method.isAccessible()) method.setAccessible(true);
{ }
method.setAccessible(true);
} }
} }
/** /**
* private/protectedpublicJDKSecurityManager * private/protectedpublicJDKSecurityManager
*/ */
public static void makeAccessible(Field field) public static void makeAccessible(Field field) {
{ if (!field.isAccessible()) {
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
|| Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) || Modifier.isFinal(field.getModifiers())) {
{ field.setAccessible(true);
field.setAccessible(true); }
} }
} }
@ -336,8 +266,7 @@ public class ReflectUtils
* , Object.class. * , Object.class.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> Class<T> getClassGenricType(final Class clazz) public static <T> Class<T> getClassGenricType(final Class clazz) {
{
return getClassGenricType(clazz, 0); return getClassGenricType(clazz, 0);
} }
@ -345,26 +274,22 @@ public class ReflectUtils
* , Class. * , Class.
* , Object.class. * , Object.class.
*/ */
public static Class getClassGenricType(final Class clazz, final int index) public static Class getClassGenricType(final Class clazz, final int index) {
{
Type genType = clazz.getGenericSuperclass(); Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) if (!(genType instanceof ParameterizedType)) {
{
logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType"); logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class; return Object.class;
} }
Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) if (index >= params.length || index < 0) {
{
logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length); + params.length);
return Object.class; return Object.class;
} }
if (!(params[index] instanceof Class)) if (!(params[index] instanceof Class)) {
{
logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class; return Object.class;
} }
@ -372,18 +297,14 @@ public class ReflectUtils
return (Class) params[index]; return (Class) params[index];
} }
public static Class<?> getUserClass(Object instance) public static Class<?> getUserClass(Object instance) {
{ if (instance == null) {
if (instance == null)
{
throw new RuntimeException("Instance must not be null"); throw new RuntimeException("Instance must not be null");
} }
Class clazz = instance.getClass(); Class clazz = instance.getClass();
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
{
Class<?> superClass = clazz.getSuperclass(); Class<?> superClass = clazz.getSuperclass();
if (superClass != null && !Object.class.equals(superClass)) if (superClass != null && !Object.class.equals(superClass)) {
{
return superClass; return superClass;
} }
} }
@ -394,15 +315,11 @@ public class ReflectUtils
/** /**
* checked exceptionunchecked exception. * checked exceptionunchecked exception.
*/ */
public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e) public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e) {
{
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|| e instanceof NoSuchMethodException) || e instanceof NoSuchMethodException) {
{
return new IllegalArgumentException(msg, e); return new IllegalArgumentException(msg, e);
} } else if (e instanceof InvocationTargetException) {
else if (e instanceof InvocationTargetException)
{
return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException()); return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException());
} }
return new RuntimeException(msg, e); return new RuntimeException(msg, e);

@ -2,76 +2,76 @@ package com.ruoyi.common.core.utils.sign;
/** /**
* Base64 * Base64
* *
* @author ruoyi * @author ruoyi
*/ */
public final class Base64 public final class Base64 {
{ static private final int BASELENGTH = 128;
static private final int BASELENGTH = 128; static private final int LOOKUPLENGTH = 64;
static private final int LOOKUPLENGTH = 64; static private final int TWENTYFOURBITGROUP = 24;
static private final int TWENTYFOURBITGROUP = 24; static private final int EIGHTBIT = 8;
static private final int EIGHTBIT = 8; static private final int SIXTEENBIT = 16;
static private final int SIXTEENBIT = 16; static private final int FOURBYTE = 4;
static private final int FOURBYTE = 4; static private final int SIGN = -128;
static private final int SIGN = -128; static private final char PAD = '=';
static private final char PAD = '='; static final private byte[] BASE_64_ALPHABET = new byte[BASELENGTH];
static final private byte[] base64Alphabet = new byte[BASELENGTH]; static final private char[] LOOK_UP_BASE_64_ALPHABET = new char[LOOKUPLENGTH];
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static static {
{ for (int i = 0; i < BASELENGTH; ++i) {
for (int i = 0; i < BASELENGTH; ++i) BASE_64_ALPHABET[i] = -1;
{
base64Alphabet[i] = -1;
} }
for (int i = 'Z'; i >= 'A'; i--) char z = 'Z';
{ char a = 'A';
base64Alphabet[i] = (byte) (i - 'A'); for (int i = z; i >= a; i--) {
BASE_64_ALPHABET[i] = (byte) (i - 'A');
} }
for (int i = 'z'; i >= 'a'; i--)
{ char z1 = 'z';
base64Alphabet[i] = (byte) (i - 'a' + 26); char a1 = 'a';
for (int i = z1; i >= a1; i--) {
BASE_64_ALPHABET[i] = (byte) (i - 'a' + 26);
} }
for (int i = '9'; i >= '0'; i--) char c = '9';
{ char c1 = '0';
base64Alphabet[i] = (byte) (i - '0' + 52); for (int i = c; i >= c1; i--) {
BASE_64_ALPHABET[i] = (byte) (i - '0' + 52);
} }
base64Alphabet['+'] = 62; BASE_64_ALPHABET['+'] = 62;
base64Alphabet['/'] = 63; BASE_64_ALPHABET['/'] = 63;
for (int i = 0; i <= 25; i++) int i1 = 25;
{ for (int i = 0; i <= i1; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i); LOOK_UP_BASE_64_ALPHABET[i] = (char) ('A' + i);
} }
for (int i = 26, j = 0; i <= 51; i++, j++) int i2 = 26;
{ int i3 = 51;
lookUpBase64Alphabet[i] = (char) ('a' + j); for (int i = i2, j = 0; i <= i3; i++, j++) {
LOOK_UP_BASE_64_ALPHABET[i] = (char) ('a' + j);
} }
for (int i = 52, j = 0; i <= 61; i++, j++) int i4 = 52;
{ int i5 = 61;
lookUpBase64Alphabet[i] = (char) ('0' + j); for (int i = i4, j = 0; i <= i5; i++, j++) {
LOOK_UP_BASE_64_ALPHABET[i] = (char) ('0' + j);
} }
lookUpBase64Alphabet[62] = (char) '+'; LOOK_UP_BASE_64_ALPHABET[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/'; LOOK_UP_BASE_64_ALPHABET[63] = (char) '/';
} }
private static boolean isWhiteSpace(char octect) private static boolean isWhiteSpace(char octect) {
{
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
} }
private static boolean isPad(char octect) private static boolean isPad(char octect) {
{
return (octect == PAD); return (octect == PAD);
} }
private static boolean isData(char octect) private static boolean isData(char octect) {
{ return (octect < BASELENGTH && BASE_64_ALPHABET[octect] != -1);
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
} }
/** /**
@ -80,23 +80,20 @@ public final class Base64
* @param binaryData Array containing binaryData * @param binaryData Array containing binaryData
* @return Encoded Base64 array * @return Encoded Base64 array
*/ */
public static String encode(byte[] binaryData) public static String encode(byte[] binaryData) {
{ if (binaryData == null) {
if (binaryData == null)
{
return null; return null;
} }
int lengthDataBits = binaryData.length * EIGHTBIT; int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) if (lengthDataBits == 0) {
{
return ""; return "";
} }
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets; int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
char encodedData[] = null; char[] encodedData = null;
encodedData = new char[numberQuartet * 4]; encodedData = new char[numberQuartet * 4];
@ -105,8 +102,7 @@ public final class Base64
int encodedIndex = 0; int encodedIndex = 0;
int dataIndex = 0; int dataIndex = 0;
for (int i = 0; i < numberTriplets; i++) for (int i = 0; i < numberTriplets; i++) {
{
b1 = binaryData[dataIndex++]; b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++]; b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++]; b3 = binaryData[dataIndex++];
@ -118,25 +114,22 @@ public final class Base64
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[b3 & 0x3f];
} }
// form integral number of 6-bit groups // form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) if (fewerThan24bits == EIGHTBIT) {
{
b1 = binaryData[dataIndex]; b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03); k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[k << 4];
encodedData[encodedIndex++] = PAD; encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD; encodedData[encodedIndex++] = PAD;
} } else if (fewerThan24bits == SIXTEENBIT) {
else if (fewerThan24bits == SIXTEENBIT)
{
b1 = binaryData[dataIndex]; b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1]; b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f); l = (byte) (b2 & 0x0f);
@ -145,9 +138,9 @@ public final class Base64
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex++] = LOOK_UP_BASE_64_ALPHABET[l << 2];
encodedData[encodedIndex++] = PAD; encodedData[encodedIndex++] = PAD;
} }
return new String(encodedData); return new String(encodedData);
@ -159,85 +152,60 @@ public final class Base64
* @param encoded string containing Base64 data * @param encoded string containing Base64 data
* @return Array containind decoded data. * @return Array containind decoded data.
*/ */
public static byte[] decode(String encoded) public static byte[] decode(String encoded) {
{ if (encoded == null) {
if (encoded == null)
{
return null; return null;
} }
char[] base64Data = encoded.toCharArray(); char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data); int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0) {
if (len % FOURBYTE != 0) return null;
{
return null;// should be divisible by four
} }
int numberQuadruple = (len / FOURBYTE); int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0) {
if (numberQuadruple == 0)
{
return new byte[0]; return new byte[0];
} }
byte[] decodedData = null;
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0; char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0; int i = 0;
int encodedIndex = 0; int encodedIndex = 0;
int dataIndex = 0; int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3]; decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++) {
for (; i < numberQuadruple - 1; i++)
{
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++])) if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++]))) || !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++]))) {
{
return null; return null;
} // if found "no data" just return null }
b1 = BASE_64_ALPHABET[d1];
b1 = base64Alphabet[d1]; b2 = BASE_64_ALPHABET[d2];
b2 = base64Alphabet[d2]; b3 = BASE_64_ALPHABET[d3];
b3 = base64Alphabet[d3]; b4 = BASE_64_ALPHABET[d4];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
} }
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) return null;
{
return null;// if found "no data" just return null
} }
b1 = BASE_64_ALPHABET[d1];
b1 = base64Alphabet[d1]; b2 = BASE_64_ALPHABET[d2];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++]; d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++]; d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) if (!isData((d3)) || !isData((d4))) {
{// Check if they are PAD characters if (isPad(d3) && isPad(d4)) {
if (isPad(d3) && isPad(d4)) int i1 = 0xf;
{ if ((b2 & i1) != 0) {
if ((b2 & 0xf) != 0)// last 4 bits should be zero
{
return null; return null;
} }
byte[] tmp = new byte[i * 3 + 1]; byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3); System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp; return tmp;
} } else if (!isPad(d3) && isPad(d4)) {
else if (!isPad(d3) && isPad(d4)) b3 = BASE_64_ALPHABET[d3];
{ int i1 = 0x3;
b3 = base64Alphabet[d3]; if ((b3 & i1) != 0) {
if ((b3 & 0x3) != 0)// last 2 bits should be zero
{
return null; return null;
} }
byte[] tmp = new byte[i * 3 + 2]; byte[] tmp = new byte[i * 3 + 2];
@ -245,20 +213,15 @@ public final class Base64
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp; return tmp;
} } else {
else
{
return null; return null;
} }
} } else { // No PAD e.g 3cQl
else b3 = BASE_64_ALPHABET[d3];
{ // No PAD e.g 3cQl b4 = BASE_64_ALPHABET[d4];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
} }
return decodedData; return decodedData;
} }
@ -269,20 +232,16 @@ public final class Base64
* @param data the byte array of base64 data (with WS) * @param data the byte array of base64 data (with WS)
* @return the new length * @return the new length
*/ */
private static int removeWhiteSpace(char[] data) private static int removeWhiteSpace(char[] data) {
{ if (data == null) {
if (data == null)
{
return 0; return 0;
} }
// count characters that's not whitespace // count characters that's not whitespace
int newSize = 0; int newSize = 0;
int len = data.length; int len = data.length;
for (int i = 0; i < len; i++) for (int i = 0; i < len; i++) {
{ if (!isWhiteSpace(data[i])) {
if (!isWhiteSpace(data[i]))
{
data[newSize++] = data[i]; data[newSize++] = data[i];
} }
} }

@ -5,11 +5,10 @@ import com.ruoyi.common.core.utils.StringUtils;
/** /**
* sql * sql
* *
* @author ruoyi * @author ruoyi
*/ */
public class SqlUtil public class SqlUtil {
{
/** /**
* sql * sql
*/ */
@ -18,15 +17,13 @@ public class SqlUtil
/** /**
* 线 * 线
*/ */
public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+"; public static String SQL_PATTERN = "[a-zA-Z0-9_ ,.]+";
/** /**
* *
*/ */
public static String escapeOrderBySql(String value) public static String escapeOrderBySql(String value) {
{ if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {
if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value))
{
throw new UtilException("参数不符合规范,不能进行查询"); throw new UtilException("参数不符合规范,不能进行查询");
} }
return value; return value;
@ -35,25 +32,20 @@ public class SqlUtil
/** /**
* order by * order by
*/ */
public static boolean isValidOrderBySql(String value) public static boolean isValidOrderBySql(String value) {
{
return value.matches(SQL_PATTERN); return value.matches(SQL_PATTERN);
} }
/** /**
* SQL * SQL
*/ */
public static void filterKeyword(String value) public static void filterKeyword(String value) {
{ if (StringUtils.isEmpty(value)) {
if (StringUtils.isEmpty(value))
{
return; return;
} }
String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|"); String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|");
for (String sqlKeyword : sqlKeywords) for (String sqlKeyword : sqlKeywords) {
{ if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1) {
if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1)
{
throw new UtilException("参数存在SQL注入风险"); throw new UtilException("参数存在SQL注入风险");
} }
} }

@ -2,48 +2,43 @@ package com.ruoyi.common.core.utils.uuid;
/** /**
* ID * ID
* *
* @author ruoyi * @author ruoyi
*/ */
public class IdUtils public class IdUtils {
{
/** /**
* UUID * UUID
* *
* @return UUID * @return UUID
*/ */
public static String randomUUID() public static String randomuuid() {
{ return UUID.randomuuid().toString();
return UUID.randomUUID().toString();
} }
/** /**
* UUID线 * UUID线
* *
* @return UUID线 * @return UUID线
*/ */
public static String simpleUUID() public static String simpleuuid() {
{ return UUID.randomuuid().toString(true);
return UUID.randomUUID().toString(true);
} }
/** /**
* UUID使ThreadLocalRandomUUID * UUID使ThreadLocalRandomUUID
* *
* @return UUID * @return UUID
*/ */
public static String fastUUID() public static String fastuuid() {
{ return UUID.fastuuid().toString();
return UUID.fastUUID().toString();
} }
/** /**
* UUID线使ThreadLocalRandomUUID * UUID线使ThreadLocalRandomUUID
* *
* @return UUID线 * @return UUID线
*/ */
public static String fastSimpleUUID() public static String fastsimpleuuid() {
{ return UUID.fastuuid().toString(true);
return UUID.fastUUID().toString(true);
} }
} }

@ -1,49 +1,56 @@
package com.ruoyi.common.core.utils.uuid; package com.ruoyi.common.core.utils.uuid;
import java.util.concurrent.atomic.AtomicInteger;
import com.ruoyi.common.core.utils.DateUtils; import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils; import com.ruoyi.common.core.utils.StringUtils;
import java.util.concurrent.atomic.AtomicInteger;
/** /**
* @author ruoyi * @author ruoyi
*/ */
public class Seq public class Seq {
{ /**
// 通用序列类型 *
public static final String commSeqType = "COMMON"; */
public static final String COMM_SEQ_TYPE = "COMMON";
// 上传序列类型 /**
public static final String uploadSeqType = "UPLOAD"; *
*/
public static final String UPLOAD_SEQ_TYPE = "UPLOAD";
// 通用接口序列数 /**
*
*/
private static AtomicInteger commSeq = new AtomicInteger(1); private static AtomicInteger commSeq = new AtomicInteger(1);
// 上传接口序列数 /**
*
*/
private static AtomicInteger uploadSeq = new AtomicInteger(1); private static AtomicInteger uploadSeq = new AtomicInteger(1);
// 机器标识 /**
*
*/
private static String machineCode = "A"; private static String machineCode = "A";
/** /**
* *
* *
* @return * @return
*/ */
public static String getId() public static String getId() {
{ return getId(COMM_SEQ_TYPE);
return getId(commSeqType);
} }
/** /**
* 16 yyMMddHHmmss + + 3 * 16 yyMMddHHmmss + + 3
* *
* @return * @return
*/ */
public static String getId(String type) public static String getId(String type) {
{
AtomicInteger atomicInt = commSeq; AtomicInteger atomicInt = commSeq;
if (uploadSeqType.equals(type)) if (UPLOAD_SEQ_TYPE.equals(type)) {
{
atomicInt = uploadSeq; atomicInt = uploadSeq;
} }
return getId(atomicInt, 3); return getId(atomicInt, 3);
@ -51,13 +58,12 @@ public class Seq
/** /**
* yyMMddHHmmss + + length * yyMMddHHmmss + + length
* *
* @param atomicInt * @param atomicInt
* @param length * @param length
* @return * @return
*/ */
public static String getId(AtomicInteger atomicInt, int length) public static String getId(AtomicInteger atomicInt, int length) {
{
String result = DateUtils.dateTimeNow(); String result = DateUtils.dateTimeNow();
result += machineCode; result += machineCode;
result += getSeq(atomicInt, length); result += getSeq(atomicInt, length);
@ -66,18 +72,16 @@ public class Seq
/** /**
* [1, 10 (length)), 0length * [1, 10 (length)), 0length
* *
* @return * @return
*/ */
private synchronized static String getSeq(AtomicInteger atomicInt, int length) private synchronized static String getSeq(AtomicInteger atomicInt, int length) {
{
// 先取值再+1 // 先取值再+1
int value = atomicInt.getAndIncrement(); int value = atomicInt.getAndIncrement();
// 如果更新后值>=10 的 (length)幂次方则重置为1 // 如果更新后值>=10 的 (length)幂次方则重置为1
int maxSeq = (int) Math.pow(10, length); int maxSeq = (int) Math.pow(10, length);
if (atomicInt.get() >= maxSeq) if (atomicInt.get() >= maxSeq) {
{
atomicInt.set(1); atomicInt.set(1);
} }
// 转字符串用0左补齐 // 转字符串用0左补齐

@ -1,53 +1,45 @@
package com.ruoyi.common.core.utils.uuid; package com.ruoyi.common.core.utils.uuid;
import com.ruoyi.common.core.exception.UtilException;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.Random; import java.util.Random;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import com.ruoyi.common.core.exception.UtilException;
/** /**
* universally unique identifierUUID * universally unique identifierUUID
* *
* @author ruoyi * @author ruoyi
*/ */
public final class UUID implements java.io.Serializable, Comparable<UUID> public final class UUID implements java.io.Serializable, Comparable<UUID> {
{
private static final long serialVersionUID = -1185015143654744140L; private static final long serialVersionUID = -1185015143654744140L;
/** /**
* SecureRandom * UUID64
*
*/ */
private static class Holder
{
static final SecureRandom numberGenerator = getSecureRandom();
}
/** 此UUID的最高64有效位 */
private final long mostSigBits; private final long mostSigBits;
/**
/** 此UUID的最低64有效位 */ * UUID64
*/
private final long leastSigBits; private final long leastSigBits;
/** /**
* *
* *
* @param data * @param data
*/ */
private UUID(byte[] data) private UUID(byte[] data) {
{
long msb = 0; long msb = 0;
long lsb = 0; long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length"; assert data.length == 16 : "data must be 16 bytes in length";
for (int i = 0; i < 8; i++) int eight = 8;
{ int sixteen = 16;
msb = (msb << 8) | (data[i] & 0xff); for (int i = 0; i < eight; i++) {
msb = (msb << eight) | (data[i] & 0xff);
} }
for (int i = 8; i < 16; i++) for (int i = eight; i < sixteen; i++) {
{ lsb = (lsb << eight) | (data[i] & 0xff);
lsb = (lsb << 8) | (data[i] & 0xff);
} }
this.mostSigBits = msb; this.mostSigBits = msb;
this.leastSigBits = lsb; this.leastSigBits = lsb;
@ -56,51 +48,47 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
/** /**
* 使 UUID * 使 UUID
* *
* @param mostSigBits {@code UUID} 64 * @param mostSigBits {@code UUID} 64
* @param leastSigBits {@code UUID} 64 * @param leastSigBits {@code UUID} 64
*/ */
public UUID(long mostSigBits, long leastSigBits) public UUID(long mostSigBits, long leastSigBits) {
{
this.mostSigBits = mostSigBits; this.mostSigBits = mostSigBits;
this.leastSigBits = leastSigBits; this.leastSigBits = leastSigBits;
} }
/** /**
* 4UUID 使线 UUID * 4UUID 使线 UUID
* *
* @return {@code UUID} * @return {@code UUID}
*/ */
public static UUID fastUUID() public static UUID fastuuid() {
{ return randomuuid(false);
return randomUUID(false);
} }
/** /**
* 4UUID 使 UUID * 4UUID 使 UUID
* *
* @return {@code UUID} * @return {@code UUID}
*/ */
public static UUID randomUUID() public static UUID randomuuid() {
{ return randomuuid(true);
return randomUUID(true);
} }
/** /**
* 4UUID 使 UUID * 4UUID 使 UUID
* *
* @param isSecure 使{@link SecureRandom} * @param isSecure 使{@link SecureRandom}
* @return {@code UUID} * @return {@code UUID}
*/ */
public static UUID randomUUID(boolean isSecure) public static UUID randomuuid(boolean isSecure) {
{ final Random ng = isSecure ? Holder.NUMBER_GENERATOR : getRandom();
final Random ng = isSecure ? Holder.numberGenerator : getRandom();
byte[] randomBytes = new byte[16]; byte[] randomBytes = new byte[16];
ng.nextBytes(randomBytes); ng.nextBytes(randomBytes);
randomBytes[6] &= 0x0f; /* clear version */ randomBytes[6] &= 0x0f;
randomBytes[6] |= 0x40; /* set to version 4 */ randomBytes[6] |= 0x40;
randomBytes[8] &= 0x3f; /* clear variant */ randomBytes[8] &= 0x3f;
randomBytes[8] |= 0x80; /* set to IETF variant */ randomBytes[8] |= 0x80;
return new UUID(randomBytes); return new UUID(randomBytes);
} }
@ -108,25 +96,20 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* 3UUID * 3UUID
* *
* @param name UUID * @param name UUID
*
* @return {@code UUID} * @return {@code UUID}
*/ */
public static UUID nameUUIDFromBytes(byte[] name) public static UUID nameUuidFromBytes(byte[] name) {
{
MessageDigest md; MessageDigest md;
try try {
{
md = MessageDigest.getInstance("MD5"); md = MessageDigest.getInstance("MD5");
} } catch (NoSuchAlgorithmException nsae) {
catch (NoSuchAlgorithmException nsae)
{
throw new InternalError("MD5 not supported"); throw new InternalError("MD5 not supported");
} }
byte[] md5Bytes = md.digest(name); byte[] md5Bytes = md.digest(name);
md5Bytes[6] &= 0x0f; /* clear version */ md5Bytes[6] &= 0x0f;
md5Bytes[6] |= 0x30; /* set to version 3 */ md5Bytes[6] |= 0x30;
md5Bytes[8] &= 0x3f; /* clear variant */ md5Bytes[8] &= 0x3f;
md5Bytes[8] |= 0x80; /* set to IETF variant */ md5Bytes[8] |= 0x80;
return new UUID(md5Bytes); return new UUID(md5Bytes);
} }
@ -136,18 +119,18 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* @param name {@code UUID} * @param name {@code UUID}
* @return {@code UUID} * @return {@code UUID}
* @throws IllegalArgumentException name {@link #toString} * @throws IllegalArgumentException name {@link #toString}
*
*/ */
public static UUID fromString(String name) public static UUID fromString(String name) {
{
String[] components = name.split("-"); String[] components = name.split("-");
if (components.length != 5) int fastFive = 5;
{ if (components.length != fastFive) {
throw new IllegalArgumentException("Invalid UUID string: " + name); throw new IllegalArgumentException("Invalid UUID string: " + name);
} }
for (int i = 0; i < 5; i++) for (int i = 0; i < fastFive; i++) {
{ StringBuilder sb = new StringBuilder();
components[i] = "0x" + components[i]; sb.append(sb);
sb.append(components[i]);
components[i] = sb.toString();
} }
long mostSigBits = Long.decode(components[0]).longValue(); long mostSigBits = Long.decode(components[0]).longValue();
@ -163,13 +146,47 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
return new UUID(mostSigBits, leastSigBits); return new UUID(mostSigBits, leastSigBits);
} }
/**
* hex
*
* @param val
* @param digits
* @return
*/
private static String digits(long val, int digits) {
long hi = 1L << (digits * 4);
return Long.toHexString(hi | (val & (hi - 1))).substring(1);
}
/**
* {@link SecureRandom} (RNG)
*
* @return {@link SecureRandom}
*/
public static SecureRandom getSecureRandom() {
try {
return SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
throw new UtilException(e);
}
}
/**
* <br>
* ThreadLocalRandomJDK 7线
*
* @return {@link ThreadLocalRandom}
*/
public static ThreadLocalRandom getRandom() {
return ThreadLocalRandom.current();
}
/** /**
* UUID 128 64 * UUID 128 64
* *
* @return UUID 128 64 * @return UUID 128 64
*/ */
public long getLeastSignificantBits() public long getLeastSignificantBits() {
{
return leastSigBits; return leastSigBits;
} }
@ -178,8 +195,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* *
* @return UUID 128 64 * @return UUID 128 64
*/ */
public long getMostSignificantBits() public long getMostSignificantBits() {
{
return mostSigBits; return mostSigBits;
} }
@ -196,8 +212,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* *
* @return {@code UUID} * @return {@code UUID}
*/ */
public int version() public int version() {
{
// Version is bits masked by 0x000000000000F000 in MS long // Version is bits masked by 0x000000000000F000 in MS long
return (int) ((mostSigBits >> 12) & 0x0f); return (int) ((mostSigBits >> 12) & 0x0f);
} }
@ -215,8 +230,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* *
* @return {@code UUID} * @return {@code UUID}
*/ */
public int variant() public int variant() {
{
// This field is composed of a varying number of bits. // This field is composed of a varying number of bits.
// 0 - - Reserved for NCS backward compatibility // 0 - - Reserved for NCS backward compatibility
// 1 0 - The IETF aka Leach-Salz variant (used by this class) // 1 0 - The IETF aka Leach-Salz variant (used by this class)
@ -238,11 +252,10 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* *
* @throws UnsupportedOperationException {@code UUID} version 1 UUID * @throws UnsupportedOperationException {@code UUID} version 1 UUID
*/ */
public long timestamp() throws UnsupportedOperationException public long timestamp() throws UnsupportedOperationException {
{
checkTimeBase(); checkTimeBase();
return (mostSigBits & 0x0FFFL) << 48// return (mostSigBits & 0x0FFFL) << 48
| ((mostSigBits >> 16) & 0x0FFFFL) << 32// | ((mostSigBits >> 16) & 0x0FFFFL) << 32
| mostSigBits >>> 32; | mostSigBits >>> 32;
} }
@ -256,11 +269,9 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* UnsupportedOperationException * UnsupportedOperationException
* *
* @return {@code UUID} * @return {@code UUID}
*
* @throws UnsupportedOperationException UUID version 1 * @throws UnsupportedOperationException UUID version 1
*/ */
public int clockSequence() throws UnsupportedOperationException public int clockSequence() throws UnsupportedOperationException {
{
checkTimeBase(); checkTimeBase();
return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48); return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48);
} }
@ -275,11 +286,9 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* UUID UUID UnsupportedOperationException * UUID UUID UnsupportedOperationException
* *
* @return {@code UUID} * @return {@code UUID}
*
* @throws UnsupportedOperationException UUID version 1 * @throws UnsupportedOperationException UUID version 1
*/ */
public long node() throws UnsupportedOperationException public long node() throws UnsupportedOperationException {
{
checkTimeBase(); checkTimeBase();
return leastSigBits & 0x0000FFFFFFFFFFFFL; return leastSigBits & 0x0000FFFFFFFFFFFFL;
} }
@ -289,7 +298,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* *
* <p> * <p>
* UUID BNF * UUID BNF
* *
* <pre> * <pre>
* {@code * {@code
* UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node> * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
@ -302,15 +311,14 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* hexDigit = [0-9a-fA-F] * hexDigit = [0-9a-fA-F]
* } * }
* </pre> * </pre>
* *
* </blockquote> * </blockquote>
* *
* @return {@code UUID} * @return {@code UUID}
* @see #toString(boolean) * @see #toString(boolean)
*/ */
@Override @Override
public String toString() public String toString() {
{
return toString(false); return toString(false);
} }
@ -319,7 +327,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* *
* <p> * <p>
* UUID BNF * UUID BNF
* *
* <pre> * <pre>
* {@code * {@code
* UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node> * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
@ -332,37 +340,32 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* hexDigit = [0-9a-fA-F] * hexDigit = [0-9a-fA-F]
* } * }
* </pre> * </pre>
* *
* </blockquote> * </blockquote>
* *
* @param isSimple '-'UUID * @param isSimple '-'UUID
* @return {@code UUID} * @return {@code UUID}
*/ */
public String toString(boolean isSimple) public String toString(boolean isSimple) {
{
final StringBuilder builder = new StringBuilder(isSimple ? 32 : 36); final StringBuilder builder = new StringBuilder(isSimple ? 32 : 36);
// time_low // time_low
builder.append(digits(mostSigBits >> 32, 8)); builder.append(digits(mostSigBits >> 32, 8));
if (false == isSimple) if (false == isSimple) {
{
builder.append('-'); builder.append('-');
} }
// time_mid // time_mid
builder.append(digits(mostSigBits >> 16, 4)); builder.append(digits(mostSigBits >> 16, 4));
if (false == isSimple) if (false == isSimple) {
{
builder.append('-'); builder.append('-');
} }
// time_high_and_version // time_high_and_version
builder.append(digits(mostSigBits, 4)); builder.append(digits(mostSigBits, 4));
if (false == isSimple) if (false == isSimple) {
{
builder.append('-'); builder.append('-');
} }
// variant_and_sequence // variant_and_sequence
builder.append(digits(leastSigBits >> 48, 4)); builder.append(digits(leastSigBits >> 48, 4));
if (false == isSimple) if (false == isSimple) {
{
builder.append('-'); builder.append('-');
} }
// node // node
@ -371,40 +374,39 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
return builder.toString(); return builder.toString();
} }
// Comparison Operations
/** /**
* UUID * UUID
* *
* @return UUID * @return UUID
*/ */
@Override @Override
public int hashCode() public int hashCode() {
{
long hilo = mostSigBits ^ leastSigBits; long hilo = mostSigBits ^ leastSigBits;
return ((int) (hilo >> 32)) ^ (int) hilo; return ((int) (hilo >> 32)) ^ (int) hilo;
} }
// -------------------------------------------------------------------------------------------------------------------
// Private method start
/** /**
* *
* <p> * <p>
* {@code null} UUID UUID varriant {@code true} * {@code null} UUID UUID varriant {@code true}
* *
* @param obj * @param obj
*
* @return {@code true} {@code false} * @return {@code true} {@code false}
*/ */
@Override @Override
public boolean equals(Object obj) public boolean equals(Object obj) {
{ if ((null == obj) || (obj.getClass() != UUID.class)) {
if ((null == obj) || (obj.getClass() != UUID.class))
{
return false; return false;
} }
UUID id = (UUID) obj; UUID id = (UUID) obj;
return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits); return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits);
} }
// Comparison Operations
/** /**
* UUID UUID * UUID UUID
* *
@ -412,73 +414,30 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* UUID UUID UUID UUID UUID * UUID UUID UUID UUID UUID
* *
* @param val UUID UUID * @param val UUID UUID
*
* @return UUID val -10 1 * @return UUID val -10 1
*
*/ */
@Override @Override
public int compareTo(UUID val) public int compareTo(UUID val) {
{
// The ordering is intentionally set up so that the UUIDs // The ordering is intentionally set up so that the UUIDs
// can simply be numerically compared as two numbers // can simply be numerically compared as two numbers
return (this.mostSigBits < val.mostSigBits ? -1 : // return (this.mostSigBits < val.mostSigBits ? -1 :
(this.mostSigBits > val.mostSigBits ? 1 : // (this.mostSigBits > val.mostSigBits ? 1 :
(this.leastSigBits < val.leastSigBits ? -1 : // (Long.compare(this.leastSigBits, val.leastSigBits))));
(this.leastSigBits > val.leastSigBits ? 1 : //
0))));
}
// -------------------------------------------------------------------------------------------------------------------
// Private method start
/**
* hex
*
* @param val
* @param digits
* @return
*/
private static String digits(long val, int digits)
{
long hi = 1L << (digits * 4);
return Long.toHexString(hi | (val & (hi - 1))).substring(1);
} }
/** /**
* time-basedUUID * time-basedUUID
*/ */
private void checkTimeBase() private void checkTimeBase() {
{ if (version() != 1) {
if (version() != 1)
{
throw new UnsupportedOperationException("Not a time-based UUID"); throw new UnsupportedOperationException("Not a time-based UUID");
} }
} }
/** /**
* {@link SecureRandom} (RNG) * SecureRandom
*
* @return {@link SecureRandom}
*/
public static SecureRandom getSecureRandom()
{
try
{
return SecureRandom.getInstance("SHA1PRNG");
}
catch (NoSuchAlgorithmException e)
{
throw new UtilException(e);
}
}
/**
* <br>
* ThreadLocalRandomJDK 7线
*
* @return {@link ThreadLocalRandom}
*/ */
public static ThreadLocalRandom getRandom() private static class Holder {
{ static final SecureRandom NUMBER_GENERATOR = getSecureRandom();
return ThreadLocalRandom.current();
} }
} }

@ -1,40 +1,37 @@
package com.ruoyi.common.core.web.controller; package com.ruoyi.common.core.web.controller;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.constant.HttpStatus; import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.DateUtils; import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.PageUtils; import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.core.web.domain.AjaxResult; import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo; import com.ruoyi.common.core.web.page.TableDataInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;
/** /**
* web * web
* *
* @author ruoyi * @author ruoyi
*/ */
public class BaseController public class BaseController {
{
protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/** /**
* Date * Date
*/ */
@InitBinder @InitBinder
public void initBinder(WebDataBinder binder) public void initBinder(WebDataBinder binder) {
{
// Date 类型转换 // Date 类型转换
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
{
@Override @Override
public void setAsText(String text) public void setAsText(String text) {
{
setValue(DateUtils.parseDate(text)); setValue(DateUtils.parseDate(text));
} }
}); });
@ -43,25 +40,22 @@ public class BaseController
/** /**
* *
*/ */
protected void startPage() protected void startPage() {
{
PageUtils.startPage(); PageUtils.startPage();
} }
/** /**
* 线 * 线
*/ */
protected void clearPage() protected void clearPage() {
{
PageUtils.clearPage(); PageUtils.clearPage();
} }
/** /**
* *
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
protected TableDataInfo getDataTable(List<?> list) protected TableDataInfo getDataTable(List<?> list) {
{
TableDataInfo rspData = new TableDataInfo(); TableDataInfo rspData = new TableDataInfo();
rspData.setCode(HttpStatus.SUCCESS); rspData.setCode(HttpStatus.SUCCESS);
rspData.setRows(list); rspData.setRows(list);
@ -72,55 +66,49 @@ public class BaseController
/** /**
* *
* *
* @param rows * @param rows
* @return * @return
*/ */
protected AjaxResult toAjax(int rows) protected AjaxResult toAjax(int rows) {
{
return rows > 0 ? AjaxResult.success() : AjaxResult.error(); return rows > 0 ? AjaxResult.success() : AjaxResult.error();
} }
/** /**
* *
* *
* @param result * @param result
* @return * @return
*/ */
protected AjaxResult toAjax(boolean result) protected AjaxResult toAjax(boolean result) {
{
return result ? success() : error(); return result ? success() : error();
} }
/** /**
* *
*/ */
public AjaxResult success() public AjaxResult success() {
{
return AjaxResult.success(); return AjaxResult.success();
} }
/** /**
* *
*/ */
public AjaxResult error() public AjaxResult error() {
{
return AjaxResult.error(); return AjaxResult.error();
} }
/** /**
* *
*/ */
public AjaxResult success(String message) public AjaxResult success(String message) {
{
return AjaxResult.success(message); return AjaxResult.success(message);
} }
/** /**
* *
*/ */
public AjaxResult error(String message) public AjaxResult error(String message) {
{
return AjaxResult.error(message); return AjaxResult.error(message);
} }
} }

@ -1,162 +1,152 @@
package com.ruoyi.common.core.web.domain; package com.ruoyi.common.core.web.domain;
import java.util.HashMap;
import com.ruoyi.common.core.constant.HttpStatus; import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.StringUtils; import com.ruoyi.common.core.utils.StringUtils;
import java.util.HashMap;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class AjaxResult extends HashMap<String, Object> public class AjaxResult extends HashMap<String, Object> {
{ /**
private static final long serialVersionUID = 1L; *
*/
/** 状态码 */
public static final String CODE_TAG = "code"; public static final String CODE_TAG = "code";
/**
/** 返回内容 */ *
*/
public static final String MSG_TAG = "msg"; public static final String MSG_TAG = "msg";
/**
/** 数据对象 */ *
*/
public static final String DATA_TAG = "data"; public static final String DATA_TAG = "data";
private static final long serialVersionUID = 1L;
/** /**
* AjaxResult 使 * AjaxResult 使
*/ */
public AjaxResult() public AjaxResult() {
{
} }
/** /**
* AjaxResult * AjaxResult
* *
* @param code * @param code
* @param msg * @param msg
*/ */
public AjaxResult(int code, String msg) public AjaxResult(int code, String msg) {
{
super.put(CODE_TAG, code); super.put(CODE_TAG, code);
super.put(MSG_TAG, msg); super.put(MSG_TAG, msg);
} }
/** /**
* AjaxResult * AjaxResult
* *
* @param code * @param code
* @param msg * @param msg
* @param data * @param data
*/ */
public AjaxResult(int code, String msg, Object data) public AjaxResult(int code, String msg, Object data) {
{
super.put(CODE_TAG, code); super.put(CODE_TAG, code);
super.put(MSG_TAG, msg); super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data)) if (StringUtils.isNotNull(data)) {
{
super.put(DATA_TAG, data); super.put(DATA_TAG, data);
} }
} }
/**
* 便
*
* @param key
* @param value
* @return
*/
@Override
public AjaxResult put(String key, Object value)
{
super.put(key, value);
return this;
}
/** /**
* *
* *
* @return * @return
*/ */
public static AjaxResult success() public static AjaxResult success() {
{
return AjaxResult.success("操作成功"); return AjaxResult.success("操作成功");
} }
/** /**
* *
* *
* @return * @return
*/ */
public static AjaxResult success(Object data) public static AjaxResult success(Object data) {
{
return AjaxResult.success("操作成功", data); return AjaxResult.success("操作成功", data);
} }
/** /**
* *
* *
* @param msg * @param msg
* @return * @return
*/ */
public static AjaxResult success(String msg) public static AjaxResult success(String msg) {
{
return AjaxResult.success(msg, null); return AjaxResult.success(msg, null);
} }
/** /**
* *
* *
* @param msg * @param msg
* @param data * @param data
* @return * @return
*/ */
public static AjaxResult success(String msg, Object data) public static AjaxResult success(String msg, Object data) {
{
return new AjaxResult(HttpStatus.SUCCESS, msg, data); return new AjaxResult(HttpStatus.SUCCESS, msg, data);
} }
/** /**
* *
* *
* @return * @return
*/ */
public static AjaxResult error() public static AjaxResult error() {
{
return AjaxResult.error("操作失败"); return AjaxResult.error("操作失败");
} }
/** /**
* *
* *
* @param msg * @param msg
* @return * @return
*/ */
public static AjaxResult error(String msg) public static AjaxResult error(String msg) {
{
return AjaxResult.error(msg, null); return AjaxResult.error(msg, null);
} }
/** /**
* *
* *
* @param msg * @param msg
* @param data * @param data
* @return * @return
*/ */
public static AjaxResult error(String msg, Object data) public static AjaxResult error(String msg, Object data) {
{
return new AjaxResult(HttpStatus.ERROR, msg, data); return new AjaxResult(HttpStatus.ERROR, msg, data);
} }
/** /**
* *
* *
* @param code * @param code
* @param msg * @param msg
* @return * @return
*/ */
public static AjaxResult error(int code, String msg) public static AjaxResult error(int code, String msg) {
{
return new AjaxResult(code, msg, null); return new AjaxResult(code, msg, null);
} }
/**
* 便
*
* @param key
* @param value
* @return
*/
@Override
public AjaxResult put(String key, Object value) {
super.put(key, value);
return this;
}
} }

@ -1,114 +1,113 @@
package com.ruoyi.common.core.web.domain; package com.ruoyi.common.core.web.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import com.fasterxml.jackson.annotation.JsonFormat;
/** /**
* Entity * Entity
* *
* @author ruoyi * @author ruoyi
*/ */
public class BaseEntity implements Serializable public class BaseEntity implements Serializable {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 搜索值 */ /**
*
*/
private String searchValue; private String searchValue;
/** 创建者 */ /**
*
*/
private String createBy; private String createBy;
/** 创建时间 */ /**
*
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime; private Date createTime;
/** 更新者 */ /**
*
*/
private String updateBy; private String updateBy;
/** 更新时间 */ /**
*
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime; private Date updateTime;
/** 备注 */ /**
*
*/
private String remark; private String remark;
/** 请求参数 */ /**
*
*/
private Map<String, Object> params; private Map<String, Object> params;
public String getSearchValue() public String getSearchValue() {
{
return searchValue; return searchValue;
} }
public void setSearchValue(String searchValue) public void setSearchValue(String searchValue) {
{
this.searchValue = searchValue; this.searchValue = searchValue;
} }
public String getCreateBy() public String getCreateBy() {
{
return createBy; return createBy;
} }
public void setCreateBy(String createBy) public void setCreateBy(String createBy) {
{
this.createBy = createBy; this.createBy = createBy;
} }
public Date getCreateTime() public Date getCreateTime() {
{
return createTime; return createTime;
} }
public void setCreateTime(Date createTime) public void setCreateTime(Date createTime) {
{
this.createTime = createTime; this.createTime = createTime;
} }
public String getUpdateBy() public String getUpdateBy() {
{
return updateBy; return updateBy;
} }
public void setUpdateBy(String updateBy) public void setUpdateBy(String updateBy) {
{
this.updateBy = updateBy; this.updateBy = updateBy;
} }
public Date getUpdateTime() public Date getUpdateTime() {
{
return updateTime; return updateTime;
} }
public void setUpdateTime(Date updateTime) public void setUpdateTime(Date updateTime) {
{
this.updateTime = updateTime; this.updateTime = updateTime;
} }
public String getRemark() public String getRemark() {
{
return remark; return remark;
} }
public void setRemark(String remark) public void setRemark(String remark) {
{
this.remark = remark; this.remark = remark;
} }
public Map<String, Object> getParams() public Map<String, Object> getParams() {
{ if (params == null) {
if (params == null) params = new HashMap<>(2);
{
params = new HashMap<>();
} }
return params; return params;
} }
public void setParams(Map<String, Object> params) public void setParams(Map<String, Object> params) {
{
this.params = params; this.params = params;
} }
} }

@ -5,75 +5,74 @@ import java.util.List;
/** /**
* Tree * Tree
* *
* @author ruoyi * @author ruoyi
*/ */
public class TreeEntity extends BaseEntity public class TreeEntity extends BaseEntity {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 父菜单名称 */ /**
*
*/
private String parentName; private String parentName;
/** 父菜单ID */ /**
* ID
*/
private Long parentId; private Long parentId;
/** 显示顺序 */ /**
*
*/
private Integer orderNum; private Integer orderNum;
/** 祖级列表 */ /**
*
*/
private String ancestors; private String ancestors;
/** 子部门 */ /**
*
*/
private List<?> children = new ArrayList<>(); private List<?> children = new ArrayList<>();
public String getParentName() public String getParentName() {
{
return parentName; return parentName;
} }
public void setParentName(String parentName) public void setParentName(String parentName) {
{
this.parentName = parentName; this.parentName = parentName;
} }
public Long getParentId() public Long getParentId() {
{
return parentId; return parentId;
} }
public void setParentId(Long parentId) public void setParentId(Long parentId) {
{
this.parentId = parentId; this.parentId = parentId;
} }
public Integer getOrderNum() public Integer getOrderNum() {
{
return orderNum; return orderNum;
} }
public void setOrderNum(Integer orderNum) public void setOrderNum(Integer orderNum) {
{
this.orderNum = orderNum; this.orderNum = orderNum;
} }
public String getAncestors() public String getAncestors() {
{
return ancestors; return ancestors;
} }
public void setAncestors(String ancestors) public void setAncestors(String ancestors) {
{
this.ancestors = ancestors; this.ancestors = ancestors;
} }
public List<?> getChildren() public List<?> getChildren() {
{
return children; return children;
} }
public void setChildren(List<?> children) public void setChildren(List<?> children) {
{
this.children = children; this.children = children;
} }
} }

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

Loading…
Cancel
Save