diff --git a/aidex-admin/pom.xml b/aidex-admin/pom.xml index 74d69837325a81fab635f8d5d04952bf7c0f3331..62a893b1403b9fbab94ea7324b87691eefb179df 100644 --- a/aidex-admin/pom.xml +++ b/aidex-admin/pom.xml @@ -24,32 +24,20 @@ true - + io.springfox - springfox-swagger2 - - - - - io.swagger - swagger-annotations - 1.5.21 + springfox-boot-starter + io.swagger swagger-models - 1.5.21 - - - - - io.springfox - springfox-swagger-ui + 1.6.2 - + mysql mysql-connector-java @@ -80,17 +68,17 @@ - - org.apache.maven.plugins - maven-war-plugin - 3.1.0 + + org.apache.maven.plugins + maven-war-plugin + 3.1.0 false ${project.artifactId} - - + + - + maven-resources-plugin utf-8 diff --git a/aidex-admin/src/main/resources/application-druid.yml b/aidex-admin/src/main/resources/application-druid.yml index 5cc5731fefbe13b7d07f9c4b9cb087546411e5ea..51c4079a2e85afdb55867bfd36767b49fc8c5628 100644 --- a/aidex-admin/src/main/resources/application-druid.yml +++ b/aidex-admin/src/main/resources/application-druid.yml @@ -6,9 +6,9 @@ spring: druid: # 主库数据源 master: - url: jdbc:mysql://localhost:3306/aidex?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&&allowMultiQueries=true - username: root - password: root + url: jdbc:mysql://47.93.172.8:3306/aidex?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&&allowMultiQueries=true + username: gxc + password: 123456 # 从库数据源 slave: # 从数据源开关/默认关闭 @@ -43,8 +43,8 @@ spring: allow: url-pattern: /druid/* # 控制台管理用户名和密码 - login-username: - login-password: + login-username: admin + login-password: 123456 filter: stat: enabled: true diff --git a/aidex-admin/src/main/resources/application.yml b/aidex-admin/src/main/resources/application.yml index 286ecd16a6c3bb97cc27229ecbe50901e31f3e27..dfa4c09720a046c8b45455f1d2307a3b8729e703 100644 --- a/aidex-admin/src/main/resources/application.yml +++ b/aidex-admin/src/main/resources/application.yml @@ -9,7 +9,7 @@ aidex: # 实例演示开关 demoEnabled: true # 文件路径 示例( Windows配置D:/aidex/uploadPath,Linux配置 /home/aidex/uploadPath) - profile: D:/aidex/uploadPath + profile: /var/polycis/aidex/uploadPath # 获取ip地址开关 addressEnabled: false # 验证码类型 math 数组计算 char 字符验证 @@ -17,8 +17,8 @@ aidex: # 开发环境配置 server: - # 服务器的HTTP端口,默认为8080 - port: 8080 + # 服务器的HTTP端口,默认为8081 + port: 8081 servlet: # 应用的访问路径 context-path: / @@ -59,13 +59,13 @@ spring: # redis 配置 redis: # 地址 - host: localhost + host: 36.133.49.205 # 端口,默认为6379 - port: 6379 + port: 10089 # 数据库索引 - database: 0 + database: 11 # 密码 - password: + password: polycis123 # 连接超时时间 timeout: 10s lettuce: @@ -106,7 +106,6 @@ mybatis: # PageHelper分页插件 pagehelper: helperDialect: mysql - reasonable: true supportMethodsArguments: true params: count=countSql @@ -118,10 +117,10 @@ swagger: pathMapping: /dev-api # 防止XSS攻击 -xss: +xss: # 过滤开关 enabled: true # 排除链接(多个用逗号分隔) - excludes: /system/notice/* + excludes: /system/notice # 匹配链接 urlPatterns: /system/*,/monitor/*,/tool/* diff --git a/aidex-admin/src/main/resources/i18n/messages.properties b/aidex-admin/src/main/resources/i18n/messages.properties index d63aa1f8ac02e265dccdc5da19d061e2b8d27a8d..3e4694f623f5867e2cfbcac33e7e58d44111929b 100644 --- a/aidex-admin/src/main/resources/i18n/messages.properties +++ b/aidex-admin/src/main/resources/i18n/messages.properties @@ -15,10 +15,11 @@ length.not.valid=长度必须在{min}到{max}个字符之间 user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成,且必须以非数字开头 user.password.not.valid=* 5-50个字符 - + user.email.not.valid=邮箱格式错误 user.mobile.phone.number.not.valid=手机号格式错误 user.login.success=登录成功 +user.register.success=注册成功 user.notfound=请重新登录 user.forcelogout=管理员强制退出,请重新登录 user.unknown.error=未知错误,请重新登录 diff --git a/aidex-admin/src/main/resources/logback.xml b/aidex-admin/src/main/resources/logback.xml index f92eebdac9a2363456f3003d50de90bf754d209c..5b1b2abebc992167778068ad20d1a53d71ae6bc6 100644 --- a/aidex-admin/src/main/resources/logback.xml +++ b/aidex-admin/src/main/resources/logback.xml @@ -1,7 +1,7 @@ - + diff --git a/aidex-common/src/main/java/com/aidex/common/annotation/RepeatSubmit.java b/aidex-common/src/main/java/com/aidex/common/annotation/RepeatSubmit.java index 24c2c721059ebcf13b25c039813ee2549fc1351b..e83a759f2fffea42620da3c8faa091e3bd4cff04 100644 --- a/aidex-common/src/main/java/com/aidex/common/annotation/RepeatSubmit.java +++ b/aidex-common/src/main/java/com/aidex/common/annotation/RepeatSubmit.java @@ -19,5 +19,13 @@ import java.lang.annotation.Target; @Documented public @interface RepeatSubmit { + /** + * 间隔时间(ms),小于此时间视为重复提交 + */ + public int interval() default 10000; + /** + * 提示消息 + */ + public String message() default "不允许重复提交,请稍后再试"; } diff --git a/aidex-common/src/main/java/com/aidex/common/config/AiDexConfig.java b/aidex-common/src/main/java/com/aidex/common/config/AiDexConfig.java index 9ea30c10225986edf21260012413212b90f91547..b2460219b1c8e9529da2374b7f44502d75779293 100644 --- a/aidex-common/src/main/java/com/aidex/common/config/AiDexConfig.java +++ b/aidex-common/src/main/java/com/aidex/common/config/AiDexConfig.java @@ -1,5 +1,6 @@ package com.aidex.common.config; +import com.aidex.common.utils.DateUtils; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @@ -7,13 +8,19 @@ import java.io.File; /** * 读取项目相关配置 - * + * * @author aidex */ @Component @ConfigurationProperties(prefix = "aidex") public class AiDexConfig { + + /** + * 文件存储后缀 + */ + private static String filePathSubfix = File.separator + DateUtils.getDate("yyyy") + File.separator + DateUtils.getDate("MM") + File.separator + DateUtils.getDate("dd"); + /** 项目名称 */ private String name; @@ -95,33 +102,34 @@ public class AiDexConfig AiDexConfig.addressEnabled = addressEnabled; } + /** + /** + * 获取导入上传路径 + */ + public static String getImportPath() { + return getProfile() + "/import" + filePathSubfix; + } + /** * 获取头像上传路径 */ - public static String getAvatarPath() - { -// return getProfile() + "/avatar"; - return getProfile() + File.separator +"avatar"; + public static String getAvatarPath() { + return getProfile() + File.separator + "avatar" + filePathSubfix; } /** * 获取下载路径 */ - public static String getDownloadPath() - { - -// return getProfile() + "/download/"; - return getProfile() + File.separator + "download" +File.separator ; + public static String getDownloadPath() { + return getProfile() + File.separator + "download" + filePathSubfix; } /** * 获取上传路径 */ - public static String getUploadPath() - { - -// return getProfile() + "/upload"; - return getProfile() + File.separator + "upload"; + public static String getUploadPath() { + //根据年月日分组 + return getProfile() + File.separator + "upload" + filePathSubfix; } public static String getDbName() { diff --git a/aidex-common/src/main/java/com/aidex/common/constant/Constants.java b/aidex-common/src/main/java/com/aidex/common/constant/Constants.java index 52520b83d1a42c296d5e9498991579dc7054826f..e40ac7f30799aef1a2552e9b1b3dedea4227a3ed 100644 --- a/aidex-common/src/main/java/com/aidex/common/constant/Constants.java +++ b/aidex-common/src/main/java/com/aidex/common/constant/Constants.java @@ -1,12 +1,13 @@ package com.aidex.common.constant; +import io.jsonwebtoken.Claims; + /** * 通用常量信息 - * + * * @author ruoyi */ -public class Constants -{ +public class Constants { /** * UTF-8 字符集 */ @@ -66,7 +67,7 @@ public class Constants * 登录用户 redis key */ public static final String LOGIN_TOKEN_KEY = "login_tokens:"; - + /** * 防重提交 redis key */ @@ -100,7 +101,7 @@ public class Constants /** * 用户名称 */ - public static final String JWT_USERNAME = "sub"; + public static final String JWT_USERNAME = Claims.SUBJECT; /** * 用户头像 @@ -157,6 +158,17 @@ public class Constants */ public static final String SYS_ROLE_KEY = "sys_role:"; + /** + * RMI 远程方法调用 + */ + public static final String LOOKUP_RMI = "rmi://"; + + + /** + * LDAP 远程方法调用 + */ + public static final String LOOKUP_LDAP = "ldap://"; + /** * 资源映射路径 前缀 */ @@ -197,7 +209,6 @@ public class Constants /** * 日志操作类型 - * */ public enum OpType { login, insert, delete, update, select, logout diff --git a/aidex-common/src/main/java/com/aidex/common/constant/UserConstants.java b/aidex-common/src/main/java/com/aidex/common/constant/UserConstants.java index 8f3e585fca36356a0de3575cfd4be01c80a67234..2ee92be0b9a93e457aadf565e2446857626e48af 100644 --- a/aidex-common/src/main/java/com/aidex/common/constant/UserConstants.java +++ b/aidex-common/src/main/java/com/aidex/common/constant/UserConstants.java @@ -2,62 +2,94 @@ package com.aidex.common.constant; /** * 用户常量信息 - * + * * @author ruoyi */ -public class UserConstants -{ +public class UserConstants { + /** * 平台内系统用户的唯一标志 */ public static final String SYS_USER = "SYS_USER"; - /** 正常状态 */ + /** + * 正常状态 + */ public static final String NORMAL = "0"; - /** 异常状态 */ + /** + * 异常状态 + */ public static final String EXCEPTION = "1"; - /** 用户封禁状态 */ + /** + * 用户封禁状态 + */ public static final String USER_DISABLE = "1"; - /** 角色封禁状态 */ + /** + * 角色封禁状态 + */ public static final String ROLE_DISABLE = "1"; - /** 部门正常状态 */ + /** + * 部门正常状态 + */ public static final String DEPT_NORMAL = "0"; - /** 部门停用状态 */ + /** + * 部门停用状态 + */ public static final String DEPT_DISABLE = "1"; - /** 字典正常状态 */ + /** + * 字典正常状态 + */ public static final String DICT_NORMAL = "0"; - /** 是否为系统默认(是) */ + /** + * 是否为系统默认(是) + */ public static final String YES = "Y"; - /** 是否菜单外链(是) */ + /** + * 是否菜单外链(是) + */ public static final String YES_FRAME = "0"; - /** 是否菜单外链(否) */ + /** + * 是否菜单外链(否) + */ public static final String NO_FRAME = "1"; - /** 菜单类型(目录) */ + /** + * 菜单类型(目录) + */ public static final String TYPE_DIR = "M"; - /** 菜单类型(菜单) */ + /** + * 菜单类型(菜单) + */ public static final String TYPE_MENU = "C"; - /** 菜单类型(按钮) */ + /** + * 菜单类型(按钮) + */ public static final String TYPE_BUTTON = "F"; - /** Layout组件标识 */ + /** + * Layout组件标识 + */ public final static String LAYOUT = "Layout"; - /** ParentView组件标识 */ + /** + * ParentView组件标识 + */ public final static String PARENT_VIEW = "ParentView"; - /** 校验返回结果码 */ + /** + * 校验返回结果码 + */ public final static String UNIQUE = "0"; public final static String NOT_UNIQUE = "1"; diff --git a/aidex-common/src/main/java/com/aidex/common/core/controller/BaseController.java b/aidex-common/src/main/java/com/aidex/common/core/controller/BaseController.java index 6bb9087c7351bacd6a11a1baedc445970ce05439..a52144e0c6426ad38149b90ccca16e58fed250a8 100644 --- a/aidex-common/src/main/java/com/aidex/common/core/controller/BaseController.java +++ b/aidex-common/src/main/java/com/aidex/common/core/controller/BaseController.java @@ -1,5 +1,7 @@ package com.aidex.common.core.controller; +import com.aidex.common.core.domain.model.LoginUser; +import com.aidex.common.utils.SecurityUtils; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.aidex.common.constant.HttpStatus; @@ -24,12 +26,12 @@ import java.util.List; /** * web层通用数据处理 - * + * * @author ruoyi */ public class BaseController { - protected final Logger logger = LoggerFactory.getLogger(BaseController.class); + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 将前台传递过来的日期格式的字符串,自动转化为Date类型 @@ -63,6 +65,19 @@ public class BaseController } } + /** + * 设置请求排序数据 + */ + protected void startOrderBy() + { + PageDomain pageDomain = TableSupport.buildPageRequest(); + if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) + { + String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); + PageHelper.orderBy(orderBy); + } + } + /** * 响应请求分页数据 */ @@ -153,5 +168,37 @@ public class BaseController return AjaxResult.error(message); } + /** + * 获取用户缓存信息 + */ + public LoginUser getLoginUser() + { + return SecurityUtils.getLoginUser(); + } + + /** + * 获取登录用户id + */ + public String getUserId() + { + return getLoginUser().getUser().getId(); + } + + /** + * 获取登录部门id + */ + public String getDeptId() + { + return getLoginUser().getUser().getDeptId(); + } + + /** + * 获取登录用户名 + */ + public String getUsername() + { + return getLoginUser().getUsername(); + } + } diff --git a/aidex-common/src/main/java/com/aidex/common/core/domain/entity/RegisterBody.java b/aidex-common/src/main/java/com/aidex/common/core/domain/entity/RegisterBody.java index bd65bc43ac42a6f7bdb8852dc0a1fb6b4128eaae..2c9cd969ce9ac7105d54e7599c49b4aa54e9e056 100644 --- a/aidex-common/src/main/java/com/aidex/common/core/domain/entity/RegisterBody.java +++ b/aidex-common/src/main/java/com/aidex/common/core/domain/entity/RegisterBody.java @@ -7,7 +7,6 @@ import com.aidex.common.core.domain.model.LoginBody; * * @author ruoyi */ -public class RegisterBody extends LoginBody -{ +public class RegisterBody extends LoginBody { } \ No newline at end of file diff --git a/aidex-common/src/main/java/com/aidex/common/core/domain/entity/SysRole.java b/aidex-common/src/main/java/com/aidex/common/core/domain/entity/SysRole.java index 73500ec08c4113f9e8a2210202a1fbcf41a4f03d..bff222a71fe6ff826c662dc369ab0d473030353b 100644 --- a/aidex-common/src/main/java/com/aidex/common/core/domain/entity/SysRole.java +++ b/aidex-common/src/main/java/com/aidex/common/core/domain/entity/SysRole.java @@ -14,7 +14,7 @@ import com.aidex.common.core.domain.BaseEntity; /** * 角色表 sys_role - * + * * @author ruoyi */ @Data @@ -36,8 +36,8 @@ public class SysRole extends BaseEntity @Excel(name = "角色排序") private String sort; - /** 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限) */ - @Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限") + /** 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限;5:仅本人数据权限) */ + @Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限,5=仅本人数据权限") private String dataScope; /** 菜单树选择项是否关联显示( 0:父子不互相关联显示 1:父子互相关联显示) */ @@ -149,7 +149,7 @@ public class SysRole extends BaseEntity this.deptCheckStrictly = deptCheckStrictly; } - private String codeOrName; + private String codeOrName; public boolean isFlag() { @@ -166,22 +166,22 @@ public class SysRole extends BaseEntity @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("id", getId()) - .append("roleName", getRoleName()) - .append("roleKey", getRoleKey()) - .append("sort", getSort()) - .append("dataScope", getDataScope()) - .append("menuCheckStrictly", isMenuCheckStrictly()) - .append("deptCheckStrictly", isDeptCheckStrictly()) - .append("status", getStatus()) - .append("delFlag", getDelFlag()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("updateIp", getUpdateIp()) - .append("version", getVersion()) - .append("remark", getRemark()) - .toString(); + .append("id", getId()) + .append("roleName", getRoleName()) + .append("roleKey", getRoleKey()) + .append("sort", getSort()) + .append("dataScope", getDataScope()) + .append("menuCheckStrictly", isMenuCheckStrictly()) + .append("deptCheckStrictly", isDeptCheckStrictly()) + .append("status", getStatus()) + .append("delFlag", getDelFlag()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("updateIp", getUpdateIp()) + .append("version", getVersion()) + .append("remark", getRemark()) + .toString(); } } diff --git a/aidex-common/src/main/java/com/aidex/common/core/text/Convert.java b/aidex-common/src/main/java/com/aidex/common/core/text/Convert.java index 6e19138db06e6d6c599fb89fbeceab4196a146ff..5959bc6b86ce1375926031fae3a1a3f9daf6af08 100644 --- a/aidex-common/src/main/java/com/aidex/common/core/text/Convert.java +++ b/aidex-common/src/main/java/com/aidex/common/core/text/Convert.java @@ -6,11 +6,14 @@ import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.text.NumberFormat; import java.util.Set; + +import com.aidex.common.core.text.CharsetKit; import com.aidex.common.utils.StringUtils; +import org.apache.commons.lang3.ArrayUtils; /** * 类型转换器 - * + * * @author ruoyi */ public class Convert @@ -19,7 +22,7 @@ public class Convert * 转换为字符串
* 如果给定的值为null,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -41,7 +44,7 @@ public class Convert * 转换为字符串
* 如果给定的值为null,或者转换失败,返回默认值null
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -54,7 +57,7 @@ public class Convert * 转换为字符
* 如果给定的值为null,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -78,7 +81,7 @@ public class Convert * 转换为字符
* 如果给定的值为null,或者转换失败,返回默认值null
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -91,7 +94,7 @@ public class Convert * 转换为byte
* 如果给定的值为null,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -129,7 +132,7 @@ public class Convert * 转换为byte
* 如果给定的值为null,或者转换失败,返回默认值null
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -142,7 +145,7 @@ public class Convert * 转换为Short
* 如果给定的值为null,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -180,7 +183,7 @@ public class Convert * 转换为Short
* 如果给定的值为null,或者转换失败,返回默认值null
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -193,7 +196,7 @@ public class Convert * 转换为Number
* 如果给定的值为空,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -227,7 +230,7 @@ public class Convert * 转换为Number
* 如果给定的值为空,或者转换失败,返回默认值null
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -240,7 +243,7 @@ public class Convert * 转换为int
* 如果给定的值为空,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -278,7 +281,7 @@ public class Convert * 转换为int
* 如果给定的值为null,或者转换失败,返回默认值null
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -289,7 +292,7 @@ public class Convert /** * 转换为Integer数组
- * + * * @param str 被转换的值 * @return 结果 */ @@ -300,7 +303,7 @@ public class Convert /** * 转换为Long数组
- * + * * @param str 被转换的值 * @return 结果 */ @@ -311,7 +314,7 @@ public class Convert /** * 转换为Integer数组
- * + * * @param split 分隔符 * @param split 被转换的值 * @return 结果 @@ -334,7 +337,7 @@ public class Convert /** * 转换为Long数组
- * + * * @param split 分隔符 * @param str 被转换的值 * @return 结果 @@ -357,7 +360,7 @@ public class Convert /** * 转换为String数组
- * + * * @param str 被转换的值 * @return 结果 */ @@ -368,7 +371,7 @@ public class Convert /** * 转换为String数组
- * + * * @param split 分隔符 * @param split 被转换的值 * @return 结果 @@ -382,7 +385,7 @@ public class Convert * 转换为long
* 如果给定的值为空,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -421,7 +424,7 @@ public class Convert * 转换为long
* 如果给定的值为null,或者转换失败,返回默认值null
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -434,7 +437,7 @@ public class Convert * 转换为double
* 如果给定的值为空,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -473,7 +476,7 @@ public class Convert * 转换为double
* 如果给定的值为空,或者转换失败,返回默认值null
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -486,7 +489,7 @@ public class Convert * 转换为Float
* 如果给定的值为空,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -524,7 +527,7 @@ public class Convert * 转换为Float
* 如果给定的值为空,或者转换失败,返回默认值null
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -537,7 +540,7 @@ public class Convert * 转换为boolean
* String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -583,7 +586,7 @@ public class Convert * 转换为boolean
* 如果给定的值为空,或者转换失败,返回默认值null
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -595,7 +598,7 @@ public class Convert /** * 转换为Enum对象
* 如果给定的值为空,或者转换失败,返回默认值
- * + * * @param clazz Enum的Class * @param value 值 * @param defaultValue 默认值 @@ -631,7 +634,7 @@ public class Convert /** * 转换为Enum对象
* 如果给定的值为空,或者转换失败,返回默认值null
- * + * * @param clazz Enum的Class * @param value 值 * @return Enum @@ -645,7 +648,7 @@ public class Convert * 转换为BigInteger
* 如果给定的值为空,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -683,7 +686,7 @@ public class Convert * 转换为BigInteger
* 如果给定的值为空,或者转换失败,返回默认值null
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -696,7 +699,7 @@ public class Convert * 转换为BigDecimal
* 如果给定的值为空,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @param defaultValue 转换错误时的默认值 * @return 结果 @@ -713,18 +716,15 @@ public class Convert } if (value instanceof Long) { - //return new BigDecimal((Long) value); - return BigDecimal.valueOf((Long) value); + return new BigDecimal((Long) value); } if (value instanceof Double) { - //return new BigDecimal((Double) value); - return BigDecimal.valueOf((Double) value); + return new BigDecimal((Double) value); } if (value instanceof Integer) { - //return new BigDecimal((Integer) value); - return BigDecimal.valueOf((Integer) value); + return new BigDecimal((Integer) value); } final String valueStr = toStr(value, null); if (StringUtils.isEmpty(valueStr)) @@ -745,7 +745,7 @@ public class Convert * 转换为BigDecimal
* 如果给定的值为空,或者转换失败,返回默认值
* 转换失败不会报错 - * + * * @param value 被转换的值 * @return 结果 */ @@ -757,7 +757,7 @@ public class Convert /** * 将对象转为字符串
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 - * + * * @param obj 对象 * @return 字符串 */ @@ -769,7 +769,7 @@ public class Convert /** * 将对象转为字符串
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 - * + * * @param obj 对象 * @param charsetName 字符集 * @return 字符串 @@ -782,7 +782,7 @@ public class Convert /** * 将对象转为字符串
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 - * + * * @param obj 对象 * @param charset 字符集 * @return 字符串 @@ -798,9 +798,14 @@ public class Convert { return (String) obj; } - else if (obj instanceof byte[] || obj instanceof Byte[]) + else if (obj instanceof byte[]) + { + return str((byte[]) obj, charset); + } + else if (obj instanceof Byte[]) { - return str((Byte[]) obj, charset); + byte[] bytes = ArrayUtils.toPrimitive((Byte[]) obj); + return str(bytes, charset); } else if (obj instanceof ByteBuffer) { @@ -811,7 +816,7 @@ public class Convert /** * 将byte数组转为字符串 - * + * * @param bytes byte数组 * @param charset 字符集 * @return 字符串 @@ -823,7 +828,7 @@ public class Convert /** * 解码字节码 - * + * * @param data 字符串 * @param charset 字符集,如果此字段为空,则解码的结果取决于平台 * @return 解码后的字符串 @@ -844,7 +849,7 @@ public class Convert /** * 将编码的byteBuffer数据转换为字符串 - * + * * @param data 数据 * @param charset 字符集,如果为空使用当前系统字符集 * @return 字符串 @@ -861,7 +866,7 @@ public class Convert /** * 将编码的byteBuffer数据转换为字符串 - * + * * @param data 数据 * @param charset 字符集,如果为空使用当前系统字符集 * @return 字符串 @@ -878,7 +883,7 @@ public class Convert // ----------------------------------------------------------------------- 全角半角转换 /** * 半角转全角 - * + * * @param input String. * @return 全角字符串. */ @@ -889,7 +894,7 @@ public class Convert /** * 半角转全角 - * + * * @param input String * @param notConvertSet 不替换的字符集合 * @return 全角字符串. @@ -920,7 +925,7 @@ public class Convert /** * 全角转半角 - * + * * @param input String. * @return 半角字符串 */ @@ -931,7 +936,7 @@ public class Convert /** * 替换全角为半角 - * + * * @param text 文本 * @param notConvertSet 不替换的字符集合 * @return 替换后的字符 @@ -963,7 +968,7 @@ public class Convert /** * 数字金额大写转换 先写个完整的然后将如零拾替换成零 - * + * * @param n 数字 * @return 中文大写数字 */ diff --git a/aidex-common/src/main/java/com/aidex/common/exception/SysException.java b/aidex-common/src/main/java/com/aidex/common/exception/SysException.java index e4296f8c6f9fd4865f0fa15c1d3499e16aff4640..1fe569af4386e832a97f9e0bb4b203b71db73c19 100644 --- a/aidex-common/src/main/java/com/aidex/common/exception/SysException.java +++ b/aidex-common/src/main/java/com/aidex/common/exception/SysException.java @@ -19,4 +19,8 @@ public class SysException extends BaseException { super(errCode, errMessage); } + public SysException(int errCode, String errMessage) { + super(String.valueOf(errCode), errMessage); + } + } diff --git a/aidex-common/src/main/java/com/aidex/common/exception/file/FileException.java b/aidex-common/src/main/java/com/aidex/common/exception/file/FileException.java index e37766df5a058ae1bcb494d1b130d425dfec721e..f968f76722be322a34a1b3dbacdf063d70566f78 100644 --- a/aidex-common/src/main/java/com/aidex/common/exception/file/FileException.java +++ b/aidex-common/src/main/java/com/aidex/common/exception/file/FileException.java @@ -1,10 +1,11 @@ package com.aidex.common.exception.file; + import com.aidex.common.exception.BaseException; /** * 文件信息异常类 - * + * * @author ruoyi */ public class FileException extends BaseException diff --git a/aidex-common/src/main/java/com/aidex/common/exception/file/InvalidExtensionException.java b/aidex-common/src/main/java/com/aidex/common/exception/file/InvalidExtensionException.java index f1ef6d36eff9409f0a8a39ea6427c110f151ae0a..813febb0d89da48822ddb188bc00986393a513e2 100644 --- a/aidex-common/src/main/java/com/aidex/common/exception/file/InvalidExtensionException.java +++ b/aidex-common/src/main/java/com/aidex/common/exception/file/InvalidExtensionException.java @@ -1,11 +1,12 @@ package com.aidex.common.exception.file; -import java.util.Arrays; import org.apache.commons.fileupload.FileUploadException; +import java.util.Arrays; + /** * 文件上传 误异常类 - * + * * @author ruoyi */ public class InvalidExtensionException extends FileUploadException @@ -68,4 +69,14 @@ public class InvalidExtensionException extends FileUploadException super(allowedExtension, extension, filename); } } + + public static class InvalidVideoExtensionException extends InvalidExtensionException + { + private static final long serialVersionUID = 1L; + + public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename) + { + super(allowedExtension, extension, filename); + } + } } diff --git a/aidex-common/src/main/java/com/aidex/common/filter/RepeatableFilter.java b/aidex-common/src/main/java/com/aidex/common/filter/RepeatableFilter.java index 683a8b68ca9401408313590bfc611a2484982d61..7eee4756086caa61e13274d374bee4a50b244320 100644 --- a/aidex-common/src/main/java/com/aidex/common/filter/RepeatableFilter.java +++ b/aidex-common/src/main/java/com/aidex/common/filter/RepeatableFilter.java @@ -13,7 +13,7 @@ import com.aidex.common.utils.StringUtils; /** * Repeatable 过滤器 - * + * * @author ruoyi */ public class RepeatableFilter implements Filter @@ -30,7 +30,7 @@ public class RepeatableFilter implements Filter { ServletRequest requestWrapper = null; if (request instanceof HttpServletRequest - && StringUtils.equalsAnyIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) + && StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) { requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response); } diff --git a/aidex-common/src/main/java/com/aidex/common/filter/RepeatedlyRequestWrapper.java b/aidex-common/src/main/java/com/aidex/common/filter/RepeatedlyRequestWrapper.java index 62213f0e08f277c42927bca9fc69da760e5988e4..4ee9101721b2763717893935c885e5f4052422b1 100644 --- a/aidex-common/src/main/java/com/aidex/common/filter/RepeatedlyRequestWrapper.java +++ b/aidex-common/src/main/java/com/aidex/common/filter/RepeatedlyRequestWrapper.java @@ -13,7 +13,7 @@ import com.aidex.common.utils.http.HttpHelper; /** * 构建可重复读取inputStream的request - * + * * @author ruoyi */ public class RepeatedlyRequestWrapper extends HttpServletRequestWrapper @@ -38,18 +38,21 @@ public class RepeatedlyRequestWrapper extends HttpServletRequestWrapper @Override public ServletInputStream getInputStream() throws IOException { - final ByteArrayInputStream bais = new ByteArrayInputStream(body); - return new ServletInputStream() { - @Override public int read() throws IOException { return bais.read(); } + @Override + public int available() throws IOException + { + return body.length; + } + @Override public boolean isFinished() { diff --git a/aidex-common/src/main/java/com/aidex/common/filter/XssFilter.java b/aidex-common/src/main/java/com/aidex/common/filter/XssFilter.java index 0aa82c0f71eaf087faaa45a5920c67ea13baaea6..d439e48578242441d350d0bae7a59a71311c0946 100644 --- a/aidex-common/src/main/java/com/aidex/common/filter/XssFilter.java +++ b/aidex-common/src/main/java/com/aidex/common/filter/XssFilter.java @@ -3,8 +3,6 @@ package com.aidex.common.filter; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -13,11 +11,12 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import com.aidex.common.utils.StringUtils; /** * 防止XSS攻击的过滤器 - * + * * @author ruoyi */ public class XssFilter implements Filter @@ -27,16 +26,10 @@ public class XssFilter implements Filter */ public List excludes = new ArrayList<>(); - /** - * xss过滤开关 - */ - public boolean enabled = false; - @Override public void init(FilterConfig filterConfig) throws ServletException { String tempExcludes = filterConfig.getInitParameter("excludes"); - String tempEnabled = filterConfig.getInitParameter("enabled"); if (StringUtils.isNotEmpty(tempExcludes)) { String[] url = tempExcludes.split(","); @@ -45,10 +38,6 @@ public class XssFilter implements Filter excludes.add(url[i]); } } - if (StringUtils.isNotEmpty(tempEnabled)) - { - enabled = Boolean.valueOf(tempEnabled); - } } @Override @@ -68,25 +57,14 @@ public class XssFilter implements Filter private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) { - if (!enabled) - { - return true; - } - if (excludes == null || excludes.isEmpty()) - { - return false; - } String url = request.getServletPath(); - for (String pattern : excludes) + String method = request.getMethod(); + // GET DELETE 不过滤 + if (method == null || method.matches("GET") || method.matches("DELETE")) { - Pattern p = Pattern.compile("^" + pattern); - Matcher m = p.matcher(url); - if (m.find()) - { - return true; - } + return true; } - return false; + return StringUtils.matches(url, excludes); } @Override diff --git a/aidex-common/src/main/java/com/aidex/common/filter/XssHttpServletRequestWrapper.java b/aidex-common/src/main/java/com/aidex/common/filter/XssHttpServletRequestWrapper.java index 287b228ac95d7436dfd667cb778abd4c1c9ce2a4..6bf1215d01db02b798d2f233d114bd711673c550 100644 --- a/aidex-common/src/main/java/com/aidex/common/filter/XssHttpServletRequestWrapper.java +++ b/aidex-common/src/main/java/com/aidex/common/filter/XssHttpServletRequestWrapper.java @@ -94,11 +94,11 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper /** * 是否是Json请求 * - * @param request + * @param */ public boolean isJsonRequest() { String header = super.getHeader(HttpHeaders.CONTENT_TYPE); - return MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(header); + return StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE); } } \ No newline at end of file diff --git a/aidex-common/src/main/java/com/aidex/common/utils/Arith.java b/aidex-common/src/main/java/com/aidex/common/utils/Arith.java index 970b6653f9c9cd7989f93000dd4e84282e882d4d..46670a2065337846823cde1b33bde81480113842 100644 --- a/aidex-common/src/main/java/com/aidex/common/utils/Arith.java +++ b/aidex-common/src/main/java/com/aidex/common/utils/Arith.java @@ -5,28 +5,30 @@ import java.math.RoundingMode; /** * 精确的浮点数运算 - * + * * @author ruoyi */ -public class Arith -{ +public class Arith { - /** 默认除法运算精度 */ + /** + * 默认除法运算精度 + */ private static final int DEF_DIV_SCALE = 10; - /** 这个类不能实例化 */ - private Arith() - { + /** + * 这个类不能实例化 + */ + private Arith() { } /** * 提供精确的加法运算。 + * * @param v1 被加数 * @param v2 加数 * @return 两个参数的和 */ - public static double add(double v1, double v2) - { + public static double add(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.add(b2).doubleValue(); @@ -34,12 +36,12 @@ public class Arith /** * 提供精确的减法运算。 + * * @param v1 被减数 * @param v2 减数 * @return 两个参数的差 */ - public static double sub(double v1, double v2) - { + public static double sub(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.subtract(b2).doubleValue(); @@ -47,12 +49,12 @@ public class Arith /** * 提供精确的乘法运算。 + * * @param v1 被乘数 * @param v2 乘数 * @return 两个参数的积 */ - public static double mul(double v1, double v2) - { + public static double mul(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.multiply(b2).doubleValue(); @@ -61,34 +63,32 @@ public class Arith /** * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 * 小数点以后10位,以后的数字四舍五入。 + * * @param v1 被除数 * @param v2 除数 * @return 两个参数的商 */ - public static double div(double v1, double v2) - { + public static double div(double v1, double v2) { return div(v1, v2, DEF_DIV_SCALE); } /** * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 * 定精度,以后的数字四舍五入。 - * @param v1 被除数 - * @param v2 除数 + * + * @param v1 被除数 + * @param v2 除数 * @param scale 表示表示需要精确到小数点以后几位。 * @return 两个参数的商 */ - public static double div(double v1, double v2, int scale) - { - if (scale < 0) - { + public static double div(double v1, double v2, int scale) { + if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); - if (b1.compareTo(BigDecimal.ZERO) == 0) - { + if (b1.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO.doubleValue(); } return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue(); @@ -96,19 +96,18 @@ public class Arith /** * 提供精确的小数位四舍五入处理。 - * @param v 需要四舍五入的数字 + * + * @param v 需要四舍五入的数字 * @param scale 小数点后保留几位 * @return 四舍五入后的结果 */ - public static double round(double v, int scale) - { - if (scale < 0) - { + public static double round(double v, int scale) { + if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(v)); - BigDecimal one = new BigDecimal("1"); + BigDecimal one = BigDecimal.ONE; return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue(); } -} +} \ No newline at end of file diff --git a/aidex-common/src/main/java/com/aidex/common/utils/ExceptionUtil.java b/aidex-common/src/main/java/com/aidex/common/utils/ExceptionUtil.java index 07cb9215bafa9134c6135f752dd85b57a5e97a62..0d5ece6ff295345bacc114ba1a0343d72f5468e3 100644 --- a/aidex-common/src/main/java/com/aidex/common/utils/ExceptionUtil.java +++ b/aidex-common/src/main/java/com/aidex/common/utils/ExceptionUtil.java @@ -22,7 +22,7 @@ public class ExceptionUtil return str; } - public static String getRootErrorMseeage(Exception e) + public static String getRootErrorMessage(Exception e) { Throwable root = ExceptionUtils.getRootCause(e); root = (root == null ? e : root); diff --git a/aidex-common/src/main/java/com/aidex/common/utils/SecurityUtils.java b/aidex-common/src/main/java/com/aidex/common/utils/SecurityUtils.java index c71df3cb725160c0067b73054a48f31f49ea818e..67278964825265d2001d6ce4a54975f00064677e 100644 --- a/aidex-common/src/main/java/com/aidex/common/utils/SecurityUtils.java +++ b/aidex-common/src/main/java/com/aidex/common/utils/SecurityUtils.java @@ -1,6 +1,9 @@ package com.aidex.common.utils; +import com.aidex.common.constant.HttpStatus; import com.aidex.common.core.domain.model.LoginUser; +import com.aidex.common.exception.SysException; +import com.aidex.common.utils.StringUtils; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @@ -11,55 +14,66 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; * @author ruoyi */ public class SecurityUtils { - /** - * 获取用户账户 - **/ - public static String getUsername() { - LoginUser loginUser = getLoginUser(); - if(null == loginUser){ - return ""; - } - return loginUser.getUsername(); - } /** * 获取用户 **/ public static LoginUser getLoginUser() { - if(null != getAuthentication()){ - Object principal = getAuthentication().getPrincipal(); - if (principal != null) { - LoginUser user = (LoginUser) principal; - if (user != null) { - return user; + try { + if (null != getAuthentication()) { + Object principal = getAuthentication().getPrincipal(); + if (principal instanceof String && principal.toString().equals("anonymousUser")) { + //匿名用户 + return new LoginUser(); + } + if (principal != null) { + LoginUser user = (LoginUser) principal; + if (user != null) { + return user; + } + return new LoginUser(); } - return new LoginUser(); } + return new LoginUser(); + } catch (Exception e) { + throw new SysException(HttpStatus.UNAUTHORIZED, "获取用户信息异常"); } - return new LoginUser(); } /** - * 获取用户ID + * 用户ID **/ - public static String getLoginUserId() { - return getLoginUser().getUser().getId() + ""; + public static String getUserId() { + try { + return getLoginUser().getUser().getId(); + } catch (Exception e) { + throw new SysException(HttpStatus.UNAUTHORIZED, "获取用户ID异常"); + } } /** * 获取部门ID **/ - public static String getLoginDeptId() { - return getLoginUser().getUser().getDeptId() + ""; + public static String getDeptId() { + try { + return getLoginUser().getUser().getDeptId(); + } catch (Exception e) { + throw new SysException(HttpStatus.UNAUTHORIZED, "获取部门ID异常"); + } } /** - * 获取部门姓名 + * 获取用户账户 **/ - public static String getLoginDeptName() { - return getLoginUser().getUser().getSysDept().getDeptName(); + public static String getUsername() { + try { + return getLoginUser().getUsername(); + } catch (Exception e) { + throw new SysException(HttpStatus.UNAUTHORIZED, "获取用户账户异常"); + } } + /** * 获取登录IP地址 **/ diff --git a/aidex-common/src/main/java/com/aidex/common/utils/StringUtils.java b/aidex-common/src/main/java/com/aidex/common/utils/StringUtils.java index 6168971dcdaed8f74f27ef3210015b3b56275c84..0ff94e34d01bec096a74ed779bf4a7abe1bb036b 100644 --- a/aidex-common/src/main/java/com/aidex/common/utils/StringUtils.java +++ b/aidex-common/src/main/java/com/aidex/common/utils/StringUtils.java @@ -8,12 +8,13 @@ import java.util.List; import java.util.Map; import java.util.Set; import com.aidex.common.core.text.StrFormatter; +import org.springframework.util.AntPathMatcher; import javax.servlet.http.HttpServletRequest; /** * 字符串工具类 - * + * * @author ruoyi */ public class StringUtils extends org.apache.commons.lang3.StringUtils @@ -27,7 +28,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils public static final String DOULEFORMAT = "#0.00"; /** * 获取参数不为空值 - * + * * @param value defaultValue 要判断的value * @return value 返回值 */ @@ -38,7 +39,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * * 判断一个Collection是否为空, 包含List,Set,Queue - * + * * @param coll 要判断的Collection * @return true:为空 false:非空 */ @@ -49,7 +50,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * * 判断一个Collection是否非空,包含List,Set,Queue - * + * * @param coll 要判断的Collection * @return true:非空 false:空 */ @@ -60,7 +61,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * * 判断一个对象数组是否为空 - * + * * @param objects 要判断的对象数组 ** @return true:为空 false:非空 */ @@ -71,7 +72,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * * 判断一个对象数组是否非空 - * + * * @param objects 要判断的对象数组 * @return true:非空 false:空 */ @@ -82,7 +83,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * * 判断一个Map是否为空 - * + * * @param map 要判断的Map * @return true:为空 false:非空 */ @@ -93,7 +94,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * * 判断一个Map是否为空 - * + * * @param map 要判断的Map * @return true:非空 false:空 */ @@ -104,7 +105,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * * 判断一个字符串是否为空串 - * + * * @param str String * @return true:为空 false:非空 */ @@ -115,7 +116,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * * 判断一个字符串是否为非空串 - * + * * @param str String * @return true:非空串 false:空串 */ @@ -126,7 +127,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * * 判断一个对象是否为空 - * + * * @param object Object * @return true:为空 false:非空 */ @@ -137,7 +138,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * * 判断一个对象是否非空 - * + * * @param object Object * @return true:非空 false:空 */ @@ -148,7 +149,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * * 判断一个对象是否是数组类型(Java基本型别的数组) - * + * * @param object 对象 * @return true:是数组 false:不是数组 */ @@ -167,7 +168,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * 截取字符串 - * + * * @param str 字符串 * @param start 开始 * @return 结果 @@ -198,7 +199,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * 截取字符串 - * + * * @param str 字符串 * @param start 开始 * @param end 结束 @@ -250,7 +251,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
- * + * * @param template 文本模板,被替换的部分用 {} 表示 * @param params 参数值 * @return 格式化后的文本 @@ -266,7 +267,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * 字符串转set - * + * * @param str 字符串 * @param sep 分隔符 * @return set集合 @@ -278,7 +279,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * 字符串转list - * + * * @param str 字符串 * @param sep 分隔符 * @param filterBlank 过滤纯空白 @@ -316,7 +317,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils } /** - * 驼峰转下划线 + * 驼峰转下划线命名 */ public static String toUnderScoreCase(String str) { @@ -366,7 +367,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** * 是否包含字符串 - * + * * @param str 验证字符串 * @param strs 字符串组 * @return 包含返回true @@ -386,9 +387,32 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils return false; } + /** + * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写 + * + * @param cs 指定字符串 + * @param searchCharSequences 需要检查的字符串数组 + * @return 是否包含任意一个字符串 + */ + public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) + { + if (isEmpty(cs) || isEmpty(searchCharSequences)) + { + return false; + } + for (CharSequence testStr : searchCharSequences) + { + if (containsIgnoreCase(cs, testStr)) + { + return true; + } + } + return false; + } + /** * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld - * + * * @param name 转换前的下划线大写方式命名的字符串 * @return 转换后的驼峰式命名的字符串 */ @@ -528,4 +552,43 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils return ""; } } + + /** + * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串 + * + * @param str 指定字符串 + * @param strs 需要检查的字符串数组 + * @return 是否匹配 + */ + public static boolean matches(String str, List 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) + { + AntPathMatcher matcher = new AntPathMatcher(); + return matcher.match(pattern, url); + } } \ No newline at end of file diff --git a/aidex-common/src/main/java/com/aidex/common/utils/file/FileTypeUtils.java b/aidex-common/src/main/java/com/aidex/common/utils/file/FileTypeUtils.java index 501c25267484f8a5d77ddc94b6a3821b8762abea..1df13a3d393d62425bd3add6e0c1ed5dd640dfae 100644 --- a/aidex-common/src/main/java/com/aidex/common/utils/file/FileTypeUtils.java +++ b/aidex-common/src/main/java/com/aidex/common/utils/file/FileTypeUtils.java @@ -1,8 +1,9 @@ package com.aidex.common.utils.file; -import java.io.File; import org.apache.commons.lang3.StringUtils; +import java.io.File; + /** * 文件类型工具类 * @@ -14,7 +15,7 @@ public class FileTypeUtils * 获取文件类型 *

* 例如: ruoyi.txt, 返回: txt - * + * * @param file 文件名 * @return 后缀(不含".") */ @@ -37,7 +38,7 @@ public class FileTypeUtils */ public static String getFileType(String fileName) { - int separatorIndex = fileName.lastIndexOf('.'); + int separatorIndex = fileName.lastIndexOf("."); if (separatorIndex < 0) { return ""; @@ -47,7 +48,7 @@ public class FileTypeUtils /** * 获取文件类型 - * + * * @param photoByte 文件字节码 * @return 后缀(不含".") */ diff --git a/aidex-common/src/main/java/com/aidex/common/utils/file/FileUploadUtils.java b/aidex-common/src/main/java/com/aidex/common/utils/file/FileUploadUtils.java index 9c91bd79a4a4f2a6ca78bd82c21c64f81b0cdb0c..e887382416b920884fcfb692cd025a1e14544d19 100644 --- a/aidex-common/src/main/java/com/aidex/common/utils/file/FileUploadUtils.java +++ b/aidex-common/src/main/java/com/aidex/common/utils/file/FileUploadUtils.java @@ -1,9 +1,5 @@ package com.aidex.common.utils.file; -import java.io.File; -import java.io.IOException; -import org.apache.commons.io.FilenameUtils; -import org.springframework.web.multipart.MultipartFile; import com.aidex.common.config.AiDexConfig; import com.aidex.common.constant.Constants; import com.aidex.common.exception.file.FileNameLengthLimitExceededException; @@ -12,6 +8,11 @@ import com.aidex.common.exception.file.InvalidExtensionException; import com.aidex.common.utils.DateUtils; import com.aidex.common.utils.StringUtils; import com.aidex.common.utils.uuid.IdUtils; +import org.apache.commons.io.FilenameUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; /** * 文件上传工具类 @@ -123,32 +124,29 @@ public class FileUploadUtils { String fileName = file.getOriginalFilename(); String extension = getExtension(file); -// fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; - fileName = DateUtils.datePath() + File.separator + IdUtils.fastUUID() + "." + extension; + fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; return fileName; } - private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException + public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException { File desc = new File(uploadDir + File.separator + fileName); - if (!desc.getParentFile().exists()) - { - desc.getParentFile().mkdirs(); - } if (!desc.exists()) { - desc.createNewFile(); + if (!desc.getParentFile().exists()) + { + desc.getParentFile().mkdirs(); + } } return desc; } - private static final String getPathFileName(String uploadDir, String fileName) throws IOException + public static final String getPathFileName(String uploadDir, String fileName) throws IOException { int dirLastIndex = AiDexConfig.getProfile().length() + 1; String currentDir = StringUtils.substring(uploadDir, dirLastIndex); -// String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName; - String pathFileName = Constants.RESOURCE_PREFIX + File.separator + currentDir + File.separator + fileName; + String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName; return pathFileName; } @@ -188,6 +186,11 @@ public class FileUploadUtils throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, fileName); } + else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) + { + throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension, + fileName); + } else { throw new InvalidExtensionException(allowedExtension, extension, fileName); diff --git a/aidex-common/src/main/java/com/aidex/common/utils/file/FileUtils.java b/aidex-common/src/main/java/com/aidex/common/utils/file/FileUtils.java index e0addc223a8fc3afc18679f12cdea0a6ba8e4346..f6124c57308afa659afe815db82f404657c28e36 100644 --- a/aidex-common/src/main/java/com/aidex/common/utils/file/FileUtils.java +++ b/aidex-common/src/main/java/com/aidex/common/utils/file/FileUtils.java @@ -1,27 +1,31 @@ package com.aidex.common.utils.file; + +import com.aidex.common.config.AiDexConfig; +import com.aidex.common.utils.DateUtils; +import com.aidex.common.utils.StringUtils; +import com.aidex.common.utils.uuid.IdUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.ArrayUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import ch.qos.logback.core.util.FileUtil; -import org.apache.commons.lang3.ArrayUtils; -import com.aidex.common.utils.StringUtils; /** * 文件处理工具类 - * + * * @author ruoyi */ -public class FileUtils extends org.apache.commons.io.FileUtils +public class FileUtils { - public static final String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; + public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; /** * 输出指定文件的byte数组 - * + * * @param filePath 文件路径 * @param os 输出流 * @return @@ -50,34 +54,52 @@ public class FileUtils extends org.apache.commons.io.FileUtils } finally { - if (os != null) - { - try - { - os.close(); - } - catch (IOException e1) - { - e1.printStackTrace(); - } - } - if (fis != null) - { - try - { - fis.close(); - } - catch (IOException e1) - { - e1.printStackTrace(); - } - } + IOUtils.close(os); + IOUtils.close(fis); + } + } + /** + * 写数据到文件中 + * + * @param data 数据 + * @return 目标文件 + * @throws IOException IO异常 + */ + public static String writeImportBytes(byte[] data) throws IOException + { + return writeBytes(data, AiDexConfig.getImportPath()); + } + + /** + * 写数据到文件中 + * + * @param data 数据 + * @param uploadDir 目标文件 + * @return 目标文件 + * @throws IOException IO异常 + */ + public static String writeBytes(byte[] data, String uploadDir) throws IOException + { + FileOutputStream fos = null; + String pathName = ""; + try + { + String extension = getFileExtendName(data); + pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; + File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName); + fos = new FileOutputStream(file); + fos.write(data); } + finally + { + IOUtils.close(fos); + } + return FileUploadUtils.getPathFileName(uploadDir, pathName); } /** * 删除文件 - * + * * @param filePath 文件 * @return */ @@ -96,7 +118,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils /** * 文件名称验证 - * + * * @param filename 文件名称 * @return true 正常 false 非法 */ @@ -107,7 +129,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils /** * 检查文件是否可下载 - * + * * @param resource 需要下载的文件 * @return true 正常 false 非法 */ @@ -131,7 +153,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils /** * 下载文件名重新编码 - * + * * @param request 请求对象 * @param fileName 文件名 * @return 编码后的文件名 @@ -184,6 +206,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils .append(percentEncodedFileName); response.setHeader("Content-disposition", contentDispositionValue.toString()); + response.setHeader("download-filename", percentEncodedFileName); } /** @@ -198,237 +221,32 @@ public class FileUtils extends org.apache.commons.io.FileUtils return encode.replaceAll("\\+", "%20"); } - - - /** - * 获取指定(fileName)的扩展名称 - * @return - */ - public static String getFileExtensionName(String filename){ - if ((filename != null) && (filename.length() > 0)) { - int dot = filename.lastIndexOf('.'); - if ((dot > -1) && (dot < (filename.length() - 1))) { - return filename.substring(dot + 1); - } - } - return filename; - } - /** - * 获取不带扩展名的文件名称 - * @param filename - * @return - */ - public static String getFileNameNoEx(String filename) { - if ((filename != null) && (filename.length() > 0)) { - int dot = filename.lastIndexOf('.'); - if ((dot >-1) && (dot < (filename.length()))) { - return filename.substring(0, dot); - } - } - return filename; - } - /** - * 根据文件名称,获取文件icon - * @param filename - * @return - */ - public static String getFileIcon(String filename){ - String icon = ""; - String exName = getFileExtensionName(filename); - if("avi".equals(exName)){// avi - icon = "avi.jpg"; - } else if("zip".equals(exName)){//zip - return "zip.jpg"; - } else if("rar".equals(exName)){//rar - return "rar.jpg"; - } else if("exe".equals(exName)){//exe - return "exe.jpg"; - } else if("xls".equals(exName) || "xlsx".equals(exName)){//xls - return "excel.jpg"; - } else if("doc".equals(exName) || "docx".equals(exName)){//doc - return "word.jpg"; - } else if("ppt".equals(exName) || "pptx".equals(exName) ){//ppt - return "ppt.jpg"; - } else if("txt".equals(exName)){//txt - return "txt.jpg"; - } else if("chm".equals(exName)){//chm - return "chm.jpg"; - } else if("pdf".equals(exName)){//pdf - return "pdf.jpg"; - } else if("jpg".equals(exName)){//jpg - return "jpg.jpg"; - } else if("png".equals(exName)){//png - return "jpg.jpg"; - }else if("bmp".equals(exName)){//bmp - return "bmp.jpg"; - } else if("gif".equals(exName)){//gif - return "pic.jpg"; - } else if("html".equals(exName) || "htm".equals(exName) || "xhtml".equals(exName)){//html - return "html.jpg"; - } else{ - return "normal.jpg"; - } - return icon; - } - public static String getFileIconCss(String filename){ - String iconCss = ""; - String exName = getFileExtensionName(filename); - if("zip".equals(exName)){//zip - return "nui-ico-file nui-ico-file-rar"; - } else if("rar".equals(exName)){//rar - return "nui-ico-file nui-ico-file-rar"; - }else if("xls".equals(exName) || "xlsx".equals(exName)){//xls - return "nui-ico-file nui-ico-file-xls"; - } else if("doc".equals(exName) || "docx".equals(exName)){//doc - return "nui-ico-file nui-ico-file-doc"; - } else if("ppt".equals(exName) || "pptx".equals(exName) ){//ppt - return "nui-ico-file nui-ico-file-ppt"; - } else if("txt".equals(exName)){//txt - return "nui-ico-file nui-ico-file-txt"; - } else if("chm".equals(exName)){//chm - return "nui-ico-file nui-ico-file-html"; - } else if("html".equals(exName) || "htm".equals(exName) || "xhtml".equals(exName)){//html - return "nui-ico-file nui-ico-file-html"; - } else{ - return "nui-ico-file nui-ico-file-default"; - } - } /** - * 获取操作系统文件路径分隔符 - */ - public static String getSep(){ - return System.getProperties().getProperty("file.separator"); - } - /** - * 检查文件路径是否有效 - * @param path - * @return - */ - public static void checkPath(String path) throws IOException{ - File filePath = new File(path); - if(!filePath.exists()){ - throw new IOException("无效的文件路径【" + path + "】;"); - } - } - /** - * 创建目录 - * @param group - * @param file - * @return + * 获取图像后缀 + * + * @param photoByte 图像数据 + * @return 后缀名 */ - public static File getDoccenterDir(String doccenterPath, String group,String file) throws IOException{ - File folder = new File(doccenterPath); - FileUtils.checkPath(folder.getAbsolutePath()); - if(!folder.exists()){ - folder.mkdir(); - } - folder = new File(folder.getAbsoluteFile() + FileUtils.getSep() +"group" + group); - if(!folder.exists()){ - folder.mkdir(); - } - folder = new File(folder.getAbsoluteFile() + FileUtils.getSep() +"file" + file); - if(!folder.exists()){ - folder.mkdir(); - } - return folder.getAbsoluteFile(); - } - - public static File getDoccenterDir(String doccenterPath, String tmpId) throws IOException{ - File folder = new File(doccenterPath); - FileUtils.checkPath(folder.getAbsolutePath()); - if(!folder.exists()){ - folder.mkdir(); - } - folder = new File(folder.getAbsoluteFile() + FileUtils.getSep() +"tmp" + tmpId); - if(!folder.exists()){ - folder.mkdir(); + public static String getFileExtendName(byte[] photoByte) + { + String strFileExtendName = "jpg"; + if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56) + && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) + { + strFileExtendName = "gif"; } - return folder.getAbsoluteFile(); - } - /** - * 单位形式,显示文件大小 - * @param fileSize - * @return - */ - public static String getFilePrettySize(Long fileSize){ - long K = 1024; - long M = K * K; - long G = M * K; - long T = G * K; - long[] dividers = { T, G, M, K, 1 }; - String[] units = { "TB", "GB", "MB", "KB", "B" }; - if (fileSize == 0) { - return "0B"; - } else if (fileSize < 0) { - return "Invalid size"; + else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) + { + strFileExtendName = "jpg"; } - - String result = ""; - long temp = 0; - for ( int i = 0; i < dividers.length; i++) { - long divider = dividers[i]; - if (fileSize >= divider) { - temp = fileSize / divider; - if (temp < 1.05) { - result = _format(fileSize,units[((i + 1) < units.length) ? (i + 1) : i]); - } else { - result = _format(temp, units[i]); - } - break; - } + else if ((photoByte[0] == 66) && (photoByte[1] == 77)) + { + strFileExtendName = "bmp"; } - return result; - } - private static String _format(Long fileSize, String unit) { - return (fileSize + " " + unit).replace(".0", ""); - } - - /*public static String getFileName(String fileName, String agent) { - String codedfilename = fileName; - try { - if (agent != null && agent.indexOf("Mozilla") != -1 && agent.indexOf("Android") != -1) {// Mozilla.. - try { - codedfilename = URLEncoder.encode(fileName, "UTF-8"); - } catch (Exception e) { - codedfilename = fileName; - } - } else if (agent.toLowerCase().indexOf("safari") != -1) {// Safari浏览器,只能采用ISO编码的中文输出 - codedfilename = new String(codedfilename.getBytes("UTF-8"), "ISO8859-1"); - } else if (agent.toLowerCase().indexOf("chrome") != -1) {// Chrome浏览器,只能采用MimeUtility编码或ISO编码的中文输出 - codedfilename = MimeUtility.encodeText(codedfilename, "UTF8", "B"); - } - // FireFox浏览器,可以使用MimeUtility或filename*或ISO编码的中文输出 - else if (agent != null && agent.toLowerCase().indexOf("mozilla") != -1 && agent.toLowerCase().indexOf("firefox") != -1) {// ff,mozilla.. - codedfilename = MimeUtility.encodeText(fileName, "GBK", "B"); - } else {// ie,opera.. - if (Charset.defaultCharset().name().indexOf("GBK") != -1) { - codedfilename = new String(fileName.getBytes(), "ISO8859_1"); - } else { - try { - codedfilename = URLEncoder.encode(fileName, "utf-8"); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - } catch (Exception e) { - - } - return codedfilename; - }*/ - - - public static byte[] InputStreamToByte(InputStream is) throws IOException { - - ByteArrayOutputStream bytestream = new ByteArrayOutputStream(); - int ch; - while ((ch = is.read()) != -1) { - bytestream.write(ch); + else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) + { + strFileExtendName = "png"; } - byte imgdata[] = bytestream.toByteArray(); - bytestream.close(); - - return imgdata; + return strFileExtendName; } } diff --git a/aidex-common/src/main/java/com/aidex/common/utils/file/ImageUtils.java b/aidex-common/src/main/java/com/aidex/common/utils/file/ImageUtils.java index 1277fa0ca4d1d7098709c9de05a7a8f0a5c8cedd..438c923dab7d9da7fa54f4ac21d1a5bd642e3045 100644 --- a/aidex-common/src/main/java/com/aidex/common/utils/file/ImageUtils.java +++ b/aidex-common/src/main/java/com/aidex/common/utils/file/ImageUtils.java @@ -1,5 +1,12 @@ package com.aidex.common.utils.file; +import com.aidex.common.config.AiDexConfig; +import com.aidex.common.constant.Constants; +import com.aidex.common.utils.StringUtils; +import org.apache.poi.util.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; @@ -7,12 +14,6 @@ import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Arrays; -import org.apache.poi.util.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.aidex.common.config.AiDexConfig; -import com.aidex.common.constant.Constants; -import com.aidex.common.utils.StringUtils; /** * 图片处理工具类 @@ -58,8 +59,8 @@ public class ImageUtils /** * 读取文件为字节数据 - * - * @param key 地址 + * + * @param url 地址 * @return 字节数据 */ public static byte[] readFile(String url) @@ -94,6 +95,7 @@ public class ImageUtils } finally { + IOUtils.closeQuietly(in); IOUtils.closeQuietly(baos); } } diff --git a/aidex-common/src/main/java/com/aidex/common/utils/file/MimeTypeUtils.java b/aidex-common/src/main/java/com/aidex/common/utils/file/MimeTypeUtils.java index 486205d098c5fa447c19fa47c111707c29439b7e..a3e11c998db68a7bb37c60089286f33bc481644b 100644 --- a/aidex-common/src/main/java/com/aidex/common/utils/file/MimeTypeUtils.java +++ b/aidex-common/src/main/java/com/aidex/common/utils/file/MimeTypeUtils.java @@ -2,7 +2,7 @@ package com.aidex.common.utils.file; /** * 媒体类型工具类 - * + * * @author ruoyi */ public class MimeTypeUtils @@ -16,7 +16,7 @@ public class MimeTypeUtils public static final String IMAGE_BMP = "image/bmp"; public static final String IMAGE_GIF = "image/gif"; - + public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" }; public static final String[] FLASH_EXTENSION = { "swf", "flv" }; @@ -24,6 +24,8 @@ public class MimeTypeUtils public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb" }; + public static final String[] VIDEO_EXTENSION = { "mp4", "avi", "rmvb" }; + public static final String[] DEFAULT_ALLOWED_EXTENSION = { // 图片 "bmp", "gif", "jpg", "jpeg", "png", @@ -31,6 +33,8 @@ public class MimeTypeUtils "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt", // 压缩文件 "rar", "zip", "gz", "bz2", + // 视频格式 + "mp4", "avi", "rmvb", // pdf "pdf" }; diff --git a/aidex-common/src/main/java/com/aidex/common/utils/html/EscapeUtil.java b/aidex-common/src/main/java/com/aidex/common/utils/html/EscapeUtil.java index 047363a6c9a03125fd70050b680897f2e32020a9..001c08c96310c1081e7b5eaae3ca3f703f521354 100644 --- a/aidex-common/src/main/java/com/aidex/common/utils/html/EscapeUtil.java +++ b/aidex-common/src/main/java/com/aidex/common/utils/html/EscapeUtil.java @@ -4,7 +4,7 @@ import com.aidex.common.utils.StringUtils; /** * 转义和反转义工具类 - * + * * @author ruoyi */ public class EscapeUtil @@ -22,7 +22,7 @@ public class EscapeUtil // special HTML characters TEXT['\''] = "'".toCharArray(); // 单引号 - TEXT['"'] = """.toCharArray(); // 单引号 + TEXT['"'] = """.toCharArray(); // 双引号 TEXT['&'] = "&".toCharArray(); // &符 TEXT['<'] = "<".toCharArray(); // 小于号 TEXT['>'] = ">".toCharArray(); // 大于号 @@ -30,7 +30,7 @@ public class EscapeUtil /** * 转义文本中的HTML字符为安全的字符 - * + * * @param text 被转义的文本 * @return 转义后的文本 */ @@ -41,7 +41,7 @@ public class EscapeUtil /** * 还原被转义的HTML特殊字符 - * + * * @param content 包含转义符的HTML内容 * @return 转换后的字符串 */ @@ -52,7 +52,7 @@ public class EscapeUtil /** * 清除所有HTML标签,但是不删除标签内的内容 - * + * * @param content 文本 * @return 清除标签后的文本 */ @@ -63,7 +63,7 @@ public class EscapeUtil /** * Escape编码 - * + * * @param text 被编码的文本 * @return 编码后的字符 */ @@ -93,7 +93,7 @@ public class EscapeUtil /** * Escape解码 - * + * * @param content 被转义的内容 * @return 解码后的字符串 */ diff --git a/aidex-common/src/main/java/com/aidex/common/utils/uuid/IdUtils.java b/aidex-common/src/main/java/com/aidex/common/utils/uuid/IdUtils.java index bb17f82db29037568379632812355432157c1d4f..5d01c245d1999442c5158d2ebb6fd83ac48624b6 100644 --- a/aidex-common/src/main/java/com/aidex/common/utils/uuid/IdUtils.java +++ b/aidex-common/src/main/java/com/aidex/common/utils/uuid/IdUtils.java @@ -4,24 +4,24 @@ import com.aidex.common.utils.uuid.UUID; /** * ID生成器工具类 - * + * * @author ruoyi */ public class IdUtils { /** * 获取随机UUID - * + * * @return 随机UUID */ public static String randomUUID() { - return UUID.randomUUID().toString().replaceAll("-", ""); + return UUID.randomUUID().toString(); } /** * 简化的UUID,去掉了横线 - * + * * @return 简化的UUID,去掉了横线 */ public static String simpleUUID() @@ -31,7 +31,7 @@ public class IdUtils /** * 获取随机UUID,使用性能更好的ThreadLocalRandom生成UUID - * + * * @return 随机UUID */ public static String fastUUID() @@ -41,7 +41,7 @@ public class IdUtils /** * 简化的UUID,去掉了横线,使用性能更好的ThreadLocalRandom生成UUID - * + * * @return 简化的UUID,去掉了横线 */ public static String fastSimpleUUID() diff --git a/aidex-controller/pom.xml b/aidex-controller/pom.xml index 1274e623e28dcfbf6b523cf221580b5bbdbb03f2..a865216ba82f9e000fe7b70ad907056838b974bb 100644 --- a/aidex-controller/pom.xml +++ b/aidex-controller/pom.xml @@ -19,30 +19,19 @@ true - + io.springfox - springfox-swagger2 - - - - - io.swagger - swagger-annotations - 1.5.21 + springfox-boot-starter + io.swagger swagger-models - 1.5.21 + 1.6.2 - - - io.springfox - springfox-swagger-ui - diff --git a/aidex-controller/src/main/java/com/aidex/web/controller/common/CaptchaController.java b/aidex-controller/src/main/java/com/aidex/web/controller/common/CaptchaController.java index ce9ec3be5147e5f2a0f866e9ff3674b60a05e121..5bbd703f3f77ef463a6c4a2b5c697f56c123e388 100644 --- a/aidex-controller/src/main/java/com/aidex/web/controller/common/CaptchaController.java +++ b/aidex-controller/src/main/java/com/aidex/web/controller/common/CaptchaController.java @@ -5,6 +5,7 @@ import com.aidex.common.core.domain.AjaxResult; import com.aidex.common.core.redis.RedisCache; import com.aidex.common.utils.sign.Base64; import com.aidex.common.utils.uuid.IdUtils; +import com.aidex.framework.cache.ConfigUtils; import com.google.code.kaptcha.Producer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -21,7 +22,7 @@ import java.util.concurrent.TimeUnit; /** * 验证码操作处理 - * + * * @author ruoyi */ @RestController @@ -35,7 +36,7 @@ public class CaptchaController @Autowired private RedisCache redisCache; - + // 验证码类型 @Value("${aidex.captchaType}") private String captchaType; @@ -46,9 +47,13 @@ public class CaptchaController @GetMapping("/captchaImage") public AjaxResult getCode(HttpServletResponse response) throws IOException { - AjaxResult ajax = null; - - + AjaxResult ajax = AjaxResult.success(); + boolean captchaOnOff = ConfigUtils.getConfigBooleanValueByKey("sys.captcha.onOff",true); + ajax.put("captchaOnOff", captchaOnOff); + if (!captchaOnOff) + { + return ajax; + } try { // 保存验证码信息 String uuid = IdUtils.simpleUUID(); diff --git a/aidex-controller/src/main/java/com/aidex/web/controller/monitor/SysOperlogController.java b/aidex-controller/src/main/java/com/aidex/web/controller/monitor/SysOperlogController.java index 8760d382e240fa7297b8d36d67a5e3666780d929..2ecf6c9951c68682a1da701f6e3506fe75ecbcab 100644 --- a/aidex-controller/src/main/java/com/aidex/web/controller/monitor/SysOperlogController.java +++ b/aidex-controller/src/main/java/com/aidex/web/controller/monitor/SysOperlogController.java @@ -47,6 +47,7 @@ public class SysOperlogController extends BaseController return util.exportExcel(list, "操作日志"); } + @Log(title = "操作日志", businessType = BusinessType.DELETE) @PreAuthorize("@ss.hasPermi('monitor:operlog:remove')") @DeleteMapping("/{operIds}") public R remove(@PathVariable String[] operIds) diff --git a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysConfigController.java b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysConfigController.java index e17f92cc5c7038ef15f3283b06b34724bfb9e72e..9eef76c216aae095f8a73503e7dbce227dbef0c1 100644 --- a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysConfigController.java +++ b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysConfigController.java @@ -6,6 +6,7 @@ import com.aidex.common.core.domain.R; import com.aidex.common.core.page.PageDomain; import com.aidex.common.enums.BusinessType; import com.aidex.common.utils.poi.ExcelUtil; +import com.aidex.framework.cache.ConfigUtils; import com.aidex.system.domain.SysConfig; import com.aidex.system.service.SysConfigService; import com.github.pagehelper.PageInfo; @@ -22,13 +23,13 @@ import java.util.Map; /** * 参数配置 信息操作处理 - * + * * @author ruoyi */ @RestController @RequestMapping("/system/config") -public class SysConfigController extends BaseController -{ +public class SysConfigController extends BaseController { + @Autowired private SysConfigService configService; @@ -65,8 +66,7 @@ public class SysConfigController extends BaseController @Log(title = "参数管理", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('system:config:export')") @GetMapping("/export") - public R export(SysConfig config) - { + public R export(SysConfig config) { List list = configService.findList(config); ExcelUtil util = new ExcelUtil(SysConfig.class); return util.exportExcel(list, "参数数据"); @@ -76,9 +76,8 @@ public class SysConfigController extends BaseController * 根据参数键名查询参数值 */ @GetMapping(value = "/configKey/{configKey}") - public R getConfigKey(@PathVariable String configKey) - { - return R.data(configService.selectConfigByKey(configKey)); + public R getConfigKey(@PathVariable String configKey) { + return R.data(ConfigUtils.getConfigValueByKey(configKey)); } @@ -92,19 +91,19 @@ public class SysConfigController extends BaseController @Log(title = "参数管理", businessType = BusinessType.DELETE) @DeleteMapping("/{ids}") public R remove(@PathVariable String[] ids) { - return R.status(configService.deleteConfigByIds(ids)); + configService.deleteConfigByIds(ids); + return R.success(); } /** - * 清空缓存 + * 刷新缓存 */ @PreAuthorize("@ss.hasPermi('system:config:remove')") @Log(title = "参数管理", businessType = BusinessType.CLEAN) - @DeleteMapping("/clearCache") - public R clearCache() - { - configService.clearCache(); + @DeleteMapping("/refreshCache") + public R refreshCache() { + configService.refreshCache(); return R.status(true); } @@ -115,12 +114,12 @@ public class SysConfigController extends BaseController @Log(title = "字典类型", businessType = BusinessType.CHECK) @GetMapping("/checkConfigKeyUnique") public R checkDictDataValueUnique(SysConfig sysConfig) { - Map checkMap = new HashMap(1); - try{ + Map checkMap = new HashMap(1); + try { configService.checkConfigKeyUnique(sysConfig); - checkMap.put("code","1"); - }catch (Exception e){ - checkMap.put("code","2"); + checkMap.put("code", "1"); + } catch (Exception e) { + checkMap.put("code", "2"); } return R.data(checkMap); } diff --git a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysDictDataController.java b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysDictDataController.java index 9766e9735c8671bdfa00b60c6493b20b62c3406a..ceb65066f3ecfb3ca06a8b443be5268f36081a9e 100644 --- a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysDictDataController.java +++ b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysDictDataController.java @@ -5,8 +5,8 @@ import com.aidex.common.core.controller.BaseController; import com.aidex.common.core.domain.R; import com.aidex.common.core.page.PageDomain; import com.aidex.common.enums.BusinessType; -import com.aidex.common.utils.StringUtils; import com.aidex.common.utils.poi.ExcelUtil; +import com.aidex.framework.cache.DictUtils; import com.aidex.system.domain.SysDictData; import com.aidex.system.service.SysDictDataService; import com.aidex.system.service.SysDictTypeService; @@ -18,20 +18,19 @@ import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 数据字典信息 - * + * * @author ruoyi */ @RestController @RequestMapping("/system/dict/data") -public class SysDictDataController extends BaseController -{ +public class SysDictDataController extends BaseController { + @Autowired private SysDictDataService dictDataService; @@ -40,8 +39,7 @@ public class SysDictDataController extends BaseController @PreAuthorize("@ss.hasPermi('system:dict:list')") @GetMapping("/page") - public R list(SysDictData dictData, HttpServletRequest request, HttpServletResponse response) - { + public R list(SysDictData dictData, HttpServletRequest request, HttpServletResponse response) { dictData.setPage(new PageDomain(request, response)); return R.data(dictDataService.findPage(dictData)); } @@ -49,8 +47,7 @@ public class SysDictDataController extends BaseController @Log(title = "字典数据", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('system:dict:export')") @GetMapping("/export") - public R export(SysDictData dictData) - { + public R export(SysDictData dictData) { List list = dictDataService.findList(dictData); ExcelUtil util = new ExcelUtil(SysDictData.class); return util.exportExcel(list, "字典数据"); @@ -61,8 +58,7 @@ public class SysDictDataController extends BaseController */ @PreAuthorize("@ss.hasPermi('system:dict:query')") @GetMapping(value = "/{id}") - public R getInfo(@PathVariable String id) - { + public R getInfo(@PathVariable String id) { return R.data(dictDataService.get(id)); } @@ -70,28 +66,16 @@ public class SysDictDataController extends BaseController * 根据字典类型查询字典数据信息 */ @GetMapping(value = "/type/{dictType}") - public R> dictType(@PathVariable String dictType) - { - List data = dictTypeService.selectDictDataByType(dictType); - if (StringUtils.isNull(data)) - { - data = new ArrayList(); - } - return R.data(data); + public R> dictType(@PathVariable String dictType) { + return R.data(DictUtils.getDictList(dictType)); } /** * 根据字典类型查询字典数据信息 */ @GetMapping(value = "/all/type/{dictType}") - public R> allDictType(@PathVariable String dictType) - { - List data = dictTypeService.selectAllDictDataByType(dictType); - if (StringUtils.isNull(data)) - { - data = new ArrayList(); - } - return R.data(data); + public R> allDictType(@PathVariable String dictType) { + return R.data(DictUtils.getAllDictList(dictType)); } @@ -101,8 +85,7 @@ public class SysDictDataController extends BaseController @PreAuthorize("@ss.hasPermi('system:dict:add')") @Log(title = "字典类型", businessType = BusinessType.INSERT) @PostMapping - public R save(@Validated @RequestBody SysDictData dictData) - { + public R save(@Validated @RequestBody SysDictData dictData) { return R.status(dictDataService.save(dictData)); } @@ -112,9 +95,9 @@ public class SysDictDataController extends BaseController @PreAuthorize("@ss.hasPermi('system:dict:remove')") @Log(title = "字典类型", businessType = BusinessType.DELETE) @DeleteMapping("/{ids}") - public R remove(@PathVariable String[] ids) - { - return R.status(dictDataService.deleteDictDataByIds(ids)); + public R remove(@PathVariable String[] ids) { + dictDataService.deleteDictDataByIds(ids); + return R.success(); } /** @@ -124,12 +107,12 @@ public class SysDictDataController extends BaseController @Log(title = "字典类型", businessType = BusinessType.CHECK) @GetMapping("/checkDictDataValueUnique") public R checkDictDataValueUnique(SysDictData sysDictData) { - Map checkMap = new HashMap(16); - try{ + Map checkMap = new HashMap(16); + try { dictDataService.checkDictDataValueUnique(sysDictData); - checkMap.put("code","1"); - }catch (Exception e){ - checkMap.put("code","2"); + checkMap.put("code", "1"); + } catch (Exception e) { + checkMap.put("code", "2"); } return R.data(checkMap); } diff --git a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysDictTypeController.java b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysDictTypeController.java index 7d5714f1967a012a35ba11e1f31b48e2d3238773..a565fab311dde9c1f8151dc277bd6a0f1943c3c9 100644 --- a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysDictTypeController.java +++ b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysDictTypeController.java @@ -22,7 +22,7 @@ import java.util.Map; /** * 数据字典信息 - * + * * @author ruoyi */ @RestController @@ -79,18 +79,19 @@ public class SysDictTypeController extends BaseController @DeleteMapping("/{ids}") public R remove(@PathVariable String[] ids) { - return R.status(dictTypeService.deleteDictTypeByIds(ids)); + dictTypeService.deleteDictTypeByIds(ids); + return R.success(); } /** - * 清空缓存 + * 刷新缓存 */ @PreAuthorize("@ss.hasPermi('system:dict:remove')") @Log(title = "字典类型", businessType = BusinessType.CLEAN) - @DeleteMapping("/clearCache") - public R clearCache() + @DeleteMapping("/refreshCache") + public R refreshCache() { - dictTypeService.clearCache(); + dictTypeService.refreshCache(); return R.status(true); } diff --git a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysIndexController.java b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysIndexController.java new file mode 100644 index 0000000000000000000000000000000000000000..5b2ab8381632b5b891cabe424d51bd39d7cf6696 --- /dev/null +++ b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysIndexController.java @@ -0,0 +1,30 @@ +package com.aidex.web.controller.system; + +import com.aidex.common.config.AiDexConfig; +import com.aidex.common.utils.StringUtils; +import com.aidex.framework.config.AnonymousAccess; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 首页 + * + * @author ruoyi + */ +@RestController +public class SysIndexController +{ + /** 系统基础配置 */ + @Autowired + private AiDexConfig aidexConfig; + + /** + * 访问首页,提示语 + */ + @RequestMapping("/") + public String index() + { + return StringUtils.format("欢迎使用{}后台管理框架,当前版本:v{},请通过前端地址访问。", aidexConfig.getName(), aidexConfig.getVersion()); + } +} diff --git a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysProfileController.java b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysProfileController.java index 24c4fd966978ff32903dd2377b3d71d9d5b60f4f..635d3beeb6390f29c88c01b5b9b82ae710801890 100644 --- a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysProfileController.java +++ b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysProfileController.java @@ -23,7 +23,7 @@ import java.util.Map; /** * 个人信息 业务处理 - * + * * @author ruoyi */ @RestController @@ -59,21 +59,28 @@ public class SysProfileController extends BaseController @PutMapping public R updateProfile(@RequestBody SysUser user) { + //校验手机号 + userService.checkPhoneUnique(user); + //校验邮箱 + userService.checkEmailUnique(user); + //获取当前登录用户 + LoginUser loginUser = getLoginUser(); + SysUser sysUser = loginUser.getUser(); + //更新用户信息 SysUser oldUser = userService.get(user.getId()); user.setVersion(oldUser.getVersion()); + user.setPassword(null); if (userService.updateUserProfile(user)) { - LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest()); // 更新缓存用户信息 - loginUser.getUser().setNickName(user.getNickName()); - loginUser.getUser().setPhonenumber(user.getPhonenumber()); - loginUser.getUser().setEmail(user.getEmail()); - loginUser.getUser().setSex(user.getSex()); - loginUser.getUser().setVersion(user.getVersion()); + sysUser.setNickName(user.getNickName()); + sysUser.setPhonenumber(user.getPhonenumber()); + sysUser.setEmail(user.getEmail()); + sysUser.setSex(user.getSex()); + sysUser.setVersion(user.getVersion()); tokenService.setLoginUser(loginUser); return R.success(); } - //return AjaxResult.error("修改个人信息异常,请联系管理员"); return R.fail("修改个人信息异常,请联系管理员"); } diff --git a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysRegisterController.java b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysRegisterController.java index a8aa5fb618bdf7126ea8af44216d56db2c52067c..a3d95ccf85ce296e4843a87d89d4764b2dba731d 100644 --- a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysRegisterController.java +++ b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysRegisterController.java @@ -1,11 +1,10 @@ package com.aidex.web.controller.system; import com.aidex.common.core.controller.BaseController; -import com.aidex.common.core.domain.AjaxResult; +import com.aidex.common.core.domain.R; import com.aidex.common.core.domain.entity.RegisterBody; import com.aidex.framework.cache.ConfigUtils; import com.aidex.framework.web.service.SysRegisterService; -import com.aidex.system.service.SysConfigService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; @@ -19,19 +18,17 @@ import org.springframework.web.bind.annotation.RestController; * @author ruoyi */ @RestController -public class SysRegisterController extends BaseController -{ +public class SysRegisterController extends BaseController { + @Autowired private SysRegisterService registerService; @PostMapping("/register") - public AjaxResult register(@RequestBody RegisterBody user) - { - if (!ConfigUtils.getConfigBooleanValueByKey("sys.account.captchaOnOff",Boolean.FALSE)) - { - return error("当前系统没有开启注册功能!"); + public R register(@RequestBody RegisterBody user) { + if (!ConfigUtils.getConfigBooleanValueByKey("sys.account.registerUser", Boolean.FALSE)) { + return R.fail("当前系统没有开启注册功能!"); } String msg = registerService.register(user); - return StringUtils.isEmpty(msg) ? success() : error(msg); + return StringUtils.isEmpty(msg) ? R.success() : R.fail(msg); } } diff --git a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysUserController.java b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysUserController.java index 5fa6aa1d2387feb53bfab429aaaaf9760e6028ad..99e0d3e5d5d6fc2898f866e6813a406181e5b06f 100644 --- a/aidex-controller/src/main/java/com/aidex/web/controller/system/SysUserController.java +++ b/aidex-controller/src/main/java/com/aidex/web/controller/system/SysUserController.java @@ -21,6 +21,7 @@ import com.aidex.system.service.ISysUserService; import com.aidex.system.service.SysPostService; import com.alibaba.fastjson.JSONObject; import com.github.pagehelper.PageInfo; +import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; @@ -36,13 +37,12 @@ import java.util.stream.Collectors; /** * 用户信息 - * + * * @author ruoyi */ @RestController @RequestMapping("/system/user") -public class SysUserController extends BaseController -{ +public class SysUserController extends BaseController { @Autowired private ISysUserService userService; @@ -60,8 +60,7 @@ public class SysUserController extends BaseController */ @PreAuthorize("@ss.hasPermi('system:user:list')") @GetMapping("/list") - public R page(SysUser user, HttpServletRequest request, HttpServletResponse response) - { + public R page(SysUser user, HttpServletRequest request, HttpServletResponse response) { user.setPage(new PageDomain(request, response)); return R.data(userService.findPage(user)); } @@ -69,8 +68,7 @@ public class SysUserController extends BaseController @Log(title = "用户管理", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('system:user:export')") @GetMapping("/export") - public R export(SysUser user) - { + public R export(SysUser user) { List list = userService.findList(user); ExcelUtil util = new ExcelUtil(SysUser.class); return util.exportExcel(list, "用户数据"); @@ -79,8 +77,7 @@ public class SysUserController extends BaseController @Log(title = "用户管理", businessType = BusinessType.IMPORT) @PreAuthorize("@ss.hasPermi('system:user:import')") @PostMapping("/importData") - public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception - { + public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { ExcelUtil util = new ExcelUtil(SysUser.class); List userList = util.importExcel(file.getInputStream()); LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest()); @@ -90,8 +87,7 @@ public class SysUserController extends BaseController } @GetMapping("/importTemplate") - public R importTemplate() - { + public R importTemplate() { ExcelUtil util = new ExcelUtil(SysUser.class); return util.importTemplateExcel("用户数据"); } @@ -100,15 +96,13 @@ public class SysUserController extends BaseController * 根据用户编号获取详细信息 */ @PreAuthorize("@ss.hasPermi('system:user:query')") - @GetMapping(value = { "/", "/{userId}" }) - public AjaxResult getInfo(@PathVariable(value = "userId", required = false) String userId) - { + @GetMapping(value = {"/", "/{userId}"}) + public AjaxResult getInfo(@PathVariable(value = "userId", required = false) String userId) { AjaxResult ajax = AjaxResult.success(); List roles = roleService.selectRoleAll(); ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList())); ajax.put("posts", postService.findList(new SysPost())); - if (StringUtils.isNotNull(userId)) - { + if (StringUtils.isNotNull(userId)) { ajax.put(AjaxResult.DATA_TAG, userService.get(userId)); ajax.put("postIds", postService.selectPostListByUserId(userId)); ajax.put("roleIds", roleService.selectRoleListByUserId(userId)); @@ -122,8 +116,7 @@ public class SysUserController extends BaseController @PreAuthorize("@ss.hasPermi('system:user:add')") @Log(title = "用户管理", businessType = BusinessType.INSERT) @PostMapping - public R add(@Validated @RequestBody SysUser user) - { + public R add(@Validated @RequestBody SysUser user) { return R.status(userService.insertUser(user)); } @@ -133,8 +126,7 @@ public class SysUserController extends BaseController @PreAuthorize("@ss.hasPermi('system:user:edit')") @Log(title = "用户管理", businessType = BusinessType.UPDATE) @PutMapping - public R edit(@Validated @RequestBody SysUser user) - { + public R edit(@Validated @RequestBody SysUser user) { userService.checkUserAllowed(user); return R.status(userService.updateUser(user)); } @@ -145,8 +137,10 @@ public class SysUserController extends BaseController @PreAuthorize("@ss.hasPermi('system:user:remove')") @Log(title = "用户管理", businessType = BusinessType.DELETE) @DeleteMapping("/{userIds}") - public R remove(@PathVariable("userIds") String[] userIds) - { + public R remove(@PathVariable("userIds") String[] userIds) { + if (ArrayUtils.contains(userIds, getUserId())) { + return R.fail("当前用户不能删除"); + } return R.status(userService.deleteUserByIds(userIds)); } @@ -156,8 +150,7 @@ public class SysUserController extends BaseController @PreAuthorize("@ss.hasPermi('system:user:resetPwd')") @Log(title = "用户管理", businessType = BusinessType.UPDATE) @PutMapping("/resetPwd") - public R resetPwd(@RequestBody SysUser user) - { + public R resetPwd(@RequestBody SysUser user) { userService.checkUserAllowed(user); user.setPassword(SecurityUtils.encryptPassword(user.getPassword())); user.setUpdateBy(SecurityUtils.getUsername()); @@ -170,12 +163,12 @@ public class SysUserController extends BaseController @PreAuthorize("@ss.hasPermi('system:user:edit')") @Log(title = "用户管理", businessType = BusinessType.UPDATE) @PutMapping("/changeStatus") - public R changeStatus(@RequestBody SysUser user) - { + public R changeStatus(@RequestBody SysUser user) { userService.checkUserAllowed(user); user.setUpdateBy(SecurityUtils.getUsername()); return R.status(userService.updateUserStatus(user)); } + /** * 校验角色编码是否存在 */ @@ -183,15 +176,16 @@ public class SysUserController extends BaseController @Log(title = "用户管理", businessType = BusinessType.CHECK) @GetMapping("/checkUserNameUnique") public R checkUserNameUnique(SysUser user) { - Map checkMap = new HashMap(1); - try{ + Map checkMap = new HashMap(1); + try { userService.checkUserNameUnique(user); - checkMap.put("code","1"); - }catch (Exception e){ - checkMap.put("code","2"); + checkMap.put("code", "1"); + } catch (Exception e) { + checkMap.put("code", "2"); } return R.data(checkMap); } + /** * 校验角色编码是否存在 */ @@ -199,15 +193,16 @@ public class SysUserController extends BaseController @Log(title = "用户管理", businessType = BusinessType.CHECK) @GetMapping("/checkEmailUnique") public R checkEmailUnique(SysUser user) { - Map checkMap = new HashMap(1); - try{ + Map checkMap = new HashMap(1); + try { userService.checkEmailUnique(user); - checkMap.put("code","1"); - }catch (Exception e){ - checkMap.put("code","2"); + checkMap.put("code", "1"); + } catch (Exception e) { + checkMap.put("code", "2"); } return R.data(checkMap); } + /** * 校验角色编码是否存在 */ @@ -215,29 +210,30 @@ public class SysUserController extends BaseController @Log(title = "用户管理", businessType = BusinessType.CHECK) @GetMapping("/checkPhoneUnique") public R checkPhoneUnique(SysUser user) { - Map checkMap = new HashMap(1); - try{ + Map checkMap = new HashMap(1); + try { userService.checkPhoneUnique(user); - checkMap.put("code","1"); - }catch (Exception e){ - checkMap.put("code","2"); + checkMap.put("code", "1"); + } catch (Exception e) { + checkMap.put("code", "2"); } return R.data(checkMap); } /** * 通用选人页面根据用户ID + * * @return */ - @PostMapping(value = { "/getUserInfoByIds"}) - public R getUserInfoByIds(@Validated @RequestBody JSONObject userIdsObj) - { - List> sysUserList = userService.getUserInfoByIds(userIdsObj); + @PostMapping(value = {"/getUserInfoByIds"}) + public R getUserInfoByIds(@Validated @RequestBody JSONObject userIdsObj) { + List> sysUserList = userService.getUserInfoByIds(userIdsObj); return R.data(sysUserList); } /** * 获取角色下所有用户信息 + * * @param sysUser * @param request * @param response @@ -245,8 +241,7 @@ public class SysUserController extends BaseController */ @PreAuthorize("@ss.hasPermi('system:user:list')") @GetMapping("/roleUserList") - public R roleUserPage(SysUser sysUser, HttpServletRequest request, HttpServletResponse response) - { + public R roleUserPage(SysUser sysUser, HttpServletRequest request, HttpServletResponse response) { sysUser.setPage(new PageDomain(request, response)); return R.data(userService.findRoleUserPage(sysUser)); } @@ -254,8 +249,7 @@ public class SysUserController extends BaseController @PreAuthorize("@ss.hasPermi('system:user:add')") @Log(title = "用户角色管理", businessType = BusinessType.INSERT) @PostMapping("/addRoleUser") - public R addRoleUser(@Validated @RequestBody SysUserRole sysUserRole) - { + public R addRoleUser(@Validated @RequestBody SysUserRole sysUserRole) { return R.status(userService.insertRoleUser(sysUserRole)); } } diff --git a/aidex-controller/src/main/java/com/aidex/web/core/config/SwaggerConfig.java b/aidex-controller/src/main/java/com/aidex/web/core/config/SwaggerConfig.java index 4fa7e3f04998c6b5e487b707b93c067bbe94b311..18af25302cc2ef9a3a1425c974ceb35a2eb21668 100644 --- a/aidex-controller/src/main/java/com/aidex/web/core/config/SwaggerConfig.java +++ b/aidex-controller/src/main/java/com/aidex/web/core/config/SwaggerConfig.java @@ -1,35 +1,40 @@ package com.aidex.web.core.config; +import java.util.ArrayList; +import java.util.List; + import com.aidex.common.config.AiDexConfig; -import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import io.swagger.annotations.ApiOperation; +import io.swagger.models.auth.In; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.*; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.ApiKey; +import springfox.documentation.service.AuthorizationScope; +import springfox.documentation.service.Contact; +import springfox.documentation.service.SecurityReference; +import springfox.documentation.service.SecurityScheme; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; -import java.util.ArrayList; -import java.util.List; /** * Swagger2的接口配置 - * + * * @author ruoyi */ @Configuration -@EnableSwagger2 public class SwaggerConfig { /** 系统基础配置 */ - @Autowired - private AiDexConfig ruoyiConfig; + @Autowired(required = false) + private AiDexConfig aidexConfig; /** 是否开启swagger */ @Value("${swagger.enabled}") @@ -45,7 +50,7 @@ public class SwaggerConfig @Bean public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) + return new Docket(DocumentationType.OAS_30) // 是否启用Swagger .enable(enabled) // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息) @@ -55,7 +60,7 @@ public class SwaggerConfig // 扫描所有有注解的api,用这种方式更灵活 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) // 扫描指定包中的swagger注解 - // .apis(RequestHandlerSelectors.basePackage("com.aidex.project.tool.swagger")) + // .apis(RequestHandlerSelectors.basePackage("com.ruoyi.project.tool.swagger")) // 扫描所有 .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() @@ -68,10 +73,10 @@ public class SwaggerConfig /** * 安全模式,这里指定token通过Authorization头请求头传递 */ - private List securitySchemes() + private List securitySchemes() { - List apiKeyList = new ArrayList(); - apiKeyList.add(new ApiKey("Authorization", "Authorization", "header")); + List apiKeyList = new ArrayList(); + apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue())); return apiKeyList; } @@ -84,7 +89,7 @@ public class SwaggerConfig securityContexts.add( SecurityContext.builder() .securityReferences(defaultAuth()) - .forPaths(PathSelectors.regex("^(?!auth).*$")) + .operationSelector(o -> o.requestMappingPattern().matches("/.*")) .build()); return securityContexts; } @@ -110,13 +115,13 @@ public class SwaggerConfig // 用ApiInfoBuilder进行定制 return new ApiInfoBuilder() // 设置标题 - .title("标题:管理系统_接口文档") + .title("标题:若依管理系统_接口文档") // 描述 .description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...") // 作者信息 - .contact(new Contact(ruoyiConfig.getName(), null, null)) + .contact(new Contact(aidexConfig.getName(), null, null)) // 版本 - .version("版本号:" + ruoyiConfig.getVersion()) + .version("版本号:" + aidexConfig.getVersion()) .build(); } } diff --git a/aidex-framework/src/main/java/com/aidex/framework/aspectj/LogAspect.java b/aidex-framework/src/main/java/com/aidex/framework/aspectj/LogAspect.java index a590b25f63286262c9f0915319841fe1f53b25a5..fa7e576dc26d54ee606da7c90a4cf93ca3659785 100644 --- a/aidex-framework/src/main/java/com/aidex/framework/aspectj/LogAspect.java +++ b/aidex-framework/src/main/java/com/aidex/framework/aspectj/LogAspect.java @@ -20,6 +20,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; +import org.springframework.validation.BindingResult; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.HandlerMapping; import com.alibaba.fastjson.JSON; @@ -200,11 +201,20 @@ public class LogAspect { */ private String argsArrayToString(Object[] paramsArray) { String params = ""; - if (paramsArray != null && paramsArray.length > 0) { - for (int i = 0; i < paramsArray.length; i++) { - if (!isFilterObject(paramsArray[i])) { - Object jsonObj = JSON.toJSON(paramsArray[i]); - params += jsonObj.toString() + " "; + if (paramsArray != null && paramsArray.length > 0) + { + for (Object o : paramsArray) + { + if (StringUtils.isNotNull(o) && !isFilterObject(o)) + { + try + { + Object jsonObj = JSON.toJSON(o); + params += jsonObj.toString() + " "; + } + catch (Exception e) + { + } } } } @@ -234,6 +244,7 @@ public class LogAspect { return entry.getValue() instanceof MultipartFile; } } - return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse; + return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse + || o instanceof BindingResult; } } diff --git a/aidex-framework/src/main/java/com/aidex/framework/config/AnonymousAccess.java b/aidex-framework/src/main/java/com/aidex/framework/config/AnonymousAccess.java new file mode 100644 index 0000000000000000000000000000000000000000..7308d6a76bdd5303795893272b8b907e833271f1 --- /dev/null +++ b/aidex-framework/src/main/java/com/aidex/framework/config/AnonymousAccess.java @@ -0,0 +1,11 @@ +package com.aidex.framework.config; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface AnonymousAccess { +} \ No newline at end of file diff --git a/aidex-framework/src/main/java/com/aidex/framework/config/FilterConfig.java b/aidex-framework/src/main/java/com/aidex/framework/config/FilterConfig.java index 3191413d5cfe1879e99f24c28afca764433846f2..f46cc6d5d9742fee5e622fae0619737f6ccf13bf 100644 --- a/aidex-framework/src/main/java/com/aidex/framework/config/FilterConfig.java +++ b/aidex-framework/src/main/java/com/aidex/framework/config/FilterConfig.java @@ -3,13 +3,15 @@ package com.aidex.framework.config; import java.util.HashMap; import java.util.Map; import javax.servlet.DispatcherType; + +import com.aidex.common.filter.RepeatableFilter; +import com.aidex.common.filter.XssFilter; +import com.aidex.common.utils.StringUtils; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.aidex.common.filter.RepeatableFilter; -import com.aidex.common.filter.XssFilter; -import com.aidex.common.utils.StringUtils; /** * Filter配置 @@ -17,11 +19,9 @@ import com.aidex.common.utils.StringUtils; * @author ruoyi */ @Configuration +@ConditionalOnProperty(value = "xss.enabled", havingValue = "true") public class FilterConfig { - @Value("${xss.enabled}") - private String enabled; - @Value("${xss.excludes}") private String excludes; @@ -38,9 +38,8 @@ public class FilterConfig registration.addUrlPatterns(StringUtils.split(urlPatterns, ",")); registration.setName("xssFilter"); registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE); - Map initParameters = new HashMap(16); + Map initParameters = new HashMap(); initParameters.put("excludes", excludes); - initParameters.put("enabled", enabled); registration.setInitParameters(initParameters); return registration; } @@ -57,4 +56,4 @@ public class FilterConfig return registration; } -} +} \ No newline at end of file diff --git a/aidex-framework/src/main/java/com/aidex/framework/config/ResourcesConfig.java b/aidex-framework/src/main/java/com/aidex/framework/config/ResourcesConfig.java index ee662b69f326c7e47393d6ff33048efdb2c237fd..615a9387433002c551c867865f34e4d8828acfd1 100644 --- a/aidex-framework/src/main/java/com/aidex/framework/config/ResourcesConfig.java +++ b/aidex-framework/src/main/java/com/aidex/framework/config/ResourcesConfig.java @@ -1,5 +1,8 @@ package com.aidex.framework.config; +import com.aidex.common.config.AiDexConfig; +import com.aidex.common.constant.Constants; +import com.aidex.framework.interceptor.RepeatSubmitInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -9,19 +12,16 @@ import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import com.aidex.common.config.AiDexConfig; -import com.aidex.common.constant.Constants; -import com.aidex.framework.interceptor.RepeatSubmitInterceptor; /** * 通用配置 - * + * * @author ruoyi */ @Configuration public class ResourcesConfig implements WebMvcConfigurer { - @Autowired + @Autowired(required = false) private RepeatSubmitInterceptor repeatSubmitInterceptor; @Override @@ -31,8 +31,7 @@ public class ResourcesConfig implements WebMvcConfigurer registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + AiDexConfig.getProfile() + "/"); /** swagger配置 */ - registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); + registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/"); } /** diff --git a/aidex-framework/src/main/java/com/aidex/framework/config/SecurityConfig.java b/aidex-framework/src/main/java/com/aidex/framework/config/SecurityConfig.java index dee3bde47533a0d893cc9e0cff17fe0656f1dddc..40329aa1fb482a73a1a4101f7e2be437ac775585 100644 --- a/aidex-framework/src/main/java/com/aidex/framework/config/SecurityConfig.java +++ b/aidex-framework/src/main/java/com/aidex/framework/config/SecurityConfig.java @@ -1,6 +1,11 @@ package com.aidex.framework.config; +import com.aidex.common.utils.spring.SpringUtils; +import com.aidex.framework.security.filter.JwtAuthenticationTokenFilter; +import com.aidex.framework.security.handle.AuthenticationEntryPointImpl; +import com.aidex.framework.security.handle.LogoutSuccessHandlerImpl; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; @@ -14,24 +19,27 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.logout.LogoutFilter; import org.springframework.web.filter.CorsFilter; -import com.aidex.framework.security.filter.JwtAuthenticationTokenFilter; -import com.aidex.framework.security.handle.AuthenticationEntryPointImpl; -import com.aidex.framework.security.handle.LogoutSuccessHandlerImpl; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; /** * spring security配置 - * + * * @author ruoyi */ @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) -public class SecurityConfig extends WebSecurityConfigurerAdapter -{ +public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * 自定义用户认证逻辑 */ - @Autowired + @Autowired(required = false) private UserDetailsService userDetailsService; - + /** * 认证失败处理类 */ @@ -55,7 +63,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter */ @Autowired private CorsFilter corsFilter; - + /** * 解决 无法直接注入 AuthenticationManager * @@ -64,8 +72,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter */ @Bean @Override - public AuthenticationManager authenticationManagerBean() throws Exception - { + public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @@ -85,8 +92,18 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter * authenticated | 用户登录后可访问 */ @Override - protected void configure(HttpSecurity httpSecurity) throws Exception - { + protected void configure(HttpSecurity httpSecurity) throws Exception { + ApplicationContext applicationContext = SpringUtils.getApplicationContext(); + //查找匿名标记URL + Map handlerMethods = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods(); + Set anonymousUrls = new HashSet(); + for (Map.Entry infoEntry : handlerMethods.entrySet()) { + HandlerMethod handlerMethod = infoEntry.getValue(); + AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class); + if (anonymousAccess != null) { + anonymousUrls.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); + } + } httpSecurity // CSRF禁用,因为不使用session .csrf().disable() @@ -96,15 +113,16 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() // 过滤请求 .authorizeRequests() - // 对于登录login 验证码captchaImage 允许匿名访问 - .antMatchers("/login", "/captchaImage","/sendSms").anonymous() + // 对于登录login 注册register 验证码captchaImage 发送短信 允许匿名访问 + .antMatchers("/login", "/register", "/captchaImage", "/sendSms").anonymous() .antMatchers( HttpMethod.GET, + "/", "/*.html", "/**/*.html", "/**/*.css", - "/**/*.js" - ).permitAll() + "/**/*.js", + "/profile/**").permitAll() .antMatchers("/profile/**").anonymous() .antMatchers("/common/download**").anonymous() .antMatchers("/common/download/resource**").anonymous() @@ -113,6 +131,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter .antMatchers("/webjars/**").anonymous() .antMatchers("/*/api-docs").anonymous() .antMatchers("/druid/**").anonymous() + .antMatchers(anonymousUrls.toArray(new String[0])).anonymous() // 除上面外的所有请求全部需要鉴权认证 .anyRequest().authenticated() .and() @@ -125,13 +144,12 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class); } - + /** * 强散列哈希加密实现 */ @Bean - public BCryptPasswordEncoder bCryptPasswordEncoder() - { + public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @@ -139,8 +157,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter * 身份认证接口 */ @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception - { + protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); } } diff --git a/aidex-framework/src/main/java/com/aidex/framework/interceptor/RepeatSubmitInterceptor.java b/aidex-framework/src/main/java/com/aidex/framework/interceptor/RepeatSubmitInterceptor.java index 36ea7aa98c21b4e75aee5a9d5ddbdd271e9f7d2c..e720cdf02a8aafee19399c18dcefd260a4e05cb3 100644 --- a/aidex-framework/src/main/java/com/aidex/framework/interceptor/RepeatSubmitInterceptor.java +++ b/aidex-framework/src/main/java/com/aidex/framework/interceptor/RepeatSubmitInterceptor.java @@ -29,7 +29,7 @@ public abstract class RepeatSubmitInterceptor extends HandlerInterceptorAdapter RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class); if (annotation != null) { - if (this.isRepeatSubmit(request)) + if (this.isRepeatSubmit(request,annotation)) { AjaxResult ajaxResult = AjaxResult.error("不允许重复提交,请稍后再试"); ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult)); @@ -51,5 +51,5 @@ public abstract class RepeatSubmitInterceptor extends HandlerInterceptorAdapter * @return * @throws Exception */ - public abstract boolean isRepeatSubmit(HttpServletRequest request); + public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation); } diff --git a/aidex-framework/src/main/java/com/aidex/framework/interceptor/impl/SameUrlDataInterceptor.java b/aidex-framework/src/main/java/com/aidex/framework/interceptor/impl/SameUrlDataInterceptor.java index 29e4eac7d19b31418e465117067cde49411ffc5b..a311b6100981dd639908657644fd210cf023aaa2 100644 --- a/aidex-framework/src/main/java/com/aidex/framework/interceptor/impl/SameUrlDataInterceptor.java +++ b/aidex-framework/src/main/java/com/aidex/framework/interceptor/impl/SameUrlDataInterceptor.java @@ -4,6 +4,8 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; + +import com.aidex.common.annotation.RepeatSubmit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -35,21 +37,10 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor @Autowired private RedisCache redisCache; - /** - * 间隔时间,单位:秒 默认10秒 - * - * 两次相同参数的请求,如果间隔时间大于该参数,系统不会认定为重复提交的数据 - */ - private int intervalTime = 10; - - public void setIntervalTime(int intervalTime) - { - this.intervalTime = intervalTime; - } @SuppressWarnings("unchecked") @Override - public boolean isRepeatSubmit(HttpServletRequest request) + public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) { String nowParams = ""; if (request instanceof RepeatedlyRequestWrapper) @@ -78,16 +69,16 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor } // 唯一标识(指定key + 消息头) - String cache_repeat_key = Constants.REPEAT_SUBMIT_KEY + submitKey; + String cacheRepeatKey = Constants.REPEAT_SUBMIT_KEY + submitKey; - Object sessionObj = redisCache.getCacheObject(cache_repeat_key); + Object sessionObj = redisCache.getCacheObject(cacheRepeatKey); if (sessionObj != null) { Map sessionMap = (Map) sessionObj; if (sessionMap.containsKey(url)) { Map preDataMap = (Map) sessionMap.get(url); - if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap)) + if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, annotation.interval())) { return true; } @@ -95,7 +86,7 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor } Map cacheMap = new HashMap(16); cacheMap.put(url, nowDataMap); - redisCache.setCacheObject(cache_repeat_key, cacheMap, intervalTime, TimeUnit.SECONDS); + redisCache.setCacheObject(cacheRepeatKey, cacheMap, annotation.interval(), TimeUnit.SECONDS); return false; } @@ -112,12 +103,11 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor /** * 判断两次间隔时间 */ - private boolean compareTime(Map nowMap, Map preMap) + private boolean compareTime(Map nowMap, Map preMap, int interval) { long time1 = (Long) nowMap.get(REPEAT_TIME); long time2 = (Long) preMap.get(REPEAT_TIME); - if ((time1 - time2) < (this.intervalTime * 1000)) - { + if ((time1 - time2) < interval) { return true; } return false; diff --git a/aidex-framework/src/main/java/com/aidex/framework/manager/factory/AsyncFactory.java b/aidex-framework/src/main/java/com/aidex/framework/manager/factory/AsyncFactory.java index ac466cfd29adaa3742de3006a619e5e14ea8da18..9b0d61af65103512d23ece73c4160f32f65bbb57 100644 --- a/aidex-framework/src/main/java/com/aidex/framework/manager/factory/AsyncFactory.java +++ b/aidex-framework/src/main/java/com/aidex/framework/manager/factory/AsyncFactory.java @@ -3,6 +3,7 @@ package com.aidex.framework.manager.factory; import com.aidex.common.constant.Constants; import com.aidex.common.utils.LogUtils; import com.aidex.common.utils.ServletUtils; +import com.aidex.common.utils.StringUtils; import com.aidex.common.utils.ip.AddressUtils; import com.aidex.common.utils.ip.IpUtils; import com.aidex.common.utils.spring.SpringUtils; @@ -18,32 +19,28 @@ import java.util.TimerTask; /** * 异步工厂(产生任务用) - * + * * @author ruoyi */ -public class AsyncFactory -{ +public class AsyncFactory { private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user"); /** * 记录登录信息 - * + * * @param username 用户名 - * @param status 状态 - * @param message 消息 - * @param args 列表 + * @param status 状态 + * @param message 消息 + * @param args 列表 * @return 任务task */ public static TimerTask recordLogininfor(final String username, final String status, final String message, - final Object... args) - { + final Object... args) { final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); final String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); - return new TimerTask() - { + return new TimerTask() { @Override - public void run() - { + public void run() { String address = AddressUtils.getRealAddressByIP(ip); StringBuilder s = new StringBuilder(); s.append(LogUtils.getBlock(ip)); @@ -66,12 +63,9 @@ public class AsyncFactory sysLoginLog.setOs(os); sysLoginLog.setMsg(message); // 日志状态 - if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) - { + if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) { sysLoginLog.setStatus(Constants.SUCCESS); - } - else if (Constants.LOGIN_FAIL.equals(status)) - { + } else if (Constants.LOGIN_FAIL.equals(status)) { sysLoginLog.setStatus(Constants.FAIL); } // 插入数据 @@ -82,17 +76,14 @@ public class AsyncFactory /** * 操作日志记录 - * + * * @param operLog 操作日志信息 * @return 任务task */ - public static TimerTask recordOper(final SysOperLog operLog) - { - return new TimerTask() - { + public static TimerTask recordOper(final SysOperLog operLog) { + return new TimerTask() { @Override - public void run() - { + public void run() { // 远程查询操作地点 operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp())); SpringUtils.getBean(SysOperLogService.class).addOperlog(operLog); diff --git a/aidex-framework/src/main/java/com/aidex/framework/web/exception/GlobalExceptionHandler.java b/aidex-framework/src/main/java/com/aidex/framework/web/exception/GlobalExceptionHandler.java index 3ecee6fa30dad2459cd01a608e19ab51e5017faa..009e72c75f177b8bec0c1e9f26d370ac305e4583 100644 --- a/aidex-framework/src/main/java/com/aidex/framework/web/exception/GlobalExceptionHandler.java +++ b/aidex-framework/src/main/java/com/aidex/framework/web/exception/GlobalExceptionHandler.java @@ -1,24 +1,24 @@ package com.aidex.framework.web.exception; import com.aidex.common.core.domain.R; -import com.aidex.common.exception.BizException; +import com.aidex.common.exception.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AccountExpiredException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.validation.BindException; +import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; import com.aidex.common.constant.HttpStatus; import com.aidex.common.core.domain.AjaxResult; -import com.aidex.common.exception.BaseException; -import com.aidex.common.exception.CustomException; -import com.aidex.common.exception.DemoModeException; import com.aidex.common.utils.StringUtils; +import javax.servlet.http.HttpServletRequest; + /** * 全局异常处理器 * @@ -26,14 +26,93 @@ import com.aidex.common.utils.StringUtils; */ @RestControllerAdvice public class GlobalExceptionHandler { + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + /** + * 权限校验异常 + */ + @ExceptionHandler(AccessDeniedException.class) + public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage()); + return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权"); + } + + /** + * 请求方式不支持 + */ + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, + HttpServletRequest request) { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod()); + return AjaxResult.error(e.getMessage()); + } + + /** + * 业务异常 + */ + @ExceptionHandler(SysException.class) + public AjaxResult handleServiceException(SysException e, HttpServletRequest request) { + log.error(e.getMessage(), e); + String code = e.getCode(); + return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage()); + } + + /** + * 拦截未知的运行时异常 + */ + @ExceptionHandler(RuntimeException.class) + public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',发生未知异常.", requestURI, e); + return AjaxResult.error(e.getMessage()); + } + + /** + * 系统异常 + */ + @ExceptionHandler(Exception.class) + public AjaxResult handleException(Exception e, HttpServletRequest request) { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',发生系统异常.", requestURI, e); + return AjaxResult.error(e.getMessage()); + } + + /** + * 自定义验证异常 + */ + @ExceptionHandler(BindException.class) + public AjaxResult handleBindException(BindException e) { + log.error(e.getMessage(), e); + String message = e.getAllErrors().get(0).getDefaultMessage(); + return AjaxResult.error(message); + } + + /** + * 自定义验证异常 + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { + log.error(e.getMessage(), e); + String message = e.getBindingResult().getFieldError().getDefaultMessage(); + return AjaxResult.error(message); + } + + /** + * 演示模式异常 + */ + @ExceptionHandler(DemoModeException.class) + public AjaxResult handleDemoModeException(DemoModeException e) { + return AjaxResult.error("演示模式,不允许操作"); + } + /** * 基础异常 */ @ExceptionHandler(BaseException.class) public AjaxResult baseException(BaseException e) { - e.printStackTrace(); return AjaxResult.error(e.getMessage()); } @@ -71,13 +150,6 @@ public class GlobalExceptionHandler { return AjaxResult.error(HttpStatus.NOT_FOUND, "路径不存在,请检查路径是否正确"); } - @ExceptionHandler(AccessDeniedException.class) - public AjaxResult handleAuthorizationException(AccessDeniedException e) { - log.error(e.getMessage()); - e.printStackTrace(); - return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权"); - } - @ExceptionHandler(AccountExpiredException.class) public AjaxResult handleAccountExpiredException(AccountExpiredException e) { log.error(e.getMessage(), e); @@ -92,39 +164,4 @@ public class GlobalExceptionHandler { return AjaxResult.error(e.getMessage()); } - @ExceptionHandler(Exception.class) - public AjaxResult handleException(Exception e) { - log.error(e.getMessage(), e); - return AjaxResult.error(e.getMessage()); - } - - /** - * 自定义验证异常 - */ - @ExceptionHandler(BindException.class) - public AjaxResult validatedBindException(BindException e) { - log.error(e.getMessage(), e); - e.printStackTrace(); - String message = e.getAllErrors().get(0).getDefaultMessage(); - return AjaxResult.error(message); - } - - /** - * 自定义验证异常 - */ - @ExceptionHandler(MethodArgumentNotValidException.class) - public Object validExceptionHandler(MethodArgumentNotValidException e) { - log.error(e.getMessage(), e); - e.printStackTrace(); - String message = e.getBindingResult().getFieldError().getDefaultMessage(); - return AjaxResult.error(message); - } - - /** - * 演示模式异常 - */ - @ExceptionHandler(DemoModeException.class) - public AjaxResult demoModeException(DemoModeException e) { - return AjaxResult.error("演示模式,不允许操作"); - } } diff --git a/aidex-framework/src/main/java/com/aidex/framework/web/service/SysLoginService.java b/aidex-framework/src/main/java/com/aidex/framework/web/service/SysLoginService.java index 3af5218846320ff76e351d0c949699ac646d5221..954e04add1660a4c716daec4b238a1c5e2c85e5c 100644 --- a/aidex-framework/src/main/java/com/aidex/framework/web/service/SysLoginService.java +++ b/aidex-framework/src/main/java/com/aidex/framework/web/service/SysLoginService.java @@ -1,31 +1,36 @@ package com.aidex.framework.web.service; -import javax.annotation.Resource; - +import com.aidex.common.constant.Constants; +import com.aidex.common.core.domain.entity.SysUser; import com.aidex.common.core.domain.entity.SysUserMenu; +import com.aidex.common.core.domain.model.LoginUser; +import com.aidex.common.core.redis.RedisCache; import com.aidex.common.exception.ExpireException; +import com.aidex.common.exception.user.CaptchaException; +import com.aidex.common.exception.user.CaptchaExpireException; +import com.aidex.common.exception.user.UserPasswordNotMatchException; +import com.aidex.common.utils.DateUtils; +import com.aidex.common.utils.MessageUtils; +import com.aidex.common.utils.ServletUtils; import com.aidex.common.utils.StringUtils; -import org.springframework.beans.factory.annotation.Value; +import com.aidex.common.utils.ip.IpUtils; +import com.aidex.framework.cache.ConfigUtils; import com.aidex.framework.manager.AsyncManager; +import com.aidex.framework.manager.factory.AsyncFactory; +import com.aidex.system.service.ISysUserService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; -import com.aidex.common.constant.Constants; -import com.aidex.common.core.domain.model.LoginUser; -import com.aidex.common.core.redis.RedisCache; -import com.aidex.common.exception.CustomException; -import com.aidex.common.exception.user.CaptchaException; -import com.aidex.common.exception.user.CaptchaExpireException; -import com.aidex.common.exception.user.UserPasswordNotMatchException; -import com.aidex.common.utils.MessageUtils; -import com.aidex.framework.manager.factory.AsyncFactory; + +import javax.annotation.Resource; /** * 登录校验方法 - * + * * @author ruoyi */ @Component @@ -33,19 +38,25 @@ public class SysLoginService { @Autowired private TokenService tokenService; + @Autowired private SysUserMenu sysDeptVo; + @Resource private AuthenticationManager authenticationManager; @Autowired private RedisCache redisCache; + + @Autowired + private ISysUserService userService; + // 是否允许账户多终端同时登录(true允许 false不允许) @Value("${token.soloLogin}") private boolean soloLogin; /** * 登录验证 - * + * * @param username 用户名 * @param password 密码 * @param code 验证码 @@ -54,18 +65,10 @@ public class SysLoginService */ public String login(String username, String password, String code, String uuid) { - String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid; - String captcha = redisCache.getCacheObject(verifyKey); - redisCache.deleteObject(verifyKey); - if (captcha == null) - { - AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); - throw new CaptchaExpireException(); - } - if (!code.equalsIgnoreCase(captcha)) + // 验证码开关 + if (ConfigUtils.getConfigBooleanValueByKey("sys.captcha.onOff",true)) { - AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); - throw new CaptchaException(); + validateCaptcha(username, code, uuid); } // 用户验证 Authentication authentication = null; @@ -103,6 +106,47 @@ public class SysLoginService // 生成token String token = tokenService.createToken(loginUser); AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); + recordLoginInfo(loginUser.getUser().getId()); return token; } + + /** + * 校验验证码 + * + * @param username 用户名 + * @param code 验证码 + * @param uuid 唯一标识 + * @return 结果 + */ + public void validateCaptcha(String username, String code, String uuid) + { + String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid; + String captcha = redisCache.getCacheObject(verifyKey); + redisCache.deleteObject(verifyKey); + if (captcha == null) + { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); + throw new CaptchaExpireException(); + } + if (!code.equalsIgnoreCase(captcha)) + { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); + throw new CaptchaException(); + } + } + + /** + * 记录登录信息 + * + * @param userId 用户ID + */ + public void recordLoginInfo(String userId) + { + SysUser sysUser = new SysUser(); + sysUser.setId(userId); + sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest())); + sysUser.setLoginDate(DateUtils.getNowDate()); + userService.updateUserLoginInfo(sysUser); + } + } diff --git a/aidex-framework/src/main/java/com/aidex/framework/web/service/SysRegisterService.java b/aidex-framework/src/main/java/com/aidex/framework/web/service/SysRegisterService.java index 1c3511f40dbf062513beffe4371c095a19ef42ce..eb93463aa7b258628b711aa947c0a1a020ab0e5c 100644 --- a/aidex-framework/src/main/java/com/aidex/framework/web/service/SysRegisterService.java +++ b/aidex-framework/src/main/java/com/aidex/framework/web/service/SysRegisterService.java @@ -26,6 +26,7 @@ import org.springframework.util.StringUtils; */ @Component public class SysRegisterService { + @Autowired private ISysUserService userService; @@ -37,13 +38,14 @@ public class SysRegisterService { /** * 注册用户 + * * @param registerBody * @return */ public String register(RegisterBody registerBody) { String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword(); // 验证码开关 - if (ConfigUtils.getConfigBooleanValueByKey("sys.account.captchaOnOff",Boolean.TRUE)) { + if (ConfigUtils.getConfigBooleanValueByKey("sys.account.captchaOnOff", Boolean.TRUE)) { validateCaptcha(username, registerBody.getCode(), registerBody.getUuid()); } if (StringUtils.isEmpty(username)) { @@ -67,7 +69,7 @@ public class SysRegisterService { msg = "保存用户'" + username + "'失败,注册账号已存在"; e.printStackTrace(); } - if(!StringUtils.hasLength(msg)){ + if (!StringUtils.hasLength(msg)) { SysUser sysUser = new SysUser(); sysUser.setUserName(username); sysUser.setNickName(username); diff --git a/aidex-framework/src/main/java/com/aidex/framework/web/service/TokenService.java b/aidex-framework/src/main/java/com/aidex/framework/web/service/TokenService.java index 55ff7541b802bdf45aaad64e3ae8bc5cf203dfff..eeb96793b18c0e502f50c598ee226eee0b6de320 100644 --- a/aidex-framework/src/main/java/com/aidex/framework/web/service/TokenService.java +++ b/aidex-framework/src/main/java/com/aidex/framework/web/service/TokenService.java @@ -27,8 +27,7 @@ import io.jsonwebtoken.SignatureAlgorithm; * @author ruoyi */ @Component -public class TokenService -{ +public class TokenService { // 令牌自定义标识 @Value("${token.header}") private String header; @@ -53,23 +52,26 @@ public class TokenService @Autowired private RedisCache redisCache; + /** * 获取用户身份信息 * * @return 用户信息 */ - public LoginUser getLoginUser(HttpServletRequest request) - { + public LoginUser getLoginUser(HttpServletRequest request) { // 获取请求携带的令牌 String token = getToken(request); - if (StringUtils.isNotEmpty(token)) - { - Claims claims = parseToken(token); - // 解析对应的权限以及用户信息 - String uuid = (String) claims.get(Constants.LOGIN_USER_KEY); - String userKey = getTokenKey(uuid); - LoginUser user = redisCache.getCacheObject(userKey); - return user; + if (StringUtils.isNotEmpty(token)) { + try { + Claims claims = parseToken(token); + // 解析对应的权限以及用户信息 + String uuid = (String) claims.get(Constants.LOGIN_USER_KEY); + String userKey = getTokenKey(uuid); + LoginUser user = redisCache.getCacheObject(userKey); + return user; + } catch (Exception e) { + e.printStackTrace(); + } } return null; } @@ -77,10 +79,8 @@ public class TokenService /** * 设置用户身份信息 */ - public void setLoginUser(LoginUser loginUser) - { - if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) - { + public void setLoginUser(LoginUser loginUser) { + if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) { refreshToken(loginUser); } } @@ -88,32 +88,29 @@ public class TokenService /** * 删除用户身份信息 */ - public void delLoginUser(String token,String userId) - { - if (StringUtils.isNotEmpty(token)) - { + public void delLoginUser(String token, String userId) { + if (StringUtils.isNotEmpty(token)) { String userKey = getTokenKey(token); redisCache.deleteObject(userKey); } - if (!soloLogin && StringUtils.isNotNull(userId)) - { + if (!soloLogin && StringUtils.isNotNull(userId)) { String userIdKey = getUserIdKey(userId); redisCache.deleteObject(userIdKey); } } - private String getUserIdKey(String userId) - { + + private String getUserIdKey(String userId) { return Constants.LOGIN_USERID_KEY + userId; } + /** * 创建令牌 * * @param loginUser 用户信息 * @return 令牌 */ - public String createToken(LoginUser loginUser) - { + public String createToken(LoginUser loginUser) { String token = IdUtils.fastUUID(); loginUser.setToken(token); setUserAgent(loginUser); @@ -129,12 +126,10 @@ public class TokenService * @param loginUser * @return 令牌 */ - public void verifyToken(LoginUser loginUser) - { + public void verifyToken(LoginUser loginUser) { long expireTime = loginUser.getExpireTime(); long currentTime = System.currentTimeMillis(); - if (expireTime - currentTime <= MILLIS_MINUTE_TEN) - { + if (expireTime - currentTime <= MILLIS_MINUTE_TEN) { refreshToken(loginUser); } } @@ -144,15 +139,13 @@ public class TokenService * * @param loginUser 登录信息 */ - public void refreshToken(LoginUser loginUser) - { + public void refreshToken(LoginUser loginUser) { loginUser.setLoginTime(System.currentTimeMillis()); loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE); // 根据uuid将loginUser缓存 String userKey = getTokenKey(loginUser.getToken()); redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES); - if (!soloLogin) - { + if (!soloLogin) { // 缓存用户唯一标识,防止同一帐号,同时登录 String userIdKey = getUserIdKey(loginUser.getUser().getId()); redisCache.setCacheObject(userIdKey, userKey, expireTime, TimeUnit.MINUTES); @@ -164,8 +157,7 @@ public class TokenService * * @param loginUser 登录信息 */ - public void setUserAgent(LoginUser loginUser) - { + public void setUserAgent(LoginUser loginUser) { UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); loginUser.setMenuPermissions(loginUser.getUser()); @@ -181,8 +173,7 @@ public class TokenService * @param claims 数据声明 * @return 令牌 */ - private String createToken(Map claims) - { + private String createToken(Map claims) { String token = Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS512, secret).compact(); @@ -195,8 +186,7 @@ public class TokenService * @param token 令牌 * @return 数据声明 */ - private Claims parseToken(String token) - { + private Claims parseToken(String token) { return Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) @@ -209,8 +199,7 @@ public class TokenService * @param token 令牌 * @return 用户名 */ - public String getUsernameFromToken(String token) - { + public String getUsernameFromToken(String token) { Claims claims = parseToken(token); return claims.getSubject(); } @@ -221,18 +210,15 @@ public class TokenService * @param request * @return token */ - private String getToken(HttpServletRequest request) - { + private String getToken(HttpServletRequest request) { String token = request.getHeader(header); - if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) - { + if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) { token = token.replace(Constants.TOKEN_PREFIX, ""); } return token; } - private String getTokenKey(String uuid) - { + private String getTokenKey(String uuid) { return Constants.LOGIN_TOKEN_KEY + uuid; } } diff --git a/aidex-generator/pom.xml b/aidex-generator/pom.xml index 0c94a9b1ae2a3dec4d5b4b554d96b2fa30f560c6..afd68dece35197b678dda533a32fa6d7e4965ffc 100644 --- a/aidex-generator/pom.xml +++ b/aidex-generator/pom.xml @@ -22,6 +22,11 @@ org.apache.velocity velocity + + + commons-collections + commons-collections + diff --git a/aidex-generator/src/main/java/com/aidex/generator/controller/GenController.java b/aidex-generator/src/main/java/com/aidex/generator/controller/GenController.java index a7a0f8bfa62e9733521b86a978748ad08ee4a9bb..20f39dcbcf4c6fc42a10bf0c4cc46ac01abb5ce8 100644 --- a/aidex-generator/src/main/java/com/aidex/generator/controller/GenController.java +++ b/aidex-generator/src/main/java/com/aidex/generator/controller/GenController.java @@ -105,7 +105,7 @@ public class GenController extends BaseController /** * 导入表结构(保存) */ - @PreAuthorize("@ss.hasPermi('tool:gen:list')") + @PreAuthorize("@ss.hasPermi('tool:gen:import')") @Log(title = "代码生成", businessType = BusinessType.IMPORT) @PostMapping("/importTable") public AjaxResult importTableSave(String tables) diff --git a/aidex-generator/src/main/java/com/aidex/generator/service/GenTableServiceImpl.java b/aidex-generator/src/main/java/com/aidex/generator/service/GenTableServiceImpl.java index 9d45794daac1fcfb9e2b2c94c63dce67fb4ec0da..ebab3309ac7eb976988e9de94f91d0f7679aaa23 100644 --- a/aidex-generator/src/main/java/com/aidex/generator/service/GenTableServiceImpl.java +++ b/aidex-generator/src/main/java/com/aidex/generator/service/GenTableServiceImpl.java @@ -7,7 +7,6 @@ import com.aidex.common.exception.CustomException; import com.aidex.common.exception.SysException; import com.aidex.common.utils.SecurityUtils; import com.aidex.common.utils.StringUtils; -import com.aidex.common.utils.file.FileUtils; import com.aidex.generator.domain.GenTable; import com.aidex.generator.domain.GenTableColumn; import com.aidex.generator.mapper.GenTableColumnMapper; @@ -17,6 +16,7 @@ import com.aidex.generator.util.VelocityInitializer; import com.aidex.generator.util.VelocityUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; +import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; diff --git a/aidex-generator/src/main/java/com/aidex/generator/util/VelocityInitializer.java b/aidex-generator/src/main/java/com/aidex/generator/util/VelocityInitializer.java index e35682a466ff96b9a70982acee7e82f7722c6fe0..346f8404c11c883383e7100e2e8fa077c98976f8 100644 --- a/aidex-generator/src/main/java/com/aidex/generator/util/VelocityInitializer.java +++ b/aidex-generator/src/main/java/com/aidex/generator/util/VelocityInitializer.java @@ -6,7 +6,7 @@ import com.aidex.common.constant.Constants; /** * VelocityEngine工厂 - * + * * @author ruoyi */ public class VelocityInitializer @@ -22,7 +22,7 @@ public class VelocityInitializer // 加载classpath目录下的vm文件 p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); // 定义字符集 - p.setProperty(Velocity.ENCODING_DEFAULT, Constants.UTF8); + p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8); p.setProperty(Velocity.OUTPUT_ENCODING, Constants.UTF8); // 初始化Velocity引擎,指定配置Properties Velocity.init(p); diff --git a/aidex-generator/src/main/resources/vm/crud/controller.java.vm b/aidex-generator/src/main/resources/vm/crud/controller.java.vm index bc6c44748e02fe678aa22266d64a9e9d72b2816a..d7975fb1b55b2a17ff174a7955fa557d5ba072d8 100644 --- a/aidex-generator/src/main/resources/vm/crud/controller.java.vm +++ b/aidex-generator/src/main/resources/vm/crud/controller.java.vm @@ -150,7 +150,7 @@ public class ${ClassName}Controller extends BaseController { List<${ClassName}> list = ${className}Service.findList(${className}); ExcelUtil<${ClassName}> util = new ExcelUtil<${ClassName}>(${ClassName}.class); - return util.exportExcel(list, "${businessName}"); + return util.exportExcel(list, "${functionName}数据"); } } diff --git a/aidex-quartz/src/main/java/com/aidex/quartz/controller/SysJobController.java b/aidex-quartz/src/main/java/com/aidex/quartz/controller/SysJobController.java index 44174065ede244cb4424f3dfd11118e59e8bbb4b..1880837fcdce6ead3166fa3c3277ec56b9b84e3a 100644 --- a/aidex-quartz/src/main/java/com/aidex/quartz/controller/SysJobController.java +++ b/aidex-quartz/src/main/java/com/aidex/quartz/controller/SysJobController.java @@ -1,12 +1,15 @@ package com.aidex.quartz.controller; import com.aidex.common.annotation.Log; +import com.aidex.common.constant.Constants; import com.aidex.common.core.controller.BaseController; import com.aidex.common.core.domain.AjaxResult; +import com.aidex.common.core.domain.R; import com.aidex.common.core.page.TableDataInfo; import com.aidex.common.enums.BusinessType; import com.aidex.common.exception.job.TaskException; -import com.aidex.common.utils.SecurityUtils; +import com.aidex.common.utils.StringUtils; +import com.aidex.common.utils.poi.ExcelUtil; import com.aidex.quartz.domain.SysJob; import com.aidex.quartz.service.ISysJobService; import com.aidex.quartz.util.CronUtils; @@ -19,7 +22,7 @@ import java.util.List; /** * 调度任务信息操作处理 - * + * * @author ruoyi */ @RestController @@ -47,12 +50,11 @@ public class SysJobController extends BaseController @PreAuthorize("@ss.hasPermi('monitor:job:export')") @Log(title = "定时任务", businessType = BusinessType.EXPORT) @GetMapping("/export") - public AjaxResult export(SysJob sysJob) + public R export(SysJob sysJob) { List list = jobService.selectJobList(sysJob); - //ExcelUtil util = new ExcelUtil(SysJob.class); - //return util.exportExcel(null, "定时任务"); - return null; + ExcelUtil util = new ExcelUtil(SysJob.class); + return util.exportExcel(list, "定时任务"); } /** @@ -71,14 +73,26 @@ public class SysJobController extends BaseController @PreAuthorize("@ss.hasPermi('monitor:job:add')") @Log(title = "定时任务", businessType = BusinessType.INSERT) @PostMapping - public AjaxResult add(@RequestBody SysJob sysJob) throws SchedulerException, TaskException + public AjaxResult add(@RequestBody SysJob job) throws SchedulerException, TaskException { - if (!CronUtils.isValid(sysJob.getCronExpression())) + if (!CronUtils.isValid(job.getCronExpression())) { - return AjaxResult.error("cron表达式不正确"); + return error("新增任务'" + job.getJobName() + "'失败,Cron表达式不正确"); } - sysJob.setCreateBy(SecurityUtils.getUsername()); - return toAjax(jobService.insertJob(sysJob)); + else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) + { + return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'rmi://'调用"); + } + else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_LDAP)) + { + return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'ldap://'调用"); + } + else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.HTTP, Constants.HTTPS })) + { + return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'http(s)//'调用"); + } + job.setCreateBy(getUsername()); + return toAjax(jobService.insertJob(job)); } /** @@ -87,15 +101,28 @@ public class SysJobController extends BaseController @PreAuthorize("@ss.hasPermi('monitor:job:edit')") @Log(title = "定时任务", businessType = BusinessType.UPDATE) @PutMapping - public AjaxResult edit(@RequestBody SysJob sysJob) throws SchedulerException, TaskException + public AjaxResult edit(@RequestBody SysJob job) throws SchedulerException, TaskException { - if (!CronUtils.isValid(sysJob.getCronExpression())) + if (!CronUtils.isValid(job.getCronExpression())) + { + return error("修改任务'" + job.getJobName() + "'失败,Cron表达式不正确"); + } + else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) + { + return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'rmi://'调用"); + } + else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_LDAP)) { - return AjaxResult.error("cron表达式不正确"); + return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'ldap://'调用"); } - sysJob.setUpdateBy(SecurityUtils.getUsername()); - return toAjax(jobService.updateJob(sysJob)); + else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.HTTP, Constants.HTTPS })) + { + return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'http(s)//'调用"); + } + job.setUpdateBy(getUsername()); + return toAjax(jobService.updateJob(job)); } + /** * 定时任务状态修改 */ @@ -109,7 +136,6 @@ public class SysJobController extends BaseController return toAjax(jobService.changeStatus(newJob)); } - /** * 定时任务立即执行一次 */ @@ -133,4 +159,4 @@ public class SysJobController extends BaseController jobService.deleteJobByIds(jobIds); return AjaxResult.success(); } -} +} \ No newline at end of file diff --git a/aidex-quartz/src/main/java/com/aidex/quartz/domain/SysJob.java b/aidex-quartz/src/main/java/com/aidex/quartz/domain/SysJob.java index 05b05ef34ea26682a31951d677d44dd2bf108b2a..eef71509999487783ec6676a1fc34d7e6c61e3fa 100644 --- a/aidex-quartz/src/main/java/com/aidex/quartz/domain/SysJob.java +++ b/aidex-quartz/src/main/java/com/aidex/quartz/domain/SysJob.java @@ -19,7 +19,7 @@ import com.aidex.quartz.util.CronUtils; /** * 定时任务调度表 sys_job - * + * * @author ruoyi */ @Data @@ -156,25 +156,22 @@ public class SysJob extends BaseEntity implements Serializable this.status = status; } - - private String customMessage; - @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("jobId", getJobId()) - .append("jobName", getJobName()) - .append("jobGroup", getJobGroup()) - .append("cronExpression", getCronExpression()) - .append("nextValidTime", getNextValidTime()) - .append("misfirePolicy", getMisfirePolicy()) - .append("concurrent", getConcurrent()) - .append("status", getStatus()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("remark", getRemark()) - .toString(); + .append("jobId", getJobId()) + .append("jobName", getJobName()) + .append("jobGroup", getJobGroup()) + .append("cronExpression", getCronExpression()) + .append("nextValidTime", getNextValidTime()) + .append("misfirePolicy", getMisfirePolicy()) + .append("concurrent", getConcurrent()) + .append("status", getStatus()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); } } diff --git a/aidex-quartz/src/main/java/com/aidex/quartz/util/AbstractQuartzJob.java b/aidex-quartz/src/main/java/com/aidex/quartz/util/AbstractQuartzJob.java index bcc8bec2ca3e13057fe1f8ccab59a148109d3661..eeeb1028fbead4007d235884f948fa27f004a044 100644 --- a/aidex-quartz/src/main/java/com/aidex/quartz/util/AbstractQuartzJob.java +++ b/aidex-quartz/src/main/java/com/aidex/quartz/util/AbstractQuartzJob.java @@ -38,10 +38,10 @@ public abstract class AbstractQuartzJob implements Job try { before(context, sysJob); - // if (sysJob != null) - // { + if (sysJob != null) + { doExecute(context, sysJob); - // } + } after(context, sysJob, null); } catch (Exception e) @@ -80,11 +80,7 @@ public abstract class AbstractQuartzJob implements Job sysJobLog.setStartTime(startTime); sysJobLog.setStopTime(new Date()); long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime(); - String customMessage = ""; - if(StringUtils.isNotBlank(sysJob.getCustomMessage())){ - customMessage = ",定时任务自定义返回信息:" + sysJob.getCustomMessage(); - } - sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒" + customMessage); + sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒"); if (e != null) { sysJobLog.setStatus(Constants.FAIL); diff --git a/aidex-quartz/src/main/java/com/aidex/quartz/util/JobInvokeUtil.java b/aidex-quartz/src/main/java/com/aidex/quartz/util/JobInvokeUtil.java index d59b980a1d2a53af3ceacb7ef9e056e764e29591..6b1a41c8b85f0f95675d3a2ad974f09455e57bda 100644 --- a/aidex-quartz/src/main/java/com/aidex/quartz/util/JobInvokeUtil.java +++ b/aidex-quartz/src/main/java/com/aidex/quartz/util/JobInvokeUtil.java @@ -1,12 +1,13 @@ package com.aidex.quartz.util; +import com.aidex.common.utils.StringUtils; +import com.aidex.common.utils.spring.SpringUtils; +import com.aidex.quartz.domain.SysJob; + import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.List; -import com.aidex.common.utils.StringUtils; -import com.aidex.common.utils.spring.SpringUtils; -import com.aidex.quartz.domain.SysJob; /** * 任务执行工具 @@ -26,18 +27,17 @@ public class JobInvokeUtil String beanName = getBeanName(invokeTarget); String methodName = getMethodName(invokeTarget); List methodParams = getMethodParams(invokeTarget); - String message = "";//定时任务方法可以返回自定义信息用户记录到执行日志 + if (!isValidClassName(beanName)) { Object bean = SpringUtils.getBean(beanName); - message = invokeMethod(bean, methodName, methodParams); + invokeMethod(bean, methodName, methodParams); } else { Object bean = Class.forName(beanName).newInstance(); - message = invokeMethod(bean, methodName, methodParams); + invokeMethod(bean, methodName, methodParams); } - sysJob.setCustomMessage(message); } /** @@ -47,28 +47,26 @@ public class JobInvokeUtil * @param methodName 方法名称 * @param methodParams 方法参数 */ - private static String invokeMethod(Object bean, String methodName, List methodParams) + private static void invokeMethod(Object bean, String methodName, List methodParams) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - String message = "";//定时任务方法可以返回自定义信息用户记录到执行日志 if (StringUtils.isNotNull(methodParams) && methodParams.size() > 0) { Method method = bean.getClass().getDeclaredMethod(methodName, getMethodParamsType(methodParams)); - message =(String)method.invoke(bean, getMethodParamsValue(methodParams)); - System.out.println("返回参数"+message); + method.invoke(bean, getMethodParamsValue(methodParams)); } else { Method method = bean.getClass().getDeclaredMethod(methodName); - message =(String)method.invoke(bean); + method.invoke(bean); } - return message; } /** * 校验是否为为class包名 - * + * + * @param invokeTarget 名称 * @return true是 false否 */ public static boolean isValidClassName(String invokeTarget) @@ -78,7 +76,7 @@ public class JobInvokeUtil /** * 获取bean名称 - * + * * @param invokeTarget 目标字符串 * @return bean名称 */ @@ -90,7 +88,7 @@ public class JobInvokeUtil /** * 获取bean方法 - * + * * @param invokeTarget 目标字符串 * @return method方法 */ @@ -102,7 +100,7 @@ public class JobInvokeUtil /** * 获取method方法参数相关列表 - * + * * @param invokeTarget 目标字符串 * @return method方法相关参数列表 */ @@ -149,7 +147,7 @@ public class JobInvokeUtil /** * 获取参数类型 - * + * * @param methodParams 参数相关列表 * @return 参数类型列表 */ @@ -167,7 +165,7 @@ public class JobInvokeUtil /** * 获取参数值 - * + * * @param methodParams 参数相关列表 * @return 参数值列表 */ @@ -182,4 +180,4 @@ public class JobInvokeUtil } return classs; } -} +} \ No newline at end of file diff --git a/aidex-system/src/main/java/com/aidex/common/utils/poi/ExcelUtil.java b/aidex-system/src/main/java/com/aidex/common/utils/poi/ExcelUtil.java index a2e845257a7ef3601f0d2fc18a6ab447add686ef..030bb5bbbf6d31918393e9a100e445a6567d49c2 100644 --- a/aidex-system/src/main/java/com/aidex/common/utils/poi/ExcelUtil.java +++ b/aidex-system/src/main/java/com/aidex/common/utils/poi/ExcelUtil.java @@ -202,6 +202,10 @@ public class ExcelUtil // 从第2行开始取数据,默认第一行是表头. Row row = sheet.getRow(i); T entity = null; + if(row == null) + { + continue; + } for (Map.Entry entry : fieldsMap.entrySet()) { Object val = this.getCellValue(row, entry.getKey()); @@ -344,8 +348,8 @@ public class ExcelUtil { //默认错误信息列不导出 if("importErrInfo".equals(field.getName())){ - importErrInfoField = field; - importErrInfoExcel = field.getAnnotation(Excel.class); + importErrInfoField = field; + importErrInfoExcel = field.getAnnotation(Excel.class); continue; } // 单注解 @@ -575,7 +579,10 @@ public class ExcelUtil } else if (ColumnType.NUMERIC == attr.cellType()) { - cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value)); + if (StringUtils.isNotNull(value)) + { + cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value)); + } } else if (ColumnType.IMAGE == attr.cellType()) { diff --git a/aidex-system/src/main/java/com/aidex/framework/cache/ConfigUtils.java b/aidex-system/src/main/java/com/aidex/framework/cache/ConfigUtils.java index befe7ffe65668263f193651da90e2c603fab0af0..88698f868fc875ff830ffef864b8340368c4bc66 100644 --- a/aidex-system/src/main/java/com/aidex/framework/cache/ConfigUtils.java +++ b/aidex-system/src/main/java/com/aidex/framework/cache/ConfigUtils.java @@ -7,8 +7,10 @@ import com.aidex.common.utils.spring.SpringUtils; import com.aidex.system.domain.SysConfig; import com.aidex.system.service.SysConfigService; import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; import java.util.Collection; +import java.util.List; /** * 字典工具类 @@ -82,7 +84,7 @@ public class ConfigUtils implements CacheUtil { * 清空字典缓存 */ public static void clearConfigCache(String configKey) { - REDIS_CACHE.deleteCacheMapValue(CACHE_NAME, configKey); + REDIS_CACHE.deleteCacheMapValue(CACHE_NAME, getCacheKey(configKey)); } /** @@ -97,40 +99,65 @@ public class ConfigUtils implements CacheUtil { /** * 根据Key值获取配置信息 + * * @param configKey * @return */ public static SysConfig getConfigByKey(String configKey) { - return REDIS_CACHE.getCacheMapValue(CACHE_NAME, getCacheKey(configKey)); + SysConfig sysConfig = REDIS_CACHE.getCacheMapValue(CACHE_NAME, getCacheKey(configKey)); + if (null == sysConfig) { + SysConfig sysConfigQuery = new SysConfig(); + sysConfigQuery.setConfigKey(configKey); + List configDatas = sysConfigService.findList(sysConfigQuery); + if (CollectionUtils.isEmpty(configDatas)) { + return null; + } else { + sysConfig = configDatas.get(0); + REDIS_CACHE.setCacheMapValue(CACHE_NAME, getCacheKey(configKey), sysConfig); + } + } + return sysConfig; } /** * 根据Key值获取配置值 + * * @param configKey * @return */ - public static String getConfigValueByKey(String configKey) { - SysConfig sysConfig = REDIS_CACHE.getCacheMapValue(CACHE_NAME, getCacheKey(configKey)); - if(null == sysConfig){ - return ""; + public static String getConfigValueByKey(String configKey,String defaultValue) { + SysConfig sysConfig = getConfigByKey(configKey); + if (null == sysConfig) { + return defaultValue; } - return sysConfig.getConfigValue(); + return sysConfig.getConfigValue(); + } + + /** + * 根据Key值获取配置值 + * + * @param configKey + * @return + */ + public static String getConfigValueByKey(String configKey) { + return getConfigValueByKey(configKey,""); } /** * 根据Key值获取配置的boolean值 + * * @param configKey * @return */ - public static boolean getConfigBooleanValueByKey(String configKey,Boolean defaultValue) { - SysConfig sysConfig = REDIS_CACHE.getCacheMapValue(CACHE_NAME, getCacheKey(configKey)); - if(null == sysConfig){ + public static boolean getConfigBooleanValueByKey(String configKey, Boolean defaultValue) { + SysConfig sysConfig = getConfigByKey(configKey); + if (null == sysConfig) { return defaultValue; } - return Convert.toBool(sysConfig.getConfigValue(),defaultValue); + return Convert.toBool(sysConfig.getConfigValue(), defaultValue); } public static void setConfigCache(SysConfig sysConfig) { - REDIS_CACHE.setCacheMapValue(CACHE_NAME, ConfigUtils.getCacheKey(sysConfig.getConfigKey()), sysConfig); + REDIS_CACHE.setCacheMapValue(CACHE_NAME, getCacheKey(sysConfig.getConfigKey()), sysConfig); } } diff --git a/aidex-system/src/main/java/com/aidex/framework/cache/DictUtils.java b/aidex-system/src/main/java/com/aidex/framework/cache/DictUtils.java index 07f88c12a019a14250f19bc4bc4528f0395f8ab7..577ccdbbb554a9c91e377b175d0e80f2b5609237 100644 --- a/aidex-system/src/main/java/com/aidex/framework/cache/DictUtils.java +++ b/aidex-system/src/main/java/com/aidex/framework/cache/DictUtils.java @@ -46,7 +46,7 @@ public class DictUtils implements CacheUtil { @Override public String getCacheValue(String key) { - return ((JSONArray)REDIS_CACHE.getCacheMapValue(CACHE_NAME, key)).toJSONString(); + return ((JSONArray) REDIS_CACHE.getCacheMapValue(CACHE_NAME, key)).toJSONString(); } @Override @@ -88,11 +88,12 @@ public class DictUtils implements CacheUtil { * 清空字典缓存 */ public static void clearDictCache(String dictType) { - REDIS_CACHE.deleteCacheMapValue(CACHE_NAME, Constants.SYS_DICT_KEY+dictType); + REDIS_CACHE.deleteCacheMapValue(CACHE_NAME, getCacheKey(dictType)); } /** * 设置cache key + * * @param configKey 参数键 * @return 缓存键key */ @@ -102,6 +103,7 @@ public class DictUtils implements CacheUtil { /** * 根据字典类型和字典值获取字典标签 + * * @param dictType 字典类型 * @param dictValue 字典值 * @return 字典标签 @@ -112,6 +114,7 @@ public class DictUtils implements CacheUtil { /** * 根据字典类型和字典值获取字典标签 + * * @param dictType 字典类型 * @param dictValue 字典值 * @param separator 分隔符 @@ -143,6 +146,7 @@ public class DictUtils implements CacheUtil { /** * 根据字典类型和字典标签获取字典值 + * * @param dictType 字典类型 * @param dictLabel 字典标签 * @return 字典值 @@ -153,6 +157,7 @@ public class DictUtils implements CacheUtil { /** * 根据字典类型和字典标签获取字典值 + * * @param dictType 字典类型 * @param dictLabel 字典标签 * @param separator 分隔符 @@ -184,6 +189,7 @@ public class DictUtils implements CacheUtil { /** * 获取数据字典列表:仅包含有效的 + * * @param dictType 字典编码 * @return */ @@ -193,22 +199,41 @@ public class DictUtils implements CacheUtil { /** * 获取所有的数据字典:包含有效和无效的,用于主页面展示 + * * @param dictType 字典编码 * @return */ public static List getAllDictList(String dictType) { List dictDatas = new ArrayList(); - JSONArray jsonArray = REDIS_CACHE.getCacheMapValue(CACHE_NAME,getCacheKey(dictType)); - if (!CollectionUtils.isEmpty(jsonArray)) - { + JSONArray jsonArray = REDIS_CACHE.getCacheMapValue(CACHE_NAME, getCacheKey(dictType)); + if (!CollectionUtils.isEmpty(jsonArray)) { dictDatas = jsonArray.toJavaList(SysDictData.class); return dictDatas; } else { SysDictData sysDictData = new SysDictData(); sysDictData.setDictType(dictType); dictDatas = sysDictDataService.findList(sysDictData); - REDIS_CACHE.setCacheMapValue(CACHE_NAME, getCacheKey(dictType), dictDatas); + setDictCache(dictType,dictDatas); return dictDatas; } } + + /** + * 设置缓存 + * @param dictType + */ + public static void setDictCache(String dictType) { + SysDictData sysDictDataQuery = new SysDictData(); + sysDictDataQuery.setDictType(dictType); + setDictCache(dictType,sysDictDataService.findList(sysDictDataQuery)); + } + + /** + * 设置缓存 + * @param dictType + * @param dictDatas + */ + public static void setDictCache(String dictType, List dictDatas) { + REDIS_CACHE.setCacheMapValue(CACHE_NAME, getCacheKey(dictType), dictDatas); + } } diff --git a/aidex-system/src/main/java/com/aidex/system/common/SysErrorCode.java b/aidex-system/src/main/java/com/aidex/system/common/SysErrorCode.java index b1d5c12c305831a49d5b13da80a92a9dffc258d3..1344998714759ceb99b421eb3e050041976f16c3 100644 --- a/aidex-system/src/main/java/com/aidex/system/common/SysErrorCode.java +++ b/aidex-system/src/main/java/com/aidex/system/common/SysErrorCode.java @@ -45,22 +45,34 @@ public enum SysErrorCode implements ErrorCodeI { B_SYSUSER_UserNameAlreadyExist("B_SYSUSER_UserNameAlreadyExist", "用户名称已存在"), + B_SYSUSER_PhoneAlreadyExist("B_SYSUSER_PhoneAlreadyExist", "用户手机号已存在"), + B_SYSUSER_EmailAlreadyExist("B_SYSUSER_EmailAlreadyExist", "用户邮箱已存在"), B_SYSMENU_MenuHasChildNotDelete("B_SYSMENU_MenuHasChildNotDelete", "该菜单包含子菜单,不允许删除"), + B_SYSMENU_MenuAlreadyUnNormal("B_SYSMENU_MenuAlreadyUnNormal", "菜单停用,不允许新增子菜单"), + B_SYSMENU_MenuMoveUnNormal("B_SYSMENU_MenuMoveUnNormal", "非法移动,不允许将节点移动到自身或者子节点下"), + B_SYSMENU_MenuIdNotEqualParentId("B_SYSMENU_MenuIdNotEqualParentId", "修改菜单失败,父级菜单不能是自己"), + B_SYSMENU_MenuHasNormalChild("B_SYSMENU_MenuHasNormalChild", "该菜单包含未停用的子菜单,不允许标记为停用"), + B_SYSMENU_MenuNameAlreadyExist("B_SYSMENU_MenuNameAlreadyExist", "菜单名称已存在"), + B_SYSMENU_PathAlreadyExist("B_SYSMENU_PathAlreadyExist", "路由地址已存在"), + B_SYSMENU_PathStartsWithHttp("B_SYSMENU_PathStartsWithHttp", "路由地址必须以http(s)://开头"), B_FILEUPLOADER_UploaderErr("B_FILEUPLOADER_UploaderErr", "上传失败"), + B_FILEUPLOADER_FileNotExist("B_FILEUPLOADER_FileNotExist", "附件不存在"), + B_FILEUPLOADER_DownloadFileNotExist("B_FILEUPLOADER_DownloadFileNotExist", "下载文件已不存在"), + B_FILEUPLOADER_NoFindFileServer("B_FILEUPLOADER_NoFindFileServer", "没有找到附件处理器"), BIZ_ERROR("BIZ_ERROR", "通用的业务逻辑错误"), diff --git a/aidex-system/src/main/java/com/aidex/system/domain/SysConfig.java b/aidex-system/src/main/java/com/aidex/system/domain/SysConfig.java index ff9cfeb8add80c2be913740e6dbe1105c99d2a6b..0eb9a1a52cbe613d3e1cdb64a2ad27d404e7b630 100644 --- a/aidex-system/src/main/java/com/aidex/system/domain/SysConfig.java +++ b/aidex-system/src/main/java/com/aidex/system/domain/SysConfig.java @@ -41,10 +41,10 @@ public class SysConfig extends BaseEntity /** 系统内置(Y是 N否) */ @Excel(name = "系统内置", readConverterExp = "Y=是,N=否") private String configType; - + @Override public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("configName", getConfigName()) .append("configKey", getConfigKey()) diff --git a/aidex-system/src/main/java/com/aidex/system/domain/SysDictType.java b/aidex-system/src/main/java/com/aidex/system/domain/SysDictType.java index fd76c8eb241aa17c77dff10dcb22b810c5df170d..8a643a3f533d9b3e8621852c4866770ca1ac79aa 100644 --- a/aidex-system/src/main/java/com/aidex/system/domain/SysDictType.java +++ b/aidex-system/src/main/java/com/aidex/system/domain/SysDictType.java @@ -12,7 +12,7 @@ import javax.validation.constraints.Size; /** * 字典类型表 sys_dict_type - * + * * @author ruoyi */ @Data @@ -33,23 +33,25 @@ public class SysDictType extends BaseEntity @Size(min = 0, max = 100, message = "字典类型类型长度不能超过100个字符") private String dictType; + private String dictTypeEq; + /** 状态(0正常 1停用) */ @Excel(name = "状态", readConverterExp = "0=正常,1=停用") private String status; - + @Override public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) - .append("id", getId()) - .append("dictName", getDictName()) - .append("dictType", getDictType()) - .append("status", getStatus()) - .append("createBy", getCreateBy()) - .append("createTime", getCreateTime()) - .append("updateBy", getUpdateBy()) - .append("updateTime", getUpdateTime()) - .append("remark", getRemark()) - .toString(); + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("dictName", getDictName()) + .append("dictType", getDictType()) + .append("status", getStatus()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); } } diff --git a/aidex-system/src/main/java/com/aidex/system/domain/SysUserOnline.java b/aidex-system/src/main/java/com/aidex/system/domain/SysUserOnline.java index 56153eb1c015fe3b7666b4e474e0957d845f9aa7..9df22be3ed2fe009d738bb4d3bb46ff4f3d8b5c3 100644 --- a/aidex-system/src/main/java/com/aidex/system/domain/SysUserOnline.java +++ b/aidex-system/src/main/java/com/aidex/system/domain/SysUserOnline.java @@ -1,113 +1,117 @@ package com.aidex.system.domain; +import com.fasterxml.jackson.annotation.JsonFormat; + +import java.util.Date; + /** * 当前在线会话 - * + * * @author ruoyi */ -public class SysUserOnline -{ - /** 会话编号 */ +public class SysUserOnline { + /** + * 会话编号 + */ private String tokenId; - /** 部门名称 */ + /** + * 部门名称 + */ private String deptName; - /** 用户名称 */ + /** + * 用户名称 + */ private String userName; - /** 登录IP地址 */ + /** + * 登录IP地址 + */ private String ipaddr; - /** 登录地址 */ + /** + * 登录地址 + */ private String loginLocation; - /** 浏览器类型 */ + /** + * 浏览器类型 + */ private String browser; - /** 操作系统 */ + /** + * 操作系统 + */ private String os; - /** 登录时间 */ - private Long loginTime; + /** + * 登录时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date loginTime; - public String getTokenId() - { + public String getTokenId() { return tokenId; } - public void setTokenId(String tokenId) - { + public void setTokenId(String tokenId) { this.tokenId = tokenId; } - public String getDeptName() - { + public String getDeptName() { return deptName; } - public void setDeptName(String deptName) - { + public void setDeptName(String deptName) { this.deptName = deptName; } - public String getUserName() - { + public String getUserName() { return userName; } - public void setUserName(String userName) - { + public void setUserName(String userName) { this.userName = userName; } - public String getIpaddr() - { + public String getIpaddr() { return ipaddr; } - public void setIpaddr(String ipaddr) - { + public void setIpaddr(String ipaddr) { this.ipaddr = ipaddr; } - public String getLoginLocation() - { + public String getLoginLocation() { return loginLocation; } - public void setLoginLocation(String loginLocation) - { + public void setLoginLocation(String loginLocation) { this.loginLocation = loginLocation; } - public String getBrowser() - { + public String getBrowser() { return browser; } - public void setBrowser(String browser) - { + public void setBrowser(String browser) { this.browser = browser; } - public String getOs() - { + public String getOs() { return os; } - public void setOs(String os) - { + public void setOs(String os) { this.os = os; } - public Long getLoginTime() - { + public Date getLoginTime() { return loginTime; } - public void setLoginTime(Long loginTime) - { + public void setLoginTime(Date loginTime) { this.loginTime = loginTime; } } diff --git a/aidex-system/src/main/java/com/aidex/system/mapper/SysDeptMapper.xml b/aidex-system/src/main/java/com/aidex/system/mapper/SysDeptMapper.xml index 4782f83c9789142ae111a1b822f39bcc233c41f6..f7052d411defd074daf31c2994bdb5d5fdbed6f8 100644 --- a/aidex-system/src/main/java/com/aidex/system/mapper/SysDeptMapper.xml +++ b/aidex-system/src/main/java/com/aidex/system/mapper/SysDeptMapper.xml @@ -269,7 +269,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - - + UPDATE sys_dict_type SET del_flag = #{DEL_FLAG_DELETE} @@ -102,23 +82,23 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - - update sys_dict_type - - - dict_name = #{dictName}, + + update sys_dict_type + + + dict_name = #{dictName}, - - dict_type = #{dictType}, + + dict_type = #{dictType}, - - status = #{status}, + + status = #{status}, - - remark = #{remark}, + + remark = #{remark}, - - update_by = #{updateBy}, + + update_by = #{updateBy}, update_time = #{updateTime}, @@ -127,18 +107,18 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" update_ip = #{updateIp}, version = version + 1 - - where id = #{id} + + where id = #{id} - - - insert into sys_dict_type( - id, - dict_name, - dict_type, - status, - remark, - create_by, + + + insert into sys_dict_type( + id, + dict_name, + dict_type, + status, + remark, + create_by, create_dept, create_time, update_by, @@ -146,21 +126,21 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" update_ip, del_flag, version - )values( - #{id}, - #{dictName}, - #{dictType}, - #{status}, - #{remark}, - #{createBy}, - #{createDept}, - #{createTime}, - #{updateBy}, - #{updateTime}, - #{updateIp}, - #{DEL_FLAG_NORMAL}, - 1 - ) + )values( + #{id}, + #{dictName}, + #{dictType}, + #{status}, + #{remark}, + #{createBy}, + #{createDept}, + #{createTime}, + #{updateBy}, + #{updateTime}, + #{updateIp}, + #{DEL_FLAG_NORMAL}, + 1 + ) - + \ No newline at end of file diff --git a/aidex-system/src/main/java/com/aidex/system/mapper/SysUserMapper.java b/aidex-system/src/main/java/com/aidex/system/mapper/SysUserMapper.java index 49b94e92509f8ae6f8b9189b674346aafc4d2c93..ec3ef137bf2dedd59a22bccb338e37dffb47d7ca 100644 --- a/aidex-system/src/main/java/com/aidex/system/mapper/SysUserMapper.java +++ b/aidex-system/src/main/java/com/aidex/system/mapper/SysUserMapper.java @@ -9,22 +9,22 @@ import java.util.Map; /** * 用户表 数据层 - * + * * @author ruoyi */ public interface SysUserMapper extends BaseMapper { /** * 根据条件分页查询用户列表 - * + * * @param sysUser 用户信息 * @return 用户信息集合信息 */ - // public List selectUserList(SysUser sysUser); + // public List selectUserList(SysUser sysUser); /** * 通过用户名查询用户 - * + * * @param userName 用户名 * @return 用户对象信息 */ @@ -32,7 +32,7 @@ public interface SysUserMapper extends BaseMapper /** * 修改用户头像 - * + * * @param userName 用户名 * @param avatar 头像地址 * @return 结果 @@ -40,25 +40,25 @@ public interface SysUserMapper extends BaseMapper public int updateUserAvatar(@Param("userName") String userName, @Param("avatar") String avatar); /** - * 重置用户密码 - * - * @param userName 用户名 - * @param password 密码 + * 记录登录信息 + * + * @param sysUser 用户 * @return 结果 */ - public int resetUserPwd(@Param("userName") String userName, @Param("password") String password); + public int updateUserLoginInfo(SysUser sysUser); /** - * 通过用户ID删除用户 + * 重置用户密码 * - * @param userId 用户ID + * @param userName 用户名 + * @param password 密码 * @return 结果 */ - public int deleteUserById(String userId); + public int resetUserPwd(@Param("userName") String userName, @Param("password") String password); /** * 批量删除用户信息 - * + * * @param userIds 需要删除的用户ID * @return 结果 */ diff --git a/aidex-system/src/main/java/com/aidex/system/mapper/SysUserMapper.xml b/aidex-system/src/main/java/com/aidex/system/mapper/SysUserMapper.xml index 80b11a378ac5411764cc7871dfc5f3b0784504ee..bd150dcf55decaefd5b21cb3bd38937f4bcfe410 100644 --- a/aidex-system/src/main/java/com/aidex/system/mapper/SysUserMapper.xml +++ b/aidex-system/src/main/java/com/aidex/system/mapper/SysUserMapper.xml @@ -41,6 +41,7 @@ t.version AS "version", t.del_flag AS "delFlag" + @@ -106,9 +107,10 @@ AND date_format(t.create_time,'%y%m%d') <= date_format(#{params.endTime},'%y%m%d') - AND (t.dept_id = #{deptId} OR t.dept_id IN ( SELECT t.id FROM sys_dept t WHERE find_in_set(#{deptId}, t.parent_ids) )) + AND t.dept_id IN (select d.id from sys_dept d where concat(d.parent_ids, '/') like concat('%', #{deptId}, '/%') ) + + + insert into sys_user( - id, - dept_id, - name, - name_en, - no, - user_name, - nick_name, - user_type, - email, - phonenumber, - sex, - avatar, - password, - birthday, - nation, - birth_address, - polity, - title, - office_tel, - fax, - work_space, - sort, - user_pinyin, - login_ip, - login_date, - status, - create_by, - create_dept, - create_time, - update_by, - update_time, - update_ip, - remark, - version, - del_flag + id, + dept_id, + name, + name_en, + no, + user_name, + nick_name, + user_type, + email, + phonenumber, + sex, + avatar, + password, + birthday, + nation, + birth_address, + polity, + title, + office_tel, + fax, + work_space, + sort, + user_pinyin, + login_ip, + login_date, + status, + create_by, + create_dept, + create_time, + update_by, + update_time, + update_ip, + remark, + version, + del_flag )values( - #{id}, - #{deptId}, - #{name}, - #{nameEn}, - #{no}, - #{userName}, - #{nickName}, - #{userType}, - #{email}, - #{phonenumber}, - #{sex}, - #{avatar}, - #{password}, - #{birthday}, - #{nation}, - #{birthAddress}, - #{polity}, - #{title}, - #{officeTel}, - #{fax}, - #{workSpace}, - #{sort}, - #{userPinyin}, - #{loginIp}, - #{loginDate}, - #{status}, - #{createBy}, - #{createDept}, - #{createTime}, - #{updateBy}, - #{updateTime}, - #{updateIp}, - #{remark}, - 1, - #{DEL_FLAG_NORMAL} - ) + #{id}, + #{deptId}, + #{name}, + #{nameEn}, + #{no}, + #{userName}, + #{nickName}, + #{userType}, + #{email}, + #{phonenumber}, + #{sex}, + #{avatar}, + #{password}, + #{birthday}, + #{nation}, + #{birthAddress}, + #{polity}, + #{title}, + #{officeTel}, + #{fax}, + #{workSpace}, + #{sort}, + #{userPinyin}, + #{loginIp}, + #{loginDate}, + #{status}, + #{createBy}, + #{createDept}, + #{createTime}, + #{updateBy}, + #{updateTime}, + #{updateIp}, + #{remark}, + 1, + #{DEL_FLAG_NORMAL} + ) + update sys_user @@ -275,45 +280,43 @@ select - t.id, - t.dept_id, - t.user_name, - t.name, - t.nick_name, - t.user_type, - t.email, - t.avatar, - t.phonenumber, - t.office_tel, - t.password, - t.sex, - t.status, - t.del_flag, - t.login_ip, - t.login_date, - t.create_by, - t.create_time, - t.remark, - d.id as dept_id, - d.parent_id, - d.dept_name, - d.tree_sort, - d.leader, - d.status as dept_status, - r.id, - r.role_name, - r.role_key, - r.sort, - r.data_scope, - r.status as role_status + t.id, + t.dept_id, + t.user_name, + t.name, + t.nick_name, + t.user_type, + t.email, + t.avatar, + t.phonenumber, + t.office_tel, + t.password, + t.sex, + t.status, + t.del_flag, + t.login_ip, + t.login_date, + t.create_by, + t.create_time, + t.remark, + d.id as dept_id, + d.parent_id, + d.dept_name, + d.tree_sort, + d.leader, + d.status as dept_status, + r.id, + r.role_name, + r.role_key, + r.sort, + r.data_scope, + r.status as role_status from sys_user t - left join sys_dept d on t.dept_id = d.id - left join sys_user_role ur on t.id = ur.user_id - left join sys_role r on r.id = ur.role_id + left join sys_dept d on t.dept_id = d.id + left join sys_user_role ur on t.id = ur.user_id + left join sys_role r on r.id = ur.role_id - - - update sys_user set status = #{status} where id = #{id} + update sys_user set status = #{status} where id = #{id} - update sys_user set avatar = #{avatar} where user_name = #{userName} + update sys_user set avatar = #{avatar} where user_name = #{userName} - - update sys_user set password = #{password} where user_name = #{userName} + + update sys_user set + login_ip = #{loginIp}, + login_date = #{loginDate} + where id = #{id} - - delete from sys_user where id = #{id} - + + update sys_user set password = #{password} where user_name = #{userName} + UPDATE sys_user SET @@ -375,7 +381,6 @@ - -