发布 4.0.0

This commit is contained in:
疯狂的狮子li
2022-02-18 11:37:21 +08:00
parent dafb7477f6
commit 400ecdf0ab
348 changed files with 10651 additions and 10508 deletions

View File

@ -1,32 +0,0 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.*;
/**
* 数据权限过滤注解
*
* @author ruoyi
* @deprecated 3.6.0 移除 {@link com.ruoyi.common.annotation.DataPermission}
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Deprecated
public @interface DataScope {
/**
* 部门表的别名
*/
String deptAlias() default "";
/**
* 用户表的别名
*/
String userAlias() default "";
/**
* 是否过滤用户权限
*/
boolean isUser() default false;
}

View File

@ -1,25 +0,0 @@
package com.ruoyi.common.annotation;
import com.ruoyi.common.enums.DataSourceType;
import java.lang.annotation.*;
/**
* 自定义多数据源切换注解
* <p>
* 优先级:先方法,后类,如果方法覆盖了类上的数据源类型,以方法的为准,否则以类上的为准
*
* @author ruoyi
* @deprecated 3.6.0 移除 使用原生注解处理 方法更全 {@link com.baomidou.dynamic.datasource.annotation.DS}
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Deprecated
public @interface DataSource {
/**
* 切换数据源名称
*/
DataSourceType value() default DataSourceType.MASTER;
}

View File

@ -0,0 +1,24 @@
package com.ruoyi.common.annotation;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.ruoyi.common.enums.SensitiveStrategy;
import com.ruoyi.common.jackson.SensitiveJsonSerializer;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 数据脱敏注解
*
* @author zhujie
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonSerialize(using = SensitiveJsonSerializer.class)
public @interface Sensitive {
SensitiveStrategy strategy();
}

View File

@ -13,73 +13,73 @@ import com.ruoyi.common.utils.StringUtils;
*/
public class UnsignedMathGenerator implements CodeGenerator {
private static final long serialVersionUID = -5514819971774091076L;
private static final long serialVersionUID = -5514819971774091076L;
private static final String operators = "+-*";
private static final String OPERATORS = "+-*";
/**
* 参与计算数字最大长度
*/
private final int numberLength;
/**
* 参与计算数字最大长度
*/
private final int numberLength;
/**
* 构造
*/
public UnsignedMathGenerator() {
this(2);
}
/**
* 构造
*/
public UnsignedMathGenerator() {
this(2);
}
/**
* 构造
*
* @param numberLength 参与计算最大数字位数
*/
public UnsignedMathGenerator(int numberLength) {
this.numberLength = numberLength;
}
/**
* 构造
*
* @param numberLength 参与计算最大数字位数
*/
public UnsignedMathGenerator(int numberLength) {
this.numberLength = numberLength;
}
@Override
public String generate() {
final int limit = getLimit();
int min = RandomUtil.randomInt(limit);
int max = RandomUtil.randomInt(min, limit);
String number1 = Integer.toString(max);
String number2 = Integer.toString(min);
number1 = StringUtils.rightPad(number1, this.numberLength, CharUtil.SPACE);
number2 = StringUtils.rightPad(number2, this.numberLength, CharUtil.SPACE);
@Override
public String generate() {
final int limit = getLimit();
int min = RandomUtil.randomInt(limit);
int max = RandomUtil.randomInt(min, limit);
String number1 = Integer.toString(max);
String number2 = Integer.toString(min);
number1 = StringUtils.rightPad(number1, this.numberLength, CharUtil.SPACE);
number2 = StringUtils.rightPad(number2, this.numberLength, CharUtil.SPACE);
return number1 + RandomUtil.randomChar(operators) + number2 + '=';
}
return number1 + RandomUtil.randomChar(OPERATORS) + number2 + '=';
}
@Override
public boolean verify(String code, String userInputCode) {
int result;
try {
result = Integer.parseInt(userInputCode);
} catch (NumberFormatException e) {
// 用户输入非数字
return false;
}
@Override
public boolean verify(String code, String userInputCode) {
int result;
try {
result = Integer.parseInt(userInputCode);
} catch (NumberFormatException e) {
// 用户输入非数字
return false;
}
final int calculateResult = (int) Calculator.conversion(code);
return result == calculateResult;
}
final int calculateResult = (int) Calculator.conversion(code);
return result == calculateResult;
}
/**
* 获取验证码长度
*
* @return 验证码长度
*/
public int getLength() {
return this.numberLength * 2 + 2;
}
/**
* 获取验证码长度
*
* @return 验证码长度
*/
public int getLength() {
return this.numberLength * 2 + 2;
}
/**
* 根据长度获取参与计算数字最大值
*
* @return 最大值
*/
private int getLimit() {
return Integer.parseInt("1" + StringUtils.repeat('0', this.numberLength));
}
/**
* 根据长度获取参与计算数字最大值
*
* @return 最大值
*/
private int getLimit() {
return Integer.parseInt("1" + StringUtils.repeat('0', this.numberLength));
}
}

View File

@ -2,7 +2,6 @@ package com.ruoyi.common.config;
import lombok.Data;
import lombok.Getter;
import lombok.experimental.Accessors;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ -13,7 +12,6 @@ import org.springframework.stereotype.Component;
*/
@Data
@Accessors(chain = true)
@Component
@ConfigurationProperties(prefix = "ruoyi")
public class RuoYiConfig {

View File

@ -1,6 +1,5 @@
package com.ruoyi.common.constant;
/**
* 通用常量信息
*
@ -66,7 +65,12 @@ public interface Constants {
/**
* 登录用户 redis key
*/
String LOGIN_TOKEN_KEY = "login_tokens:";
public static final String LOGIN_TOKEN_KEY = "Authorization:login:token:";
/**
* 在线用户 redis key
*/
public static final String ONLINE_TOKEN_KEY = "online_tokens:";
/**
* 防重提交 redis key
@ -103,41 +107,11 @@ public interface Constants {
*/
String TOKEN = "token";
/**
* 令牌前缀
*/
String TOKEN_PREFIX = "Bearer ";
/**
* 令牌前缀
*/
String LOGIN_USER_KEY = "login_user_key";
/**
* 用户ID
*/
String JWT_USERID = "userid";
/**
* 用户名称
*/
String JWT_USERNAME = "sub";
/**
* 用户头像
*/
String JWT_AVATAR = "avatar";
/**
* 创建时间
*/
String JWT_CREATED = "created";
/**
* 用户权限
*/
String JWT_AUTHORITIES = "authorities";
/**
* 参数管理 cache key
*/
@ -149,3 +123,4 @@ public interface Constants {
String SYS_DICT_KEY = "sys_dict:";
}

View File

@ -181,6 +181,11 @@ public interface GenConstants {
*/
String QUERY_LIKE = "LIKE";
/**
* 相等查询
*/
String QUERY_EQ = "EQ";
/**
* 需要
*/

View File

@ -4,8 +4,9 @@ import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;
@ -20,32 +21,32 @@ import java.math.BigDecimal;
@Slf4j
public class ExcelBigNumberConvert implements Converter<Long> {
@Override
public Class<Long> supportJavaTypeKey() {
return Long.class;
}
@Override
public Class<Long> supportJavaTypeKey() {
return Long.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
return Convert.toLong(cellData.getData());
}
@Override
public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
return Convert.toLong(cellData.getData());
}
@Override
public CellData<Object> convertToExcelData(Long object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if (ObjectUtil.isNotNull(object)) {
String str = Convert.toStr(object);
if (str.length() > 15) {
return new CellData<>(str);
}
}
CellData<Object> cellData = new CellData<>(new BigDecimal(object));
cellData.setType(CellDataTypeEnum.NUMBER);
return cellData;
}
@Override
public WriteCellData<Object> convertToExcelData(Long object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if (ObjectUtil.isNotNull(object)) {
String str = Convert.toStr(object);
if (str.length() > 15) {
return new WriteCellData<>(str);
}
}
WriteCellData<Object> cellData = new WriteCellData<>(new BigDecimal(object));
cellData.setType(CellDataTypeEnum.NUMBER);
return cellData;
}
}

View File

@ -2,10 +2,12 @@ package com.ruoyi.common.convert;
import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.ruoyi.common.annotation.ExcelDictFormat;
import com.ruoyi.common.core.service.DictService;
@ -24,48 +26,48 @@ import java.lang.reflect.Field;
@Slf4j
public class ExcelDictConvert implements Converter<Object> {
@Override
public Class<Object> supportJavaTypeKey() {
return Object.class;
}
@Override
public Class<Object> supportJavaTypeKey() {
return Object.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return null;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return null;
}
@Override
public Object convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
ExcelDictFormat anno = getAnnotation(contentProperty.getField());
String type = anno.dictType();
String label = cellData.getStringValue();
String value;
if (StringUtils.isBlank(type)) {
value = ExcelUtil.reverseByExp(label, anno.readConverterExp(), anno.separator());
} else {
value = SpringUtils.getBean(DictService.class).getDictValue(type, label, anno.separator());
}
return Convert.convert(contentProperty.getField().getType(), value);
}
@Override
public Object convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
ExcelDictFormat anno = getAnnotation(contentProperty.getField());
String type = anno.dictType();
String label = cellData.getStringValue();
String value;
if (StringUtils.isBlank(type)) {
value = ExcelUtil.reverseByExp(label, anno.readConverterExp(), anno.separator());
} else {
value = SpringUtils.getBean(DictService.class).getDictValue(type, label, anno.separator());
}
return Convert.convert(contentProperty.getField().getType(), value);
}
@Override
public CellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if (StringUtils.isNull(object)) {
return new CellData<>("");
}
ExcelDictFormat anno = getAnnotation(contentProperty.getField());
String type = anno.dictType();
String value = Convert.toStr(object);
String label;
if (StringUtils.isBlank(type)) {
label = ExcelUtil.convertByExp(value, anno.readConverterExp(), anno.separator());
} else {
label = SpringUtils.getBean(DictService.class).getDictLabel(type, value, anno.separator());
}
return new CellData<>(label);
}
@Override
public WriteCellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if (ObjectUtil.isNull(object)) {
return new WriteCellData<>("");
}
ExcelDictFormat anno = getAnnotation(contentProperty.getField());
String type = anno.dictType();
String value = Convert.toStr(object);
String label;
if (StringUtils.isBlank(type)) {
label = ExcelUtil.convertByExp(value, anno.readConverterExp(), anno.separator());
} else {
label = SpringUtils.getBean(DictService.class).getDictLabel(type, value, anno.separator());
}
return new WriteCellData<>(label);
}
private ExcelDictFormat getAnnotation(Field field) {
return AnnotationUtil.getAnnotation(field, ExcelDictFormat.class);
}
private ExcelDictFormat getAnnotation(Field field) {
return AnnotationUtil.getAnnotation(field, ExcelDictFormat.class);
}
}

View File

@ -1,53 +1,25 @@
package com.ruoyi.common.core.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
/**
* web层通用数据处理
*
* @author ruoyi
* @author Lion Li
*/
public class BaseController {
/**
* 返回成功
*/
public AjaxResult<Void> success() {
return AjaxResult.success();
}
/**
* 返回失败消息
*/
public AjaxResult<Void> error() {
return AjaxResult.error();
}
/**
* 返回成功消息
*/
public AjaxResult<Void> success(String message) {
return AjaxResult.success(message);
}
/**
* 返回失败消息
*/
public AjaxResult<Void> error(String message) {
return AjaxResult.error(message);
}
/**
* 响应返回结果
*
* @param rows 影响行数
* @return 操作结果
*/
protected AjaxResult<Void> toAjax(int rows) {
return rows > 0 ? AjaxResult.success() : AjaxResult.error();
protected R<Void> toAjax(int rows) {
return rows > 0 ? R.ok() : R.fail();
}
/**
@ -56,8 +28,8 @@ public class BaseController {
* @param result 结果
* @return 操作结果
*/
protected AjaxResult<Void> toAjax(boolean result) {
return result ? success() : error();
protected R<Void> toAjax(boolean result) {
return result ? R.ok() : R.fail();
}
/**
@ -71,27 +43,27 @@ public class BaseController {
* 获取用户缓存信息
*/
public LoginUser getLoginUser() {
return SecurityUtils.getLoginUser();
return LoginHelper.getLoginUser();
}
/**
* 获取登录用户id
*/
public Long getUserId() {
return getLoginUser().getUserId();
return LoginHelper.getUserId();
}
/**
* 获取登录部门id
*/
public Long getDeptId() {
return getLoginUser().getDeptId();
return LoginHelper.getDeptId();
}
/**
* 获取登录用户名
*/
public String getUsername() {
return getLoginUser().getUsername();
return LoginHelper.getUsername();
}
}

View File

@ -1,134 +0,0 @@
package com.ruoyi.common.core.domain;
import cn.hutool.http.HttpStatus;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* 操作消息提醒
*
* @author Lion Li
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel("请求响应对象")
public class AjaxResult<T> {
private static final long serialVersionUID = 1L;
/**
* 状态码
*/
@ApiModelProperty("消息状态码")
private int code;
/**
* 返回内容
*/
@ApiModelProperty("消息内容")
private String msg;
/**
* 数据对象
*/
@ApiModelProperty("数据对象")
private T data;
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
*/
public AjaxResult(int code, String msg) {
this.code = code;
this.msg = msg;
}
/**
* 返回成功消息
*
* @return 成功消息
*/
public static AjaxResult<Void> success() {
return AjaxResult.success("操作成功");
}
/**
* 返回成功数据
*
* @return 成功消息
*/
public static <T> AjaxResult<T> success(T data) {
return AjaxResult.success("操作成功", data);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @return 成功消息
*/
public static AjaxResult<Void> success(String msg) {
return AjaxResult.success(msg, null);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public static <T> AjaxResult<T> success(String msg, T data) {
return new AjaxResult<>(HttpStatus.HTTP_OK, msg, data);
}
/**
* 返回错误消息
*
* @return
*/
public static AjaxResult<Void> error() {
return AjaxResult.error("操作失败");
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult<Void> error(String msg) {
return AjaxResult.error(msg, null);
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static <T> AjaxResult<T> error(String msg, T data) {
return new AjaxResult<>(HttpStatus.HTTP_INTERNAL_ERROR, msg, data);
}
/**
* 返回错误消息
*
* @param code 状态码
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult<Void> error(int code, String msg) {
return new AjaxResult<>(code, msg, null);
}
}

View File

@ -4,7 +4,6 @@ import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
@ -18,51 +17,50 @@ import java.util.Map;
*/
@Data
@Accessors(chain = true)
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/**
* 搜索值
*/
@ApiModelProperty(value = "搜索值")
@TableField(exist = false)
private String searchValue;
/**
* 搜索值
*/
@ApiModelProperty(value = "搜索值")
@TableField(exist = false)
private String searchValue;
/**
* 创建者
*/
@ApiModelProperty(value = "创建者")
@TableField(fill = FieldFill.INSERT)
private String createBy;
/**
* 创建者
*/
@ApiModelProperty(value = "创建者")
@TableField(fill = FieldFill.INSERT)
private String createBy;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
private Date createTime;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
private Date createTime;
/**
* 更新者
*/
@ApiModelProperty(value = "更新者")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy;
/**
* 更新者
*/
@ApiModelProperty(value = "更新者")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy;
/**
* 更新时间
*/
@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
/**
* 更新时间
*/
@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
/**
* 请求参数
*/
@ApiModelProperty(value = "请求参数")
@TableField(exist = false)
private Map<String, Object> params = new HashMap<>();
/**
* 请求参数
*/
@ApiModelProperty(value = "请求参数")
@TableField(exist = false)
private Map<String, Object> params = new HashMap<>();
}

View File

@ -7,7 +7,6 @@ import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
@ -18,10 +17,9 @@ import java.io.Serializable;
*/
@Data
@Accessors(chain = true)
public class PageQuery implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/**
* 分页大小

View File

@ -0,0 +1,84 @@
package com.ruoyi.common.core.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 响应信息主体
*
* @author Lion Li
*/
@Data
@NoArgsConstructor
@ApiModel("请求响应对象")
public class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 成功
*/
public static final int SUCCESS = 200;
/**
* 失败
*/
public static final int FAIL = 500;
@ApiModelProperty("消息状态码")
private int code;
@ApiModelProperty("消息内容")
private String msg;
@ApiModelProperty("数据对象")
private T data;
public static <T> R<T> ok() {
return restResult(null, SUCCESS, null);
}
public static <T> R<T> ok(T data) {
return restResult(data, SUCCESS, null);
}
public static <T> R<T> ok(String msg) {
return restResult(null, SUCCESS, msg);
}
public static <T> R<T> ok(String msg, T data) {
return restResult(data, SUCCESS, msg);
}
public static <T> R<T> fail() {
return restResult(null, FAIL, null);
}
public static <T> R<T> fail(String msg) {
return restResult(null, FAIL, msg);
}
public static <T> R<T> fail(T data) {
return restResult(data, FAIL, null);
}
public static <T> R<T> fail(String msg, T data) {
return restResult(data, FAIL, msg);
}
public static <T> R<T> fail(int code, String msg) {
return restResult(null, code, msg);
}
private static <T> R<T> restResult(T data, int code, String msg) {
R<T> r = new R<>();
r.setCode(code);
r.setData(data);
r.setMsg(msg);
return r;
}
}

View File

@ -4,7 +4,6 @@ import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.util.ArrayList;
import java.util.List;
@ -17,29 +16,28 @@ import java.util.List;
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class TreeEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/**
* 父菜单名称
*/
@TableField(exist = false)
@ApiModelProperty(value = "父菜单名称")
private String parentName;
/**
* 父菜单名称
*/
@TableField(exist = false)
@ApiModelProperty(value = "父菜单名称")
private String parentName;
/**
* 父菜单ID
*/
@ApiModelProperty(value = "父菜单ID")
private Long parentId;
/**
* 父菜单ID
*/
@ApiModelProperty(value = "父菜单ID")
private Long parentId;
/**
* 子部门
*/
@TableField(exist = false)
@ApiModelProperty(value = "子部门")
private List<?> children = new ArrayList<>();
/**
* 子部门
*/
@TableField(exist = false)
@ApiModelProperty(value = "子部门")
private List<?> children = new ArrayList<>();
}

View File

@ -1,8 +1,6 @@
package com.ruoyi.common.core.domain.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
@ -14,8 +12,6 @@ import java.util.Date;
*/
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class OperLogDTO implements Serializable {
private static final long serialVersionUID = 1L;

View File

@ -0,0 +1,38 @@
package com.ruoyi.common.core.domain.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 角色
*
* @author Lion Li
*/
@Data
@NoArgsConstructor
public class RoleDTO implements Serializable {
/**
* 角色ID
*/
private Long roleId;
/**
* 角色名称
*/
private String roleName;
/**
* 角色权限
*/
private String roleKey;
/**
* 数据范围1所有数据权限2自定义数据权限3本部门数据权限4本部门及以下数据权限5仅本人数据权限
*/
private String dataScope;
}

View File

@ -0,0 +1,61 @@
package com.ruoyi.common.core.domain.dto;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 当前在线会话
*
* @author ruoyi
*/
@Data
@NoArgsConstructor
public class UserOnlineDTO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 会话编号
*/
private String tokenId;
/**
* 部门名称
*/
private String deptName;
/**
* 用户名称
*/
private String userName;
/**
* 登录IP地址
*/
private String ipaddr;
/**
* 登录地址
*/
private String loginLocation;
/**
* 浏览器类型
*/
private String browser;
/**
* 操作系统
*/
private String os;
/**
* 登录时间
*/
private Long loginTime;
}

View File

@ -8,10 +8,10 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
@ -22,72 +22,71 @@ import javax.validation.constraints.Size;
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("sys_dept")
@ApiModel("部门业务对象")
public class SysDept extends TreeEntity {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/**
* 部门ID
*/
@ApiModelProperty(value = "部门id")
@TableId(value = "dept_id")
private Long deptId;
/**
* 部门ID
*/
@ApiModelProperty(value = "部门id")
@TableId(value = "dept_id")
private Long deptId;
/**
* 部门名称
*/
@ApiModelProperty(value = "部门名称")
@NotBlank(message = "部门名称不能为空")
@Size(min = 0, max = 30, message = "部门名称长度不能超过30个字符")
private String deptName;
/**
* 部门名称
*/
@ApiModelProperty(value = "部门名称")
@NotBlank(message = "部门名称不能为空")
@Size(min = 0, max = 30, message = "部门名称长度不能超过30个字符")
private String deptName;
/**
* 显示顺序
*/
@ApiModelProperty(value = "显示顺序")
@NotBlank(message = "显示顺序不能为空")
private String orderNum;
/**
* 显示顺序
*/
@ApiModelProperty(value = "显示顺序")
@NotNull(message = "显示顺序不能为空")
private Long orderNum;
/**
* 负责人
*/
@ApiModelProperty(value = "负责人")
private String leader;
/**
* 负责人
*/
@ApiModelProperty(value = "负责人")
private String leader;
/**
* 联系电话
*/
@ApiModelProperty(value = "联系电话")
@Size(min = 0, max = 11, message = "联系电话长度不能超过11个字符")
private String phone;
/**
* 联系电话
*/
@ApiModelProperty(value = "联系电话")
@Size(min = 0, max = 11, message = "联系电话长度不能超过11个字符")
private String phone;
/**
* 邮箱
*/
@ApiModelProperty(value = "邮箱")
@Email(message = "邮箱格式不正确")
@Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
private String email;
/**
* 邮箱
*/
@ApiModelProperty(value = "邮箱")
@Email(message = "邮箱格式不正确")
@Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
private String email;
/**
* 部门状态:0正常,1停用
*/
@ApiModelProperty(value = "部门状态:0正常,1停用")
private String status;
/**
* 部门状态:0正常,1停用
*/
@ApiModelProperty(value = "部门状态:0正常,1停用")
private String status;
/**
* 删除标志0代表存在 2代表删除
*/
@ApiModelProperty(value = "删除标志0代表存在 2代表删除")
@TableLogic
private String delFlag;
/**
* 删除标志0代表存在 2代表删除
*/
@ApiModelProperty(value = "删除标志0代表存在 2代表删除")
@TableLogic
private String delFlag;
/**
* 祖级列表
*/
@ApiModelProperty(value = "祖级列表")
private String ancestors;
/**
* 祖级列表
*/
@ApiModelProperty(value = "祖级列表")
private String ancestors;
}

View File

@ -12,7 +12,6 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@ -25,91 +24,90 @@ import javax.validation.constraints.Size;
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("sys_dict_data")
@ExcelIgnoreUnannotated
@ApiModel("字典数据业务对象")
public class SysDictData extends BaseEntity {
/**
* 字典编码
*/
@ApiModelProperty(value = "字典编码")
@ExcelProperty(value = "字典编码")
@TableId(value = "dict_code")
private Long dictCode;
/**
* 字典编码
*/
@ApiModelProperty(value = "字典编码")
@ExcelProperty(value = "字典编码")
@TableId(value = "dict_code")
private Long dictCode;
/**
* 字典排序
*/
@ApiModelProperty(value = "字典排序")
@ExcelProperty(value = "字典排序")
private Long dictSort;
/**
* 字典排序
*/
@ApiModelProperty(value = "字典排序")
@ExcelProperty(value = "字典排序")
private Long dictSort;
/**
* 字典标签
*/
@ApiModelProperty(value = "字典标签")
@ExcelProperty(value = "字典标签")
@NotBlank(message = "字典标签不能为空")
@Size(min = 0, max = 100, message = "字典标签长度不能超过100个字符")
private String dictLabel;
/**
* 字典标签
*/
@ApiModelProperty(value = "字典标签")
@ExcelProperty(value = "字典标签")
@NotBlank(message = "字典标签不能为空")
@Size(min = 0, max = 100, message = "字典标签长度不能超过100个字符")
private String dictLabel;
/**
* 字典键值
*/
@ApiModelProperty(value = "字典键值")
@ExcelProperty(value = "字典键值")
@NotBlank(message = "字典键值不能为空")
@Size(min = 0, max = 100, message = "字典键值长度不能超过100个字符")
private String dictValue;
/**
* 字典键值
*/
@ApiModelProperty(value = "字典键值")
@ExcelProperty(value = "字典键值")
@NotBlank(message = "字典键值不能为空")
@Size(min = 0, max = 100, message = "字典键值长度不能超过100个字符")
private String dictValue;
/**
* 字典类型
*/
@ApiModelProperty(value = "字典类型")
@ExcelProperty(value = "字典类型")
@NotBlank(message = "字典类型不能为空")
@Size(min = 0, max = 100, message = "字典类型长度不能超过100个字符")
private String dictType;
/**
* 字典类型
*/
@ApiModelProperty(value = "字典类型")
@ExcelProperty(value = "字典类型")
@NotBlank(message = "字典类型不能为空")
@Size(min = 0, max = 100, message = "字典类型长度不能超过100个字符")
private String dictType;
/**
* 样式属性(其他样式扩展)
*/
@ApiModelProperty(value = "样式属性(其他样式扩展)")
@Size(min = 0, max = 100, message = "样式属性长度不能超过100个字符")
private String cssClass;
/**
* 样式属性(其他样式扩展)
*/
@ApiModelProperty(value = "样式属性(其他样式扩展)")
@Size(min = 0, max = 100, message = "样式属性长度不能超过100个字符")
private String cssClass;
/**
* 表格字典样式
*/
@ApiModelProperty(value = "表格字典样式")
private String listClass;
/**
* 表格字典样式
*/
@ApiModelProperty(value = "表格字典样式")
private String listClass;
/**
* 是否默认Y是 N否
*/
@ApiModelProperty(value = "是否默认Y是 N否")
@ExcelProperty(value = "是否默认", converter = ExcelDictConvert.class)
@ExcelDictFormat(dictType = "sys_yes_no")
private String isDefault;
/**
* 是否默认Y是 N否
*/
@ApiModelProperty(value = "是否默认Y是 N否")
@ExcelProperty(value = "是否默认", converter = ExcelDictConvert.class)
@ExcelDictFormat(dictType = "sys_yes_no")
private String isDefault;
/**
* 状态0正常 1停用
*/
@ApiModelProperty(value = "状态0正常 1停用")
@ExcelProperty(value = "状态", converter = ExcelDictConvert.class)
@ExcelDictFormat(dictType = "sys_normal_disable")
private String status;
/**
* 状态0正常 1停用
*/
@ApiModelProperty(value = "状态0正常 1停用")
@ExcelProperty(value = "状态", converter = ExcelDictConvert.class)
@ExcelDictFormat(dictType = "sys_normal_disable")
private String status;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String remark;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String remark;
public boolean getDefault() {
return UserConstants.YES.equals(this.isDefault);
}
public boolean getDefault() {
return UserConstants.YES.equals(this.isDefault);
}
}

View File

@ -24,50 +24,49 @@ import javax.validation.constraints.Size;
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("sys_dict_type")
@ExcelIgnoreUnannotated
@ApiModel("字典类型业务对象")
public class SysDictType extends BaseEntity {
/**
* 字典主键
*/
@ApiModelProperty(value = "字典主键")
@ExcelProperty(value = "字典主键")
@TableId(value = "dict_id")
private Long dictId;
/**
* 字典主键
*/
@ApiModelProperty(value = "字典主键")
@ExcelProperty(value = "字典主键")
@TableId(value = "dict_id")
private Long dictId;
/**
* 字典名称
*/
@ApiModelProperty(value = "字典名称")
@ExcelProperty(value = "字典名称")
@NotBlank(message = "字典名称不能为空")
@Size(min = 0, max = 100, message = "字典类型名称长度不能超过100个字符")
private String dictName;
/**
* 字典名称
*/
@ApiModelProperty(value = "字典名称")
@ExcelProperty(value = "字典名称")
@NotBlank(message = "字典名称不能为空")
@Size(min = 0, max = 100, message = "字典类型名称长度不能超过100个字符")
private String dictName;
/**
* 字典类型
*/
@ApiModelProperty(value = "字典类型")
@ExcelProperty(value = "字典类型")
@NotBlank(message = "字典类型不能为空")
@Size(min = 0, max = 100, message = "字典类型类型长度不能超过100个字符")
private String dictType;
/**
* 字典类型
*/
@ApiModelProperty(value = "字典类型")
@ExcelProperty(value = "字典类型")
@NotBlank(message = "字典类型不能为空")
@Size(min = 0, max = 100, message = "字典类型类型长度不能超过100个字符")
private String dictType;
/**
* 状态0正常 1停用
*/
@ApiModelProperty(value = "状态0正常 1停用")
@ExcelProperty(value = "状态", converter = ExcelDictConvert.class)
@ExcelDictFormat(dictType = "sys_normal_disable")
private String status;
/**
* 状态0正常 1停用
*/
@ApiModelProperty(value = "状态0正常 1停用")
@ExcelProperty(value = "状态", converter = ExcelDictConvert.class)
@ExcelDictFormat(dictType = "sys_normal_disable")
private String status;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String remark;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String remark;
}

View File

@ -8,9 +8,9 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
@ -21,102 +21,101 @@ import javax.validation.constraints.Size;
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("sys_menu")
@ApiModel("菜单权限业务对象")
public class SysMenu extends TreeEntity {
/**
* 菜单ID
*/
@ApiModelProperty(value = "菜单ID")
@TableId(value = "menu_id")
private Long menuId;
/**
* 菜单ID
*/
@ApiModelProperty(value = "菜单ID")
@TableId(value = "menu_id")
private Long menuId;
/**
* 菜单名称
*/
@ApiModelProperty(value = "菜单名称")
@NotBlank(message = "菜单名称不能为空")
@Size(min = 0, max = 50, message = "菜单名称长度不能超过50个字符")
private String menuName;
/**
* 菜单名称
*/
@ApiModelProperty(value = "菜单名称")
@NotBlank(message = "菜单名称不能为空")
@Size(min = 0, max = 50, message = "菜单名称长度不能超过50个字符")
private String menuName;
/**
* 显示顺序
*/
@ApiModelProperty(value = "显示顺序")
@NotBlank(message = "显示顺序不能为空")
private String orderNum;
/**
* 显示顺序
*/
@ApiModelProperty(value = "显示顺序")
@NotNull(message = "显示顺序不能为空")
private Long orderNum;
/**
* 路由地址
*/
@ApiModelProperty(value = "路由地址")
@Size(min = 0, max = 200, message = "路由地址不能超过200个字符")
private String path;
/**
* 路由地址
*/
@ApiModelProperty(value = "路由地址")
@Size(min = 0, max = 200, message = "路由地址不能超过200个字符")
private String path;
/**
* 组件路径
*/
@ApiModelProperty(value = "组件路径")
@Size(min = 0, max = 200, message = "组件路径不能超过255个字符")
private String component;
/**
* 组件路径
*/
@ApiModelProperty(value = "组件路径")
@Size(min = 0, max = 200, message = "组件路径不能超过255个字符")
private String component;
/**
* 路由参数
*/
@ApiModelProperty(value = "路由参数")
@ApiModelProperty(value = "路由参数")
@TableField("`query`")
private String query;
/**
* 是否为外链0是 1否
*/
@ApiModelProperty(value = "是否为外链0是 1否")
private String isFrame;
/**
* 是否为外链0是 1否
*/
@ApiModelProperty(value = "是否为外链0是 1否")
private String isFrame;
/**
* 是否缓存0缓存 1不缓存
*/
@ApiModelProperty(value = "是否缓存0缓存 1不缓存")
private String isCache;
/**
* 是否缓存0缓存 1不缓存
*/
@ApiModelProperty(value = "是否缓存0缓存 1不缓存")
private String isCache;
/**
* 类型M目录 C菜单 F按钮
*/
@ApiModelProperty(value = "类型M目录 C菜单 F按钮")
@NotBlank(message = "菜单类型不能为空")
private String menuType;
/**
* 类型M目录 C菜单 F按钮
*/
@ApiModelProperty(value = "类型M目录 C菜单 F按钮")
@NotBlank(message = "菜单类型不能为空")
private String menuType;
/**
* 显示状态0显示 1隐藏
*/
@ApiModelProperty(value = "显示状态0显示 1隐藏")
private String visible;
/**
* 显示状态0显示 1隐藏
*/
@ApiModelProperty(value = "显示状态0显示 1隐藏")
private String visible;
/**
* 菜单状态0显示 1隐藏
*/
@ApiModelProperty(value = "菜单状态0显示 1隐藏")
private String status;
/**
* 菜单状态0显示 1隐藏
*/
@ApiModelProperty(value = "菜单状态0显示 1隐藏")
private String status;
/**
* 权限字符串
*/
@ApiModelProperty(value = "权限字符串")
@Size(min = 0, max = 100, message = "权限标识长度不能超过100个字符")
private String perms;
/**
* 权限字符串
*/
@ApiModelProperty(value = "权限字符串")
@Size(min = 0, max = 100, message = "权限标识长度不能超过100个字符")
private String perms;
/**
* 菜单图标
*/
@ApiModelProperty(value = "菜单图标")
private String icon;
/**
* 菜单图标
*/
@ApiModelProperty(value = "菜单图标")
private String icon;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String remark;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String remark;
}

View File

@ -13,7 +13,6 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@ -27,118 +26,117 @@ import javax.validation.constraints.Size;
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("sys_role")
@ExcelIgnoreUnannotated
public class SysRole extends BaseEntity {
/**
* 角色ID
*/
@ApiModelProperty(value = "角色ID")
@ExcelProperty(value = "角色序号")
@TableId(value = "role_id")
private Long roleId;
/**
* 角色ID
*/
@ApiModelProperty(value = "角色ID")
@ExcelProperty(value = "角色序号")
@TableId(value = "role_id")
private Long roleId;
/**
* 角色名称
*/
@ApiModelProperty(value = "角色名称")
@ExcelProperty(value = "角色名称")
@NotBlank(message = "角色名称不能为空")
@Size(min = 0, max = 30, message = "角色名称长度不能超过30个字符")
private String roleName;
/**
* 角色名称
*/
@ApiModelProperty(value = "角色名称")
@ExcelProperty(value = "角色名称")
@NotBlank(message = "角色名称不能为空")
@Size(min = 0, max = 30, message = "角色名称长度不能超过30个字符")
private String roleName;
/**
* 角色权限
*/
@ApiModelProperty(value = "角色权限")
@ExcelProperty(value = "角色权限")
@NotBlank(message = "权限字符不能为空")
@Size(min = 0, max = 100, message = "权限字符长度不能超过100个字符")
private String roleKey;
/**
* 角色权限
*/
@ApiModelProperty(value = "角色权限")
@ExcelProperty(value = "角色权限")
@NotBlank(message = "权限字符不能为空")
@Size(min = 0, max = 100, message = "权限字符长度不能超过100个字符")
private String roleKey;
/**
* 角色排序
*/
@ApiModelProperty(value = "角色排序")
@ExcelProperty(value = "角色排序")
@NotBlank(message = "显示顺序不能为空")
private String roleSort;
/**
* 角色排序
*/
@ApiModelProperty(value = "角色排序")
@ExcelProperty(value = "角色排序")
@NotBlank(message = "显示顺序不能为空")
private String roleSort;
/**
* 数据范围1所有数据权限2自定义数据权限3本部门数据权限4本部门及以下数据权限5仅本人数据权限
*/
@ApiModelProperty(value = "数据范围1所有数据权限2自定义数据权限3本部门数据权限4本部门及以下数据权限5仅本人数据权限")
@ExcelProperty(value = "数据范围", converter = ExcelDictConvert.class)
@ExcelDictFormat(readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限,5=仅本人数据权限")
private String dataScope;
/**
* 数据范围1所有数据权限2自定义数据权限3本部门数据权限4本部门及以下数据权限5仅本人数据权限
*/
@ApiModelProperty(value = "数据范围1所有数据权限2自定义数据权限3本部门数据权限4本部门及以下数据权限5仅本人数据权限")
@ExcelProperty(value = "数据范围", converter = ExcelDictConvert.class)
@ExcelDictFormat(readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限,5=仅本人数据权限")
private String dataScope;
/**
* 菜单树选择项是否关联显示( 0父子不互相关联显示 1父子互相关联显示
*/
@ApiModelProperty(value = "菜单树选择项是否关联显示( 0父子不互相关联显示 1父子互相关联显示")
private boolean menuCheckStrictly;
/**
* 菜单树选择项是否关联显示( 0父子不互相关联显示 1父子互相关联显示
*/
@ApiModelProperty(value = "菜单树选择项是否关联显示( 0父子不互相关联显示 1父子互相关联显示")
private boolean menuCheckStrictly;
/**
* 部门树选择项是否关联显示0父子不互相关联显示 1父子互相关联显示
*/
@ApiModelProperty(value = "部门树选择项是否关联显示0父子不互相关联显示 1父子互相关联显示 ")
private boolean deptCheckStrictly;
/**
* 部门树选择项是否关联显示0父子不互相关联显示 1父子互相关联显示
*/
@ApiModelProperty(value = "部门树选择项是否关联显示0父子不互相关联显示 1父子互相关联显示 ")
private boolean deptCheckStrictly;
/**
* 角色状态0正常 1停用
*/
@ApiModelProperty(value = "角色状态0正常 1停用")
@ExcelProperty(value = "角色状态", converter = ExcelDictConvert.class)
@ExcelDictFormat(dictType = "sys_common_status")
private String status;
/**
* 角色状态0正常 1停用
*/
@ApiModelProperty(value = "角色状态0正常 1停用")
@ExcelProperty(value = "角色状态", converter = ExcelDictConvert.class)
@ExcelDictFormat(dictType = "sys_common_status")
private String status;
/**
* 删除标志0代表存在 2代表删除
*/
@ApiModelProperty(value = "删除标志0代表存在 2代表删除")
@TableLogic
private String delFlag;
/**
* 删除标志0代表存在 2代表删除
*/
@ApiModelProperty(value = "删除标志0代表存在 2代表删除")
@TableLogic
private String delFlag;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String remark;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String remark;
/**
* 用户是否存在此角色标识 默认不存在
*/
@ApiModelProperty(value = "用户是否存在此角色标识 默认不存在")
@TableField(exist = false)
private boolean flag = false;
/**
* 用户是否存在此角色标识 默认不存在
*/
@ApiModelProperty(value = "用户是否存在此角色标识 默认不存在")
@TableField(exist = false)
private boolean flag = false;
/**
* 菜单组
*/
@ApiModelProperty(value = "菜单组")
@TableField(exist = false)
private Long[] menuIds;
/**
* 菜单组
*/
@ApiModelProperty(value = "菜单组")
@TableField(exist = false)
private Long[] menuIds;
/**
* 部门组(数据权限)
*/
@ApiModelProperty(value = "部门组(数据权限)")
@TableField(exist = false)
private Long[] deptIds;
/**
* 部门组(数据权限)
*/
@ApiModelProperty(value = "部门组(数据权限)")
@TableField(exist = false)
private Long[] deptIds;
public SysRole(Long roleId) {
this.roleId = roleId;
}
public SysRole(Long roleId) {
this.roleId = roleId;
}
@ApiModelProperty(value = "是否管理员")
public boolean isAdmin() {
return isAdmin(this.roleId);
}
@ApiModelProperty(value = "是否管理员")
public boolean isAdmin() {
return isAdmin(this.roleId);
}
public static boolean isAdmin(Long roleId) {
return roleId != null && 1L == roleId;
}
public static boolean isAdmin(Long roleId) {
return roleId != null && 1L == roleId;
}
}

View File

@ -3,14 +3,15 @@ package com.ruoyi.common.core.domain.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.ruoyi.common.annotation.Sensitive;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.enums.SensitiveStrategy;
import com.ruoyi.common.xss.Xss;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
@ -27,161 +28,168 @@ import java.util.List;
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("sys_user")
@ApiModel("用户信息业务对象")
public class SysUser extends BaseEntity {
/**
* 用户ID
*/
@ApiModelProperty(value = "用户ID")
@TableId(value = "user_id")
private Long userId;
/**
* 用户ID
*/
@ApiModelProperty(value = "用户ID")
@TableId(value = "user_id")
private Long userId;
/**
* 部门ID
*/
@ApiModelProperty(value = "部门ID")
private Long deptId;
/**
* 部门ID
*/
@ApiModelProperty(value = "部门ID")
private Long deptId;
/**
* 用户账号
*/
@ApiModelProperty(value = "用户账号")
/**
* 用户账号
*/
@ApiModelProperty(value = "用户账号")
@Xss(message = "用户账号不能包含脚本字符")
@NotBlank(message = "用户账号不能为空")
@Size(min = 0, max = 30, message = "用户账号长度不能超过30个字符")
private String userName;
@Size(min = 0, max = 30, message = "用户账号长度不能超过30个字符")
private String userName;
/**
* 用户昵称
*/
/**
* 用户昵称
*/
@ApiModelProperty(value = "用户昵称")
@Xss(message = "用户昵称不能包含脚本字符")
@Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符")
private String nickName;
private String nickName;
/**
* 用户邮箱
*/
@ApiModelProperty(value = "用户邮箱")
@Email(message = "邮箱格式不正确")
@Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
private String email;
/**
* 用户类型sys_user系统用户
*/
@ApiModelProperty(value = "用户类型")
private String userType;
/**
* 手机号码
*/
@ApiModelProperty(value = "手机号码")
private String phonenumber;
/**
* 用户邮箱
*/
@Sensitive(strategy = SensitiveStrategy.EMAIL)
@ApiModelProperty(value = "用户邮箱")
@Email(message = "邮箱格式不正确")
@Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
private String email;
/**
* 用户性别
*/
@ApiModelProperty(value = "用户性别")
private String sex;
/**
* 手机号码
*/
@Sensitive(strategy = SensitiveStrategy.PHONE)
@ApiModelProperty(value = "手机号码")
private String phonenumber;
/**
* 用户头像
*/
@ApiModelProperty(value = "用户头像")
private String avatar;
/**
* 用户性别
*/
@ApiModelProperty(value = "用户性别")
private String sex;
/**
* 密码
*/
@ApiModelProperty(value = "密码")
@TableField(
insertStrategy = FieldStrategy.NOT_EMPTY,
updateStrategy = FieldStrategy.NOT_EMPTY,
whereStrategy = FieldStrategy.NOT_EMPTY
)
private String password;
/**
* 用户头像
*/
@ApiModelProperty(value = "用户头像")
private String avatar;
@JsonIgnore
@JsonProperty
public String getPassword() {
return password;
}
/**
* 密码
*/
@ApiModelProperty(value = "密码")
@TableField(
insertStrategy = FieldStrategy.NOT_EMPTY,
updateStrategy = FieldStrategy.NOT_EMPTY,
whereStrategy = FieldStrategy.NOT_EMPTY
)
private String password;
/**
* 帐号状态0正常 1停用
*/
@ApiModelProperty(value = "帐号状态0正常 1停用")
private String status;
@JsonIgnore
@JsonProperty
public String getPassword() {
return password;
}
/**
* 删除标志0代表存在 2代表删除
*/
@ApiModelProperty(value = "删除标志0代表存在 2代表删除")
@TableLogic
private String delFlag;
/**
* 帐号状态0正常 1停用
*/
@ApiModelProperty(value = "帐号状态0正常 1停用")
private String status;
/**
* 最后登录IP
*/
@ApiModelProperty(value = "最后登录IP")
private String loginIp;
/**
* 删除标志0代表存在 2代表删除
*/
@ApiModelProperty(value = "删除标志0代表存在 2代表删除")
@TableLogic
private String delFlag;
/**
* 最后登录时间
*/
@ApiModelProperty(value = "最后登录时间")
private Date loginDate;
/**
* 最后登录IP
*/
@ApiModelProperty(value = "最后登录IP")
private String loginIp;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String remark;
/**
* 最后登录时间
*/
@ApiModelProperty(value = "最后登录时间")
private Date loginDate;
/**
* 部门对象
*/
@ApiModelProperty(value = "部门对象")
@TableField(exist = false)
private SysDept dept;
/**
* 备注
*/
@ApiModelProperty(value = "备注")
private String remark;
/**
* 角色对象
*/
@ApiModelProperty(value = "角色对象")
@TableField(exist = false)
private List<SysRole> roles;
/**
* 部门对象
*/
@ApiModelProperty(value = "部门对象")
@TableField(exist = false)
private SysDept dept;
/**
* 角色
*/
@ApiModelProperty(value = "角色")
@TableField(exist = false)
private Long[] roleIds;
/**
* 角色对象
*/
@ApiModelProperty(value = "角色对象")
@TableField(exist = false)
private List<SysRole> roles;
/**
* 岗位
*/
@ApiModelProperty(value = "岗位")
@TableField(exist = false)
private Long[] postIds;
/**
* 角色
*/
@ApiModelProperty(value = "角色")
@TableField(exist = false)
private Long[] roleIds;
/**
* 数据权限 当前角色ID
*/
@ApiModelProperty(value = "角色ID")
@TableField(exist = false)
private Long roleId;
/**
* 岗位组
*/
@ApiModelProperty(value = "岗位组")
@TableField(exist = false)
private Long[] postIds;
public SysUser(Long userId) {
this.userId = userId;
}
/**
* 数据权限 当前角色ID
*/
@ApiModelProperty(value = "角色ID")
@TableField(exist = false)
private Long roleId;
@ApiModelProperty(value = "是否管理员")
public boolean isAdmin() {
return isAdmin(this.userId);
}
public SysUser(Long userId) {
this.userId = userId;
}
public static boolean isAdmin(Long userId) {
return userId != null && 1L == userId;
}
@ApiModelProperty(value = "是否管理员")
public boolean isAdmin() {
return isAdmin(this.userId);
}
public static boolean isAdmin(Long userId) {
return userId != null && 1L == userId;
}
}

View File

@ -1,9 +1,12 @@
package com.ruoyi.common.core.domain.model;
import com.ruoyi.common.constant.UserConstants;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
/**
* 用户登录对象
@ -12,19 +15,22 @@ import lombok.experimental.Accessors;
*/
@Data
@Accessors(chain = true)
@ApiModel("用户登录对象")
public class LoginBody {
/**
* 用户名
*/
@NotBlank(message = "{user.username.not.blank}")
@Length(min = UserConstants.USERNAME_MIN_LENGTH, max = UserConstants.USERNAME_MAX_LENGTH, message = "{user.username.length.valid}")
@ApiModelProperty(value = "用户名")
private String username;
/**
* 用户密码
*/
@NotBlank(message = "{user.password.not.blank}")
@Length(min = UserConstants.PASSWORD_MIN_LENGTH, max = UserConstants.PASSWORD_MAX_LENGTH, message = "{user.password.length.valid}")
@ApiModelProperty(value = "用户密码")
private String password;
@ -38,6 +44,6 @@ public class LoginBody {
* 唯一标识
*/
@ApiModelProperty(value = "唯一标识")
private String uuid = "";
private String uuid;
}

View File

@ -1,13 +1,12 @@
package com.ruoyi.common.core.domain.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ruoyi.common.core.domain.dto.RoleDTO;
import com.ruoyi.common.helper.LoginHelper;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
/**
@ -18,8 +17,7 @@ import java.util.Set;
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class LoginUser implements UserDetails {
public class LoginUser implements Serializable {
private static final long serialVersionUID = 1L;
@ -33,11 +31,21 @@ public class LoginUser implements UserDetails {
*/
private Long deptId;
/**
* 部门名
*/
private String deptName;
/**
* 用户唯一标识
*/
private String token;
/**
* 用户类型
*/
private String userType;
/**
* 登录时间
*/
@ -71,12 +79,12 @@ public class LoginUser implements UserDetails {
/**
* 菜单权限
*/
private Set<String> menuPermissions;
private Set<String> menuPermission;
/**
* 角色权限
*/
private Set<String> rolePermissions;
private Set<String> rolePermission;
/**
* 用户名
@ -84,59 +92,20 @@ public class LoginUser implements UserDetails {
private String username;
/**
* 密码
* 角色对象
*/
private String password;
@JsonIgnore
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
private List<RoleDTO> roles;
/**
* 账户是否未过期,过期无法验证
* 数据权限 当前角色ID
*/
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
}
private Long roleId;
/**
* 指定用户是否解锁,锁定的用户无法进行身份验证
* 获取登录id
*/
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return true;
public String getLoginId() {
return userType + LoginHelper.JOIN_CODE + userId;
}
/**
* 指示是否已过期的用户的凭据(密码),过期的凭据防止认证
*/
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
}
/**
* 是否可用 ,禁用的用户不能身份验证
*/
@JsonIgnore
@Override
public boolean isEnabled() {
return true;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
}

View File

@ -1,13 +1,21 @@
package com.ruoyi.common.core.domain.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 用户注册对象
*
* @author Lion Li
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel("用户注册对象")
public class RegisterBody extends LoginBody {
@ApiModelProperty(value = "用户类型")
private String userType;
}

View File

@ -0,0 +1,229 @@
package com.ruoyi.common.core.mapper;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.ruoyi.common.utils.BeanCopyUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* 自定义 Mapper 接口, 实现 自定义扩展
*
* @param <M> mapper 泛型
* @param <T> table 泛型
* @param <V> vo 泛型
* @author Lion Li
* @since 2021-05-13
*/
@SuppressWarnings("unchecked")
public interface BaseMapperPlus<M, T, V> extends BaseMapper<T> {
Log log = LogFactory.getLog(BaseMapperPlus.class);
int DEFAULT_BATCH_SIZE = 1000;
default Class<V> currentVoClass() {
return (Class<V>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseMapperPlus.class, 2);
}
default Class<T> currentModelClass() {
return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseMapperPlus.class, 1);
}
default Class<M> currentMapperClass() {
return (Class<M>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseMapperPlus.class, 0);
}
default List<T> selectList() {
return this.selectList(new QueryWrapper<>());
}
/**
* 批量插入
*/
default boolean insertBatch(Collection<T> entityList) {
return insertBatch(entityList, DEFAULT_BATCH_SIZE);
}
/**
* 批量更新
*/
default boolean updateBatchById(Collection<T> entityList) {
return updateBatchById(entityList, DEFAULT_BATCH_SIZE);
}
/**
* 批量插入或更新
*/
default boolean insertOrUpdateBatch(Collection<T> entityList) {
return insertOrUpdateBatch(entityList, DEFAULT_BATCH_SIZE);
}
/**
* 批量插入(包含限制条数)
*/
default boolean insertBatch(Collection<T> entityList, int batchSize) {
String sqlStatement = SqlHelper.getSqlStatement(this.currentMapperClass(), SqlMethod.INSERT_ONE);
return SqlHelper.executeBatch(this.currentModelClass(), log, entityList, batchSize,
(sqlSession, entity) -> sqlSession.insert(sqlStatement, entity));
}
/**
* 批量更新(包含限制条数)
*/
default boolean updateBatchById(Collection<T> entityList, int batchSize) {
String sqlStatement = SqlHelper.getSqlStatement(this.currentMapperClass(), SqlMethod.UPDATE_BY_ID);
return SqlHelper.executeBatch(this.currentModelClass(), log, entityList, batchSize,
(sqlSession, entity) -> {
MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
param.put(Constants.ENTITY, entity);
sqlSession.update(sqlStatement, param);
});
}
/**
* 批量插入或更新(包含限制条数)
*/
default boolean insertOrUpdateBatch(Collection<T> entityList, int batchSize) {
TableInfo tableInfo = TableInfoHelper.getTableInfo(this.currentModelClass());
Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
String keyProperty = tableInfo.getKeyProperty();
Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");
return SqlHelper.saveOrUpdateBatch(this.currentModelClass(), this.currentMapperClass(), log, entityList, batchSize, (sqlSession, entity) -> {
Object idVal = tableInfo.getPropertyValue(entity, keyProperty);
String sqlStatement = SqlHelper.getSqlStatement(this.currentMapperClass(), SqlMethod.SELECT_BY_ID);
return StringUtils.checkValNull(idVal)
|| CollectionUtils.isEmpty(sqlSession.selectList(sqlStatement, entity));
}, (sqlSession, entity) -> {
MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
param.put(Constants.ENTITY, entity);
String sqlStatement = SqlHelper.getSqlStatement(this.currentMapperClass(), SqlMethod.UPDATE_BY_ID);
sqlSession.update(sqlStatement, param);
});
}
/**
* 插入或更新(包含限制条数)
*/
default boolean insertOrUpdate(T entity) {
if (null != entity) {
TableInfo tableInfo = TableInfoHelper.getTableInfo(this.currentModelClass());
Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
String keyProperty = tableInfo.getKeyProperty();
Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");
Object idVal = tableInfo.getPropertyValue(entity, tableInfo.getKeyProperty());
return StringUtils.checkValNull(idVal) || Objects.isNull(selectById((Serializable) idVal)) ? insert(entity) > 0 : updateById(entity) > 0;
}
return false;
}
default V selectVoById(Serializable id) {
return selectVoById(id, this.currentVoClass());
}
/**
* 根据 ID 查询
*/
default <C> C selectVoById(Serializable id, Class<C> voClass) {
T obj = this.selectById(id);
if (ObjectUtil.isNull(obj)) {
return null;
}
return BeanCopyUtils.copy(obj, voClass);
}
default List<V> selectVoById(Collection<? extends Serializable> idList) {
return selectVoBatchIds(idList, this.currentVoClass());
}
/**
* 查询根据ID 批量查询)
*/
default <C> List<C> selectVoBatchIds(Collection<? extends Serializable> idList, Class<C> voClass) {
List<T> list = this.selectBatchIds(idList);
if (CollUtil.isEmpty(list)) {
return CollUtil.newArrayList();
}
return BeanCopyUtils.copyList(list, voClass);
}
default List<V> selectVoByMap(Map<String, Object> map) {
return selectVoByMap(map, this.currentVoClass());
}
/**
* 查询(根据 columnMap 条件)
*/
default <C> List<C> selectVoByMap(Map<String, Object> map, Class<C> voClass) {
List<T> list = this.selectByMap(map);
if (CollUtil.isEmpty(list)) {
return CollUtil.newArrayList();
}
return BeanCopyUtils.copyList(list, voClass);
}
default V selectVoOne(Wrapper<T> wrapper) {
return selectVoOne(wrapper, this.currentVoClass());
}
/**
* 根据 entity 条件,查询一条记录
*/
default <C> C selectVoOne(Wrapper<T> wrapper, Class<C> voClass) {
T obj = this.selectOne(wrapper);
if (ObjectUtil.isNull(obj)) {
return null;
}
return BeanCopyUtils.copy(obj, voClass);
}
default List<V> selectVoList(Wrapper<T> wrapper) {
return selectVoList(wrapper, this.currentVoClass());
}
/**
* 根据 entity 条件,查询全部记录
*/
default <C> List<C> selectVoList(Wrapper<T> wrapper, Class<C> voClass) {
List<T> list = this.selectList(wrapper);
if (CollUtil.isEmpty(list)) {
return CollUtil.newArrayList();
}
return BeanCopyUtils.copyList(list, voClass);
}
default <P extends IPage<V>> P selectVoPage(IPage<T> page, Wrapper<T> wrapper) {
return selectVoPage(page, wrapper, this.currentVoClass());
}
/**
* 分页查询VO
*/
default <C, P extends IPage<C>> P selectVoPage(IPage<T> page, Wrapper<T> wrapper, Class<C> voClass) {
IPage<T> pageData = this.selectPage(page, wrapper);
IPage<C> voPage = new Page<>(pageData.getCurrent(), pageData.getSize(), pageData.getTotal());
if (CollUtil.isEmpty(pageData.getRecords())) {
return (P) voPage;
}
voPage.setRecords(BeanCopyUtils.copyList(pageData.getRecords(), voClass));
return (P) voPage;
}
}

View File

@ -1,98 +0,0 @@
package com.ruoyi.common.core.mybatisplus.core;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.BeanCopyUtils;
import org.apache.ibatis.annotations.Param;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* 自定义 Mapper 接口, 实现 自定义扩展
*
* @author Lion Li
* @since 2021-05-13
*/
public interface BaseMapperPlus<T> extends BaseMapper<T> {
/**
* 单sql批量插入( 全量填充 )
*/
int insertAll(@Param("list") Collection<T> batchList);
/**
* 根据 ID 查询
*/
default <V> V selectVoById(Serializable id, Class<V> voClass){
T obj = this.selectById(id);
if (ObjectUtil.isNull(obj)) {
return null;
}
return BeanCopyUtils.copy(obj, voClass);
}
/**
* 查询根据ID 批量查询)
*/
default <V> List<V> selectVoBatchIds(Collection<? extends Serializable> idList, Class<V> voClass){
List<T> list = this.selectBatchIds(idList);
if (CollUtil.isEmpty(list)) {
return CollUtil.newArrayList();
}
return BeanCopyUtils.copyList(list, voClass);
}
/**
* 查询(根据 columnMap 条件)
*/
default <V> List<V> selectVoByMap(Map<String, Object> map, Class<V> voClass){
List<T> list = this.selectByMap(map);
if (CollUtil.isEmpty(list)) {
return CollUtil.newArrayList();
}
return BeanCopyUtils.copyList(list, voClass);
}
/**
* 根据 entity 条件,查询一条记录
*/
default <V> V selectVoOne(Wrapper<T> wrapper, Class<V> voClass) {
T obj = this.selectOne(wrapper);
if (ObjectUtil.isNull(obj)) {
return null;
}
return BeanCopyUtils.copy(obj, voClass);
}
/**
* 根据 entity 条件,查询全部记录
*/
default <V> List<V> selectVoList(Wrapper<T> wrapper, Class<V> voClass) {
List<T> list = this.selectList(wrapper);
if (CollUtil.isEmpty(list)) {
return CollUtil.newArrayList();
}
return BeanCopyUtils.copyList(list, voClass);
}
/**
* 分页查询VO
*/
default <V, P extends IPage<V>> P selectVoPage(IPage<T> page, Wrapper<T> wrapper, Class<V> voClass) {
IPage<T> pageData = this.selectPage(page, wrapper);
IPage<V> voPage = new Page<>(pageData.getCurrent(), pageData.getSize(), pageData.getTotal());
if (CollUtil.isEmpty(pageData.getRecords())) {
return (P) voPage;
}
voPage.setRecords(BeanCopyUtils.copyList(pageData.getRecords(), voClass));
return (P) voPage;
}
}

View File

@ -1,155 +0,0 @@
package com.ruoyi.common.core.mybatisplus.core;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ruoyi.common.core.page.PagePlus;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* 自定义 Service 接口, 实现 数据库实体与 vo 对象转换返回
*
* @param <T> 数据实体类
* @param <V> vo类
* @author Lion Li
*/
public interface IServicePlus<T, V> extends IService<T> {
/**
* @param id 主键id
* @return V对象
*/
V getVoById(Serializable id);
/**
* @param convertor 自定义转换器
*/
default V getVoById(Serializable id, Function<T, V> convertor) {
return convertor.apply(getById(id));
}
/**
* @param idList id列表
* @return V对象
*/
List<V> listVoByIds(Collection<? extends Serializable> idList);
/**
* @param convertor 自定义转换器
*/
default List<V> listVoByIds(Collection<? extends Serializable> idList,
Function<Collection<T>, List<V>> convertor) {
List<T> list = getBaseMapper().selectBatchIds(idList);
if (list == null) {
return null;
}
return convertor.apply(list);
}
/**
* @param columnMap 表字段 map 对象
* @return V对象
*/
List<V> listVoByMap(Map<String, Object> columnMap);
/**
* @param convertor 自定义转换器
*/
default List<V> listVoByMap(Map<String, Object> columnMap,
Function<Collection<T>, List<V>> convertor) {
List<T> list = getBaseMapper().selectByMap(columnMap);
if (list == null) {
return null;
}
return convertor.apply(list);
}
/**
* @param queryWrapper 查询条件
* @return V对象
*/
V getVoOne(Wrapper<T> queryWrapper);
/**
* @param convertor 自定义转换器
*/
default V getVoOne(Wrapper<T> queryWrapper, Function<T, V> convertor) {
return convertor.apply(getOne(queryWrapper, true));
}
/**
* @param queryWrapper 查询条件
* @return V对象
*/
List<V> listVo(Wrapper<T> queryWrapper);
/**
* @param convertor 自定义转换器
*/
default List<V> listVo(Wrapper<T> queryWrapper, Function<Collection<T>, List<V>> convertor) {
List<T> list = getBaseMapper().selectList(queryWrapper);
if (list == null) {
return null;
}
return convertor.apply(list);
}
default List<V> listVo() {
return listVo(Wrappers.emptyWrapper());
}
/**
* @param convertor 自定义转换器
*/
default List<V> listVo(Function<Collection<T>, List<V>> convertor) {
return listVo(Wrappers.emptyWrapper(), convertor);
}
/**
* @param page 分页对象
* @param queryWrapper 查询条件
* @return V对象
* @deprecated 3.6.0 移除 请使用 {@link ServicePlusImpl#pageVo(IPage, Wrapper)}
*/
@Deprecated
PagePlus<T, V> pageVo(PagePlus<T, V> page, Wrapper<T> queryWrapper);
/**
* @param convertor 自定义转换器
* @deprecated 3.6.0 移除 请使用 {@link ServicePlusImpl#pageVo(IPage, Wrapper)}
*/
@Deprecated
default PagePlus<T, V> pageVo(PagePlus<T, V> page, Wrapper<T> queryWrapper,
Function<Collection<T>, List<V>> convertor) {
PagePlus<T, V> result = getBaseMapper().selectPage(page, queryWrapper);
return result.setRecordsVo(convertor.apply(result.getRecords()));
}
/**
* @deprecated 3.6.0 移除 请使用 {@link ServicePlusImpl#pageVo(IPage, Wrapper)}
*/
@Deprecated
default PagePlus<T, V> pageVo(PagePlus<T, V> page) {
return pageVo(page, Wrappers.emptyWrapper());
}
/**
* @param convertor 自定义转换器
* @deprecated 3.6.0 移除 请使用 {@link ServicePlusImpl#pageVo(IPage, Wrapper)}
*/
@Deprecated
default PagePlus<T, V> pageVo(PagePlus<T, V> page, Function<Collection<T>, List<V>> convertor) {
return pageVo(page, Wrappers.emptyWrapper(), convertor);
}
boolean saveAll(Collection<T> entityList);
boolean saveOrUpdateAll(Collection<T> entityList);
}

View File

@ -1,226 +0,0 @@
package com.ruoyi.common.core.mybatisplus.core;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.reflect.ReflectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* IServicePlus 实现类
*
* @param <M> Mapper类
* @param <T> 数据实体类
* @param <V> vo类
* @author Lion Li
*/
@Slf4j
@SuppressWarnings("unchecked")
public class ServicePlusImpl<M extends BaseMapperPlus<T>, T, V> extends ServiceImpl<M, T> implements IServicePlus<T, V> {
@Autowired
protected M baseMapper;
@Override
public M getBaseMapper() {
return baseMapper;
}
protected Class<T> entityClass = currentModelClass();
@Override
public Class<T> getEntityClass() {
return entityClass;
}
protected Class<M> mapperClass = currentMapperClass();
protected Class<V> voClass = currentVoClass();
public Class<V> getVoClass() {
return voClass;
}
@Override
protected Class<M> currentMapperClass() {
return (Class<M>) ReflectionKit.getSuperClassGenericType(this.getClass(), ServicePlusImpl.class, 0);
}
@Override
protected Class<T> currentModelClass() {
return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), ServicePlusImpl.class, 1);
}
protected Class<V> currentVoClass() {
return (Class<V>) ReflectionKit.getSuperClassGenericType(this.getClass(), ServicePlusImpl.class, 2);
}
/**
* 单条执行性能差 适用于列表对象内容不确定
*/
@Override
public boolean saveBatch(Collection<T> entityList, int batchSize) {
return super.saveBatch(entityList, batchSize);
}
@Override
public boolean saveOrUpdate(T entity) {
return super.saveOrUpdate(entity);
}
/**
* 单条执行性能差 适用于列表对象内容不确定
*/
@Override
public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize) {
return super.saveOrUpdateBatch(entityList, batchSize);
}
@Override
public boolean updateBatchById(Collection<T> entityList, int batchSize) {
return super.updateBatchById(entityList, batchSize);
}
/**
* 单sql批量插入( 全量填充 无视数据库默认值 )
* 适用于无脑插入
*/
@Override
public boolean saveBatch(Collection<T> entityList) {
return saveBatch(entityList, DEFAULT_BATCH_SIZE);
}
@Override
public boolean saveOrUpdateBatch(Collection<T> entityList) {
return saveOrUpdateBatch(entityList, DEFAULT_BATCH_SIZE);
}
@Override
public boolean updateBatchById(Collection<T> entityList) {
return updateBatchById(entityList, DEFAULT_BATCH_SIZE);
}
/**
* 单sql批量插入( 全量填充 )
*/
@Override
public boolean saveAll(Collection<T> entityList) {
if (CollUtil.isEmpty(entityList)) {
return false;
}
return baseMapper.insertAll(entityList) == entityList.size();
}
/**
* 全量保存或更新 ( 按主键区分 )
*/
@Override
public boolean saveOrUpdateAll(Collection<T> entityList) {
if (CollUtil.isEmpty(entityList)) {
return false;
}
TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
String keyProperty = tableInfo.getKeyProperty();
Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");
List<T> addList = new ArrayList<>();
List<T> updateList = new ArrayList<>();
int row = 0;
for (T entity : entityList) {
Object id = ReflectUtils.invokeGetter(entity, keyProperty);
if (ObjectUtil.isNull(id)) {
addList.add(entity);
} else {
updateList.add(entity);
}
}
if (CollUtil.isNotEmpty(updateList) && updateBatchById(updateList)) {
row += updateList.size();
}
if (CollUtil.isNotEmpty(addList)) {
row += baseMapper.insertAll(addList);
}
return row == entityList.size();
}
/**
* 根据 ID 查询
*/
@Override
public V getVoById(Serializable id) {
return getBaseMapper().selectVoById(id, voClass);
}
/**
* 查询根据ID 批量查询)
*/
@Override
public List<V> listVoByIds(Collection<? extends Serializable> idList) {
return getBaseMapper().selectVoBatchIds(idList, voClass);
}
/**
* 查询(根据 columnMap 条件)
*/
@Override
public List<V> listVoByMap(Map<String, Object> columnMap) {
return getBaseMapper().selectVoByMap(columnMap, voClass);
}
/**
* 根据 Wrapper查询一条记录 <br/>
* <p>结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")</p>
*/
@Override
public V getVoOne(Wrapper<T> queryWrapper) {
return getBaseMapper().selectVoOne(queryWrapper, voClass);
}
/**
* 查询列表
*/
@Override
public List<V> listVo(Wrapper<T> queryWrapper) {
return getBaseMapper().selectVoList(queryWrapper, voClass);
}
/**
* 翻页查询
* @deprecated 3.6.0 移除 请使用 {@link #pageVo(IPage, Wrapper)}
*/
@Override
@Deprecated
public PagePlus<T, V> pageVo(PagePlus<T, V> page, Wrapper<T> queryWrapper) {
PagePlus<T, V> result = getBaseMapper().selectPage(page, queryWrapper);
List<V> volist = BeanCopyUtils.copyList(result.getRecords(), voClass);
result.setRecordsVo(volist);
return result;
}
/**
* 翻页查询
*
* @param page 翻页对象
* @param queryWrapper 实体对象封装操作类
*/
public <P extends IPage<V>> P pageVo(IPage<T> page, Wrapper<T> queryWrapper) {
return getBaseMapper().selectVoPage(page, queryWrapper, voClass);
}
}

View File

@ -1,101 +0,0 @@
package com.ruoyi.common.core.mybatisplus.methods;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.ruoyi.common.utils.StringUtils;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import java.util.List;
/**
* 单sql批量插入( 全量填充 )
*
* @author Lion Li
*/
public class InsertAll extends AbstractMethod {
private final static String[] FILL_PROPERTY = {"createTime", "createBy", "updateTime", "updateBy"};
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
final String sql = "<script>insert into %s %s values %s</script>";
final String fieldSql = prepareFieldSql(tableInfo);
final String valueSql = prepareValuesSqlForMysqlBatch(tableInfo);
KeyGenerator keyGenerator = new NoKeyGenerator();
String sqlMethod = "insertAll";
String keyProperty = null;
String keyColumn = null;
// 表包含主键处理逻辑,如果不包含主键当普通字段处理
if (StringUtils.isNotBlank(tableInfo.getKeyProperty())) {
if (tableInfo.getIdType() == IdType.AUTO) {
/** 自增主键 */
keyGenerator = new Jdbc3KeyGenerator();
keyProperty = tableInfo.getKeyProperty();
keyColumn = tableInfo.getKeyColumn();
} else {
if (null != tableInfo.getKeySequence()) {
keyGenerator = TableInfoHelper.genKeyGenerator(sqlMethod, tableInfo, builderAssistant);
keyProperty = tableInfo.getKeyProperty();
keyColumn = tableInfo.getKeyColumn();
}
}
}
final String sqlResult = String.format(sql, tableInfo.getTableName(), fieldSql, valueSql);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
return this.addInsertMappedStatement(mapperClass, modelClass, sqlMethod, sqlSource, keyGenerator, keyProperty, keyColumn);
}
private String prepareFieldSql(TableInfo tableInfo) {
StringBuilder fieldSql = new StringBuilder();
if (StringUtils.isNotBlank(tableInfo.getKeyColumn())) {
fieldSql.append(tableInfo.getKeyColumn()).append(",");
}
tableInfo.getFieldList().forEach(x -> fieldSql.append(x.getColumn()).append(","));
fieldSql.delete(fieldSql.length() - 1, fieldSql.length());
fieldSql.insert(0, "(");
fieldSql.append(")");
return fieldSql.toString();
}
private String prepareValuesSqlForMysqlBatch(TableInfo tableInfo) {
final StringBuilder valueSql = new StringBuilder();
valueSql.append("<foreach collection=\"list\" item=\"item\" index=\"index\" open=\"(\" separator=\"),(\" close=\")\">");
if (StringUtils.isNotBlank(tableInfo.getKeyColumn())) {
valueSql.append("\n#{item.").append(tableInfo.getKeyProperty()).append("},\n");
}
List<TableFieldInfo> fieldList = tableInfo.getFieldList();
int last = fieldList.size() - 1;
for (int i = 0; i < fieldList.size(); i++) {
String property = fieldList.get(i).getProperty();
if (!StringUtils.equalsAny(property, FILL_PROPERTY)) {
valueSql.append("<if test=\"item.").append(property).append(" != null\">");
valueSql.append("#{item.").append(property).append("}");
if (i != last) {
valueSql.append(",");
}
valueSql.append("</if>");
valueSql.append("<if test=\"item.").append(property).append(" == null\">");
valueSql.append("DEFAULT");
if (i != last) {
valueSql.append(",");
}
valueSql.append("</if>");
} else {
valueSql.append("#{item.").append(property).append("}");
if (i != last) {
valueSql.append(",");
}
}
}
valueSql.append("</foreach>");
return valueSql.toString();
}
}

View File

@ -1,158 +0,0 @@
package com.ruoyi.common.core.page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* 分页 Page 增强对象
*
* @param <T> 数据库实体
* @param <K> vo实体
* @author Lion Li
* @deprecated 3.6.0 删除 请使用 {@link com.ruoyi.common.core.domain.PageQuery#build()}
*/
@Data
@Accessors(chain = true)
@Deprecated
public class PagePlus<T,K> implements IPage<T> {
/**
* domain实体列表
*/
private List<T> records = Collections.emptyList();
/**
* vo实体列表
*/
private List<K> recordsVo = Collections.emptyList();
/**
* 总数
*/
private long total = 0L;
/**
* 页长度
*/
private long size = 10L;
/**
* 当前页
*/
private long current = 1L;
/**
* 排序字段信息
*/
private List<OrderItem> orders = new ArrayList<>();
/**
* 自动优化 COUNT SQL
*/
private boolean optimizeCountSql = true;
/**
* 是否进行 count 查询
*/
private boolean isSearchCount = true;
/**
* 是否命中count缓存
*/
private boolean hitCount = false;
/**
* countId
*/
private String countId;
/**
* 最大limit
*/
private Long maxLimit;
public PagePlus() {
}
public PagePlus(long current, long size) {
this(current, size, 0L);
}
public PagePlus(long current, long size, long total) {
this(current, size, total, true);
}
public PagePlus(long current, long size, boolean isSearchCount) {
this(current, size, 0L, isSearchCount);
}
public PagePlus(long current, long size, long total, boolean isSearchCount) {
if (current > 1L) {
this.current = current;
}
this.size = size;
this.total = total;
this.isSearchCount = isSearchCount;
}
@Override
public String countId() {
return this.getCountId();
}
@Override
public Long maxLimit() {
return this.getMaxLimit();
}
public PagePlus<T, K> addOrder(OrderItem... items) {
this.orders.addAll(Arrays.asList(items));
return this;
}
public PagePlus<T, K> addOrder(List<OrderItem> items) {
this.orders.addAll(items);
return this;
}
@Override
public List<OrderItem> orders() {
return this.getOrders();
}
@Override
public boolean optimizeCountSql() {
return this.optimizeCountSql;
}
@Override
public long getPages() {
// 解决 github issues/3208
return IPage.super.getPages();
}
public static <T,K> PagePlus<T,K> of(long current, long size) {
return of(current, size, 0);
}
public static <T,K> PagePlus<T,K> of(long current, long size, long total) {
return of(current, size, total, true);
}
public static <T,K> PagePlus<T,K> of(long current, long size, boolean searchCount) {
return of(current, size, 0, searchCount);
}
public static <T,K> PagePlus<T,K> of(long current, long size, long total, boolean searchCount) {
return new PagePlus<>(current, size, total, searchCount);
}
}

View File

@ -19,45 +19,44 @@ import java.util.List;
@Data
@NoArgsConstructor
@Accessors(chain = true)
@ApiModel("分页响应对象")
public class TableDataInfo<T> implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/**
* 总记录数
*/
@ApiModelProperty("总记录数")
private long total;
/**
* 总记录数
*/
@ApiModelProperty("总记录数")
private long total;
/**
* 列表数据
*/
@ApiModelProperty("列表数据")
private List<T> rows;
/**
* 列表数据
*/
@ApiModelProperty("列表数据")
private List<T> rows;
/**
* 消息状态码
*/
@ApiModelProperty("消息状态码")
private int code;
/**
* 消息状态码
*/
@ApiModelProperty("消息状态码")
private int code;
/**
* 消息内容
*/
@ApiModelProperty("消息内容")
private String msg;
/**
* 消息内容
*/
@ApiModelProperty("消息内容")
private String msg;
/**
* 分页
*
* @param list 列表数据
* @param total 总记录数
*/
public TableDataInfo(List<T> list, long total) {
this.rows = list;
this.total = total;
}
/**
* 分页
*
* @param list 列表数据
* @param total 总记录数
*/
public TableDataInfo(List<T> list, long total) {
this.rows = list;
this.total = total;
}
public static <T> TableDataInfo<T> build(IPage<T> page) {
TableDataInfo<T> rspData = new TableDataInfo<>();

View File

@ -0,0 +1,18 @@
package com.ruoyi.common.core.service;
/**
* 脱敏服务
* 默认管理员不过滤
* 需自行根据业务重写实现
*
* @author Lion Li
* @version 3.6.0
*/
public interface SensitiveService {
/**
* 是否脱敏
*/
boolean isSensitive();
}

View File

@ -1,69 +0,0 @@
package com.ruoyi.common.core.service;
import com.ruoyi.common.core.domain.model.LoginUser;
import javax.servlet.http.HttpServletRequest;
/**
* token验证处理
*
* @author Lion Li
*/
public interface TokenService {
/**
* 获取用户身份信息
*
* @return 用户信息
*/
LoginUser getLoginUser(HttpServletRequest request);
/**
* 设置用户身份信息
*/
void setLoginUser(LoginUser loginUser);
/**
* 删除用户身份信息
*/
void delLoginUser(String token);
/**
* 创建令牌
*
* @param loginUser 用户信息
* @return 令牌
*/
String createToken(LoginUser loginUser);
/**
* 验证令牌有效期相差不足20分钟自动刷新缓存
*
* @param loginUser
* @return 令牌
*/
void verifyToken(LoginUser loginUser);
/**
* 刷新令牌有效期
*
* @param loginUser 登录信息
*/
void refreshToken(LoginUser loginUser);
/**
* 设置用户代理信息
*
* @param loginUser 登录信息
*/
void setUserAgent(LoginUser loginUser);
/**
* 从令牌中获取用户名
*
* @param token 令牌
* @return 用户名
*/
String getUsernameFromToken(String token);
}

View File

@ -1,28 +0,0 @@
package com.ruoyi.common.core.service;
import com.ruoyi.common.core.domain.entity.SysUser;
/**
* 通用 用户业务
*
* @author Lion Li
*/
public interface UserService {
/**
* 通过用户名查询用户
*
* @param userName 用户名
* @return 用户对象信息
*/
SysUser selectUserByUserName(String userName);
/**
* 通过用户ID查询用户
*
* @param userId 用户ID
* @return 用户对象信息
*/
SysUser selectUserById(Long userId);
}

View File

@ -6,10 +6,10 @@ import lombok.Getter;
/**
* 数据权限类型
*
* <p>
* 语法支持 spel 模板表达式
*
* 内置数据 user 当前用户 内容参考 SysUser
* <p>
* 内置数据 user 当前用户 内容参考 LoginUser
* 如需扩展数据 可使用 {@link com.ruoyi.common.helper.DataPermissionHelper} 操作
* 内置服务 sdss 系统数据权限服务 内容参考 SysDataScopeService
* 如需扩展更多自定义服务 可以参考 sdss 自行编写
@ -44,7 +44,7 @@ public enum DataScopeType {
/**
* 仅本人数据权限
*/
SELF("5", " #{#userName} = #{#user.userId} " , " 1 = 0 ");
SELF("5", " #{#userName} = #{#user.userId} ", " 1 = 0 ");
private final String code;

View File

@ -1,27 +0,0 @@
package com.ruoyi.common.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 数据源
*
* @author Lion Li
* @deprecated 3.6.0 移除
*/
@AllArgsConstructor
@Deprecated
public enum DataSourceType {
/**
* 主库
*/
MASTER("master"),
/**
* 从库
*/
SLAVE("slave");
@Getter
private final String source;
}

View File

@ -0,0 +1,27 @@
package com.ruoyi.common.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 设备类型
* 针对一套 用户体系
*
* @author Lion Li
*/
@Getter
@AllArgsConstructor
public enum DeviceType {
/**
* pc端
*/
PC("pc"),
/**
* app端
*/
APP("app");
private final String device;
}

View File

@ -0,0 +1,49 @@
package com.ruoyi.common.enums;
import cn.hutool.core.util.DesensitizedUtil;
import lombok.AllArgsConstructor;
import java.util.function.Function;
/**
* 脱敏策略
*
* @author Yjoioooo
* @version 3.6.0
*/
@AllArgsConstructor
public enum SensitiveStrategy {
/**
* 身份证脱敏
*/
ID_CARD(s -> DesensitizedUtil.idCardNum(s, 3, 4)),
/**
* 手机号脱敏
*/
PHONE(DesensitizedUtil::mobilePhone),
/**
* 地址脱敏
*/
ADDRESS(s -> DesensitizedUtil.address(s, 8)),
/**
* 邮箱脱敏
*/
EMAIL(DesensitizedUtil::email),
/**
* 银行卡
*/
BANK_CARD(DesensitizedUtil::bankCard);
//可自行添加其他脱敏策略
private final Function<String, String> desensitizer;
public Function<String, String> desensitizer() {
return desensitizer;
}
}

View File

@ -0,0 +1,37 @@
package com.ruoyi.common.enums;
import com.ruoyi.common.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 设备类型
* 针对多套 用户体系
*
* @author Lion Li
*/
@Getter
@AllArgsConstructor
public enum UserType {
/**
* pc端
*/
SYS_USER("sys_user"),
/**
* app端
*/
APP_USER("app_user");
private final String userType;
public static UserType getUserType(String str) {
for (UserType value : values()) {
if (StringUtils.contains(str, value.getUserType())) {
return value;
}
}
throw new RuntimeException("'UserType' not found By " + str);
}
}

View File

@ -2,7 +2,9 @@ package com.ruoyi.common.exception.base;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* 基础异常

View File

@ -20,10 +20,10 @@ public class RepeatableFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
throws IOException, ServletException {
ServletRequest requestWrapper = null;
if (request instanceof HttpServletRequest
&& StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
&& StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
}
if (null == requestWrapper) {

View File

@ -33,7 +33,7 @@ public class XssFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
if (handleExcludeURL(req, resp)) {

View File

@ -2,6 +2,8 @@ package com.ruoyi.common.helper;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.ServletUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
@ -13,6 +15,7 @@ import java.util.Map;
* @author Lion Li
* @version 3.5.0
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@SuppressWarnings("unchecked cast")
public class DataPermissionHelper {
@ -24,7 +27,6 @@ public class DataPermissionHelper {
}
public static void setVariable(String key, Object value) {
Map<String, Object> context = getContext();
context.put(key, value);

View File

@ -0,0 +1,136 @@
package com.ruoyi.common.helper;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.DeviceType;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.StringUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* 登录鉴权助手
* 为适配多端登录而封装
*
* @author Lion Li
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class LoginHelper {
public static final String JOIN_CODE = ":";
public static final String LOGIN_USER_KEY = "loginUser";
private static final ThreadLocal<LoginUser> LOGIN_CACHE = new ThreadLocal<>();
/**
* 登录系统
* 针对两套用户体系
*
* @param loginUser 登录用户信息
*/
public static void login(LoginUser loginUser) {
LOGIN_CACHE.set(loginUser);
StpUtil.login(loginUser.getLoginId());
setLoginUser(loginUser);
}
/**
* 登录系统 基于 设备类型
* 针对一套用户体系
*
* @param loginUser 登录用户信息
*/
public static void loginByDevice(LoginUser loginUser, DeviceType deviceType) {
LOGIN_CACHE.set(loginUser);
StpUtil.login(loginUser.getLoginId(), deviceType.getDevice());
setLoginUser(loginUser);
}
/**
* 设置用户数据(多级缓存)
*/
public static void setLoginUser(LoginUser loginUser) {
StpUtil.getTokenSession().set(LOGIN_USER_KEY, loginUser);
}
/**
* 获取用户(多级缓存)
*/
public static LoginUser getLoginUser() {
LoginUser loginUser = LOGIN_CACHE.get();
if (loginUser != null) {
return loginUser;
}
return (LoginUser) StpUtil.getTokenSession().get(LOGIN_USER_KEY);
}
/**
* 清除一级缓存 防止内存问题
*/
public static void clearCache() {
LOGIN_CACHE.remove();
}
/**
* 获取用户id
*/
public static Long getUserId() {
LoginUser loginUser = getLoginUser();
if (ObjectUtil.isNull(loginUser)) {
String loginId = StpUtil.getLoginIdAsString();
String userId = null;
for (UserType value : UserType.values()) {
if (StringUtils.contains(loginId, value.getUserType())) {
String[] strs = StringUtils.split(loginId, JOIN_CODE);
// 用户id在总是在最后
userId = strs[strs.length - 1];
}
}
if (StringUtils.isBlank(userId)) {
throw new UtilException("登录用户: LoginId异常 => " + loginId);
}
return Long.parseLong(userId);
}
return loginUser.getUserId();
}
/**
* 获取部门ID
*/
public static Long getDeptId() {
return getLoginUser().getDeptId();
}
/**
* 获取用户账户
*/
public static String getUsername() {
return getLoginUser().getUsername();
}
/**
* 获取用户类型
*/
public static UserType getUserType() {
String loginId = StpUtil.getLoginIdAsString();
return UserType.getUserType(loginId);
}
/**
* 是否为管理员
*
* @param userId 用户ID
* @return 结果
*/
public static boolean isAdmin(Long userId) {
return userId != null && 1L == userId;
}
public static boolean isAdmin() {
Long userId = getUserId();
return userId != null && 1L == userId;
}
}

View File

@ -0,0 +1,46 @@
package com.ruoyi.common.jackson;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.ruoyi.common.annotation.Sensitive;
import com.ruoyi.common.core.service.SensitiveService;
import com.ruoyi.common.enums.SensitiveStrategy;
import com.ruoyi.common.utils.spring.SpringUtils;
import java.io.IOException;
import java.util.Objects;
/**
* 数据脱敏json序列化工具
*
* @author Yjoioooo
*/
public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {
private SensitiveStrategy strategy;
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
SensitiveService sensitiveService = SpringUtils.getBean(SensitiveService.class);
if (sensitiveService.isSensitive()) {
gen.writeString(value);
} else {
gen.writeString(strategy.desensitizer().apply(value));
}
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
Sensitive annotation = property.getAnnotation(Sensitive.class);
if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) {
this.strategy = annotation.strategy();
return this;
}
return prov.findValueSerializer(property.getType(), property);
}
}

View File

@ -1,31 +0,0 @@
package com.ruoyi.common.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* token 配置属性
*
* @author Lion Li
*/
@Data
@Component
@ConfigurationProperties(prefix = "token")
public class TokenProperties {
/**
* 令牌自定义标识
*/
private String header;
/**
* 令牌秘钥
*/
private String secret;
/**
* 令牌有效期默认30分钟
*/
private int expireTime;
}

View File

@ -13,6 +13,10 @@ import java.util.Map;
/**
* bean深拷贝工具(基于 cglib 性能优异)
* <p>
* 重点 cglib 不支持 拷贝到链式对象
* 例如: 源对象 拷贝到 目标(链式对象)
* 请区分好`浅拷贝`和`深拷贝`再做使用
*
* @author Lion Li
*/

View File

@ -28,9 +28,9 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
/**
* 获取当前Date型日期

View File

@ -1,6 +1,8 @@
package com.ruoyi.common.utils;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -11,7 +13,6 @@ import lombok.NoArgsConstructor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* JSON 工具类
@ -28,7 +29,7 @@ public class JsonUtils {
}
public static String toJsonString(Object object) {
if (StringUtils.isNull(object)) {
if (ObjectUtil.isNull(object)) {
return null;
}
try {
@ -71,13 +72,23 @@ public class JsonUtils {
}
}
public static <T> Map<String, T> parseMap(String text) {
public static Dict parseMap(String text) {
if (StringUtils.isBlank(text)) {
return null;
}
try {
return OBJECT_MAPPER.readValue(text, new TypeReference<Map<String, T>>() {
});
return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructType(Dict.class));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static List<Dict> parseArrayMap(String text) {
if (StringUtils.isBlank(text)) {
return null;
}
try {
return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, Dict.class));
} catch (IOException e) {
throw new RuntimeException(e);
}

View File

@ -1,193 +0,0 @@
package com.ruoyi.common.utils;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.sql.SqlUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* 分页工具
*
* @author Lion Li
* @deprecated 3.6.0 删除 请使用 {@link PageQuery} 与 {@link TableDataInfo}
*/
@Deprecated
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PageUtils {
/**
* 当前记录起始索引
*/
@Deprecated
public static final String PAGE_NUM = "pageNum";
/**
* 每页显示记录数
*/
@Deprecated
public static final String PAGE_SIZE = "pageSize";
/**
* 排序列
*/
@Deprecated
public static final String ORDER_BY_COLUMN = "orderByColumn";
/**
* 排序的方向 "desc" 或者 "asc".
*/
@Deprecated
public static final String IS_ASC = "isAsc";
/**
* 当前记录起始索引 默认值
*/
@Deprecated
public static final int DEFAULT_PAGE_NUM = 1;
/**
* 每页显示记录数 默认值 默认查全部
*/
@Deprecated
public static final int DEFAULT_PAGE_SIZE = Integer.MAX_VALUE;
/**
* 构建 plus 分页对象
*
* @param <T> domain 实体
* @param <K> vo 实体
* @return 分页对象
* @deprecated 3.6.0 删除 请使用 {@link PageQuery#build()}
* 由于使用 Servlet 获取只能从 param 获取 灵活性降低 故将传参操作交给用户
*/
@Deprecated
public static <T, K> PagePlus<T, K> buildPagePlus() {
Integer pageNum = ServletUtils.getParameterToInt(PAGE_NUM, DEFAULT_PAGE_NUM);
Integer pageSize = ServletUtils.getParameterToInt(PAGE_SIZE, DEFAULT_PAGE_SIZE);
String orderByColumn = ServletUtils.getParameter(ORDER_BY_COLUMN);
String isAsc = ServletUtils.getParameter(IS_ASC);
if (pageNum <= 0) {
pageNum = DEFAULT_PAGE_NUM;
}
PagePlus<T, K> page = new PagePlus<>(pageNum, pageSize);
OrderItem orderItem = buildOrderItem(orderByColumn, isAsc);
if (ObjectUtil.isNotNull(orderItem)) {
page.addOrder(orderItem);
}
return page;
}
@Deprecated
public static <T> Page<T> buildPage() {
return buildPage(null, null);
}
/**
* 构建 MP 普通分页对象
*
* @param <T> domain 实体
* @return 分页对象
* @deprecated 3.6.0 删除 请使用 {@link PageQuery#build()}
* 由于使用 Servlet 获取只能从 param 获取 灵活性降低 故将传参操作交给用户
*/
@Deprecated
public static <T> Page<T> buildPage(String defaultOrderByColumn, String defaultIsAsc) {
Integer pageNum = ServletUtils.getParameterToInt(PAGE_NUM, DEFAULT_PAGE_NUM);
Integer pageSize = ServletUtils.getParameterToInt(PAGE_SIZE, DEFAULT_PAGE_SIZE);
String orderByColumn = ServletUtils.getParameter(ORDER_BY_COLUMN, defaultOrderByColumn);
String isAsc = ServletUtils.getParameter(IS_ASC, defaultIsAsc);
if (pageNum <= 0) {
pageNum = DEFAULT_PAGE_NUM;
}
Page<T> page = new Page<>(pageNum, pageSize);
OrderItem orderItem = buildOrderItem(orderByColumn, isAsc);
if (ObjectUtil.isNotNull(orderItem)) {
page.addOrder(orderItem);
}
return page;
}
private static OrderItem buildOrderItem(String orderByColumn, String isAsc) {
// 兼容前端排序类型
if ("ascending".equals(isAsc)) {
isAsc = "asc";
} else if ("descending".equals(isAsc)) {
isAsc = "desc";
}
if (StringUtils.isNotBlank(orderByColumn)) {
String orderBy = SqlUtil.escapeOrderBySql(orderByColumn);
orderBy = StringUtils.toUnderScoreCase(orderBy);
if ("asc".equals(isAsc)) {
return OrderItem.asc(orderBy);
} else if ("desc".equals(isAsc)) {
return OrderItem.desc(orderBy);
}
}
return null;
}
/**
* 构建 MP 普通分页对象
*
* @param <T> domain 实体
* @return 分页对象
* @deprecated 3.6.0 删除 请使用 {@link PageQuery#build()}
* 由于使用 Servlet 获取只能从 param 获取 灵活性降低 故将传参操作交给用户
*/
@Deprecated
public static <T, K> TableDataInfo<K> buildDataInfo(PagePlus<T, K> page) {
TableDataInfo<K> rspData = new TableDataInfo<>();
rspData.setCode(HttpStatus.HTTP_OK);
rspData.setMsg("查询成功");
rspData.setRows(page.getRecordsVo());
rspData.setTotal(page.getTotal());
return rspData;
}
/**
* @deprecated 3.6.0 删除 请使用 {@link TableDataInfo#build(IPage)}
*/
@Deprecated
public static <T> TableDataInfo<T> buildDataInfo(Page<T> page) {
TableDataInfo<T> rspData = new TableDataInfo<>();
rspData.setCode(HttpStatus.HTTP_OK);
rspData.setMsg("查询成功");
rspData.setRows(page.getRecords());
rspData.setTotal(page.getTotal());
return rspData;
}
/**
* @deprecated 3.6.0 删除 请使用 {@link TableDataInfo#build(List)}
*/
@Deprecated
public static <T> TableDataInfo<T> buildDataInfo(List<T> list) {
TableDataInfo<T> rspData = new TableDataInfo<>();
rspData.setCode(HttpStatus.HTTP_OK);
rspData.setMsg("查询成功");
rspData.setRows(list);
rspData.setTotal(list.size());
return rspData;
}
/**
* @deprecated 3.6.0 删除 请使用 {@link TableDataInfo#build()}
*/
@Deprecated
public static <T> TableDataInfo<T> buildDataInfo() {
TableDataInfo<T> rspData = new TableDataInfo<>();
rspData.setCode(HttpStatus.HTTP_OK);
rspData.setMsg("查询成功");
return rspData;
}
}

View File

@ -1,103 +0,0 @@
package com.ruoyi.common.utils;
import cn.hutool.http.HttpStatus;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* 安全服务工具类
*
* @author ruoyi
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SecurityUtils {
/**
* 用户ID
**/
public static Long getUserId() {
try {
return getLoginUser().getUserId();
} catch (Exception e) {
throw new ServiceException("获取用户ID异常", HttpStatus.HTTP_UNAUTHORIZED);
}
}
/**
* 获取部门ID
**/
public static Long getDeptId() {
try {
return getLoginUser().getDeptId();
} catch (Exception e) {
throw new ServiceException("获取部门ID异常", HttpStatus.HTTP_UNAUTHORIZED);
}
}
/**
* 获取用户账户
**/
public static String getUsername() {
try {
return getLoginUser().getUsername();
} catch (Exception e) {
throw new ServiceException("获取用户账户异常", HttpStatus.HTTP_UNAUTHORIZED);
}
}
/**
* 获取用户
**/
public static LoginUser getLoginUser() {
try {
return (LoginUser) getAuthentication().getPrincipal();
} catch (Exception e) {
throw new ServiceException("获取用户信息异常", HttpStatus.HTTP_UNAUTHORIZED);
}
}
/**
* 获取Authentication
*/
public static Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
/**
* 生成BCryptPasswordEncoder密码
*
* @param password 密码
* @return 加密字符串
*/
public static String encryptPassword(String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.encode(password);
}
/**
* 判断密码是否相同
*
* @param rawPassword 真实密码
* @param encodedPassword 加密后字符
* @return 结果
*/
public static boolean matchesPassword(String rawPassword, String encodedPassword) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.matches(rawPassword, encodedPassword);
}
/**
* 是否为管理员
*
* @param userId 用户ID
* @return 结果
*/
public static boolean isAdmin(Long userId) {
return userId != null && 1L == userId;
}
}

View File

@ -97,9 +97,8 @@ public class ServletUtils extends ServletUtil {
*
* @param response 渲染对象
* @param string 待渲染的字符串
* @return null
*/
public static String renderString(HttpServletResponse response, String string) {
public static void renderString(HttpServletResponse response, String string) {
try {
response.setStatus(HttpStatus.HTTP_OK);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
@ -108,7 +107,6 @@ public class ServletUtils extends ServletUtil {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
@ -119,12 +117,12 @@ public class ServletUtils extends ServletUtil {
public static boolean isAjaxRequest(HttpServletRequest request) {
String accept = request.getHeader("accept");
if (accept != null && accept.indexOf("application/json") != -1) {
if (accept != null && accept.contains("application/json")) {
return true;
}
String xRequestedWith = request.getHeader("X-Requested-With");
if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) {
return true;
}
@ -134,10 +132,7 @@ public class ServletUtils extends ServletUtil {
}
String ajax = request.getParameter("__ajax");
if (StringUtils.equalsAnyIgnoreCase(ajax, "json", "xml")) {
return true;
}
return false;
return StringUtils.equalsAnyIgnoreCase(ajax, "json", "xml");
}
public static String getClientIP() {

View File

@ -2,15 +2,15 @@ package com.ruoyi.common.utils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.util.AntPathMatcher;
import java.util.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 字符串工具类
@ -20,338 +20,215 @@ import java.util.*;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
* 获取参数不为空值
*
* @param value defaultValue 要判断的value
* @return value 返回值
*/
public static <T> T nvl(T value, T defaultValue) {
return ObjectUtil.defaultIfNull(value, defaultValue);
}
/**
* 获取参数不为空值
*
* @param str defaultValue 要判断的value
* @return value 返回值
*/
public static String blankToDefault(String str, String defaultValue) {
return StrUtil.blankToDefault(str, defaultValue);
}
/**
* 获取参数不为空
*
* @param str defaultValue 要判断的value
* @return value 返回值
*/
public static String blankToDefault(String str, String defaultValue) {
return StrUtil.blankToDefault(str, defaultValue);
}
/**
* * 判断一个字符串是否为空
*
* @param str String
* @return true为空 false非空
*/
public static boolean isEmpty(String str) {
return StrUtil.isEmpty(str);
}
/**
* * 判断一个Collection是否为空 包含ListSetQueue
*
* @param coll 要判断的Collection
* @return true为空 false
*/
public static boolean isEmpty(Collection<?> coll) {
return CollUtil.isEmpty(coll);
}
/**
* * 判断一个字符串是否为非空串
*
* @param str String
* @return true非空串 false
*/
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
/**
* * 判断一个Collection是否非空包含ListSetQueue
*
* @param coll 要判断的Collection
* @return true非空 false
*/
public static boolean isNotEmpty(Collection<?> coll) {
return !isEmpty(coll);
}
/**
* 去空格
*/
public static String trim(String str) {
return StrUtil.trim(str);
}
/**
* * 判断一个对象数组是否为空
*
* @param objects 要判断的对象数组
* * @return true为空 false非空
*/
public static boolean isEmpty(Object[] objects) {
return ArrayUtil.isEmpty(objects);
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @return 结果
*/
public static String substring(final String str, int start) {
return substring(str, start, str.length());
}
/**
* * 判断一个对象数组是否非空
*
* @param objects 要判断的对象数组
* @return true非空 false
*/
public static boolean isNotEmpty(Object[] objects) {
return !isEmpty(objects);
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @param end 结束
* @return 结果
*/
public static String substring(final String str, int start, int end) {
return StrUtil.sub(str, start, end);
}
/**
* * 判断一个对象是否为空
*
* @param object 要判断的对象数组
* * @return true为空 false非空
*/
public static boolean isEmpty(Object object) {
return ObjectUtil.isEmpty(object);
}
/**
* 格式化文本, {} 表示占位符<br>
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* 例:<br>
* 通常使用format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{} format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param template 文本模板,被替换的部分用 {} 表示
* @param params 参数值
* @return 格式化后的文本
*/
public static String format(String template, Object... params) {
return StrUtil.format(template, params);
}
/**
* * 判断一个对象是否非空
*
* @param object 要判断的对象数组
* @return true非空 false
*/
public static boolean isNotEmpty(Object object) {
return !isEmpty(object);
}
/**
* 是否为http(s)://开头
*
* @param link 链接
* @return 结果
*/
public static boolean ishttp(String link) {
return Validator.isUrl(link);
}
/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true为空 false非空
*/
public static boolean isEmpty(Map<?, ?> map) {
return MapUtil.isEmpty(map);
}
/**
* 字符串转set
*
* @param str 字符串
* @param sep 分隔符
* @return set集合
*/
public static Set<String> str2Set(String str, String sep) {
return new HashSet<>(str2List(str, sep, true, false));
}
/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true非空 false
*/
public static boolean isNotEmpty(Map<?, ?> map) {
return !isEmpty(map);
}
/**
* 字符串转list
*
* @param str 字符串
* @param sep 分隔符
* @param filterBlank 过滤纯空白
* @param trim 去掉首尾空白
* @return list集合
*/
public static List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
List<String> list = new ArrayList<>();
if (isEmpty(str)) {
return list;
}
/**
* * 判断一个字符串是否为空串
*
* @param str String
* @return true为空 false非空
*/
public static boolean isEmpty(String str) {
return StrUtil.isEmpty(str);
}
// 过滤空白字符串
if (filterBlank && isBlank(str)) {
return list;
}
String[] split = str.split(sep);
for (String string : split) {
if (filterBlank && isBlank(string)) {
continue;
}
if (trim) {
string = trim(string);
}
list.add(string);
}
/**
* * 判断一个字符串是否为非空串
*
* @param str String
* @return true非空串 false空串
*/
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
return list;
}
/**
* * 判断一个对象是否为空
*
* @param object Object
* @return true为空 false非空
*/
public static boolean isNull(Object object) {
return ObjectUtil.isNull(object);
}
/**
* 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写
*
* @param cs 指定字符串
* @param searchCharSequences 需要检查的字符串数组
* @return 是否包含任意一个字符串
*/
public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {
return StrUtil.containsAnyIgnoreCase(cs, searchCharSequences);
}
/**
* * 判断一个对象是否非空
*
* @param object Object
* @return true非空 false
*/
public static boolean isNotNull(Object object) {
return !isNull(object);
}
/**
* 驼峰转下划线命名
*/
public static String toUnderScoreCase(String str) {
return StrUtil.toUnderlineCase(str);
}
/**
* * 判断一个对象是否是数组类型Java基本型别的数组
*
* @param object 对象
* @return true是数组 false不是数
*/
public static boolean isArray(Object object) {
return ArrayUtil.isArray(object);
}
/**
* 是否包含字符串
*
* @param str 验证字符串
* @param strs 字符串
* @return 包含返回true
*/
public static boolean inStringIgnoreCase(String str, String... strs) {
return StrUtil.equalsAnyIgnoreCase(str, strs);
}
/**
* 去空格
*/
public static String trim(String str) {
return StrUtil.trim(str);
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如HELLO_WORLD->HelloWorld
*
* @param name 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String convertToCamelCase(String name) {
return StrUtil.upperFirst(StrUtil.toCamelCase(name));
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @return 结果
*/
public static String substring(final String str, int start) {
return substring(str, start, str.length());
}
/**
* 驼峰式命名法 例如user_name->userName
*/
public static String toCamelCase(String s) {
return StrUtil.toCamelCase(s);
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @param end 结束
* @return 结果
*/
public static String substring(final String str, int start, int end) {
return StrUtil.sub(str, start, end);
}
/**
* 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
*
* @param str 指定字符串
* @param strs 需要检查的字符串数组
* @return 是否匹配
*/
public static boolean matches(String str, List<String> strs) {
if (isEmpty(str) || CollUtil.isEmpty(strs)) {
return false;
}
for (String pattern : strs) {
if (isMatch(pattern, str)) {
return true;
}
}
return false;
}
/**
* 格式化文本, {} 表示占位符<br>
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* 例:<br>
* 通常使用format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{} format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param template 文本模板,被替换的部分用 {} 表示
* @param params 参数值
* @return 格式化后的文本
*/
public static String format(String template, Object... params) {
return StrUtil.format(template, params);
}
/**
* 判断url是否与规则配置:
* ? 表示单个字符;
* * 表示一层路径内的任意字符串,不可跨层级;
* ** 表示任意层路径;
*
* @param pattern 匹配规则
* @param url 需要匹配的url
* @return
*/
public static boolean isMatch(String pattern, String url) {
AntPathMatcher matcher = new AntPathMatcher();
return matcher.match(pattern, url);
}
/**
* 是否为http(s)://开头
*
* @param link 链接
* @return 结果
*/
public static boolean ishttp(String link) {
return Validator.isUrl(link);
}
/**
* 字符串转set
*
* @param str 字符串
* @param sep 分隔符
* @return set集合
*/
public static Set<String> str2Set(String str, String sep) {
return new HashSet<>(str2List(str, sep, true, false));
}
/**
* 字符串转list
*
* @param str 字符串
* @param sep 分隔符
* @param filterBlank 过滤纯空白
* @param trim 去掉首尾空白
* @return list集合
*/
public static List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
List<String> list = new ArrayList<>();
if (isEmpty(str)) {
return list;
}
// 过滤空白字符串
if (filterBlank && isBlank(str)) {
return list;
}
String[] split = str.split(sep);
for (String string : split) {
if (filterBlank && isBlank(string)) {
continue;
}
if (trim) {
string = trim(string);
}
list.add(string);
}
return list;
}
/**
* 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写
*
* @param cs 指定字符串
* @param searchCharSequences 需要检查的字符串数组
* @return 是否包含任意一个字符串
*/
public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {
return StrUtil.containsAnyIgnoreCase(cs, searchCharSequences);
}
/**
* 驼峰转下划线命名
*/
public static String toUnderScoreCase(String str) {
return StrUtil.toUnderlineCase(str);
}
/**
* 是否包含字符串
*
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
public static boolean inStringIgnoreCase(String str, String... strs) {
return StrUtil.equalsAnyIgnoreCase(str, strs);
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如HELLO_WORLD->HelloWorld
*
* @param name 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String convertToCamelCase(String name) {
return StrUtil.upperFirst(StrUtil.toCamelCase(name));
}
/**
* 驼峰式命名法 例如user_name->userName
*/
public static String toCamelCase(String s) {
return StrUtil.toCamelCase(s);
}
/**
* 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
*
* @param str 指定字符串
* @param strs 需要检查的字符串数组
* @return 是否匹配
*/
public static boolean matches(String str, List<String> strs) {
if (isEmpty(str) || isEmpty(strs)) {
return false;
}
for (String pattern : strs) {
if (isMatch(pattern, str)) {
return true;
}
}
return false;
}
/**
* 判断url是否与规则配置:
* ? 表示单个字符;
* * 表示一层路径内的任意字符串,不可跨层级;
* ** 表示任意层路径;
*
* @param pattern 匹配规则
* @param url 需要匹配的url
* @return
*/
public static boolean isMatch(String pattern, String url) {
return ReUtil.isMatch(pattern, url);
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj) {
return (T) obj;
}
}

View File

@ -1,9 +1,11 @@
package com.ruoyi.common.utils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.lang.tree.parser.NodeParser;
import com.ruoyi.common.utils.reflect.ReflectUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@ -22,8 +24,12 @@ public class TreeBuildUtils extends TreeUtil {
*/
public static final TreeNodeConfig DEFAULT_CONFIG = TreeNodeConfig.DEFAULT_CONFIG.setNameKey("label");
public static <T> List<Tree<Long>> build(List<T> list, Long parentId, NodeParser<T, Long> nodeParser) {
return TreeUtil.build(list, parentId, DEFAULT_CONFIG, nodeParser);
public static <T, K> List<Tree<K>> build(List<T> list, NodeParser<T, K> nodeParser) {
if (CollUtil.isEmpty(list)) {
return null;
}
K k = ReflectUtils.invokeGetter(list.get(0), "parentId");
return TreeUtil.build(list, k, DEFAULT_CONFIG, nodeParser);
}
}

View File

@ -17,9 +17,9 @@ import java.util.Set;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ValidatorUtils {
private static final Validator VALID = SpringUtils.getBean(Validator.class);
private static final Validator VALID = SpringUtils.getBean(Validator.class);
public static <T> void validate(T object, Class<?>... groups) {
public static <T> void validate(T object, Class<?>... groups) {
Set<ConstraintViolation<T>> validate = VALID.validate(object, groups);
if (!validate.isEmpty()) {
throw new ConstraintViolationException("参数校验异常", validate);

View File

@ -29,11 +29,11 @@ public class FileUtils extends FileUtil {
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(percentEncodedFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(percentEncodedFileName);
.append(percentEncodedFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(percentEncodedFileName);
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");

View File

@ -1,5 +1,6 @@
package com.ruoyi.common.utils.ip;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.net.NetUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpUtil;
@ -11,8 +12,6 @@ import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
/**
* 获取地址类
*
@ -41,21 +40,21 @@ public class AddressUtils {
if (RuoYiConfig.isAddressEnabled()) {
try {
String rspStr = HttpUtil.createGet(IP_URL)
.body("ip=" + ip + "&json=true", Constants.GBK)
.execute()
.body();
.body("ip=" + ip + "&json=true", Constants.GBK)
.execute()
.body();
if (StringUtils.isEmpty(rspStr)) {
log.error("获取地理位置异常 {}", ip);
return UNKNOWN;
}
Map<String, String> obj = JsonUtils.parseMap(rspStr);
String region = obj.get("pro");
String city = obj.get("city");
Dict obj = JsonUtils.parseMap(rspStr);
String region = obj.getStr("pro");
String city = obj.getStr("city");
return String.format("%s %s", region, city);
} catch (Exception e) {
log.error("获取地理位置异常 {}", ip);
}
}
return address;
return UNKNOWN;
}
}

View File

@ -0,0 +1,222 @@
package com.ruoyi.common.utils.redis;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.redisson.api.*;
import java.util.Comparator;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* 分布式队列工具
* 轻量级队列 重量级数据量 请使用 MQ
* 要求 redis 5.X 以上
*
* @author Lion Li
* @version 3.6.0 新增
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class QueueUtils {
private static final RedissonClient CLIENT = SpringUtils.getBean(RedissonClient.class);
/**
* 获取客户端实例
*/
public static RedissonClient getClient() {
return CLIENT;
}
/**
* 添加延迟队列数据 默认毫秒
*
* @param queueName 队列名
* @param data 数据
* @param time 延迟时间
*/
public static <T> void addDelayedQueueObject(String queueName, T data, long time) {
addDelayedQueueObject(queueName, data, time, TimeUnit.MILLISECONDS);
}
/**
* 添加延迟队列数据
*
* @param queueName 队列名
* @param data 数据
* @param time 延迟时间
* @param timeUnit 单位
*/
public static <T> void addDelayedQueueObject(String queueName, T data, long time, TimeUnit timeUnit) {
RBlockingQueue<T> queue = CLIENT.getBlockingQueue(queueName);
RDelayedQueue<T> delayedQueue = CLIENT.getDelayedQueue(queue);
delayedQueue.offer(data, time, timeUnit);
}
/**
* 获取一个延迟队列数据 没有数据返回 null
*
* @param queueName 队列名
*/
public static <T> T getDelayedQueueObject(String queueName) {
RBlockingQueue<T> queue = CLIENT.getBlockingQueue(queueName);
RDelayedQueue<T> delayedQueue = CLIENT.getDelayedQueue(queue);
return delayedQueue.poll();
}
/**
* 删除延迟队列数据
*/
public static <T> boolean removeDelayedQueueObject(String queueName, T data) {
RBlockingQueue<T> queue = CLIENT.getBlockingQueue(queueName);
RDelayedQueue<T> delayedQueue = CLIENT.getDelayedQueue(queue);
return delayedQueue.remove(data);
}
/**
* 销毁延迟队列 所有阻塞监听 报错
*/
public static <T> void destroyDelayedQueue(String queueName) {
RBlockingQueue<T> queue = CLIENT.getBlockingQueue(queueName);
RDelayedQueue<T> delayedQueue = CLIENT.getDelayedQueue(queue);
delayedQueue.destroy();
}
/**
* 尝试设置 优先队列比较器 用于排序优先级
*
* @param queueName 队列名
* @param comparator 比较器
*/
public static <T> boolean trySetPriorityQueueComparator(String queueName, Comparator<T> comparator) {
RPriorityBlockingQueue<T> priorityBlockingQueue = CLIENT.getPriorityBlockingQueue(queueName);
return priorityBlockingQueue.trySetComparator(comparator);
}
/**
* 尝试设置 优先队列比较器 用于排序优先级
*
* @param queueName 队列名
* @param comparator 比较器
* @param destroy 已存在是否销毁
*/
public static <T> boolean trySetPriorityQueueComparator(String queueName, Comparator<T> comparator, boolean destroy) {
RPriorityBlockingQueue<T> priorityBlockingQueue = CLIENT.getPriorityBlockingQueue(queueName);
if (priorityBlockingQueue.isExists() && destroy) {
destroyPriorityQueueObject(queueName);
}
return priorityBlockingQueue.trySetComparator(comparator);
}
/**
* 添加优先队列数据
*
* @param queueName 队列名
* @param data 数据
*/
public static <T> boolean addPriorityQueueObject(String queueName, T data) {
RPriorityBlockingQueue<T> priorityBlockingQueue = CLIENT.getPriorityBlockingQueue(queueName);
return priorityBlockingQueue.offer(data);
}
/**
* 获取一个优先队列数据 没有数据返回 null
*
* @param queueName 队列名
*/
public static <T> T getPriorityQueueObject(String queueName) {
RPriorityBlockingQueue<T> priorityBlockingQueue = CLIENT.getPriorityBlockingQueue(queueName);
return priorityBlockingQueue.poll();
}
/**
* 删除优先队列数据
*/
public static <T> boolean removePriorityQueueObject(String queueName, T data) {
RPriorityBlockingQueue<T> priorityBlockingQueue = CLIENT.getPriorityBlockingQueue(queueName);
return priorityBlockingQueue.remove(data);
}
/**
* 销毁优先队列
*/
public static boolean destroyPriorityQueueObject(String queueName) {
RPriorityBlockingQueue<?> priorityBlockingQueue = CLIENT.getPriorityBlockingQueue(queueName);
return priorityBlockingQueue.delete();
}
/**
* 尝试设置 有界队列 容量 用于限制数量
*
* @param queueName 队列名
* @param capacity 容量
*/
public static <T> boolean trySetBoundedQueueCapacity(String queueName, int capacity) {
RBoundedBlockingQueue<T> boundedBlockingQueue = CLIENT.getBoundedBlockingQueue(queueName);
return boundedBlockingQueue.trySetCapacity(capacity);
}
/**
* 尝试设置 有界队列 容量 用于限制数量
*
* @param queueName 队列名
* @param capacity 容量
* @param destroy 已存在是否销毁
*/
public static <T> boolean trySetBoundedQueueCapacity(String queueName, int capacity, boolean destroy) {
RBoundedBlockingQueue<T> boundedBlockingQueue = CLIENT.getBoundedBlockingQueue(queueName);
if (boundedBlockingQueue.isExists() && destroy) {
destroyBoundedQueueObject(queueName);
}
return boundedBlockingQueue.trySetCapacity(capacity);
}
/**
* 添加有界队列数据
*
* @param queueName 队列名
* @param data 数据
* @return 添加成功 true 已达到界限 false
*/
public static <T> boolean addBoundedQueueObject(String queueName, T data) {
RBoundedBlockingQueue<T> boundedBlockingQueue = CLIENT.getBoundedBlockingQueue(queueName);
return boundedBlockingQueue.offer(data);
}
/**
* 获取一个有界队列数据 没有数据返回 null
*
* @param queueName 队列名
*/
public static <T> T getBoundedQueueObject(String queueName) {
RBoundedBlockingQueue<T> boundedBlockingQueue = CLIENT.getBoundedBlockingQueue(queueName);
return boundedBlockingQueue.poll();
}
/**
* 删除有界队列数据
*/
public static <T> boolean removeBoundedQueueObject(String queueName, T data) {
RBoundedBlockingQueue<T> boundedBlockingQueue = CLIENT.getBoundedBlockingQueue(queueName);
return boundedBlockingQueue.remove(data);
}
/**
* 销毁有界队列
*/
public static boolean destroyBoundedQueueObject(String queueName) {
RBoundedBlockingQueue<?> boundedBlockingQueue = CLIENT.getBoundedBlockingQueue(queueName);
return boundedBlockingQueue.delete();
}
/**
* 订阅阻塞队列(可订阅所有实现类 例如: 延迟 优先 有界 等)
*/
public static <T> void subscribeBlockingQueue(String queueName, Consumer<T> consumer) {
RBlockingQueue<T> queue = CLIENT.getBlockingQueue(queueName);
queue.subscribeOnElements(consumer);
}
}

View File

@ -1,4 +1,4 @@
package com.ruoyi.common.utils;
package com.ruoyi.common.utils.redis;
import cn.hutool.core.collection.IterUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
@ -130,7 +130,7 @@ public class RedisUtils {
/**
* 注册对象监听器
*
* <p>
* key 监听器需开启 `notify-keyspace-events` redis 相关配置
*
* @param key 缓存的键值
@ -223,7 +223,7 @@ public class RedisUtils {
/**
* 注册List监听器
*
* <p>
* key 监听器需开启 `notify-keyspace-events` redis 相关配置
*
* @param key 缓存的键值
@ -259,7 +259,7 @@ public class RedisUtils {
/**
* 注册Set监听器
*
* <p>
* key 监听器需开启 `notify-keyspace-events` redis 相关配置
*
* @param key 缓存的键值
@ -296,7 +296,7 @@ public class RedisUtils {
/**
* 注册Map监听器
*
* <p>
* key 监听器需开启 `notify-keyspace-events` redis 相关配置
*
* @param key 缓存的键值
@ -376,4 +376,14 @@ public class RedisUtils {
Iterable<String> iterable = CLIENT.getKeys().getKeysByPattern(pattern);
return IterUtil.toList(iterable);
}
/**
* 检查redis中是否存在key
*
* @param key
*/
public static Boolean hasKey(String key) {
RKeys rKeys = CLIENT.getKeys();
return rKeys.countExists(key) > 0;
}
}

View File

@ -16,7 +16,7 @@ public class SqlUtil {
/**
* 定义常用的 sql关键字
*/
public static String SQL_REGEX = "select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare ";
public static final String SQL_REGEX = "select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare ";
/**
* 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)

View File

@ -1,11 +1,10 @@
package com.ruoyi.demo.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.redis.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
@ -23,7 +22,7 @@ import java.util.concurrent.TimeUnit;
// 类级别 缓存统一配置
//@CacheConfig(cacheNames = "redissonCacheMap")
@Api(value = "spring-cache 演示案例", tags = {"spring-cache 演示案例"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo/cache")
public class RedisCacheController {
@ -45,8 +44,8 @@ public class RedisCacheController {
@ApiOperation("测试 @Cacheable")
@Cacheable(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
@GetMapping("/test1")
public AjaxResult<String> test1(String key, String value) {
return AjaxResult.success("操作成功", value);
public R<String> test1(String key, String value) {
return R.ok("操作成功", value);
}
/**
@ -60,8 +59,8 @@ public class RedisCacheController {
@ApiOperation("测试 @CachePut")
@CachePut(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
@GetMapping("/test2")
public AjaxResult<String> test2(String key, String value) {
return AjaxResult.success("操作成功", value);
public R<String> test2(String key, String value) {
return R.ok("操作成功", value);
}
/**
@ -75,8 +74,8 @@ public class RedisCacheController {
@ApiOperation("测试 @CacheEvict")
@CacheEvict(cacheNames = "redissonCacheMap", key = "#key", condition = "#key != null")
@GetMapping("/test3")
public AjaxResult<String> test3(String key, String value) {
return AjaxResult.success("操作成功", value);
public R<String> test3(String key, String value) {
return R.ok("操作成功", value);
}
/**
@ -86,7 +85,7 @@ public class RedisCacheController {
*/
@ApiOperation("测试设置过期时间")
@GetMapping("/test6")
public AjaxResult<Boolean> test6(String key, String value) {
public R<Boolean> test6(String key, String value) {
RedisUtils.setCacheObject(key, value);
boolean flag = RedisUtils.expire(key, 10, TimeUnit.SECONDS);
System.out.println("***********" + flag);
@ -96,7 +95,7 @@ public class RedisCacheController {
e.printStackTrace();
}
Object obj = RedisUtils.getCacheObject(key);
return AjaxResult.success("操作成功", value.equals(obj));
return R.ok(value.equals(obj));
}
}

View File

@ -4,7 +4,7 @@ import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
@ -36,7 +36,7 @@ public class RedisLockController {
@ApiOperation("测试lock4j 注解")
@Lock4j(keys = {"#key"})
@GetMapping("/testLock4j")
public AjaxResult<String> testLock4j(String key, String value) {
public R<String> testLock4j(String key, String value) {
System.out.println("start:" + key + ",time:" + LocalTime.now().toString());
try {
Thread.sleep(10000);
@ -44,15 +44,15 @@ public class RedisLockController {
e.printStackTrace();
}
System.out.println("end :" + key + ",time:" + LocalTime.now().toString());
return AjaxResult.success("操作成功", value);
return R.ok("操作成功", value);
}
/**
* 测试lock4j 工具
*/
@ApiOperation("测试lock4j 工具")
@GetMapping("/testLock4jLockTemaplate")
public AjaxResult<String> testLock4jLockTemaplate(String key, String value) {
@GetMapping("/testLock4jLockTemplate")
public R<String> testLock4jLockTemplate(String key, String value) {
final LockInfo lockInfo = lockTemplate.lock(key, 30000L, 5000L, RedissonLockExecutor.class);
if (null == lockInfo) {
throw new RuntimeException("业务处理中,请稍后再试");
@ -70,7 +70,7 @@ public class RedisLockController {
lockTemplate.releaseLock(lockInfo);
}
//结束
return AjaxResult.success("操作成功", value);
return R.ok("操作成功", value);
}
}

View File

@ -1,12 +1,11 @@
package com.ruoyi.demo.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.redis.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@ -17,27 +16,27 @@ import org.springframework.web.bind.annotation.RestController;
* @author Lion Li
*/
@Api(value = "Redis发布订阅 演示案例", tags = {"Redis发布订阅"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo/redis/pubsub")
public class RedisPubSubController {
@ApiOperation("发布消息")
@GetMapping("/pub")
public AjaxResult<Void> pub(@ApiParam("通道Key") String key, @ApiParam("发送内容") String value) {
public R<Void> pub(@ApiParam("通道Key") String key, @ApiParam("发送内容") String value) {
RedisUtils.publish(key, value, consumer -> {
System.out.println("发布通道 => " + key + ", 发送值 => " + value);
});
return AjaxResult.success("操作成功");
return R.ok("操作成功");
}
@ApiOperation("订阅消息")
@GetMapping("/sub")
public AjaxResult<Void> sub(@ApiParam("通道Key") String key) {
public R<Void> sub(@ApiParam("通道Key") String key) {
RedisUtils.subscribe(key, String.class, msg -> {
System.out.println("订阅通道 => " + key + ", 接收值 => " + msg);
});
return AjaxResult.success("操作成功");
return R.ok("操作成功");
}
}

View File

@ -1,7 +1,7 @@
package com.ruoyi.demo.controller;
import com.ruoyi.common.annotation.RateLimiter;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.LimitType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@ -29,8 +29,8 @@ public class RedisRateLimiterController {
@ApiOperation("测试全局限流")
@RateLimiter(count = 2, time = 10)
@GetMapping("/test")
public AjaxResult<String> test(String value) {
return AjaxResult.success("操作成功", value);
public R<String> test(String value) {
return R.ok("操作成功", value);
}
/**
@ -40,8 +40,8 @@ public class RedisRateLimiterController {
@ApiOperation("测试请求IP限流")
@RateLimiter(count = 2, time = 10, limitType = LimitType.IP)
@GetMapping("/testip")
public AjaxResult<String> testip(String value) {
return AjaxResult.success("操作成功", value);
public R<String> testip(String value) {
return R.ok("操作成功", value);
}
/**
@ -51,8 +51,8 @@ public class RedisRateLimiterController {
@ApiOperation("测试集群实例限流")
@RateLimiter(count = 2, time = 10, limitType = LimitType.CLUSTER)
@GetMapping("/testcluster")
public AjaxResult<String> testcluster(String value) {
return AjaxResult.success("操作成功", value);
public R<String> testcluster(String value) {
return R.ok("操作成功", value);
}
}

View File

@ -1,6 +1,6 @@
package com.ruoyi.demo.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
@ -11,6 +11,8 @@ import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
/**
* swagger3 用法示例
*
@ -24,15 +26,14 @@ public class Swagger3DemoController {
/**
* 上传请求
* 必须使用 @RequestPart 注解标注为文件
* dataType 必须为 "java.io.File"
*/
@ApiOperation(value = "通用上传请求")
@ApiImplicitParams({
@ApiImplicitParam(name = "file", value = "文件", dataType = "java.io.File", required = true),
@ApiImplicitParam(name = "file", value = "文件", paramType = "query", dataTypeClass = File.class, required = true)
})
@PostMapping(value = "/upload")
public AjaxResult<String> upload(@RequestPart("file") MultipartFile file) {
return AjaxResult.success("操作成功", file.getOriginalFilename());
public R<String> upload(@RequestPart("file") MultipartFile file) {
return R.ok("操作成功", file.getOriginalFilename());
}
}

View File

@ -2,13 +2,12 @@ package com.ruoyi.demo.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.demo.domain.TestDemo;
import com.ruoyi.demo.service.ITestDemoService;
import com.ruoyi.demo.mapper.TestDemoMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
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.RequestMapping;
@ -24,51 +23,62 @@ import java.util.List;
* @date 2021-05-30
*/
@Api(value = "测试批量方法", tags = {"测试批量方法"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo/batch")
public class TestBatchController extends BaseController {
private final ITestDemoService iTestDemoService;
/**
* 为了便于测试 直接引入mapper
*/
private final TestDemoMapper testDemoMapper;
/**
* 新增批量方法 可完美替代 saveBatch 秒级插入上万数据 (对mysql负荷较大)
*
* <p>
* 3.5.0 版本 增加 rewriteBatchedStatements=true 批处理参数 使 MP 原生批处理可以达到同样的速度
*/
@ApiOperation(value = "新增批量方法")
@PostMapping("/add")
// @DS("slave")
public AjaxResult<Void> add() {
// @DS("slave")
public R<Void> add() {
List<TestDemo> list = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
list.add(new TestDemo().setOrderNum(-1L).setTestKey("批量新增").setValue("测试新增"));
TestDemo testDemo = new TestDemo();
testDemo.setOrderNum(-1L);
testDemo.setTestKey("批量新增");
testDemo.setValue("测试新增");
list.add(testDemo);
}
return toAjax(iTestDemoService.saveAll(list) ? 1 : 0);
return toAjax(testDemoMapper.insertBatch(list) ? 1 : 0);
}
/**
* 新增或更新 可完美替代 saveOrUpdateBatch 高性能
*
* <p>
* 3.5.0 版本 增加 rewriteBatchedStatements=true 批处理参数 使 MP 原生批处理可以达到同样的速度
*/
@ApiOperation(value = "新增或更新批量方法")
@PostMapping("/addOrUpdate")
// @DS("slave")
public AjaxResult<Void> addOrUpdate() {
// @DS("slave")
public R<Void> addOrUpdate() {
List<TestDemo> list = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
list.add(new TestDemo().setOrderNum(-1L).setTestKey("批量新增").setValue("测试新增"));
}
iTestDemoService.saveAll(list);
TestDemo testDemo = new TestDemo();
testDemo.setOrderNum(-1L);
testDemo.setTestKey("批量新增");
testDemo.setValue("测试新增");
list.add(testDemo); }
testDemoMapper.insertBatch(list);
for (int i = 0; i < list.size(); i++) {
TestDemo testDemo = list.get(i);
testDemo.setTestKey("批量新增或修改").setValue("批量新增或修改");
testDemo.setTestKey("批量新增或修改");
testDemo.setValue("批量新增或修改");
if (i % 2 == 0) {
testDemo.setId(null);
}
}
return toAjax(iTestDemoService.saveOrUpdateAll(list) ? 1 : 0);
return toAjax(testDemoMapper.insertOrUpdateBatch(list) ? 1 : 0);
}
/**
@ -76,10 +86,10 @@ public class TestBatchController extends BaseController {
*/
@ApiOperation(value = "删除批量方法")
@DeleteMapping()
// @DS("slave")
public AjaxResult<Void> remove() {
return toAjax(iTestDemoService.remove(new LambdaQueryWrapper<TestDemo>()
.eq(TestDemo::getOrderNum, -1L)) ? 1 : 0);
// @DS("slave")
public R<Void> remove() {
return toAjax(testDemoMapper.delete(new LambdaQueryWrapper<TestDemo>()
.eq(TestDemo::getOrderNum, -1L)));
}
}

View File

@ -1,18 +1,19 @@
package com.ruoyi.demo.controller;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ValidatorUtils;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.utils.ValidatorUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.demo.domain.TestDemo;
import com.ruoyi.demo.domain.bo.TestDemoBo;
@ -21,8 +22,6 @@ import com.ruoyi.demo.domain.vo.TestDemoVo;
import com.ruoyi.demo.service.ITestDemoService;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@ -42,7 +41,7 @@ import java.util.concurrent.TimeUnit;
*/
@Validated
@Api(value = "测试单表控制器", tags = {"测试单表管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo/demo")
public class TestDemoController extends BaseController {
@ -53,7 +52,7 @@ public class TestDemoController extends BaseController {
* 查询测试单表列表
*/
@ApiOperation("查询测试单表列表")
@PreAuthorize("@ss.hasPermi('demo:demo:list')")
@SaCheckPermission("demo:demo:list")
@GetMapping("/list")
public TableDataInfo<TestDemoVo> list(@Validated(QueryGroup.class) TestDemoBo bo, PageQuery pageQuery) {
return iTestDemoService.queryPageList(bo, pageQuery);
@ -63,7 +62,7 @@ public class TestDemoController extends BaseController {
* 自定义分页查询
*/
@ApiOperation("自定义分页查询")
@PreAuthorize("@ss.hasPermi('demo:demo:list')")
@SaCheckPermission("demo:demo:list")
@GetMapping("/page")
public TableDataInfo<TestDemoVo> page(@Validated(QueryGroup.class) TestDemoBo bo, PageQuery pageQuery) {
return iTestDemoService.customPageList(bo, pageQuery);
@ -74,29 +73,29 @@ public class TestDemoController extends BaseController {
@ApiImplicitParam(name = "file", value = "导入文件", dataType = "java.io.File", required = true),
})
@Log(title = "测试单表", businessType = BusinessType.IMPORT)
@PreAuthorize("@ss.hasPermi('demo:demo:import')")
@SaCheckPermission("demo:demo:import")
@PostMapping("/importData")
public AjaxResult<Void> importData(@RequestPart("file") MultipartFile file) throws Exception {
public R<Void> importData(@RequestPart("file") MultipartFile file) throws Exception {
ExcelResult<TestDemoImportVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), TestDemoImportVo.class, true);
List<TestDemoImportVo> volist = excelResult.getList();
List<TestDemo> list = BeanUtil.copyToList(volist, TestDemo.class);
iTestDemoService.saveAll(list);
return AjaxResult.success(excelResult.getAnalysis());
iTestDemoService.saveBatch(list);
return R.ok(excelResult.getAnalysis());
}
/**
* 导出测试单表列表
*/
@ApiOperation("导出测试单表列表")
@PreAuthorize("@ss.hasPermi('demo:demo:export')")
@SaCheckPermission("demo:demo:export")
@Log(title = "测试单表", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(@Validated TestDemoBo bo, HttpServletResponse response) {
List<TestDemoVo> list = iTestDemoService.queryList(bo);
// 测试雪花id导出
// for (TestDemoVo vo : list) {
// vo.setId(1234567891234567893L);
// }
// vo.setId(1234567891234567893L);
// }
ExcelUtil.exportExcel(list, "测试单表", TestDemoVo.class, response);
}
@ -104,23 +103,23 @@ public class TestDemoController extends BaseController {
* 获取测试单表详细信息
*/
@ApiOperation("获取测试单表详细信息")
@PreAuthorize("@ss.hasPermi('demo:demo:query')")
@SaCheckPermission("demo:demo:query")
@GetMapping("/{id}")
public AjaxResult<TestDemoVo> getInfo(@ApiParam("测试ID")
public R<TestDemoVo> getInfo(@ApiParam("测试ID")
@NotNull(message = "主键不能为空")
@PathVariable("id") Long id) {
return AjaxResult.success(iTestDemoService.queryById(id));
return R.ok(iTestDemoService.queryById(id));
}
/**
* 新增测试单表
*/
@ApiOperation("新增测试单表")
@PreAuthorize("@ss.hasPermi('demo:demo:add')")
@SaCheckPermission("demo:demo:add")
@Log(title = "测试单表", businessType = BusinessType.INSERT)
@RepeatSubmit(interval = 2, timeUnit = TimeUnit.SECONDS, message = "不允许重复提交")
@PostMapping()
public AjaxResult<Void> add(@RequestBody TestDemoBo bo) {
public R<Void> add(@RequestBody TestDemoBo bo) {
// 使用校验工具对标 @Validated(AddGroup.class) 注解
// 用于在非 Controller 的地方校验对象
ValidatorUtils.validate(bo, AddGroup.class);
@ -131,11 +130,11 @@ public class TestDemoController extends BaseController {
* 修改测试单表
*/
@ApiOperation("修改测试单表")
@PreAuthorize("@ss.hasPermi('demo:demo:edit')")
@SaCheckPermission("demo:demo:edit")
@Log(title = "测试单表", businessType = BusinessType.UPDATE)
@RepeatSubmit
@PutMapping()
public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody TestDemoBo bo) {
public R<Void> edit(@Validated(EditGroup.class) @RequestBody TestDemoBo bo) {
return toAjax(iTestDemoService.updateByBo(bo) ? 1 : 0);
}
@ -143,10 +142,10 @@ public class TestDemoController extends BaseController {
* 删除测试单表
*/
@ApiOperation("删除测试单表")
@PreAuthorize("@ss.hasPermi('demo:demo:remove')")
@SaCheckPermission("demo:demo:remove")
@Log(title = "测试单表", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult<Void> remove(@ApiParam("测试ID串")
public R<Void> remove(@ApiParam("测试ID串")
@NotEmpty(message = "主键不能为空")
@PathVariable Long[] ids) {
return toAjax(iTestDemoService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);

View File

@ -1,6 +1,6 @@
package com.ruoyi.demo.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.MessageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@ -27,40 +27,40 @@ import javax.validation.constraints.NotNull;
@RequestMapping("/demo/i18n")
public class TestI18nController {
/**
* 通过code获取国际化内容
* code为 messages.properties 中的 key
*
* 测试使用 user.register.success
*/
@ApiOperation("通过code获取国际化内容")
@GetMapping()
public AjaxResult<Void> get(@ApiParam("国际化code") String code) {
return AjaxResult.success(MessageUtils.message(code));
}
/**
* 通过code获取国际化内容
* code为 messages.properties 中的 key
* <p>
* 测试使用 user.register.success
*/
@ApiOperation("通过code获取国际化内容")
@GetMapping()
public R<Void> get(@ApiParam("国际化code") String code) {
return R.ok(MessageUtils.message(code));
}
/**
* Validator 校验国际化
* 不传值 分别查看异常返回
*
* <p>
* 测试使用 not.null
*/
@ApiOperation("Validator 校验国际化")
@GetMapping("/test1")
public AjaxResult<Void> test1(@NotBlank(message = "{not.null}") String str) {
return AjaxResult.success(str);
public R<Void> test1(@NotBlank(message = "{not.null}") String str) {
return R.ok(str);
}
/**
* Bean 校验国际化
* 不传值 分别查看异常返回
*
* <p>
* 测试使用 not.null
*/
@ApiOperation("Bean 校验国际化")
@GetMapping("/test2")
public AjaxResult<TestI18nBo> test2(@Validated TestI18nBo bo) {
return AjaxResult.success(bo);
public R<TestI18nBo> test2(@Validated TestI18nBo bo) {
return R.ok(bo);
}
@Data

View File

@ -0,0 +1,79 @@
package com.ruoyi.demo.controller;
import com.ruoyi.common.annotation.Sensitive;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.SensitiveStrategy;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 测试数据脱敏控制器
* <p>
* 默认管理员不过滤
* 需自行根据业务重写实现
*
* @author Lion Li
* @version 3.6.0
* @see com.ruoyi.common.core.service.SensitiveService
*/
@Api(value = "测试数据脱敏控制器", tags = {"测试数据脱敏管理"})
@RestController
@RequestMapping("/demo/sensitive")
public class TestSensitiveController extends BaseController {
/**
* 测试数据脱敏
*/
@ApiOperation("查询测试单表列表")
@GetMapping("/test")
public R<TestSensitive> test() {
TestSensitive testSensitive = new TestSensitive();
testSensitive.setIdCard("210397198608215431");
testSensitive.setPhone("17640125371");
testSensitive.setAddress("北京市朝阳区某某四合院1203室");
testSensitive.setEmail("17640125371@163.com");
testSensitive.setBankCard("6226456952351452853");
return R.ok(testSensitive);
}
@Data
static class TestSensitive {
/**
* 身份证
*/
@Sensitive(strategy = SensitiveStrategy.ID_CARD)
private String idCard;
/**
* 电话
*/
@Sensitive(strategy = SensitiveStrategy.PHONE)
private String phone;
/**
* 地址
*/
@Sensitive(strategy = SensitiveStrategy.ADDRESS)
private String address;
/**
* 邮箱
*/
@Sensitive(strategy = SensitiveStrategy.EMAIL)
private String email;
/**
* 银行卡
*/
@Sensitive(strategy = SensitiveStrategy.BANK_CARD)
private String bankCard;
}
}

View File

@ -1,9 +1,10 @@
package com.ruoyi.demo.controller;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
@ -16,8 +17,6 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@ -35,7 +34,7 @@ import java.util.List;
*/
@Validated
@Api(value = "测试树表控制器", tags = {"测试树表管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo/tree")
public class TestTreeController extends BaseController {
@ -46,18 +45,18 @@ public class TestTreeController extends BaseController {
* 查询测试树表列表
*/
@ApiOperation("查询测试树表列表")
@PreAuthorize("@ss.hasPermi('demo:tree:list')")
@SaCheckPermission("demo:tree:list")
@GetMapping("/list")
public AjaxResult<List<TestTreeVo>> list(@Validated(QueryGroup.class) TestTreeBo bo) {
public R<List<TestTreeVo>> list(@Validated(QueryGroup.class) TestTreeBo bo) {
List<TestTreeVo> list = iTestTreeService.queryList(bo);
return AjaxResult.success(list);
return R.ok(list);
}
/**
* 导出测试树表列表
*/
@ApiOperation("导出测试树表列表")
@PreAuthorize("@ss.hasPermi('demo:tree:export')")
@SaCheckPermission("demo:tree:export")
@Log(title = "测试树表", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public void export(@Validated TestTreeBo bo, HttpServletResponse response) {
@ -69,23 +68,23 @@ public class TestTreeController extends BaseController {
* 获取测试树表详细信息
*/
@ApiOperation("获取测试树表详细信息")
@PreAuthorize("@ss.hasPermi('demo:tree:query')")
@SaCheckPermission("demo:tree:query")
@GetMapping("/{id}")
public AjaxResult<TestTreeVo> getInfo(@ApiParam("测试树ID")
public R<TestTreeVo> getInfo(@ApiParam("测试树ID")
@NotNull(message = "主键不能为空")
@PathVariable("id") Long id) {
return AjaxResult.success(iTestTreeService.queryById(id));
return R.ok(iTestTreeService.queryById(id));
}
/**
* 新增测试树表
*/
@ApiOperation("新增测试树表")
@PreAuthorize("@ss.hasPermi('demo:tree:add')")
@SaCheckPermission("demo:tree:add")
@Log(title = "测试树表", businessType = BusinessType.INSERT)
@RepeatSubmit
@PostMapping()
public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody TestTreeBo bo) {
public R<Void> add(@Validated(AddGroup.class) @RequestBody TestTreeBo bo) {
return toAjax(iTestTreeService.insertByBo(bo) ? 1 : 0);
}
@ -93,11 +92,11 @@ public class TestTreeController extends BaseController {
* 修改测试树表
*/
@ApiOperation("修改测试树表")
@PreAuthorize("@ss.hasPermi('demo:tree:edit')")
@SaCheckPermission("demo:tree:edit")
@Log(title = "测试树表", businessType = BusinessType.UPDATE)
@RepeatSubmit
@PutMapping()
public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody TestTreeBo bo) {
public R<Void> edit(@Validated(EditGroup.class) @RequestBody TestTreeBo bo) {
return toAjax(iTestTreeService.updateByBo(bo) ? 1 : 0);
}
@ -105,10 +104,10 @@ public class TestTreeController extends BaseController {
* 删除测试树表
*/
@ApiOperation("删除测试树表")
@PreAuthorize("@ss.hasPermi('demo:tree:remove')")
@SaCheckPermission("demo:tree:remove")
@Log(title = "测试树表", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult<Void> remove(@ApiParam("测试树ID串")
public R<Void> remove(@ApiParam("测试树ID串")
@NotEmpty(message = "主键不能为空")
@PathVariable Long[] ids) {
return toAjax(iTestTreeService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);

View File

@ -0,0 +1,82 @@
package com.ruoyi.demo.controller.queue;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.redis.QueueUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 有界队列 演示案例
* <p>
* 轻量级队列 重量级数据量 请使用 MQ
* <p>
* 集群测试通过 同一个数据只会被消费一次 做好事务补偿
* 集群测试流程 在其中一台发送数据 两端分别调用获取接口 一次获取一条
*
* @author Lion Li
* @version 3.6.0
*/
@Slf4j
@Api(value = "有界队列 演示案例", tags = {"有界队列"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo/queue/bounded")
public class BoundedQueueController {
@ApiOperation("添加队列数据")
@GetMapping("/add")
public R<Void> add(@ApiParam("队列名") String queueName,
@ApiParam("容量") int capacity) {
// 用完了一定要销毁 否则会一直存在
boolean b = QueueUtils.destroyBoundedQueueObject(queueName);
log.info("通道: {} , 删除: {}", queueName, b);
// 初始化设置一次即可
if (QueueUtils.trySetBoundedQueueCapacity(queueName, capacity)) {
log.info("通道: {} , 设置容量: {}", queueName, capacity);
} else {
log.info("通道: {} , 设置容量失败", queueName);
return R.fail("操作失败");
}
for (int i = 0; i < 11; i++) {
String data = "data-" + i;
boolean flag = QueueUtils.addBoundedQueueObject(queueName, data);
if (flag == false) {
log.info("通道: {} , 发送数据: {} 失败, 通道已满", queueName, data);
} else {
log.info("通道: {} , 发送数据: {}", queueName, data);
}
}
return R.ok("操作成功");
}
@ApiOperation("删除队列数据")
@GetMapping("/remove")
public R<Void> remove(@ApiParam("队列名") String queueName) {
String data = "data-" + 5;
if (QueueUtils.removeBoundedQueueObject(queueName, data)) {
log.info("通道: {} , 删除数据: {}", queueName, data);
} else {
return R.fail("操作失败");
}
return R.ok("操作成功");
}
@ApiOperation("获取队列数据")
@GetMapping("/get")
public R<Void> get(@ApiParam("队列名") String queueName) {
String data;
do {
data = QueueUtils.getBoundedQueueObject(queueName);
log.info("通道: {} , 获取数据: {}", queueName, data);
} while (data != null);
return R.ok("操作成功");
}
}

View File

@ -0,0 +1,78 @@
package com.ruoyi.demo.controller.queue;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.redis.QueueUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
/**
* 延迟队列 演示案例
* <p>
* 轻量级队列 重量级数据量 请使用 MQ
* 例如: 创建订单30分钟后过期处理
* <p>
* 集群测试通过 同一个数据只会被消费一次 做好事务补偿
* 集群测试流程 两台集群分别开启订阅 在其中一台发送数据 观察接收消息的规律
*
* @author Lion Li
* @version 3.6.0
*/
@Slf4j
@Api(value = "延迟队列 演示案例", tags = {"延迟队列"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo/queue/delayed")
public class DelayedQueueController {
@ApiOperation("订阅队列")
@GetMapping("/subscribe")
public R<Void> subscribe(@ApiParam("队列名") String queueName) {
log.info("通道: {} 监听中......", queueName);
// 项目初始化设置一次即可
QueueUtils.subscribeBlockingQueue(queueName, (String orderNum) -> {
// 观察接收时间
log.info("通道: {}, 收到数据: {}", queueName, orderNum);
});
return R.ok("操作成功");
}
@ApiOperation("添加队列数据")
@GetMapping("/add")
public R<Void> add(@ApiParam("队列名") String queueName,
@ApiParam("订单号") String orderNum,
@ApiParam("延迟时间(秒)") Long time) {
QueueUtils.addDelayedQueueObject(queueName, orderNum, time, TimeUnit.SECONDS);
// 观察发送时间
log.info("通道: {} , 发送数据: {}", queueName, orderNum);
return R.ok("操作成功");
}
@ApiOperation("删除队列数据")
@GetMapping("/remove")
public R<Void> remove(@ApiParam("队列名") String queueName,
@ApiParam("订单号") String orderNum) {
if (QueueUtils.removeDelayedQueueObject(queueName, orderNum)) {
log.info("通道: {} , 删除数据: {}", queueName, orderNum);
} else {
return R.fail("操作失败");
}
return R.ok("操作成功");
}
@ApiOperation("销毁队列")
@GetMapping("/destroy")
public R<Void> destroy(@ApiParam("队列名") String queueName) {
// 用完了一定要销毁 否则会一直存在
QueueUtils.destroyDelayedQueue(queueName);
return R.ok("操作成功");
}
}

View File

@ -0,0 +1,17 @@
package com.ruoyi.demo.controller.queue;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 实体类 注意不允许使用内部类 否则会找不到类
*
* @author Lion Li
* @version 3.6.0
*/
@Data
@NoArgsConstructor
public class PriorityDemo {
private String name;
private Integer orderNum;
}

View File

@ -0,0 +1,16 @@
package com.ruoyi.demo.controller.queue;
import java.util.Comparator;
/**
* 比较器 注意不允许使用 内部类或匿名类或lambda表达式 会找不到类
*
* @author Lion Li
* @version 3.6.0
*/
public class PriorityDemoComparator implements Comparator<PriorityDemo> {
@Override
public int compare(PriorityDemo pd1, PriorityDemo pd2) {
return Integer.compare(pd1.getOrderNum(), pd2.getOrderNum());
}
}

View File

@ -0,0 +1,88 @@
package com.ruoyi.demo.controller.queue;
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.redis.QueueUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 优先队列 演示案例
* <p>
* 轻量级队列 重量级数据量 请使用 MQ
* <p>
* 集群测试通过 同一个消息只会被消费一次 做好事务补偿
* 集群测试流程 在其中一台发送数据 两端分别调用获取接口 一次获取一条
*
* @author Lion Li
* @version 3.6.0
*/
@Slf4j
@Api(value = "优先队列 演示案例", tags = {"优先队列"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo/queue/priority")
public class PriorityQueueController {
@ApiOperation("添加队列数据")
@GetMapping("/add")
public R<Void> add(@ApiParam("队列名") String queueName) {
// 用完了一定要销毁 否则会一直存在
boolean b = QueueUtils.destroyPriorityQueueObject(queueName);
log.info("通道: {} , 删除: {}", queueName, b);
// 初始化设置一次即可 此处注意 不允许用内部类或匿名类
boolean flag = QueueUtils.trySetPriorityQueueComparator(queueName, new PriorityDemoComparator());
if (flag) {
log.info("通道: {} , 设置比较器成功", queueName);
} else {
log.info("通道: {} , 设置比较器失败", queueName);
return R.fail("操作失败");
}
for (int i = 0; i < 10; i++) {
int randomNum = RandomUtil.randomInt(10);
PriorityDemo data = new PriorityDemo();
data.setName("data-" + i);
data.setOrderNum(randomNum);
if (QueueUtils.addPriorityQueueObject(queueName, data)) {
log.info("通道: {} , 发送数据: {}", queueName, data);
} else {
log.info("通道: {} , 发送数据: {}, 发送失败", queueName, data);
}
}
return R.ok("操作成功");
}
@ApiOperation("删除队列数据")
@GetMapping("/remove")
public R<Void> remove(@ApiParam("队列名") String queueName,
@ApiParam("对象名") String name,
@ApiParam("排序号") Integer orderNum) {
PriorityDemo data = new PriorityDemo();
data.setName(name);
data.setOrderNum(orderNum);
if (QueueUtils.removePriorityQueueObject(queueName, data)) {
log.info("通道: {} , 删除数据: {}", queueName, data);
} else {
return R.fail("操作失败");
}
return R.ok("操作成功");
}
@ApiOperation("获取队列数据")
@GetMapping("/get")
public R<Void> get(@ApiParam("队列名") String queueName) {
PriorityDemo data;
do {
data = QueueUtils.getPriorityQueueObject(queueName);
log.info("通道: {} , 获取数据: {}", queueName, data);
} while (data != null);
return R.ok("操作成功");
}
}

View File

@ -4,7 +4,6 @@ import com.baomidou.mybatisplus.annotation.*;
import com.ruoyi.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* 测试单表对象 test_demo
@ -14,16 +13,15 @@ import lombok.experimental.Accessors;
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("test_demo")
public class TestDemo extends BaseEntity {
private static final long serialVersionUID=1L;
private static final long serialVersionUID = 1L;
/**
* 主键
*/
/**
* 主键
*/
@TableId(value = "id")
private Long id;
@ -40,7 +38,7 @@ public class TestDemo extends BaseEntity {
/**
* 排序号
*/
@OrderBy(asc = false, sort = 1)
@OrderBy(asc = false, sort = 1)
private Long orderNum;
/**

View File

@ -7,7 +7,6 @@ import com.baomidou.mybatisplus.annotation.Version;
import com.ruoyi.common.core.domain.TreeEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* 测试树表对象 test_tree
@ -17,11 +16,10 @@ import lombok.experimental.Accessors;
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("test_tree")
public class TestTree extends TreeEntity {
private static final long serialVersionUID=1L;
private static final long serialVersionUID = 1L;
/**

View File

@ -26,43 +26,43 @@ public class TestDemoBo extends BaseEntity {
/**
* 主键
*/
@ApiModelProperty("主键")
@NotNull(message = "主键不能为空", groups = { EditGroup.class })
@ApiModelProperty("主键")
@NotNull(message = "主键不能为空", groups = {EditGroup.class})
private Long id;
/**
* 部门id
*/
@ApiModelProperty("部门id")
@NotNull(message = "部门id不能为空", groups = { AddGroup.class, EditGroup.class })
@ApiModelProperty("部门id")
@NotNull(message = "部门id不能为空", groups = {AddGroup.class, EditGroup.class})
private Long deptId;
/**
* 用户id
*/
@ApiModelProperty("用户id")
@NotNull(message = "用户id不能为空", groups = { AddGroup.class, EditGroup.class })
@ApiModelProperty("用户id")
@NotNull(message = "用户id不能为空", groups = {AddGroup.class, EditGroup.class})
private Long userId;
/**
* 排序号
*/
@ApiModelProperty("排序号")
@NotNull(message = "排序号不能为空", groups = { AddGroup.class, EditGroup.class })
@ApiModelProperty("排序号")
@NotNull(message = "排序号不能为空", groups = {AddGroup.class, EditGroup.class})
private Long orderNum;
/**
* key键
*/
@ApiModelProperty("key键")
@NotBlank(message = "key键不能为空", groups = { AddGroup.class, EditGroup.class })
@ApiModelProperty("key键")
@NotBlank(message = "key键不能为空", groups = {AddGroup.class, EditGroup.class})
private String testKey;
/**
* 值
*/
@ApiModelProperty("")
@NotBlank(message = "值不能为空", groups = { AddGroup.class, EditGroup.class })
@ApiModelProperty("")
@NotBlank(message = "值不能为空", groups = {AddGroup.class, EditGroup.class})
private String value;
}

View File

@ -26,29 +26,29 @@ public class TestTreeBo extends TreeEntity {
/**
* 主键
*/
@ApiModelProperty("主键")
@NotNull(message = "主键不能为空", groups = { EditGroup.class })
@ApiModelProperty("主键")
@NotNull(message = "主键不能为空", groups = {EditGroup.class})
private Long id;
/**
* 部门id
*/
@ApiModelProperty("部门id")
@NotNull(message = "部门id不能为空", groups = { AddGroup.class, EditGroup.class })
@ApiModelProperty("部门id")
@NotNull(message = "部门id不能为空", groups = {AddGroup.class, EditGroup.class})
private Long deptId;
/**
* 用户id
*/
@ApiModelProperty("用户id")
@NotNull(message = "用户id不能为空", groups = { AddGroup.class, EditGroup.class })
@ApiModelProperty("用户id")
@NotNull(message = "用户id不能为空", groups = {AddGroup.class, EditGroup.class})
private Long userId;
/**
* 树节点名
*/
@ApiModelProperty("树节点名")
@NotBlank(message = "树节点名不能为空", groups = { AddGroup.class, EditGroup.class })
@ApiModelProperty("树节点名")
@NotBlank(message = "树节点名不能为空", groups = {AddGroup.class, EditGroup.class})
private String treeName;
}

View File

@ -9,7 +9,6 @@ import lombok.Data;
import java.util.Date;
/**
* 测试单表视图对象 test_demo
*
@ -21,77 +20,77 @@ import java.util.Date;
@ExcelIgnoreUnannotated
public class TestDemoVo {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/**
* 主键
/**
* 主键
*/
@ExcelProperty(value = "主键")
@ApiModelProperty("主键")
private Long id;
@ExcelProperty(value = "主键")
@ApiModelProperty("主键")
private Long id;
/**
* 部门id
*/
@ExcelProperty(value = "部门id")
@ApiModelProperty("部门id")
private Long deptId;
@ExcelProperty(value = "部门id")
@ApiModelProperty("部门id")
private Long deptId;
/**
* 用户id
*/
@ExcelProperty(value = "用户id")
@ApiModelProperty("用户id")
private Long userId;
@ExcelProperty(value = "用户id")
@ApiModelProperty("用户id")
private Long userId;
/**
* 排序号
*/
@ExcelProperty(value = "排序号")
@ApiModelProperty("排序号")
private Long orderNum;
@ExcelProperty(value = "排序号")
@ApiModelProperty("排序号")
private Long orderNum;
/**
* key键
*/
@ExcelProperty(value = "key键")
@ApiModelProperty("key键")
private String testKey;
@ExcelProperty(value = "key键")
@ApiModelProperty("key键")
private String testKey;
/**
* 值
*/
@ExcelProperty(value = "")
@ApiModelProperty("")
private String value;
@ExcelProperty(value = "")
@ApiModelProperty("")
private String value;
/**
* 创建时间
*/
@ExcelProperty(value = "创建时间")
@ApiModelProperty("创建时间")
private Date createTime;
@ExcelProperty(value = "创建时间")
@ApiModelProperty("创建时间")
private Date createTime;
/**
* 创建人
*/
@ExcelProperty(value = "创建人")
@ApiModelProperty("创建人")
private String createBy;
@ExcelProperty(value = "创建人")
@ApiModelProperty("创建人")
private String createBy;
/**
* 更新时间
*/
@ExcelProperty(value = "更新时间")
@ApiModelProperty("更新时间")
private Date updateTime;
@ExcelProperty(value = "更新时间")
@ApiModelProperty("更新时间")
private Date updateTime;
/**
* 更新人
*/
@ExcelProperty(value = "更新人")
@ApiModelProperty("更新人")
private String updateBy;
@ExcelProperty(value = "更新人")
@ApiModelProperty("更新人")
private String updateBy;
}

View File

@ -9,7 +9,6 @@ import lombok.Data;
import java.util.Date;
/**
* 测试树表视图对象 test_tree
*
@ -21,48 +20,48 @@ import java.util.Date;
@ExcelIgnoreUnannotated
public class TestTreeVo {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/**
* 主键
/**
* 主键
*/
@ApiModelProperty("主键")
private Long id;
@ApiModelProperty("主键")
private Long id;
/**
* 父id
*/
@ExcelProperty(value = "父id")
@ApiModelProperty("父id")
private Long parentId;
@ExcelProperty(value = "父id")
@ApiModelProperty("父id")
private Long parentId;
/**
* 部门id
*/
@ExcelProperty(value = "部门id")
@ApiModelProperty("部门id")
private Long deptId;
@ExcelProperty(value = "部门id")
@ApiModelProperty("部门id")
private Long deptId;
/**
* 用户id
*/
@ExcelProperty(value = "用户id")
@ApiModelProperty("用户id")
private Long userId;
@ExcelProperty(value = "用户id")
@ApiModelProperty("用户id")
private Long userId;
/**
* 树节点名
*/
@ExcelProperty(value = "树节点名")
@ApiModelProperty("树节点名")
private String treeName;
@ExcelProperty(value = "树节点名")
@ApiModelProperty("树节点名")
private String treeName;
/**
* 创建时间
*/
@ExcelProperty(value = "创建时间")
@ApiModelProperty("创建时间")
private Date createTime;
@ExcelProperty(value = "创建时间")
@ApiModelProperty("创建时间")
private Date createTime;
}

View File

@ -6,12 +6,11 @@ import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.DataColumn;
import com.ruoyi.common.annotation.DataPermission;
import com.ruoyi.common.core.mybatisplus.core.BaseMapperPlus;
import com.ruoyi.common.core.mapper.BaseMapperPlus;
import com.ruoyi.demo.domain.TestDemo;
import com.ruoyi.demo.domain.vo.TestDemoVo;
import org.apache.ibatis.annotations.Param;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
@ -21,7 +20,7 @@ import java.util.List;
* @author Lion Li
* @date 2021-07-26
*/
public interface TestDemoMapper extends BaseMapperPlus<TestDemo> {
public interface TestDemoMapper extends BaseMapperPlus<TestDemoMapper, TestDemo, TestDemoVo> {
@DataPermission({
@DataColumn(key = "deptName", value = "dept_id"),
@ -55,5 +54,5 @@ public interface TestDemoMapper extends BaseMapperPlus<TestDemo> {
@DataColumn(key = "deptName", value = "dept_id"),
@DataColumn(key = "userName", value = "user_id")
})
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<?> idList);
}

View File

@ -2,8 +2,9 @@ package com.ruoyi.demo.mapper;
import com.ruoyi.common.annotation.DataColumn;
import com.ruoyi.common.annotation.DataPermission;
import com.ruoyi.common.core.mybatisplus.core.BaseMapperPlus;
import com.ruoyi.common.core.mapper.BaseMapperPlus;
import com.ruoyi.demo.domain.TestTree;
import com.ruoyi.demo.domain.vo.TestTreeVo;
/**
* 测试树表Mapper接口
@ -15,6 +16,6 @@ import com.ruoyi.demo.domain.TestTree;
@DataColumn(key = "deptName", value = "dept_id"),
@DataColumn(key = "userName", value = "user_id")
})
public interface TestTreeMapper extends BaseMapperPlus<TestTree> {
public interface TestTreeMapper extends BaseMapperPlus<TestTreeMapper, TestTree, TestTreeVo> {
}

View File

@ -1,11 +1,10 @@
package com.ruoyi.demo.service;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.demo.domain.TestDemo;
import com.ruoyi.demo.domain.vo.TestDemoVo;
import com.ruoyi.demo.domain.bo.TestDemoBo;
import com.ruoyi.common.core.mybatisplus.core.IServicePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.demo.domain.TestDemo;
import com.ruoyi.demo.domain.bo.TestDemoBo;
import com.ruoyi.demo.domain.vo.TestDemoVo;
import java.util.Collection;
import java.util.List;
@ -16,48 +15,57 @@ import java.util.List;
* @author Lion Li
* @date 2021-07-26
*/
public interface ITestDemoService extends IServicePlus<TestDemo, TestDemoVo> {
/**
* 查询单个
* @return
*/
TestDemoVo queryById(Long id);
/**
* 查询列表
*/
TableDataInfo<TestDemoVo> queryPageList(TestDemoBo bo, PageQuery pageQuery);
/**
* 自定义分页查询
*/
TableDataInfo<TestDemoVo> customPageList(TestDemoBo bo, PageQuery pageQuery);
public interface ITestDemoService {
/**
* 查询列表
*/
List<TestDemoVo> queryList(TestDemoBo bo);
* 查询单个
*
* @return
*/
TestDemoVo queryById(Long id);
/**
* 根据新增业务对象插入测试单
* @param bo 测试单表新增业务对象
* @return
*/
Boolean insertByBo(TestDemoBo bo);
/**
* 查询列
*/
TableDataInfo<TestDemoVo> queryPageList(TestDemoBo bo, PageQuery pageQuery);
/**
* 根据编辑业务对象修改测试单表
* @param bo 测试单表编辑业务对象
* @return
*/
Boolean updateByBo(TestDemoBo bo);
/**
* 自定义分页查询
*/
TableDataInfo<TestDemoVo> customPageList(TestDemoBo bo, PageQuery pageQuery);
/**
* 校验并删除数据
* @param ids 主键集合
* @param isValid 是否校验,true-删除前校验,false-不校验
* @return
*/
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
/**
* 查询列表
*/
List<TestDemoVo> queryList(TestDemoBo bo);
/**
* 根据新增业务对象插入测试单表
*
* @param bo 测试单表新增业务对象
* @return
*/
Boolean insertByBo(TestDemoBo bo);
/**
* 根据编辑业务对象修改测试单表
*
* @param bo 测试单表编辑业务对象
* @return
*/
Boolean updateByBo(TestDemoBo bo);
/**
* 校验并删除数据
*
* @param ids 主键集合
* @param isValid 是否校验,true-删除前校验,false-不校验
* @return
*/
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
/**
* 批量保存
*/
Boolean saveBatch(List<TestDemo> list);
}

View File

@ -1,9 +1,7 @@
package com.ruoyi.demo.service;
import com.ruoyi.demo.domain.TestTree;
import com.ruoyi.demo.domain.vo.TestTreeVo;
import com.ruoyi.demo.domain.bo.TestTreeBo;
import com.ruoyi.common.core.mybatisplus.core.IServicePlus;
import com.ruoyi.demo.domain.vo.TestTreeVo;
import java.util.Collection;
import java.util.List;
@ -14,37 +12,41 @@ import java.util.List;
* @author Lion Li
* @date 2021-07-26
*/
public interface ITestTreeService extends IServicePlus<TestTree, TestTreeVo> {
/**
* 查询单个
* @return
*/
TestTreeVo queryById(Long id);
public interface ITestTreeService {
/**
* 查询单个
*
* @return
*/
TestTreeVo queryById(Long id);
/**
* 查询列表
*/
List<TestTreeVo> queryList(TestTreeBo bo);
/**
* 查询列表
*/
List<TestTreeVo> queryList(TestTreeBo bo);
/**
* 根据新增业务对象插入测试树表
* @param bo 测试树表新增业务对象
* @return
*/
Boolean insertByBo(TestTreeBo bo);
/**
* 根据新增业务对象插入测试树表
*
* @param bo 测试树表新增业务对象
* @return
*/
Boolean insertByBo(TestTreeBo bo);
/**
* 根据编辑业务对象修改测试树表
* @param bo 测试树表编辑业务对象
* @return
*/
Boolean updateByBo(TestTreeBo bo);
/**
* 根据编辑业务对象修改测试树表
*
* @param bo 测试树表编辑业务对象
* @return
*/
Boolean updateByBo(TestTreeBo bo);
/**
* 校验并删除数据
* @param ids 主键集合
* @param isValid 是否校验,true-删除前校验,false-不校验
* @return
*/
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
/**
* 校验并删除数据
*
* @param ids 主键集合
* @param isValid 是否校验,true-删除前校验,false-不校验
* @return
*/
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
}

View File

@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.demo.domain.TestDemo;
@ -13,6 +12,7 @@ import com.ruoyi.demo.domain.bo.TestDemoBo;
import com.ruoyi.demo.domain.vo.TestDemoVo;
import com.ruoyi.demo.mapper.TestDemoMapper;
import com.ruoyi.demo.service.ITestDemoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
@ -25,78 +25,86 @@ import java.util.Map;
* @author Lion Li
* @date 2021-07-26
*/
@RequiredArgsConstructor
@Service
public class TestDemoServiceImpl extends ServicePlusImpl<TestDemoMapper, TestDemo, TestDemoVo> implements ITestDemoService {
public class TestDemoServiceImpl implements ITestDemoService {
@Override
public TestDemoVo queryById(Long id) {
return getVoById(id);
}
private final TestDemoMapper baseMapper;
@Override
public TableDataInfo<TestDemoVo> queryPageList(TestDemoBo bo, PageQuery pageQuery) {
@Override
public TestDemoVo queryById(Long id) {
return baseMapper.selectVoById(id);
}
@Override
public TableDataInfo<TestDemoVo> queryPageList(TestDemoBo bo, PageQuery pageQuery) {
LambdaQueryWrapper<TestDemo> lqw = buildQueryWrapper(bo);
Page<TestDemoVo> result = pageVo(pageQuery.build(), lqw);
return TableDataInfo.build(result);
}
Page<TestDemoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
return TableDataInfo.build(result);
}
/**
* 自定义分页查询
*/
@Override
public TableDataInfo<TestDemoVo> customPageList(TestDemoBo bo, PageQuery pageQuery) {
/**
* 自定义分页查询
*/
@Override
public TableDataInfo<TestDemoVo> customPageList(TestDemoBo bo, PageQuery pageQuery) {
LambdaQueryWrapper<TestDemo> lqw = buildQueryWrapper(bo);
Page<TestDemoVo> result = baseMapper.customPageList(pageQuery.build(), lqw);
return TableDataInfo.build(result);
}
Page<TestDemoVo> result = baseMapper.customPageList(pageQuery.build(), lqw);
return TableDataInfo.build(result);
}
@Override
public List<TestDemoVo> queryList(TestDemoBo bo) {
return listVo(buildQueryWrapper(bo));
}
@Override
public List<TestDemoVo> queryList(TestDemoBo bo) {
return baseMapper.selectVoList(buildQueryWrapper(bo));
}
private LambdaQueryWrapper<TestDemo> buildQueryWrapper(TestDemoBo bo) {
Map<String, Object> params = bo.getParams();
LambdaQueryWrapper<TestDemo> lqw = Wrappers.lambdaQuery();
lqw.like(StringUtils.isNotBlank(bo.getTestKey()), TestDemo::getTestKey, bo.getTestKey());
lqw.eq(StringUtils.isNotBlank(bo.getValue()), TestDemo::getValue, bo.getValue());
lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
TestDemo::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
return lqw;
}
private LambdaQueryWrapper<TestDemo> buildQueryWrapper(TestDemoBo bo) {
Map<String, Object> params = bo.getParams();
LambdaQueryWrapper<TestDemo> lqw = Wrappers.lambdaQuery();
lqw.like(StringUtils.isNotBlank(bo.getTestKey()), TestDemo::getTestKey, bo.getTestKey());
lqw.eq(StringUtils.isNotBlank(bo.getValue()), TestDemo::getValue, bo.getValue());
lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
TestDemo::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
return lqw;
}
@Override
public Boolean insertByBo(TestDemoBo bo) {
TestDemo add = BeanUtil.toBean(bo, TestDemo.class);
validEntityBeforeSave(add);
boolean flag = save(add);
if (flag) {
bo.setId(add.getId());
}
return flag;
}
@Override
public Boolean insertByBo(TestDemoBo bo) {
TestDemo add = BeanUtil.toBean(bo, TestDemo.class);
validEntityBeforeSave(add);
boolean flag = baseMapper.insert(add) > 0;
if (flag) {
bo.setId(add.getId());
}
return flag;
}
@Override
public Boolean updateByBo(TestDemoBo bo) {
TestDemo update = BeanUtil.toBean(bo, TestDemo.class);
validEntityBeforeSave(update);
return updateById(update);
}
@Override
public Boolean updateByBo(TestDemoBo bo) {
TestDemo update = BeanUtil.toBean(bo, TestDemo.class);
validEntityBeforeSave(update);
return baseMapper.updateById(update) > 0;
}
/**
* 保存前的数据校验
*
* @param entity 实体类数据
*/
private void validEntityBeforeSave(TestDemo entity) {
//TODO 做一些数据校验,如唯一约束
}
/**
* 保存前的数据校验
*
* @param entity 实体类数据
*/
private void validEntityBeforeSave(TestDemo entity) {
//TODO 做一些数据校验,如唯一约束
}
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
if (isValid) {
//TODO 做一些业务上的校验,判断是否需要校验
}
return removeByIds(ids);
}
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
if (isValid) {
//TODO 做一些业务上的校验,判断是否需要校验
}
return baseMapper.deleteBatchIds(ids) > 0;
}
@Override
public Boolean saveBatch(List<TestDemo> list) {
return baseMapper.insertBatch(list);
}
}

View File

@ -3,13 +3,13 @@ package com.ruoyi.demo.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.demo.domain.TestTree;
import com.ruoyi.demo.domain.bo.TestTreeBo;
import com.ruoyi.demo.domain.vo.TestTreeVo;
import com.ruoyi.demo.mapper.TestTreeMapper;
import com.ruoyi.demo.service.ITestTreeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
@ -23,62 +23,65 @@ import java.util.Map;
* @date 2021-07-26
*/
// @DS("slave") // 切换从库查询
@RequiredArgsConstructor
@Service
public class TestTreeServiceImpl extends ServicePlusImpl<TestTreeMapper, TestTree, TestTreeVo> implements ITestTreeService {
public class TestTreeServiceImpl implements ITestTreeService {
@Override
public TestTreeVo queryById(Long id) {
return getVoById(id);
}
private final TestTreeMapper baseMapper;
// @DS("slave") // 切换从库查询
@Override
public List<TestTreeVo> queryList(TestTreeBo bo) {
@Override
public TestTreeVo queryById(Long id) {
return baseMapper.selectVoById(id);
}
// @DS("slave") // 切换从库查询
@Override
public List<TestTreeVo> queryList(TestTreeBo bo) {
LambdaQueryWrapper<TestTree> lqw = buildQueryWrapper(bo);
return listVo(lqw);
}
return baseMapper.selectVoList(lqw);
}
private LambdaQueryWrapper<TestTree> buildQueryWrapper(TestTreeBo bo) {
Map<String, Object> params = bo.getParams();
LambdaQueryWrapper<TestTree> lqw = Wrappers.lambdaQuery();
lqw.like(StringUtils.isNotBlank(bo.getTreeName()), TestTree::getTreeName, bo.getTreeName());
lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
TestTree::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
return lqw;
}
private LambdaQueryWrapper<TestTree> buildQueryWrapper(TestTreeBo bo) {
Map<String, Object> params = bo.getParams();
LambdaQueryWrapper<TestTree> lqw = Wrappers.lambdaQuery();
lqw.like(StringUtils.isNotBlank(bo.getTreeName()), TestTree::getTreeName, bo.getTreeName());
lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
TestTree::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
return lqw;
}
@Override
public Boolean insertByBo(TestTreeBo bo) {
TestTree add = BeanUtil.toBean(bo, TestTree.class);
validEntityBeforeSave(add);
boolean flag = save(add);
if (flag) {
bo.setId(add.getId());
}
return flag;
}
@Override
public Boolean insertByBo(TestTreeBo bo) {
TestTree add = BeanUtil.toBean(bo, TestTree.class);
validEntityBeforeSave(add);
boolean flag = baseMapper.insert(add) > 0;
if (flag) {
bo.setId(add.getId());
}
return flag;
}
@Override
public Boolean updateByBo(TestTreeBo bo) {
TestTree update = BeanUtil.toBean(bo, TestTree.class);
validEntityBeforeSave(update);
return updateById(update);
}
@Override
public Boolean updateByBo(TestTreeBo bo) {
TestTree update = BeanUtil.toBean(bo, TestTree.class);
validEntityBeforeSave(update);
return baseMapper.updateById(update) > 0;
}
/**
* 保存前的数据校验
*
* @param entity 实体类数据
*/
private void validEntityBeforeSave(TestTree entity) {
//TODO 做一些数据校验,如唯一约束
}
/**
* 保存前的数据校验
*
* @param entity 实体类数据
*/
private void validEntityBeforeSave(TestTree entity) {
//TODO 做一些数据校验,如唯一约束
}
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
if (isValid) {
//TODO 做一些业务上的校验,判断是否需要校验
}
return removeByIds(ids);
}
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
if (isValid) {
//TODO 做一些业务上的校验,判断是否需要校验
}
return baseMapper.deleteBatchIds(ids) > 0;
}
}

View File

@ -1,142 +0,0 @@
package com.ruoyi.framework.aspectj;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.service.UserService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* 数据过滤处理
*
* @author Lion Li
* @deprecated 3.6.0 移除 {@link com.ruoyi.framework.handler.PlusDataPermissionHandler}
*/
@Aspect
@Component
@Deprecated
public class DataScopeAspect {
/**
* 全部数据权限
*/
public static final String DATA_SCOPE_ALL = "1";
/**
* 自定数据权限
*/
public static final String DATA_SCOPE_CUSTOM = "2";
/**
* 部门数据权限
*/
public static final String DATA_SCOPE_DEPT = "3";
/**
* 部门及以下数据权限
*/
public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";
/**
* 仅本人数据权限
*/
public static final String DATA_SCOPE_SELF = "5";
/**
* 数据权限过滤关键字
*/
public static final String DATA_SCOPE = "dataScope";
@Before("@annotation(controllerDataScope)")
public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable {
clearDataScope(point);
handleDataScope(point, controllerDataScope);
}
protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope) {
// 获取当前的用户
LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNotNull(loginUser)) {
SysUser currentUser = SpringUtils.getBean(UserService.class).selectUserById(loginUser.getUserId());
// 如果是超级管理员,则不过滤数据
if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) {
dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
controllerDataScope.userAlias(), controllerDataScope.isUser());
}
}
}
/**
* 数据范围过滤
*
* @param joinPoint 切点
* @param user 用户
* @param userAlias 别名
*/
public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias, boolean isUser) {
StringBuilder sqlString = new StringBuilder();
// 将 "." 提取出,不写别名为单表查询,写别名为多表查询
deptAlias = StringUtils.isNotBlank(deptAlias) ? deptAlias + "." : "";
userAlias = StringUtils.isNotBlank(userAlias) ? userAlias + "." : "";
for (SysRole role : user.getRoles()) {
String dataScope = role.getDataScope();
if (DATA_SCOPE_ALL.equals(dataScope)) {
sqlString = new StringBuilder();
break;
} else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
sqlString.append(StringUtils.format(
" OR {}dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ",
deptAlias, role.getRoleId()));
} else if (DATA_SCOPE_DEPT.equals(dataScope)) {
sqlString.append(StringUtils.format(" OR {}dept_id = {} ",
deptAlias, user.getDeptId()));
} else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
sqlString.append(StringUtils.format(
" OR {}dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )",
deptAlias, user.getDeptId(), user.getDeptId()));
} else if (DATA_SCOPE_SELF.equals(dataScope)) {
if (isUser) {
sqlString.append(StringUtils.format(" OR {}user_id = {} ",
userAlias, user.getUserId()));
} else {
// 数据权限为仅本人且没有userAlias别名不查询任何数据
sqlString.append(" OR 1=0 ");
}
}
}
if (StringUtils.isNotBlank(sqlString.toString())) {
putDataScope(joinPoint, sqlString.substring(4));
}
}
/**
* 拼接权限sql前先清空params.dataScope参数防止注入
*/
private void clearDataScope(final JoinPoint joinPoint) {
Object params = joinPoint.getArgs()[0];
if (StringUtils.isNotNull(params)) {
putDataScope(joinPoint, "");
}
}
private static void putDataScope(JoinPoint joinPoint, String sql) {
Object params = joinPoint.getArgs()[0];
if (StringUtils.isNotNull(params)) {
if (params instanceof BaseEntity) {
BaseEntity baseEntity = (BaseEntity) params;
baseEntity.getParams().put(DATA_SCOPE, sql);
}
}
}
}

View File

@ -1,65 +0,0 @@
package com.ruoyi.framework.aspectj;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Objects;
/**
* 多数据源处理
*
* @author Lion Li
* @deprecated 3.6.0 移除 使用原生方法处理 功能更全
*/
@Aspect
@Order(-500)
@Component
@Deprecated
public class DataSourceAspect {
@Pointcut("@annotation(com.ruoyi.common.annotation.DataSource)"
+ "|| @within(com.ruoyi.common.annotation.DataSource)")
public void dsPointCut() {
}
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
DataSource dataSource = getDataSource(point);
if (StringUtils.isNotNull(dataSource)) {
DynamicDataSourceContextHolder.poll();
String source = dataSource.value().getSource();
DynamicDataSourceContextHolder.push(source);
}
try {
return point.proceed();
} finally {
// 销毁数据源 在执行方法之后
DynamicDataSourceContextHolder.clear();
}
}
/**
* 获取需要切换的数据源
*/
public DataSource getDataSource(ProceedingJoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
if (Objects.nonNull(dataSource)) {
return dataSource;
}
return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
}
}

View File

@ -1,13 +1,13 @@
package com.ruoyi.framework.aspectj;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.dto.OperLogDTO;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.service.OperLogService;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.enums.HttpMethod;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
@ -60,9 +60,6 @@ public class LogAspect {
protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
try {
// 获取当前的用户
LoginUser loginUser = SecurityUtils.getLoginUser();
// *========数据库日志=========*//
OperLogDTO operLog = new OperLogDTO();
operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
@ -70,9 +67,7 @@ public class LogAspect {
String ip = ServletUtils.getClientIP();
operLog.setOperIp(ip);
operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
if (loginUser != null) {
operLog.setOperName(loginUser.getUsername());
}
operLog.setOperName(LoginHelper.getUsername());
if (e != null) {
operLog.setStatus(BusinessStatus.FAIL.ordinal());
@ -116,7 +111,7 @@ public class LogAspect {
setRequestValue(joinPoint, operLog);
}
// 是否需要保存response参数和值
if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) {
if (log.isSaveResponseData() && ObjectUtil.isNotNull(jsonResult)) {
operLog.setJsonResult(StringUtils.substring(JsonUtils.toJsonString(jsonResult), 0, 2000));
}
}
@ -145,7 +140,7 @@ public class LogAspect {
StringBuilder params = new StringBuilder();
if (paramsArray != null && paramsArray.length > 0) {
for (Object o : paramsArray) {
if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
try {
params.append(JsonUtils.toJsonString(o)).append(" ");
} catch (Exception e) {
@ -181,6 +176,6 @@ public class LogAspect {
}
}
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
|| o instanceof BindingResult;
|| o instanceof BindingResult;
}
}

View File

@ -3,8 +3,8 @@ package com.ruoyi.framework.aspectj;
import com.ruoyi.common.annotation.RateLimiter;
import com.ruoyi.common.enums.LimitType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
@ -52,7 +52,7 @@ public class RateLimiterAspect {
if (rateLimiter.limitType() == LimitType.IP) {
// 获取请求ip
stringBuffer.append(ServletUtils.getClientIP()).append("-");
} else if (rateLimiter.limitType() == LimitType.CLUSTER){
} else if (rateLimiter.limitType() == LimitType.CLUSTER) {
// 获取客户端实例id
stringBuffer.append(RedisUtils.getClient().getId()).append("-");
}

View File

@ -1,21 +1,21 @@
package com.ruoyi.framework.aspectj;
import cn.dev33.satoken.SaManager;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.properties.TokenProperties;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.framework.config.properties.RepeatSubmitProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
@ -32,12 +32,11 @@ import java.util.concurrent.TimeUnit;
* @author Lion Li
*/
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RequiredArgsConstructor
@Aspect
@Component
public class RepeatSubmitAspect {
private final TokenProperties tokenProperties;
private final RepeatSubmitProperties repeatSubmitProperties;
@Before("@annotation(repeatSubmit)")
@ -57,13 +56,11 @@ public class RepeatSubmitAspect {
String url = request.getRequestURI();
// 唯一值(没有消息头则使用请求地址)
String submitKey = request.getHeader(tokenProperties.getHeader());
if (StringUtils.isEmpty(submitKey)) {
submitKey = url;
}
String submitKey = StringUtils.trimToEmpty(request.getHeader(SaManager.getConfig().getTokenName()));
submitKey = SecureUtil.md5(submitKey + ":" + nowParams);
// 唯一标识指定key + 消息头)
String cacheRepeatKey = Constants.REPEAT_SUBMIT_KEY + submitKey;
// 唯一标识指定key + url + 消息头)
String cacheRepeatKey = Constants.REPEAT_SUBMIT_KEY + url + submitKey;
String key = RedisUtils.getCacheObject(cacheRepeatKey);
if (key == null) {
RedisUtils.setCacheObject(cacheRepeatKey, "", interval, TimeUnit.MILLISECONDS);
@ -79,7 +76,7 @@ public class RepeatSubmitAspect {
StringBuilder params = new StringBuilder();
if (paramsArray != null && paramsArray.length > 0) {
for (Object o : paramsArray) {
if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
try {
params.append(JsonUtils.toJsonString(o)).append(" ");
} catch (Exception e) {

View File

@ -1,55 +0,0 @@
package com.ruoyi.framework.config;
import cn.hutool.core.util.ArrayUtil;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.security.concurrent.DelegatingSecurityContextExecutorService;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
/**
* 异步配置
*
* @author Lion Li
*/
@EnableAsync
@Configuration
public class AsyncConfig extends AsyncConfigurerSupport {
@Autowired
@Qualifier("scheduledExecutorService")
private ScheduledExecutorService scheduledExecutorService;
/**
* 异步执行需要使用权限框架自带的包装线程池 保证权限信息的传递
*/
@Override
public Executor getAsyncExecutor() {
return new DelegatingSecurityContextExecutorService(scheduledExecutorService);
}
/**
* 异步执行异常处理
*/
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (throwable, method, objects) -> {
throwable.printStackTrace();
StringBuilder sb = new StringBuilder();
sb.append("Exception message - ").append(throwable.getMessage())
.append(", Method name - ").append(method.getName());
if (ArrayUtil.isNotEmpty(objects)) {
sb.append(", Parameter value - ").append(Arrays.toString(objects));
}
throw new ServiceException(sb.toString());
};
}
}

View File

@ -21,11 +21,10 @@ public class DruidConfig {
/**
* 去除监控页面底部的广告
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
@ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties)
{
public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) {
// 获取web监控页面的参数
DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
// 提取common.js的配置路径
@ -33,16 +32,14 @@ public class DruidConfig {
String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
final String filePath = "support/http/resources/js/common.js";
// 创建filter进行过滤
Filter filter = new Filter()
{
Filter filter = new Filter() {
@Override
public void init(javax.servlet.FilterConfig filterConfig) throws ServletException
{
public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
throws IOException, ServletException {
chain.doFilter(request, response);
// 重置缓冲区,响应头不会被重置
// response.resetBuffer();
@ -53,9 +50,9 @@ public class DruidConfig {
text = text.replaceAll("powered.*?shrek.wang</a>", "");
response.getWriter().write(text);
}
@Override
public void destroy()
{
public void destroy() {
}
};
FilterRegistrationBean registrationBean = new FilterRegistrationBean();

View File

@ -17,30 +17,30 @@ import java.util.Locale;
@Configuration
public class I18nConfig {
@Bean
public LocaleResolver localeResolver() {
return new I18nLocaleResolver();
}
@Bean
public LocaleResolver localeResolver() {
return new I18nLocaleResolver();
}
/**
* 获取请求头国际化信息
*/
static class I18nLocaleResolver implements LocaleResolver {
/**
* 获取请求头国际化信息
*/
static class I18nLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String language = httpServletRequest.getHeader("content-language");
Locale locale = Locale.getDefault();
if (StrUtil.isNotBlank(language)) {
String[] split = language.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String language = httpServletRequest.getHeader("content-language");
Locale locale = Locale.getDefault();
if (StrUtil.isNotBlank(language)) {
String[] split = language.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
}
}
}

View File

@ -28,23 +28,23 @@ import java.util.TimeZone;
@Configuration
public class JacksonConfig {
@Primary
@Bean
public ObjectMapper getObjectMapper(Jackson2ObjectMapperBuilder builder, JacksonProperties jacksonProperties) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 全局配置序列化返回 JSON 处理
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, BigNumberSerializer.INSTANCE);
simpleModule.addSerializer(Long.TYPE, BigNumberSerializer.INSTANCE);
simpleModule.addSerializer(BigInteger.class, BigNumberSerializer.INSTANCE);
simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat());
simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
simpleModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
objectMapper.registerModule(simpleModule);
objectMapper.setTimeZone(TimeZone.getDefault());
log.info("初始化 jackson 配置");
return objectMapper;
}
@Primary
@Bean
public ObjectMapper getObjectMapper(Jackson2ObjectMapperBuilder builder, JacksonProperties jacksonProperties) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 全局配置序列化返回 JSON 处理
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, BigNumberSerializer.INSTANCE);
simpleModule.addSerializer(Long.TYPE, BigNumberSerializer.INSTANCE);
simpleModule.addSerializer(BigInteger.class, BigNumberSerializer.INSTANCE);
simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat());
simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
simpleModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
objectMapper.registerModule(simpleModule);
objectMapper.setTimeZone(TimeZone.getDefault());
log.info("初始化 jackson 配置");
return objectMapper;
}
}

View File

@ -4,14 +4,9 @@ import cn.hutool.core.net.NetUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.ruoyi.common.core.mybatisplus.methods.InsertAll;
import com.ruoyi.framework.handler.CreateAndUpdateMetaObjectHandler;
import com.ruoyi.framework.interceptor.PlusDataPermissionInterceptor;
import org.mybatis.spring.annotation.MapperScan;
@ -19,8 +14,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.List;
/**
* mybatis-plus配置类(下方注释有插件介绍)
*
@ -31,17 +24,17 @@ import java.util.List;
@MapperScan("${mybatis-plus.mapperPackage}")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 数据权限处理
interceptor.addInnerInterceptor(dataPermissionInterceptor());
// 分页插件
interceptor.addInnerInterceptor(paginationInnerInterceptor());
// 乐观锁插件
interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
return interceptor;
}
// 分页插件
interceptor.addInnerInterceptor(paginationInnerInterceptor());
// 乐观锁插件
interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
return interceptor;
}
/**
* 数据权限拦截器
@ -50,47 +43,32 @@ public class MybatisPlusConfig {
return new PlusDataPermissionInterceptor();
}
/**
* 分页插件,自动识别数据库类型
*/
public PaginationInnerInterceptor paginationInnerInterceptor() {
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
// 设置最大单页限制数量,默认 500 条,-1 不受限制
paginationInnerInterceptor.setMaxLimit(-1L);
// 分页合理化
paginationInnerInterceptor.setOverflow(true);
return paginationInnerInterceptor;
}
/**
* 分页插件,自动识别数据库类型
*/
public PaginationInnerInterceptor paginationInnerInterceptor() {
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
// 设置最大单页限制数量,默认 500 条,-1 不受限制
paginationInnerInterceptor.setMaxLimit(-1L);
// 分页合理化
paginationInnerInterceptor.setOverflow(true);
return paginationInnerInterceptor;
}
/**
* 乐观锁插件
*/
public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {
return new OptimisticLockerInnerInterceptor();
}
/**
* 乐观锁插件
*/
public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {
return new OptimisticLockerInnerInterceptor();
}
/**
* 元对象字段填充控制器
*/
@Bean
public MetaObjectHandler metaObjectHandler() {
return new CreateAndUpdateMetaObjectHandler();
}
/**
* sql注入器配置
*/
@Bean
public ISqlInjector sqlInjector() {
return new DefaultSqlInjector() {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
methodList.add(new InsertAll());
return methodList;
}
};
}
/**
* 元对象字段填充控制器
*/
@Bean
public MetaObjectHandler metaObjectHandler() {
return new CreateAndUpdateMetaObjectHandler();
}
/**
* 使用网卡信息绑定雪花生成器
@ -101,24 +79,24 @@ public class MybatisPlusConfig {
return new DefaultIdentifierGenerator(NetUtil.getLocalhost());
}
/**
* PaginationInnerInterceptor 分页插件,自动识别数据库类型
* https://baomidou.com/pages/97710a/
* OptimisticLockerInnerInterceptor 乐观锁插件
* https://baomidou.com/pages/0d93c0/
* MetaObjectHandler 元对象字段填充控制器
* https://baomidou.com/pages/4c6bcf/
* ISqlInjector sql注入器
* https://baomidou.com/pages/42ea4a/
* BlockAttackInnerInterceptor 如果是对全表的删除或更新操作,就会终止该操作
* https://baomidou.com/pages/f9a237/
* IllegalSQLInnerInterceptor sql性能规范插件(垃圾SQL拦截)
* IdentifierGenerator 自定义主键策略
* https://baomidou.com/pages/568eb2/
* TenantLineInnerInterceptor 多租户插件
* https://baomidou.com/pages/aef2f2/
* DynamicTableNameInnerInterceptor 动态表名插件
* https://baomidou.com/pages/2a45ff/
*/
/**
* PaginationInnerInterceptor 分页插件,自动识别数据库类型
* https://baomidou.com/pages/97710a/
* OptimisticLockerInnerInterceptor 乐观锁插件
* https://baomidou.com/pages/0d93c0/
* MetaObjectHandler 元对象字段填充控制器
* https://baomidou.com/pages/4c6bcf/
* ISqlInjector sql注入器
* https://baomidou.com/pages/42ea4a/
* BlockAttackInnerInterceptor 如果是对全表的删除或更新操作,就会终止该操作
* https://baomidou.com/pages/f9a237/
* IllegalSQLInnerInterceptor sql性能规范插件(垃圾SQL拦截)
* IdentifierGenerator 自定义主键策略
* https://baomidou.com/pages/568eb2/
* TenantLineInnerInterceptor 多租户插件
* https://baomidou.com/pages/aef2f2/
* DynamicTableNameInnerInterceptor 动态表名插件
* https://baomidou.com/pages/2a45ff/
*/
}

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