全项目代码格式化

2.X
疯狂的狮子li 2021-12-31 16:31:17 +08:00
parent a53db40b49
commit db9fd081e6
239 changed files with 4509 additions and 9471 deletions

View File

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

View File

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

View File

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

View File

@ -1,16 +1,16 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import java.util.ArrayList; import com.ruoyi.common.core.web.domain.BaseEntity;
import java.util.List; import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.validation.constraints.Email; import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.util.ArrayList;
import lombok.*; import java.util.List;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.core.web.domain.BaseEntity;
/** /**
* sys_dept * sys_dept

View File

@ -1,16 +1,16 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import lombok.*;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
import com.ruoyi.common.core.constant.UserConstants; import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
/** /**
* sys_dict_data * sys_dict_data

View File

@ -1,15 +1,15 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import lombok.*;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
/** /**
* sys_dict_type * sys_dict_type

View File

@ -1,9 +1,8 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import lombok.*; import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/** /**
* *

View File

@ -1,13 +1,15 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import java.util.Date;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import lombok.*; import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import java.util.Date;
/** /**
* 访 sys_logininfor * 访 sys_logininfor
* *
@ -18,7 +20,6 @@ import lombok.experimental.Accessors;
@NoArgsConstructor @NoArgsConstructor
@Accessors(chain = true) @Accessors(chain = true)
public class SysLogininfor extends BaseEntity { public class SysLogininfor extends BaseEntity {
private static final long serialVersionUID = 1L;
/** /**
* ID * ID

View File

@ -1,14 +1,15 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import lombok.*; import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import java.util.Date;
/** /**
* oper_log * oper_log
* *
@ -19,7 +20,6 @@ import lombok.experimental.Accessors;
@NoArgsConstructor @NoArgsConstructor
@Accessors(chain = true) @Accessors(chain = true)
public class SysOperLog extends BaseEntity { public class SysOperLog extends BaseEntity {
private static final long serialVersionUID = 1L;
/** /**
* *

View File

@ -1,15 +1,15 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import lombok.*;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
/** /**
* sys_role * sys_role
@ -21,7 +21,6 @@ import com.ruoyi.common.core.web.domain.BaseEntity;
@NoArgsConstructor @NoArgsConstructor
@Accessors(chain = true) @Accessors(chain = true)
public class SysRole extends BaseEntity { public class SysRole extends BaseEntity {
private static final long serialVersionUID = 1L;
/** /**
* ID * ID

View File

@ -1,13 +1,5 @@
package com.ruoyi.system.api.domain; package com.ruoyi.system.api.domain;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.*;
import lombok.*;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.ruoyi.common.core.annotation.Excel; import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.annotation.Excel.ColumnType; import com.ruoyi.common.core.annotation.Excel.ColumnType;
@ -15,6 +7,16 @@ import com.ruoyi.common.core.annotation.Excel.Type;
import com.ruoyi.common.core.annotation.Excels; import com.ruoyi.common.core.annotation.Excels;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import com.ruoyi.common.core.xss.Xss; import com.ruoyi.common.core.xss.Xss;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.List;
/** /**
* sys_user * sys_user
@ -26,7 +28,6 @@ import com.ruoyi.common.core.xss.Xss;
@NoArgsConstructor @NoArgsConstructor
@Accessors(chain = true) @Accessors(chain = true)
public class SysUser extends BaseEntity { public class SysUser extends BaseEntity {
private static final long serialVersionUID = 1L;
/** /**
* ID * ID
@ -89,7 +90,9 @@ public class SysUser extends BaseEntity {
@JsonProperty @JsonProperty
private String password; private String password;
/** 帐号状态0正常 1停用 */ /**
* 0 1
*/
@Excel(name = "帐号状态", readConverterExp = "0=正常,1=停用") @Excel(name = "帐号状态", readConverterExp = "0=正常,1=停用")
private String status; private String status;

View File

@ -1,14 +1,12 @@
package com.ruoyi.system.api.factory; package com.ruoyi.system.api.factory;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.RemoteFileService; import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.SysFile; import com.ruoyi.system.api.domain.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
/** /**
* *

View File

@ -1,14 +1,12 @@
package com.ruoyi.system.api.factory; package com.ruoyi.system.api.factory;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.RemoteLogService; import com.ruoyi.system.api.RemoteLogService;
import com.ruoyi.system.api.domain.SysLogininfor; import com.ruoyi.system.api.domain.SysLogininfor;
import com.ruoyi.system.api.domain.SysOperLog; import com.ruoyi.system.api.domain.SysOperLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
/** /**
* *

View File

@ -1,14 +1,12 @@
package com.ruoyi.system.api.factory; package com.ruoyi.system.api.factory;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.RemoteUserService; import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser; import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser; import com.ruoyi.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
/** /**
* *

View File

@ -1,12 +1,13 @@
package com.ruoyi.system.api.model; package com.ruoyi.system.api.model;
import com.ruoyi.system.api.domain.SysUser;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable; import java.io.Serializable;
import java.util.Set; import java.util.Set;
import com.ruoyi.system.api.domain.SysUser;
import lombok.*;
import lombok.experimental.Accessors;
/** /**
* *
* *

View File

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

View File

@ -1,11 +1,5 @@
package com.ruoyi.auth.controller; package com.ruoyi.auth.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.auth.form.LoginBody; import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.RegisterBody; import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.service.SysLoginService; import com.ruoyi.auth.service.SysLoginService;
@ -16,24 +10,29 @@ import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService; import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils; import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser; import com.ruoyi.system.api.model.LoginUser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/** /**
* token * token
* *
* @author ruoyi * @author ruoyi
*/ */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController @RestController
public class TokenController public class TokenController {
{
@Autowired
private TokenService tokenService;
@Autowired private final TokenService tokenService;
private SysLoginService sysLoginService; private final SysLoginService sysLoginService;
@PostMapping("login") @PostMapping("login")
public R<?> login(@RequestBody LoginBody form) public R<?> login(@RequestBody LoginBody form) {
{
// 用户登录 // 用户登录
LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword()); LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
// 获取登录token // 获取登录token
@ -41,11 +40,9 @@ public class TokenController
} }
@DeleteMapping("logout") @DeleteMapping("logout")
public R<?> logout(HttpServletRequest request) public R<?> logout(HttpServletRequest request) {
{
String token = SecurityUtils.getToken(request); String token = SecurityUtils.getToken(request);
if (StringUtils.isNotEmpty(token)) if (StringUtils.isNotEmpty(token)) {
{
String username = JwtUtils.getUserName(token); String username = JwtUtils.getUserName(token);
// 删除用户缓存记录 // 删除用户缓存记录
AuthUtil.logoutByToken(token); AuthUtil.logoutByToken(token);
@ -56,11 +53,9 @@ public class TokenController
} }
@PostMapping("refresh") @PostMapping("refresh")
public R<?> refresh(HttpServletRequest request) public R<?> refresh(HttpServletRequest request) {
{
LoginUser loginUser = tokenService.getLoginUser(request); LoginUser loginUser = tokenService.getLoginUser(request);
if (StringUtils.isNotNull(loginUser)) if (StringUtils.isNotNull(loginUser)) {
{
// 刷新令牌有效期 // 刷新令牌有效期
tokenService.refreshToken(loginUser); tokenService.refreshToken(loginUser);
return R.ok(); return R.ok();
@ -69,8 +64,7 @@ public class TokenController
} }
@PostMapping("register") @PostMapping("register")
public R<?> register(@RequestBody RegisterBody registerBody) public R<?> register(@RequestBody RegisterBody registerBody) {
{
// 用户注册 // 用户注册
sysLoginService.register(registerBody.getUsername(), registerBody.getPassword()); sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
return R.ok(); return R.ok();

View File

@ -1,6 +1,7 @@
package com.ruoyi.auth.form; package com.ruoyi.auth.form;
import lombok.*; import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
/** /**

View File

@ -5,7 +5,6 @@ package com.ruoyi.auth.form;
* *
* @author ruoyi * @author ruoyi
*/ */
public class RegisterBody extends LoginBody public class RegisterBody extends LoginBody {
{
} }

View File

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

View File

@ -1,11 +1,12 @@
package com.ruoyi.common.core.annotation; package com.ruoyi.common.core.annotation;
import com.ruoyi.common.core.utils.poi.ExcelHandlerAdapter;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import java.math.BigDecimal; import java.math.BigDecimal;
import com.ruoyi.common.core.utils.poi.ExcelHandlerAdapter;
/** /**
* Excel * Excel
@ -14,8 +15,7 @@ import com.ruoyi.common.core.utils.poi.ExcelHandlerAdapter;
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD) @Target(ElementType.FIELD)
public @interface Excel public @interface Excel {
{
/** /**
* excel * excel
*/ */
@ -116,18 +116,15 @@ public @interface Excel
*/ */
public String[] args() default {}; public String[] args() default {};
public enum Align public enum Align {
{
AUTO(0), LEFT(1), CENTER(2), RIGHT(3); AUTO(0), LEFT(1), CENTER(2), RIGHT(3);
private final int value; private final int value;
Align(int value) Align(int value) {
{
this.value = value; this.value = value;
} }
public int value() public int value() {
{
return this.value; return this.value;
} }
} }
@ -137,34 +134,28 @@ public @interface Excel
*/ */
Type type() default Type.ALL; Type type() default Type.ALL;
public enum Type public enum Type {
{
ALL(0), EXPORT(1), IMPORT(2); ALL(0), EXPORT(1), IMPORT(2);
private final int value; private final int value;
Type(int value) Type(int value) {
{
this.value = value; this.value = value;
} }
public int value() public int value() {
{
return this.value; return this.value;
} }
} }
public enum ColumnType public enum ColumnType {
{
NUMERIC(0), STRING(1), IMAGE(2); NUMERIC(0), STRING(1), IMAGE(2);
private final int value; private final int value;
ColumnType(int value) ColumnType(int value) {
{
this.value = value; this.value = value;
} }
public int value() public int value() {
{
return this.value; return this.value;
} }
} }

View File

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

View File

@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.ruoyi.common.core.jackson.BigNumberSerializer; import com.ruoyi.common.core.jackson.BigNumberSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
@ -22,8 +23,11 @@ import java.time.format.DateTimeFormatter;
import java.util.TimeZone; import java.util.TimeZone;
/** /**
* JacksonConfig * jackson
*
* @author Lion Li
*/ */
@Slf4j
@Configuration @Configuration
@ConditionalOnClass(ObjectMapper.class) @ConditionalOnClass(ObjectMapper.class)
@AutoConfigureBefore(JacksonAutoConfiguration.class) @AutoConfigureBefore(JacksonAutoConfiguration.class)
@ -44,7 +48,7 @@ public class JacksonConfig {
simpleModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter)); simpleModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
objectMapper.registerModule(simpleModule); objectMapper.registerModule(simpleModule);
objectMapper.setTimeZone(TimeZone.getDefault()); objectMapper.setTimeZone(TimeZone.getDefault());
log.info("初始化 jackson 配置");
return objectMapper; return objectMapper;
} }

View File

@ -3,22 +3,21 @@ package com.ruoyi.common.core.constant;
/** /**
* key * key
* *
* @author ruoyi * @author Lion Li
*/ */
public class CacheConstants public interface CacheConstants {
{
/** /**
* 720 * 720
*/ */
public final static long EXPIRATION = 720; long EXPIRATION = 720;
/** /**
* 120 * 120
*/ */
public final static long REFRESH_TIME = 120; long REFRESH_TIME = 120;
/** /**
* *
*/ */
public final static String LOGIN_TOKEN_KEY = "login_tokens:"; String LOGIN_TOKEN_KEY = "login_tokens:";
} }

View File

@ -3,119 +3,113 @@ package com.ruoyi.common.core.constant;
/** /**
* *
* *
* @author ruoyi * @author Lion Li
*/ */
public class Constants public interface Constants {
{
/** /**
* UTF-8 * UTF-8
*/ */
public static final String UTF8 = "UTF-8"; String UTF8 = "UTF-8";
/** /**
* GBK * GBK
*/ */
public static final String GBK = "GBK"; String GBK = "GBK";
/** /**
* RMI * RMI
*/ */
public static final String LOOKUP_RMI = "rmi://"; String LOOKUP_RMI = "rmi://";
/** /**
* LDAP * LDAP
*/ */
public static final String LOOKUP_LDAP = "ldap://"; String LOOKUP_LDAP = "ldap://";
/** /**
* http * http
*/ */
public static final String HTTP = "http://"; String HTTP = "http://";
/** /**
* https * https
*/ */
public static final String HTTPS = "https://"; String HTTPS = "https://";
/** /**
* *
*/ */
public static final Integer SUCCESS = 200; Integer SUCCESS = 200;
/** /**
* *
*/ */
public static final Integer FAIL = 500; Integer FAIL = 500;
/** /**
* *
*/ */
public static final String LOGIN_SUCCESS = "Success"; String LOGIN_SUCCESS = "Success";
/** /**
* *
*/ */
public static final String LOGOUT = "Logout"; String LOGOUT = "Logout";
/** /**
* *
*/ */
public static final String REGISTER = "Register"; String REGISTER = "Register";
/** /**
* *
*/ */
public static final String LOGIN_FAIL = "Error"; String LOGIN_FAIL = "Error";
/** /**
* *
*/ */
public static final String PAGE_NUM = "pageNum"; String PAGE_NUM = "pageNum";
/** /**
* *
*/ */
public static final String PAGE_SIZE = "pageSize"; String PAGE_SIZE = "pageSize";
/** /**
* *
*/ */
public static final String ORDER_BY_COLUMN = "orderByColumn"; String ORDER_BY_COLUMN = "orderByColumn";
/** /**
* "desc" "asc". * "desc" "asc".
*/ */
public static final String IS_ASC = "isAsc"; String IS_ASC = "isAsc";
/** /**
* redis key * redis key
*/ */
public static final String CAPTCHA_CODE_KEY = "captcha_codes:"; String CAPTCHA_CODE_KEY = "captcha_codes:";
/** /**
* *
*/ */
public static final long CAPTCHA_EXPIRATION = 2; long CAPTCHA_EXPIRATION = 2;
/** /**
* cache key * cache key
*/ */
public static final String SYS_CONFIG_KEY = "sys_config:"; String SYS_CONFIG_KEY = "sys_config:";
/** /**
* cache key * cache key
*/ */
public static final String SYS_DICT_KEY = "sys_dict:"; String SYS_DICT_KEY = "sys_dict:";
/** /**
* *
*/ */
public static final String RESOURCE_PREFIX = "/profile"; String RESOURCE_PREFIX = "/profile";
/**
*
*/
public static final String[] JOB_ERROR_STR = { "java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml",
"org.springframework.jndi" };
} }

View File

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

View File

@ -3,87 +3,86 @@ package com.ruoyi.common.core.constant;
/** /**
* *
* *
* @author ruoyi * @author Lion Li
*/ */
public class HttpStatus public interface HttpStatus {
{
/** /**
* *
*/ */
public static final int SUCCESS = 200; int SUCCESS = 200;
/** /**
* *
*/ */
public static final int CREATED = 201; int CREATED = 201;
/** /**
* *
*/ */
public static final int ACCEPTED = 202; int ACCEPTED = 202;
/** /**
* *
*/ */
public static final int NO_CONTENT = 204; int NO_CONTENT = 204;
/** /**
* *
*/ */
public static final int MOVED_PERM = 301; int MOVED_PERM = 301;
/** /**
* *
*/ */
public static final int SEE_OTHER = 303; int SEE_OTHER = 303;
/** /**
* *
*/ */
public static final int NOT_MODIFIED = 304; int NOT_MODIFIED = 304;
/** /**
* *
*/ */
public static final int BAD_REQUEST = 400; int BAD_REQUEST = 400;
/** /**
* *
*/ */
public static final int UNAUTHORIZED = 401; int UNAUTHORIZED = 401;
/** /**
* 访 * 访
*/ */
public static final int FORBIDDEN = 403; int FORBIDDEN = 403;
/** /**
* *
*/ */
public static final int NOT_FOUND = 404; int NOT_FOUND = 404;
/** /**
* http * http
*/ */
public static final int BAD_METHOD = 405; int BAD_METHOD = 405;
/** /**
* *
*/ */
public static final int CONFLICT = 409; int CONFLICT = 409;
/** /**
* *
*/ */
public static final int UNSUPPORTED_TYPE = 415; int UNSUPPORTED_TYPE = 415;
/** /**
* *
*/ */
public static final int ERROR = 500; int ERROR = 500;
/** /**
* *
*/ */
public static final int NOT_IMPLEMENTED = 501; int NOT_IMPLEMENTED = 501;
} }

View File

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

View File

@ -3,42 +3,41 @@ package com.ruoyi.common.core.constant;
/** /**
* *
* *
* @author ruoyi * @author Lion Li
*/ */
public class SecurityConstants public interface SecurityConstants {
{
/** /**
* ID * ID
*/ */
public static final String DETAILS_USER_ID = "user_id"; String DETAILS_USER_ID = "user_id";
/** /**
* *
*/ */
public static final String DETAILS_USERNAME = "username"; String DETAILS_USERNAME = "username";
/** /**
* *
*/ */
public static final String AUTHORIZATION_HEADER = "authorization"; String AUTHORIZATION_HEADER = "authorization";
/** /**
* *
*/ */
public static final String FROM_SOURCE = "from-source"; String FROM_SOURCE = "from-source";
/** /**
* *
*/ */
public static final String INNER = "inner"; String INNER = "inner";
/** /**
* *
*/ */
public static final String USER_KEY = "user_key"; String USER_KEY = "user_key";
/** /**
* *
*/ */
public static final String LOGIN_USER = "login_user"; String LOGIN_USER = "login_user";
} }

View File

@ -3,22 +3,11 @@ package com.ruoyi.common.core.constant;
/** /**
* *
* *
* @author ruoyi * @author Lion Li
*/ */
public class ServiceNameConstants public interface ServiceNameConstants {
{
/**
* serviceid
*/
public static final String AUTH_SERVICE = "ruoyi-auth";
/** String AUTH_SERVICE = "ruoyi-auth";
* serviceid String SYSTEM_SERVICE = "ruoyi-system";
*/ String FILE_SERVICE = "ruoyi-file";
public static final String SYSTEM_SERVICE = "ruoyi-system";
/**
* serviceid
*/
public static final String FILE_SERVICE = "ruoyi-file";
} }

View File

@ -3,23 +3,22 @@ package com.ruoyi.common.core.constant;
/** /**
* TokenKey * TokenKey
* *
* @author ruoyi * @author Lion Li
*/ */
public class TokenConstants public interface TokenConstants {
{
/** /**
* *
*/ */
public static final String AUTHENTICATION = "Authorization"; String AUTHENTICATION = "Authorization";
/** /**
* *
*/ */
public static final String PREFIX = "Bearer "; String PREFIX = "Bearer ";
/** /**
* *
*/ */
public final static String SECRET = "abcdefghijklmnopqrstuvwxyz"; String SECRET = "abcdefghijklmnopqrstuvwxyz";
} }

View File

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

View File

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

View File

@ -1,11 +1,12 @@
package com.ruoyi.common.core.domain; package com.ruoyi.common.core.domain;
import java.io.Serializable;
import com.ruoyi.common.core.constant.Constants; import com.ruoyi.common.core.constant.Constants;
import lombok.*; import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import java.io.Serializable;
/** /**
* *
* *

View File

@ -10,8 +10,7 @@ import lombok.Getter;
*/ */
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public enum UserStatus public enum UserStatus {
{
OK("0", "正常"), DISABLE("1", "停用"), DELETED("2", "删除"); OK("0", "正常"), DISABLE("1", "停用"), DELETED("2", "删除");
private final String code; private final String code;

View File

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

View File

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

View File

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

View File

@ -5,8 +5,7 @@ package com.ruoyi.common.core.exception;
* *
* @author ruoyi * @author ruoyi
*/ */
public class GlobalException extends RuntimeException public class GlobalException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -23,34 +22,28 @@ public class GlobalException extends RuntimeException
/** /**
* *
*/ */
public GlobalException() public GlobalException() {
{
} }
public GlobalException(String message) public GlobalException(String message) {
{
this.message = message; this.message = message;
} }
public String getDetailMessage() public String getDetailMessage() {
{
return detailMessage; return detailMessage;
} }
public GlobalException setDetailMessage(String detailMessage) public GlobalException setDetailMessage(String detailMessage) {
{
this.detailMessage = detailMessage; this.detailMessage = detailMessage;
return this; return this;
} }
@Override @Override
public String getMessage() public String getMessage() {
{
return message; return message;
} }
public GlobalException setMessage(String message) public GlobalException setMessage(String message) {
{
this.message = message; this.message = message;
return this; return this;
} }

View File

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

View File

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

View File

@ -5,8 +5,7 @@ package com.ruoyi.common.core.exception;
* *
* @author ruoyi * @author ruoyi
*/ */
public final class ServiceException extends RuntimeException public final class ServiceException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
@ -27,44 +26,36 @@ public final class ServiceException extends RuntimeException
/** /**
* *
*/ */
public ServiceException() public ServiceException() {
{
} }
public ServiceException(String message) public ServiceException(String message) {
{
this.message = message; this.message = message;
} }
public ServiceException(String message, Integer code) public ServiceException(String message, Integer code) {
{
this.message = message; this.message = message;
this.code = code; this.code = code;
} }
public String getDetailMessage() public String getDetailMessage() {
{
return detailMessage; return detailMessage;
} }
public String getMessage() public String getMessage() {
{
return message; return message;
} }
public Integer getCode() public Integer getCode() {
{
return code; return code;
} }
public ServiceException setMessage(String message) public ServiceException setMessage(String message) {
{
this.message = message; this.message = message;
return this; return this;
} }
public ServiceException setDetailMessage(String detailMessage) public ServiceException setDetailMessage(String detailMessage) {
{
this.detailMessage = detailMessage; this.detailMessage = detailMessage;
return this; return this;
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -10,8 +10,7 @@ import lombok.Getter;
*/ */
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public class BaseException extends RuntimeException public class BaseException extends RuntimeException {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
@ -34,23 +33,19 @@ public class BaseException extends RuntimeException
*/ */
private String defaultMessage; private String defaultMessage;
public BaseException(String module, String code, Object[] args) public BaseException(String module, String code, Object[] args) {
{
this(module, code, args, null); this(module, code, args, null);
} }
public BaseException(String module, String defaultMessage) public BaseException(String module, String defaultMessage) {
{
this(module, null, null, defaultMessage); this(module, null, null, defaultMessage);
} }
public BaseException(String code, Object[] args) public BaseException(String code, Object[] args) {
{
this(null, code, args, null); this(null, code, args, null);
} }
public BaseException(String defaultMessage) public BaseException(String defaultMessage) {
{
this(null, null, null, defaultMessage); this(null, null, null, defaultMessage);
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,28 +15,28 @@ import java.io.IOException;
@JacksonStdImpl @JacksonStdImpl
public class BigNumberSerializer extends NumberSerializer { public class BigNumberSerializer extends NumberSerializer {
/** /**
* JS Number.MAX_SAFE_INTEGER Number.MIN_SAFE_INTEGER * JS Number.MAX_SAFE_INTEGER Number.MIN_SAFE_INTEGER
*/ */
private static final long MAX_SAFE_INTEGER = 9007199254740991L; private static final long MAX_SAFE_INTEGER = 9007199254740991L;
private static final long MIN_SAFE_INTEGER = -9007199254740991L; private static final long MIN_SAFE_INTEGER = -9007199254740991L;
/** /**
* *
*/ */
public static final BigNumberSerializer INSTANCE = new BigNumberSerializer(Number.class); public static final BigNumberSerializer INSTANCE = new BigNumberSerializer(Number.class);
public BigNumberSerializer(Class<? extends Number> rawType) { public BigNumberSerializer(Class<? extends Number> rawType) {
super(rawType); super(rawType);
} }
@Override @Override
public void serialize(Number value, JsonGenerator gen, SerializerProvider provider) throws IOException { public void serialize(Number value, JsonGenerator gen, SerializerProvider provider) throws IOException {
// 超出范围 序列化位字符串 // 超出范围 序列化位字符串
if (value.longValue() > MIN_SAFE_INTEGER && value.longValue() < MAX_SAFE_INTEGER) { if (value.longValue() > MIN_SAFE_INTEGER && value.longValue() < MAX_SAFE_INTEGER) {
super.serialize(value, gen, provider); super.serialize(value, gen, provider);
} else { } else {
gen.writeString(value.toString()); gen.writeString(value.toString());
} }
} }
} }

View File

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

View File

@ -1,92 +0,0 @@
package com.ruoyi.common.core.text;
import com.ruoyi.common.core.utils.StringUtils;
/**
*
*
* @author ruoyi
*/
public class StrFormatter
{
public static final String EMPTY_JSON = "{}";
public static final char C_BACKSLASH = '\\';
public static final char C_DELIM_START = '{';
public static final char C_DELIM_END = '}';
/**
* <br>
* {} <br>
* {} 使 \\ { {} \ 使 \\\\ <br>
* <br>
* 使format("this is {} for {}", "a", "b") -> this is a for b<br>
* {} format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* \ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param strPattern
* @param argArray
* @return
*/
public static String format(final String strPattern, final Object... argArray)
{
if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray))
{
return strPattern;
}
final int strPatternLength = strPattern.length();
// 初始化定义好的长度以获得更好的性能
StringBuilder sbuf = new StringBuilder(strPatternLength + 50);
int handledPosition = 0;
int delimIndex;// 占位符所在位置
for (int argIndex = 0; argIndex < argArray.length; argIndex++)
{
delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
if (delimIndex == -1)
{
if (handledPosition == 0)
{
return strPattern;
}
else
{ // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
sbuf.append(strPattern, handledPosition, strPatternLength);
return sbuf.toString();
}
}
else
{
if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH)
{
if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH)
{
// 转义符之前还有一个转义符,占位符依旧有效
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2;
}
else
{
// 占位符被转义
argIndex--;
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(C_DELIM_START);
handledPosition = delimIndex + 1;
}
}
else
{
// 正常占位符
sbuf.append(strPattern, handledPosition, delimIndex);
sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2;
}
}
}
// 加入最后一个占位符后所有的字符
sbuf.append(strPattern, handledPosition, strPattern.length());
return sbuf.toString();
}
}

View File

@ -1,484 +0,0 @@
package com.ruoyi.common.core.text;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import com.ruoyi.common.core.exception.UtilException;
/**
* universally unique identifierUUID
*
* @author ruoyi
*/
public final class UUID implements java.io.Serializable, Comparable<UUID>
{
private static final long serialVersionUID = -1185015143654744140L;
/**
* SecureRandom
*
*/
private static class Holder
{
static final SecureRandom numberGenerator = getSecureRandom();
}
/** 此UUID的最高64有效位 */
private final long mostSigBits;
/** 此UUID的最低64有效位 */
private final long leastSigBits;
/**
*
*
* @param data
*/
private UUID(byte[] data)
{
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i = 0; i < 8; i++)
{
msb = (msb << 8) | (data[i] & 0xff);
}
for (int i = 8; i < 16; i++)
{
lsb = (lsb << 8) | (data[i] & 0xff);
}
this.mostSigBits = msb;
this.leastSigBits = lsb;
}
/**
* 使 UUID
*
* @param mostSigBits {@code UUID} 64
* @param leastSigBits {@code UUID} 64
*/
public UUID(long mostSigBits, long leastSigBits)
{
this.mostSigBits = mostSigBits;
this.leastSigBits = leastSigBits;
}
/**
* 4UUID 使线 UUID
*
* @return {@code UUID}
*/
public static UUID fastUUID()
{
return randomUUID(false);
}
/**
* 4UUID 使 UUID
*
* @return {@code UUID}
*/
public static UUID randomUUID()
{
return randomUUID(true);
}
/**
* 4UUID 使 UUID
*
* @param isSecure 使{@link SecureRandom}
* @return {@code UUID}
*/
public static UUID randomUUID(boolean isSecure)
{
final Random ng = isSecure ? Holder.numberGenerator : getRandom();
byte[] randomBytes = new byte[16];
ng.nextBytes(randomBytes);
randomBytes[6] &= 0x0f; /* clear version */
randomBytes[6] |= 0x40; /* set to version 4 */
randomBytes[8] &= 0x3f; /* clear variant */
randomBytes[8] |= 0x80; /* set to IETF variant */
return new UUID(randomBytes);
}
/**
* 3UUID
*
* @param name UUID
*
* @return {@code UUID}
*/
public static UUID nameUUIDFromBytes(byte[] name)
{
MessageDigest md;
try
{
md = MessageDigest.getInstance("MD5");
}
catch (NoSuchAlgorithmException nsae)
{
throw new InternalError("MD5 not supported");
}
byte[] md5Bytes = md.digest(name);
md5Bytes[6] &= 0x0f; /* clear version */
md5Bytes[6] |= 0x30; /* set to version 3 */
md5Bytes[8] &= 0x3f; /* clear variant */
md5Bytes[8] |= 0x80; /* set to IETF variant */
return new UUID(md5Bytes);
}
/**
* {@link #toString()} {@code UUID}
*
* @param name {@code UUID}
* @return {@code UUID}
* @throws IllegalArgumentException name {@link #toString}
*
*/
public static UUID fromString(String name)
{
String[] components = name.split("-");
if (components.length != 5)
{
throw new IllegalArgumentException("Invalid UUID string: " + name);
}
for (int i = 0; i < 5; i++)
{
components[i] = "0x" + components[i];
}
long mostSigBits = Long.decode(components[0]).longValue();
mostSigBits <<= 16;
mostSigBits |= Long.decode(components[1]).longValue();
mostSigBits <<= 16;
mostSigBits |= Long.decode(components[2]).longValue();
long leastSigBits = Long.decode(components[3]).longValue();
leastSigBits <<= 48;
leastSigBits |= Long.decode(components[4]).longValue();
return new UUID(mostSigBits, leastSigBits);
}
/**
* UUID 128 64
*
* @return UUID 128 64
*/
public long getLeastSignificantBits()
{
return leastSigBits;
}
/**
* UUID 128 64
*
* @return UUID 128 64
*/
public long getMostSignificantBits()
{
return mostSigBits;
}
/**
* {@code UUID} . {@code UUID}
* <p>
* :
* <ul>
* <li>1 UUID
* <li>2 DCE UUID
* <li>3 UUID
* <li>4 UUID
* </ul>
*
* @return {@code UUID}
*/
public int version()
{
// Version is bits masked by 0x000000000000F000 in MS long
return (int) ((mostSigBits >> 12) & 0x0f);
}
/**
* {@code UUID} {@code UUID}
* <p>
*
* <ul>
* <li>0 NCS
* <li>2 <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF&nbsp;RFC&nbsp;4122</a>(Leach-Salz),
* <li>6
* <li>7 使
* </ul>
*
* @return {@code UUID}
*/
public int variant()
{
// This field is composed of a varying number of bits.
// 0 - - Reserved for NCS backward compatibility
// 1 0 - The IETF aka Leach-Salz variant (used by this class)
// 1 1 0 Reserved, Microsoft backward compatibility
// 1 1 1 Reserved for future definition.
return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62))) & (leastSigBits >> 63));
}
/**
* UUID
*
* <p>
* 60 {@code UUID} time_lowtime_mid time_hi <br>
* 100 UTC 1582 10 15
*
* <p>
* UUID version 1<br>
* {@code UUID} UUID UnsupportedOperationException
*
* @throws UnsupportedOperationException {@code UUID} version 1 UUID
*/
public long timestamp() throws UnsupportedOperationException
{
checkTimeBase();
return (mostSigBits & 0x0FFFL) << 48//
| ((mostSigBits >> 16) & 0x0FFFFL) << 32//
| mostSigBits >>> 32;
}
/**
* UUID
*
* <p>
* 14 UUID clock_seq clock_seq UUID
* <p>
* {@code clockSequence} UUID version 1 UUID UUID
* UnsupportedOperationException
*
* @return {@code UUID}
*
* @throws UnsupportedOperationException UUID version 1
*/
public int clockSequence() throws UnsupportedOperationException
{
checkTimeBase();
return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48);
}
/**
* UUID
*
* <p>
* 48 UUID node IEEE 802 UUID
* <p>
* UUID version 1<br>
* UUID UUID UnsupportedOperationException
*
* @return {@code UUID}
*
* @throws UnsupportedOperationException UUID version 1
*/
public long node() throws UnsupportedOperationException
{
checkTimeBase();
return leastSigBits & 0x0000FFFFFFFFFFFFL;
}
/**
* {@code UUID}
*
* <p>
* UUID BNF
*
* <pre>
* {@code
* UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
* time_low = 4*<hexOctet>
* time_mid = 2*<hexOctet>
* time_high_and_version = 2*<hexOctet>
* variant_and_sequence = 2*<hexOctet>
* node = 6*<hexOctet>
* hexOctet = <hexDigit><hexDigit>
* hexDigit = [0-9a-fA-F]
* }
* </pre>
*
* </blockquote>
*
* @return {@code UUID}
* @see #toString(boolean)
*/
@Override
public String toString()
{
return toString(false);
}
/**
* {@code UUID}
*
* <p>
* UUID BNF
*
* <pre>
* {@code
* UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
* time_low = 4*<hexOctet>
* time_mid = 2*<hexOctet>
* time_high_and_version = 2*<hexOctet>
* variant_and_sequence = 2*<hexOctet>
* node = 6*<hexOctet>
* hexOctet = <hexDigit><hexDigit>
* hexDigit = [0-9a-fA-F]
* }
* </pre>
*
* </blockquote>
*
* @param isSimple '-'UUID
* @return {@code UUID}
*/
public String toString(boolean isSimple)
{
final StringBuilder builder = new StringBuilder(isSimple ? 32 : 36);
// time_low
builder.append(digits(mostSigBits >> 32, 8));
if (false == isSimple)
{
builder.append('-');
}
// time_mid
builder.append(digits(mostSigBits >> 16, 4));
if (false == isSimple)
{
builder.append('-');
}
// time_high_and_version
builder.append(digits(mostSigBits, 4));
if (false == isSimple)
{
builder.append('-');
}
// variant_and_sequence
builder.append(digits(leastSigBits >> 48, 4));
if (false == isSimple)
{
builder.append('-');
}
// node
builder.append(digits(leastSigBits, 12));
return builder.toString();
}
/**
* UUID
*
* @return UUID
*/
@Override
public int hashCode()
{
long hilo = mostSigBits ^ leastSigBits;
return ((int) (hilo >> 32)) ^ (int) hilo;
}
/**
*
* <p>
* {@code null} UUID UUID varriant {@code true}
*
* @param obj
*
* @return {@code true} {@code false}
*/
@Override
public boolean equals(Object obj)
{
if ((null == obj) || (obj.getClass() != UUID.class))
{
return false;
}
UUID id = (UUID) obj;
return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits);
}
// Comparison Operations
/**
* UUID UUID
*
* <p>
* UUID UUID UUID UUID UUID
*
* @param val UUID UUID
*
* @return UUID val -10 1
*
*/
@Override
public int compareTo(UUID val)
{
// The ordering is intentionally set up so that the UUIDs
// can simply be numerically compared as two numbers
return (this.mostSigBits < val.mostSigBits ? -1 : //
(this.mostSigBits > val.mostSigBits ? 1 : //
(this.leastSigBits < val.leastSigBits ? -1 : //
(this.leastSigBits > val.leastSigBits ? 1 : //
0))));
}
// -------------------------------------------------------------------------------------------------------------------
// Private method start
/**
* hex
*
* @param val
* @param digits
* @return
*/
private static String digits(long val, int digits)
{
long hi = 1L << (digits * 4);
return Long.toHexString(hi | (val & (hi - 1))).substring(1);
}
/**
* time-basedUUID
*/
private void checkTimeBase()
{
if (version() != 1)
{
throw new UnsupportedOperationException("Not a time-based UUID");
}
}
/**
* {@link SecureRandom} (RNG)
*
* @return {@link SecureRandom}
*/
public static SecureRandom getSecureRandom()
{
try
{
return SecureRandom.getInstance("SHA1PRNG");
}
catch (NoSuchAlgorithmException e)
{
throw new UtilException(e);
}
}
/**
* <br>
* ThreadLocalRandomJDK 7线
*
* @return {@link ThreadLocalRandom}
*/
public static ThreadLocalRandom getRandom()
{
return ThreadLocalRandom.current();
}
}

View File

@ -1,18 +1,18 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
{
public static String YYYY = "yyyy"; public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM"; public static String YYYY_MM = "yyyy-MM";
@ -33,8 +33,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
* *
* @return Date() * @return Date()
*/ */
public static Date getNowDate() public static Date getNowDate() {
{
return new Date(); return new Date();
} }
@ -43,44 +42,34 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
* *
* @return String * @return String
*/ */
public static String getDate() public static String getDate() {
{
return dateTimeNow(YYYY_MM_DD); return dateTimeNow(YYYY_MM_DD);
} }
public static final String getTime() public static final String getTime() {
{
return dateTimeNow(YYYY_MM_DD_HH_MM_SS); return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
} }
public static final String dateTimeNow() public static final String dateTimeNow() {
{
return dateTimeNow(YYYYMMDDHHMMSS); return dateTimeNow(YYYYMMDDHHMMSS);
} }
public static final String dateTimeNow(final String format) public static final String dateTimeNow(final String format) {
{
return parseDateToStr(format, new Date()); return parseDateToStr(format, new Date());
} }
public static final String dateTime(final Date date) public static final String dateTime(final Date date) {
{
return parseDateToStr(YYYY_MM_DD, date); return parseDateToStr(YYYY_MM_DD, date);
} }
public static final String parseDateToStr(final String format, final Date date) public static final String parseDateToStr(final String format, final Date date) {
{
return new SimpleDateFormat(format).format(date); return new SimpleDateFormat(format).format(date);
} }
public static final Date dateTime(final String format, final String ts) public static final Date dateTime(final String format, final String ts) {
{ try {
try
{
return new SimpleDateFormat(format).parse(ts); return new SimpleDateFormat(format).parse(ts);
} } catch (ParseException e) {
catch (ParseException e)
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -88,8 +77,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* // 2018/08/08 * // 2018/08/08
*/ */
public static final String datePath() public static final String datePath() {
{
Date now = new Date(); Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd"); return DateFormatUtils.format(now, "yyyy/MM/dd");
} }
@ -97,8 +85,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* // 20180808 * // 20180808
*/ */
public static final String dateTime() public static final String dateTime() {
{
Date now = new Date(); Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd"); return DateFormatUtils.format(now, "yyyyMMdd");
} }
@ -106,18 +93,13 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* *
*/ */
public static Date parseDate(Object str) public static Date parseDate(Object str) {
{ if (str == null) {
if (str == null)
{
return null; return null;
} }
try try {
{
return parseDate(str.toString(), parsePatterns); return parseDate(str.toString(), parsePatterns);
} } catch (ParseException e) {
catch (ParseException e)
{
return null; return null;
} }
} }
@ -125,8 +107,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* *
*/ */
public static Date getServerStartDate() public static Date getServerStartDate() {
{
long time = ManagementFactory.getRuntimeMXBean().getStartTime(); long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time); return new Date(time);
} }
@ -134,8 +115,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/** /**
* *
*/ */
public static String getDatePoor(Date endDate, Date nowDate) public static String getDatePoor(Date endDate, Date nowDate) {
{
long nd = 1000 * 24 * 60 * 60; long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60; long nh = 1000 * 60 * 60;
long nm = 1000 * 60; long nm = 1000 * 60;

View File

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

View File

@ -1,51 +0,0 @@
package com.ruoyi.common.core.utils;
import com.ruoyi.common.core.text.UUID;
/**
* ID
*
* @author ruoyi
*/
public class IdUtils
{
/**
* UUID
*
* @return UUID
*/
public static String randomUUID()
{
return UUID.randomUUID().toString();
}
/**
* UUID线
*
* @return UUID线
*/
public static String simpleUUID()
{
return UUID.randomUUID().toString(true);
}
/**
* UUID使ThreadLocalRandomUUID
*
* @return UUID
*/
public static String fastUUID()
{
return UUID.fastUUID().toString();
}
/**
* UUID线使ThreadLocalRandomUUID
*
* @return UUID线
*/
public static String fastSimpleUUID()
{
return UUID.fastUUID().toString(true);
}
}

View File

@ -23,9 +23,9 @@ public class JsonUtils {
private static ObjectMapper objectMapper = SpringUtils.getBean(ObjectMapper.class); private static ObjectMapper objectMapper = SpringUtils.getBean(ObjectMapper.class);
public static String toJsonString(Object object) { public static String toJsonString(Object object) {
if (StringUtils.isNull(object)) { if (StringUtils.isNull(object)) {
return null; return null;
} }
try { try {
return objectMapper.writeValueAsString(object); return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
@ -56,9 +56,9 @@ public class JsonUtils {
} }
public static <T> T parseObject(String text, TypeReference<T> typeReference) { public static <T> T parseObject(String text, TypeReference<T> typeReference) {
if (StringUtils.isBlank(text)) { if (StringUtils.isBlank(text)) {
return null; return null;
} }
try { try {
return objectMapper.readValue(text, typeReference); return objectMapper.readValue(text, typeReference);
} catch (IOException e) { } catch (IOException e) {
@ -66,16 +66,17 @@ public class JsonUtils {
} }
} }
public static <T> Map<String, T> parseMap(String text) { public static <T> Map<String, T> parseMap(String text) {
if (StringUtils.isBlank(text)) { if (StringUtils.isBlank(text)) {
return null; return null;
} }
try { try {
return objectMapper.readValue(text, new TypeReference<Map<String, T>>() {}); return objectMapper.readValue(text, new TypeReference<Map<String, T>>() {
} catch (IOException e) { });
throw new RuntimeException(e); } catch (IOException e) {
} throw new RuntimeException(e);
} }
}
public static <T> List<T> parseArray(String text, Class<T> clazz) { public static <T> List<T> parseArray(String text, Class<T> clazz) {
if (StringUtils.isEmpty(text)) { if (StringUtils.isEmpty(text)) {

View File

@ -1,12 +1,12 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject; import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWTUtil; import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner; import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil; import cn.hutool.jwt.signers.JWTSignerUtil;
import com.ruoyi.common.core.constant.SecurityConstants; import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.TokenConstants; import com.ruoyi.common.core.constant.TokenConstants;
import com.ruoyi.common.core.text.Convert;
import java.util.Map; import java.util.Map;
@ -15,8 +15,7 @@ import java.util.Map;
* *
* @author ruoyi * @author ruoyi
*/ */
public class JwtUtils public class JwtUtils {
{
public static String secret = TokenConstants.SECRET; public static String secret = TokenConstants.SECRET;
/** /**
@ -25,8 +24,7 @@ public class JwtUtils
* @param claims * @param claims
* @return * @return
*/ */
public static String createToken(Map<String, Object> claims) public static String createToken(Map<String, Object> claims) {
{
JWTSigner signer = JWTSignerUtil.hs512(secret.getBytes()); JWTSigner signer = JWTSignerUtil.hs512(secret.getBytes());
String token = JWTUtil.createToken(claims, signer); String token = JWTUtil.createToken(claims, signer);
return token; return token;
@ -38,8 +36,7 @@ public class JwtUtils
* @param token * @param token
* @return * @return
*/ */
public static JSONObject parseToken(String token) public static JSONObject parseToken(String token) {
{
JWTSigner signer = JWTSignerUtil.hs512(secret.getBytes()); JWTSigner signer = JWTSignerUtil.hs512(secret.getBytes());
return JWTUtil.parseToken(token).setSigner(signer).getPayload().getClaimsJson(); return JWTUtil.parseToken(token).setSigner(signer).getPayload().getClaimsJson();
} }
@ -50,8 +47,7 @@ public class JwtUtils
* @param token * @param token
* @return ID * @return ID
*/ */
public static String getUserKey(String token) public static String getUserKey(String token) {
{
JSONObject claims = parseToken(token); JSONObject claims = parseToken(token);
return getValue(claims, SecurityConstants.USER_KEY); return getValue(claims, SecurityConstants.USER_KEY);
} }
@ -62,8 +58,7 @@ public class JwtUtils
* @param claims * @param claims
* @return ID * @return ID
*/ */
public static String getUserKey(JSONObject claims) public static String getUserKey(JSONObject claims) {
{
return getValue(claims, SecurityConstants.USER_KEY); return getValue(claims, SecurityConstants.USER_KEY);
} }
@ -73,8 +68,7 @@ public class JwtUtils
* @param token * @param token
* @return ID * @return ID
*/ */
public static String getUserId(String token) public static String getUserId(String token) {
{
JSONObject claims = parseToken(token); JSONObject claims = parseToken(token);
return getValue(claims, SecurityConstants.DETAILS_USER_ID); return getValue(claims, SecurityConstants.DETAILS_USER_ID);
} }
@ -85,8 +79,7 @@ public class JwtUtils
* @param claims * @param claims
* @return ID * @return ID
*/ */
public static String getUserId(JSONObject claims) public static String getUserId(JSONObject claims) {
{
return getValue(claims, SecurityConstants.DETAILS_USER_ID); return getValue(claims, SecurityConstants.DETAILS_USER_ID);
} }
@ -96,8 +89,7 @@ public class JwtUtils
* @param token * @param token
* @return * @return
*/ */
public static String getUserName(String token) public static String getUserName(String token) {
{
JSONObject claims = parseToken(token); JSONObject claims = parseToken(token);
return getValue(claims, SecurityConstants.DETAILS_USERNAME); return getValue(claims, SecurityConstants.DETAILS_USERNAME);
} }
@ -108,8 +100,7 @@ public class JwtUtils
* @param claims * @param claims
* @return * @return
*/ */
public static String getUserName(JSONObject claims) public static String getUserName(JSONObject claims) {
{
return getValue(claims, SecurityConstants.DETAILS_USERNAME); return getValue(claims, SecurityConstants.DETAILS_USERNAME);
} }
@ -117,11 +108,10 @@ public class JwtUtils
* *
* *
* @param claims * @param claims
* @param key * @param key
* @return * @return
*/ */
public static String getValue(JSONObject claims, String key) public static String getValue(JSONObject claims, String key) {
{
return Convert.toStr(claims.get(key), ""); return Convert.toStr(claims.get(key), "");
} }
} }

View File

@ -10,18 +10,15 @@ import com.ruoyi.common.core.web.page.TableSupport;
* *
* @author ruoyi * @author ruoyi
*/ */
public class PageUtils extends PageHelper public class PageUtils extends PageHelper {
{
/** /**
* *
*/ */
public static void startPage() public static void startPage() {
{
PageDomain pageDomain = TableSupport.buildPageRequest(); PageDomain pageDomain = TableSupport.buildPageRequest();
Integer pageNum = pageDomain.getPageNum(); Integer pageNum = pageDomain.getPageNum();
Integer pageSize = pageDomain.getPageSize(); Integer pageSize = pageDomain.getPageSize();
if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
{
String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
PageHelper.startPage(pageNum, pageSize, orderBy); PageHelper.startPage(pageNum, pageSize, orderBy);
} }

View File

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

View File

@ -1,15 +1,8 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import java.io.IOException; import cn.hutool.core.convert.Convert;
import java.io.UnsupportedEncodingException; import com.ruoyi.common.core.constant.Constants;
import java.net.URLDecoder; import com.ruoyi.common.core.domain.R;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@ -18,77 +11,74 @@ import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.text.Convert;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class ServletUtils public class ServletUtils {
{
/** /**
* String * String
*/ */
public static String getParameter(String name) public static String getParameter(String name) {
{
return getRequest().getParameter(name); return getRequest().getParameter(name);
} }
/** /**
* String * String
*/ */
public static String getParameter(String name, String defaultValue) public static String getParameter(String name, String defaultValue) {
{
return Convert.toStr(getRequest().getParameter(name), defaultValue); return Convert.toStr(getRequest().getParameter(name), defaultValue);
} }
/** /**
* Integer * Integer
*/ */
public static Integer getParameterToInt(String name) public static Integer getParameterToInt(String name) {
{
return Convert.toInt(getRequest().getParameter(name)); return Convert.toInt(getRequest().getParameter(name));
} }
/** /**
* Integer * Integer
*/ */
public static Integer getParameterToInt(String name, Integer defaultValue) public static Integer getParameterToInt(String name, Integer defaultValue) {
{
return Convert.toInt(getRequest().getParameter(name), defaultValue); return Convert.toInt(getRequest().getParameter(name), defaultValue);
} }
/** /**
* Boolean * Boolean
*/ */
public static Boolean getParameterToBool(String name) public static Boolean getParameterToBool(String name) {
{
return Convert.toBool(getRequest().getParameter(name)); return Convert.toBool(getRequest().getParameter(name));
} }
/** /**
* Boolean * Boolean
*/ */
public static Boolean getParameterToBool(String name, Boolean defaultValue) public static Boolean getParameterToBool(String name, Boolean defaultValue) {
{
return Convert.toBool(getRequest().getParameter(name), defaultValue); return Convert.toBool(getRequest().getParameter(name), defaultValue);
} }
/** /**
* request * request
*/ */
public static HttpServletRequest getRequest() public static HttpServletRequest getRequest() {
{ try {
try
{
return getRequestAttributes().getRequest(); return getRequestAttributes().getRequest();
} } catch (Exception e) {
catch (Exception e)
{
return null; return null;
} }
} }
@ -96,14 +86,10 @@ public class ServletUtils
/** /**
* response * response
*/ */
public static HttpServletResponse getResponse() public static HttpServletResponse getResponse() {
{ try {
try
{
return getRequestAttributes().getResponse(); return getRequestAttributes().getResponse();
} } catch (Exception e) {
catch (Exception e)
{
return null; return null;
} }
} }
@ -111,42 +97,32 @@ public class ServletUtils
/** /**
* session * session
*/ */
public static HttpSession getSession() public static HttpSession getSession() {
{
return getRequest().getSession(); return getRequest().getSession();
} }
public static ServletRequestAttributes getRequestAttributes() public static ServletRequestAttributes getRequestAttributes() {
{ try {
try
{
RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes; return (ServletRequestAttributes) attributes;
} } catch (Exception e) {
catch (Exception e)
{
return null; return null;
} }
} }
public static String getHeader(HttpServletRequest request, String name) public static String getHeader(HttpServletRequest request, String name) {
{
String value = request.getHeader(name); String value = request.getHeader(name);
if (StringUtils.isEmpty(value)) if (StringUtils.isEmpty(value)) {
{
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
return urlDecode(value); return urlDecode(value);
} }
public static Map<String, String> getHeaders(HttpServletRequest request) public static Map<String, String> getHeaders(HttpServletRequest request) {
{
Map<String, String> map = new LinkedHashMap<>(); Map<String, String> map = new LinkedHashMap<>();
Enumeration<String> enumeration = request.getHeaderNames(); Enumeration<String> enumeration = request.getHeaderNames();
if (enumeration != null) if (enumeration != null) {
{ while (enumeration.hasMoreElements()) {
while (enumeration.hasMoreElements())
{
String key = enumeration.nextElement(); String key = enumeration.nextElement();
String value = request.getHeader(key); String value = request.getHeader(key);
map.put(key, value); map.put(key, value);
@ -159,20 +135,16 @@ public class ServletUtils
* *
* *
* @param response * @param response
* @param string * @param string
* @return null * @return null
*/ */
public static String renderString(HttpServletResponse response, String string) public static String renderString(HttpServletResponse response, String string) {
{ try {
try
{
response.setStatus(200); response.setStatus(200);
response.setContentType("application/json"); response.setContentType("application/json");
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.getWriter().print(string); response.getWriter().print(string);
} } catch (IOException e) {
catch (IOException e)
{
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
@ -183,29 +155,24 @@ public class ServletUtils
* *
* @param request * @param request
*/ */
public static boolean isAjaxRequest(HttpServletRequest request) public static boolean isAjaxRequest(HttpServletRequest request) {
{
String accept = request.getHeader("accept"); String accept = request.getHeader("accept");
if (accept != null && accept.indexOf("application/json") != -1) if (accept != null && accept.indexOf("application/json") != -1) {
{
return true; return true;
} }
String xRequestedWith = request.getHeader("X-Requested-With"); String xRequestedWith = request.getHeader("X-Requested-With");
if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
{
return true; return true;
} }
String uri = request.getRequestURI(); String uri = request.getRequestURI();
if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) {
{
return true; return true;
} }
String ajax = request.getParameter("__ajax"); String ajax = request.getParameter("__ajax");
if (StringUtils.inStringIgnoreCase(ajax, "json", "xml")) if (StringUtils.inStringIgnoreCase(ajax, "json", "xml")) {
{
return true; return true;
} }
return false; return false;
@ -217,14 +184,10 @@ public class ServletUtils
* @param str * @param str
* @return * @return
*/ */
public static String urlEncode(String str) public static String urlEncode(String str) {
{ try {
try
{
return URLEncoder.encode(str, Constants.UTF8); return URLEncoder.encode(str, Constants.UTF8);
} } catch (UnsupportedEncodingException e) {
catch (UnsupportedEncodingException e)
{
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
} }
@ -235,14 +198,10 @@ public class ServletUtils
* @param str * @param str
* @return * @return
*/ */
public static String urlDecode(String str) public static String urlDecode(String str) {
{ try {
try
{
return URLDecoder.decode(str, Constants.UTF8); return URLDecoder.decode(str, Constants.UTF8);
} } catch (UnsupportedEncodingException e) {
catch (UnsupportedEncodingException e)
{
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
} }
@ -251,11 +210,10 @@ public class ServletUtils
* webflux * webflux
* *
* @param response ServerHttpResponse * @param response ServerHttpResponse
* @param value * @param value
* @return Mono<Void> * @return Mono<Void>
*/ */
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value) public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value) {
{
return webFluxResponseWriter(response, HttpStatus.OK, value, R.FAIL); return webFluxResponseWriter(response, HttpStatus.OK, value, R.FAIL);
} }
@ -263,12 +221,11 @@ public class ServletUtils
* webflux * webflux
* *
* @param response ServerHttpResponse * @param response ServerHttpResponse
* @param code * @param code
* @param value * @param value
* @return Mono<Void> * @return Mono<Void>
*/ */
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value, int code) public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value, int code) {
{
return webFluxResponseWriter(response, HttpStatus.OK, value, code); return webFluxResponseWriter(response, HttpStatus.OK, value, code);
} }
@ -276,28 +233,26 @@ public class ServletUtils
* webflux * webflux
* *
* @param response ServerHttpResponse * @param response ServerHttpResponse
* @param status http * @param status http
* @param code * @param code
* @param value * @param value
* @return Mono<Void> * @return Mono<Void>
*/ */
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, HttpStatus status, Object value, int code) public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, HttpStatus status, Object value, int code) {
{
return webFluxResponseWriter(response, MediaType.APPLICATION_JSON_VALUE, status, value, code); return webFluxResponseWriter(response, MediaType.APPLICATION_JSON_VALUE, status, value, code);
} }
/** /**
* webflux * webflux
* *
* @param response ServerHttpResponse * @param response ServerHttpResponse
* @param contentType content-type * @param contentType content-type
* @param status http * @param status http
* @param code * @param code
* @param value * @param value
* @return Mono<Void> * @return Mono<Void>
*/ */
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, HttpStatus status, Object value, int code) public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, HttpStatus status, Object value, int code) {
{
response.setStatusCode(status); response.setStatusCode(status);
response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType); response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
R<?> result = R.fail(code, value.toString()); R<?> result = R.fail(code, value.toString());

View File

@ -1,56 +1,17 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.aop.framework.AopContext; import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
* spring 便springbean * spring
* *
* @author ruoyi * @author Lion Li
*/ */
@Component @Component
public final class SpringUtils implements BeanFactoryPostProcessor public final class SpringUtils extends SpringUtil {
{
/** Spring应用上下文环境 */
private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
SpringUtils.beanFactory = beanFactory;
}
/**
*
*
* @param name
* @return Object bean
* @throws org.springframework.beans.BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException
{
return (T) beanFactory.getBean(name);
}
/**
* requiredType
*
* @param clz
* @return
* @throws org.springframework.beans.BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException
{
T result = (T) beanFactory.getBean(clz);
return result;
}
/** /**
* BeanFactorybeantrue * BeanFactorybeantrue
@ -58,46 +19,36 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param name * @param name
* @return boolean * @return boolean
*/ */
public static boolean containsBean(String name) public static boolean containsBean(String name) {
{ return getBeanFactory().containsBean(name);
return beanFactory.containsBean(name);
} }
/** /**
* beansingletonprototype beanNoSuchBeanDefinitionException * beansingletonprototype
* beanNoSuchBeanDefinitionException
* *
* @param name * @param name
* @return boolean * @return boolean
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/ */
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
{ return getBeanFactory().isSingleton(name);
return beanFactory.isSingleton(name);
} }
/** /**
* @param name * @param name
* @return Class * @return Class
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/ */
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
{ return getBeanFactory().getType(name);
return beanFactory.getType(name);
} }
/** /**
* beanbean * beanbean
* *
* @param name * @param name
* @return
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/ */
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
{ return getBeanFactory().getAliases(name);
return beanFactory.getAliases(name);
} }
/** /**
@ -107,8 +58,7 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @return * @return
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T getAopProxy(T invoker) public static <T> T getAopProxy(T invoker) {
{
return (T) AopContext.currentProxy(); return (T) AopContext.currentProxy();
} }
} }

View File

@ -1,481 +1,357 @@
package com.ruoyi.common.core.utils; package com.ruoyi.common.core.utils;
import java.util.Collection; import cn.hutool.core.collection.CollUtil;
import java.util.List; import cn.hutool.core.lang.Validator;
import java.util.Map; import cn.hutool.core.map.MapUtil;
import org.springframework.util.AntPathMatcher; import cn.hutool.core.util.ArrayUtil;
import com.ruoyi.common.core.constant.Constants; import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.text.StrFormatter; import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.*;
/** /**
* *
* *
* @author ruoyi * @author Lion Li
*/ */
public class StringUtils extends org.apache.commons.lang3.StringUtils @NoArgsConstructor(access = AccessLevel.PRIVATE)
{ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/** 空字符串 */
private static final String NULLSTR = "";
/** 下划线 */ /**
private static final char SEPARATOR = '_'; *
*
* @param value defaultValue value
* @return value
*/
public static <T> T nvl(T value, T defaultValue) {
return ObjectUtil.defaultIfNull(value, defaultValue);
}
/** /**
* *
* *
* @param value defaultValue value * @param str defaultValue value
* @return value * @return value
*/ */
public static <T> T nvl(T value, T defaultValue) public static String blankToDefault(String str, String defaultValue) {
{ return StrUtil.blankToDefault(str, defaultValue);
return value != null ? value : defaultValue; }
}
/** /**
* * Collection ListSetQueue * * Collection ListSetQueue
* *
* @param coll Collection * @param coll Collection
* @return true false * @return true false
*/ */
public static boolean isEmpty(Collection<?> coll) public static boolean isEmpty(Collection<?> coll) {
{ return CollUtil.isEmpty(coll);
return isNull(coll) || coll.isEmpty(); }
}
/** /**
* * CollectionListSetQueue * * CollectionListSetQueue
* *
* @param coll Collection * @param coll Collection
* @return true false * @return true false
*/ */
public static boolean isNotEmpty(Collection<?> coll) public static boolean isNotEmpty(Collection<?> coll) {
{ return !isEmpty(coll);
return !isEmpty(coll); }
}
/** /**
* * * *
* *
* @param objects * @param objects
** @return true false * * @return true false
*/ */
public static boolean isEmpty(Object[] objects) public static boolean isEmpty(Object[] objects) {
{ return ArrayUtil.isEmpty(objects);
return isNull(objects) || (objects.length == 0); }
}
/** /**
* * * *
* *
* @param objects * @param objects
* @return true false * @return true false
*/ */
public static boolean isNotEmpty(Object[] objects) public static boolean isNotEmpty(Object[] objects) {
{ return !isEmpty(objects);
return !isEmpty(objects); }
}
/** /**
* * Map * *
* *
* @param map Map * @param object
* @return true false * * @return true false
*/ */
public static boolean isEmpty(Map<?, ?> map) public static boolean isEmpty(Object object) {
{ return ObjectUtil.isEmpty(object);
return isNull(map) || map.isEmpty(); }
}
/** /**
* * Map * *
* *
* @param map Map * @param object
* @return true false * @return true false
*/ */
public static boolean isNotEmpty(Map<?, ?> map) public static boolean isNotEmpty(Object object) {
{ return !isEmpty(object);
return !isEmpty(map); }
}
/** /**
* * * * Map
* *
* @param str String * @param map Map
* @return true false * @return true false
*/ */
public static boolean isEmpty(String str) public static boolean isEmpty(Map<?, ?> map) {
{ return MapUtil.isEmpty(map);
return isNull(str) || NULLSTR.equals(str.trim()); }
}
/** /**
* * * * Map
* *
* @param str String * @param map Map
* @return true false * @return true false
*/ */
public static boolean isNotEmpty(String str) public static boolean isNotEmpty(Map<?, ?> map) {
{ return !isEmpty(map);
return !isEmpty(str); }
}
/** /**
* * * *
* *
* @param object Object * @param str String
* @return true false * @return true false
*/ */
public static boolean isNull(Object object) public static boolean isEmpty(String str) {
{ return StrUtil.isEmpty(str);
return object == null; }
}
/** /**
* * * *
* *
* @param object Object * @param str String
* @return true false * @return true false
*/ */
public static boolean isNotNull(Object object) public static boolean isNotEmpty(String str) {
{ return !isEmpty(str);
return !isNull(object); }
}
/** /**
* * Java * *
* *
* @param object * @param object Object
* @return true false * @return true false
*/ */
public static boolean isArray(Object object) public static boolean isNull(Object object) {
{ return ObjectUtil.isNull(object);
return isNotNull(object) && object.getClass().isArray(); }
}
/** /**
* * *
*/ *
public static String trim(String str) * @param object Object
{ * @return true false
return (str == null ? "" : str.trim()); */
} public static boolean isNotNull(Object object) {
return !isNull(object);
}
/** /**
* * * Java
* *
* @param str * @param object
* @param start * @return true false
* @return */
*/ public static boolean isArray(Object object) {
public static String substring(final String str, int start) return ArrayUtil.isArray(object);
{ }
if (str == null)
{
return NULLSTR;
}
if (start < 0) /**
{ *
start = str.length() + start; */
} public static String trim(String str) {
return StrUtil.trim(str);
}
if (start < 0) /**
{ *
start = 0; *
} * @param str
if (start > str.length()) * @param start
{ * @return
return NULLSTR; */
} public static String substring(final String str, int start) {
return substring(str, start, str.length());
}
return str.substring(start); /**
} *
*
* @param str
* @param start
* @param end
* @return
*/
public static String substring(final String str, int start, int end) {
return StrUtil.sub(str, start, end);
}
/** /**
* * , {} <br>
* * {} <br>
* @param str * {} 使 \\ { {} \ 使 \\\\ <br>
* @param start * <br>
* @param end * 使format("this is {} for {}", "a", "b") -> this is a for b<br>
* @return * {} format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
*/ * \ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
public static String substring(final String str, int start, int end) *
{ * @param template {}
if (str == null) * @param params
{ * @return
return NULLSTR; */
} public static String format(String template, Object... params) {
return StrUtil.format(template, params);
}
if (end < 0) /**
{ * http(s)://开头
end = str.length() + end; *
} * @param link
if (start < 0) * @return
{ */
start = str.length() + start; public static boolean ishttp(String link) {
} return Validator.isUrl(link);
}
if (end > str.length()) /**
{ * set
end = str.length(); *
} * @param str
* @param sep
* @return set
*/
public static Set<String> str2Set(String str, String sep) {
return new HashSet<>(str2List(str, sep, true, false));
}
if (start > end) /**
{ * list
return NULLSTR; *
} * @param str
* @param sep
* @param filterBlank
* @param trim
* @return list
*/
public static List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
List<String> list = new ArrayList<>();
if (isEmpty(str)) {
return list;
}
if (start < 0) // 过滤空白字符串
{ if (filterBlank && isBlank(str)) {
start = 0; return list;
} }
if (end < 0) String[] split = str.split(sep);
{ for (String string : split) {
end = 0; if (filterBlank && isBlank(string)) {
} continue;
}
if (trim) {
string = trim(string);
}
list.add(string);
}
return str.substring(start, end); return list;
} }
/** /**
* *
* *
* @param str value * @param cs
* @return * @param searchCharSequences
*/ * @return
public static boolean hasText(String str) */
{ public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {
return (str != null && !str.isEmpty() && containsText(str)); return StrUtil.containsAnyIgnoreCase(cs, searchCharSequences);
} }
private static boolean containsText(CharSequence str) /**
{ * 线
int strLen = str.length(); */
for (int i = 0; i < strLen; i++) public static String toUnderScoreCase(String str) {
{ return StrUtil.toUnderlineCase(str);
if (!Character.isWhitespace(str.charAt(i))) }
{
return true;
}
}
return false;
}
/** /**
* , {} <br> *
* {} <br> *
* {} 使 \\ { {} \ 使 \\\\ <br> * @param str
* <br> * @param strs
* 使format("this is {} for {}", "a", "b") -> this is a for b<br> * @return true
* {} format("this is \\{} for {}", "a", "b") -> this is \{} for a<br> */
* \ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br> public static boolean inStringIgnoreCase(String str, String... strs) {
* return StrUtil.equalsAnyIgnoreCase(str, strs);
* @param template {} }
* @param params
* @return
*/
public static String format(String template, Object... params)
{
if (isEmpty(params) || isEmpty(template))
{
return template;
}
return StrFormatter.format(template, params);
}
/** /**
* http(s)://开头 * 线线 HELLO_WORLD->HelloWorld
* *
* @param link * @param name 线
* @return * @return
*/ */
public static boolean ishttp(String link) public static String convertToCamelCase(String name) {
{ return StrUtil.upperFirst(StrUtil.toCamelCase(name));
return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS); }
}
/** /**
* 线 * user_name->userName
*/ */
public static String toUnderScoreCase(String str) public static String toCamelCase(String s) {
{ return StrUtil.toCamelCase(s);
if (str == null) }
{
return null;
}
StringBuilder sb = new StringBuilder();
// 前置字符是否大写
boolean preCharIsUpperCase = true;
// 当前字符是否大写
boolean curreCharIsUpperCase = true;
// 下一字符是否大写
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if (i > 0)
{
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
}
else
{
preCharIsUpperCase = false;
}
curreCharIsUpperCase = Character.isUpperCase(c); /**
*
*
* @param str
* @param strs
* @return
*/
public static boolean matches(String str, List<String> strs) {
if (isEmpty(str) || isEmpty(strs)) {
return false;
}
for (String pattern : strs) {
if (isMatch(pattern, str)) {
return true;
}
}
return false;
}
if (i < (str.length() - 1)) /**
{ * url:
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1)); * ? ;
} * * ;
* ** ;
*
* @param pattern
* @param url url
* @return
*/
public static boolean isMatch(String pattern, String url) {
return ReUtil.isMatch(pattern, url);
}
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) @SuppressWarnings("unchecked")
{ public static <T> T cast(Object obj) {
sb.append(SEPARATOR); return (T) obj;
} }
else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)
{
sb.append(SEPARATOR);
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
/**
*
*
* @param str
* @param strs
* @return true
*/
public static boolean inStringIgnoreCase(String str, String... strs)
{
if (str != null && strs != null)
{
for (String s : strs)
{
if (str.equalsIgnoreCase(trim(s)))
{
return true;
}
}
}
return false;
}
/**
* 线线 HELLO_WORLD->HelloWorld
*
* @param name 线
* @return
*/
public static String convertToCamelCase(String name)
{
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty())
{
// 没必要转换
return "";
}
else if (!name.contains("_"))
{
// 不含下划线,仅将首字母大写
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
// 用下划线将原始字符串分割
String[] camels = name.split("_");
for (String camel : camels)
{
// 跳过原始字符串中开头、结尾的下换线或双重下划线
if (camel.isEmpty())
{
continue;
}
// 首字母大写
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
return result.toString();
}
/**
* user_name->userName
*/
public static String toCamelCase(String s)
{
if (s == null)
{
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c == SEPARATOR)
{
upperCase = true;
}
else if (upperCase)
{
sb.append(Character.toUpperCase(c));
upperCase = false;
}
else
{
sb.append(c);
}
}
return sb.toString();
}
/**
*
*
* @param str
* @param strs
* @return
*/
public static boolean matches(String str, List<String> strs)
{
if (isEmpty(str) || isEmpty(strs))
{
return false;
}
for (String pattern : strs)
{
if (isMatch(pattern, str))
{
return true;
}
}
return false;
}
/**
* url:
* ? ;
* * ;
* ** ;
*
* @param pattern
* @param url url
* @return
*/
public static boolean isMatch(String pattern, String url)
{
AntPathMatcher matcher = new AntPathMatcher();
return matcher.match(pattern, url);
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj)
{
return (T) obj;
}
} }

View File

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

View File

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

View File

@ -1,15 +1,15 @@
package com.ruoyi.common.core.utils.file; package com.ruoyi.common.core.utils.file;
import java.io.File;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import java.io.File;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class FileTypeUtils public class FileTypeUtils {
{
/** /**
* *
* <p> * <p>
@ -18,10 +18,8 @@ public class FileTypeUtils
* @param file * @param file
* @return ".") * @return ".")
*/ */
public static String getFileType(File file) public static String getFileType(File file) {
{ if (null == file) {
if (null == file)
{
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
return getFileType(file.getName()); return getFileType(file.getName());
@ -35,11 +33,9 @@ public class FileTypeUtils
* @param fileName * @param fileName
* @return ".") * @return ".")
*/ */
public static String getFileType(String fileName) public static String getFileType(String fileName) {
{
int separatorIndex = fileName.lastIndexOf("."); int separatorIndex = fileName.lastIndexOf(".");
if (separatorIndex < 0) if (separatorIndex < 0) {
{
return ""; return "";
} }
return fileName.substring(separatorIndex + 1).toLowerCase(); return fileName.substring(separatorIndex + 1).toLowerCase();
@ -51,24 +47,16 @@ public class FileTypeUtils
* @param photoByte * @param photoByte
* @return ".") * @return ".")
*/ */
public static String getFileExtendName(byte[] photoByte) public static String getFileExtendName(byte[] photoByte) {
{
String strFileExtendName = "JPG"; String strFileExtendName = "JPG";
if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56) if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
&& ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) {
{
strFileExtendName = "GIF"; strFileExtendName = "GIF";
} } else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) {
else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70))
{
strFileExtendName = "JPG"; strFileExtendName = "JPG";
} } else if ((photoByte[0] == 66) && (photoByte[1] == 77)) {
else if ((photoByte[0] == 66) && (photoByte[1] == 77))
{
strFileExtendName = "BMP"; strFileExtendName = "BMP";
} } else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) {
else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71))
{
strFileExtendName = "PNG"; strFileExtendName = "PNG";
} }
return strFileExtendName; return strFileExtendName;

View File

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

View File

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

View File

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

View File

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

View File

@ -1,570 +0,0 @@
package com.ruoyi.common.core.utils.html;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* HTMLXSS
*
* @author ruoyi
*/
public final class HTMLFilter
{
/**
* regex flag union representing /si modifiers in php
**/
private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL;
private static final Pattern P_COMMENTS = Pattern.compile("<!--(.*?)-->", Pattern.DOTALL);
private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI);
private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL);
private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI);
private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI);
private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI);
private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI);
private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI);
private static final Pattern P_ENTITY = Pattern.compile("&#(\\d+);?");
private static final Pattern P_ENTITY_UNICODE = Pattern.compile("&#x([0-9a-f]+);?");
private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?");
private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))");
private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL);
private static final Pattern P_END_ARROW = Pattern.compile("^>");
private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)");
private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)");
private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)");
private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)");
private static final Pattern P_AMP = Pattern.compile("&");
private static final Pattern P_QUOTE = Pattern.compile("\"");
private static final Pattern P_LEFT_ARROW = Pattern.compile("<");
private static final Pattern P_RIGHT_ARROW = Pattern.compile(">");
private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>");
// @xxx could grow large... maybe use sesat's ReferenceMap
private static final ConcurrentMap<String, Pattern> P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, Pattern> P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<>();
/**
* set of allowed html elements, along with allowed attributes for each element
**/
private final Map<String, List<String>> vAllowed;
/**
* counts of open tags for each (allowable) html element
**/
private final Map<String, Integer> vTagCounts = new HashMap<>();
/**
* html elements which must always be self-closing (e.g. "<img />")
**/
private final String[] vSelfClosingTags;
/**
* html elements which must always have separate opening and closing tags (e.g. "<b></b>")
**/
private final String[] vNeedClosingTags;
/**
* set of disallowed html elements
**/
private final String[] vDisallowed;
/**
* attributes which should be checked for valid protocols
**/
private final String[] vProtocolAtts;
/**
* allowed protocols
**/
private final String[] vAllowedProtocols;
/**
* tags which should be removed if they contain no content (e.g. "<b></b>" or "<b />")
**/
private final String[] vRemoveBlanks;
/**
* entities allowed within html markup
**/
private final String[] vAllowedEntities;
/**
* flag determining whether comments are allowed in input String.
*/
private final boolean stripComment;
private final boolean encodeQuotes;
/**
* flag determining whether to try to make tags when presented with "unbalanced" angle brackets (e.g. "<b text </b>"
* becomes "<b> text </b>"). If set to false, unbalanced angle brackets will be html escaped.
*/
private final boolean alwaysMakeTags;
/**
* Default constructor.
*/
public HTMLFilter()
{
vAllowed = new HashMap<>();
final ArrayList<String> a_atts = new ArrayList<>();
a_atts.add("href");
a_atts.add("target");
vAllowed.put("a", a_atts);
final ArrayList<String> img_atts = new ArrayList<>();
img_atts.add("src");
img_atts.add("width");
img_atts.add("height");
img_atts.add("alt");
vAllowed.put("img", img_atts);
final ArrayList<String> no_atts = new ArrayList<>();
vAllowed.put("b", no_atts);
vAllowed.put("strong", no_atts);
vAllowed.put("i", no_atts);
vAllowed.put("em", no_atts);
vSelfClosingTags = new String[] { "img" };
vNeedClosingTags = new String[] { "a", "b", "strong", "i", "em" };
vDisallowed = new String[] {};
vAllowedProtocols = new String[] { "http", "mailto", "https" }; // no ftp.
vProtocolAtts = new String[] { "src", "href" };
vRemoveBlanks = new String[] { "a", "b", "strong", "i", "em" };
vAllowedEntities = new String[] { "amp", "gt", "lt", "quot" };
stripComment = true;
encodeQuotes = true;
alwaysMakeTags = false;
}
/**
* Map-parameter configurable constructor.
*
* @param conf map containing configuration. keys match field names.
*/
@SuppressWarnings("unchecked")
public HTMLFilter(final Map<String, Object> conf)
{
assert conf.containsKey("vAllowed") : "configuration requires vAllowed";
assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags";
assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags";
assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed";
assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols";
assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts";
assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks";
assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities";
vAllowed = Collections.unmodifiableMap((HashMap<String, List<String>>) conf.get("vAllowed"));
vSelfClosingTags = (String[]) conf.get("vSelfClosingTags");
vNeedClosingTags = (String[]) conf.get("vNeedClosingTags");
vDisallowed = (String[]) conf.get("vDisallowed");
vAllowedProtocols = (String[]) conf.get("vAllowedProtocols");
vProtocolAtts = (String[]) conf.get("vProtocolAtts");
vRemoveBlanks = (String[]) conf.get("vRemoveBlanks");
vAllowedEntities = (String[]) conf.get("vAllowedEntities");
stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true;
encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true;
alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true;
}
private void reset()
{
vTagCounts.clear();
}
// ---------------------------------------------------------------
// my versions of some PHP library functions
public static String chr(final int decimal)
{
return String.valueOf((char) decimal);
}
public static String htmlSpecialChars(final String s)
{
String result = s;
result = regexReplace(P_AMP, "&amp;", result);
result = regexReplace(P_QUOTE, "&quot;", result);
result = regexReplace(P_LEFT_ARROW, "&lt;", result);
result = regexReplace(P_RIGHT_ARROW, "&gt;", result);
return result;
}
// ---------------------------------------------------------------
/**
* given a user submitted input String, filter out any invalid or restricted html.
*
* @param input text (i.e. submitted by a user) than may contain html
* @return "clean" version of input, with only valid, whitelisted html elements allowed
*/
public String filter(final String input)
{
reset();
String s = input;
s = escapeComments(s);
s = balanceHTML(s);
s = checkTags(s);
s = processRemoveBlanks(s);
// s = validateEntities(s);
return s;
}
public boolean isAlwaysMakeTags()
{
return alwaysMakeTags;
}
public boolean isStripComments()
{
return stripComment;
}
private String escapeComments(final String s)
{
final Matcher m = P_COMMENTS.matcher(s);
final StringBuffer buf = new StringBuffer();
if (m.find())
{
final String match = m.group(1); // (.*?)
m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->"));
}
m.appendTail(buf);
return buf.toString();
}
private String balanceHTML(String s)
{
if (alwaysMakeTags)
{
//
// try and form html
//
s = regexReplace(P_END_ARROW, "", s);
// 不追加结束标签
s = regexReplace(P_BODY_TO_END, "<$1>", s);
s = regexReplace(P_XML_CONTENT, "$1<$2", s);
}
else
{
//
// escape stray brackets
//
s = regexReplace(P_STRAY_LEFT_ARROW, "&lt;$1", s);
s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2&gt;<", s);
//
// the last regexp causes '<>' entities to appear
// (we need to do a lookahead assertion so that the last bracket can
// be used in the next pass of the regexp)
//
s = regexReplace(P_BOTH_ARROWS, "", s);
}
return s;
}
private String checkTags(String s)
{
Matcher m = P_TAGS.matcher(s);
final StringBuffer buf = new StringBuffer();
while (m.find())
{
String replaceStr = m.group(1);
replaceStr = processTag(replaceStr);
m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr));
}
m.appendTail(buf);
// these get tallied in processTag
// (remember to reset before subsequent calls to filter method)
final StringBuilder sBuilder = new StringBuilder(buf.toString());
for (String key : vTagCounts.keySet())
{
for (int ii = 0; ii < vTagCounts.get(key); ii++)
{
sBuilder.append("</").append(key).append(">");
}
}
s = sBuilder.toString();
return s;
}
private String processRemoveBlanks(final String s)
{
String result = s;
for (String tag : vRemoveBlanks)
{
if (!P_REMOVE_PAIR_BLANKS.containsKey(tag))
{
P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
}
result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result);
if (!P_REMOVE_SELF_BLANKS.containsKey(tag))
{
P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
}
result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result);
}
return result;
}
private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s)
{
Matcher m = regex_pattern.matcher(s);
return m.replaceAll(replacement);
}
private String processTag(final String s)
{
// ending tags
Matcher m = P_END_TAG.matcher(s);
if (m.find())
{
final String name = m.group(1).toLowerCase();
if (allowed(name))
{
if (false == inArray(name, vSelfClosingTags))
{
if (vTagCounts.containsKey(name))
{
vTagCounts.put(name, vTagCounts.get(name) - 1);
return "</" + name + ">";
}
}
}
}
// starting tags
m = P_START_TAG.matcher(s);
if (m.find())
{
final String name = m.group(1).toLowerCase();
final String body = m.group(2);
String ending = m.group(3);
// debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" );
if (allowed(name))
{
final StringBuilder params = new StringBuilder();
final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body);
final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body);
final List<String> paramNames = new ArrayList<>();
final List<String> paramValues = new ArrayList<>();
while (m2.find())
{
paramNames.add(m2.group(1)); // ([a-z0-9]+)
paramValues.add(m2.group(3)); // (.*?)
}
while (m3.find())
{
paramNames.add(m3.group(1)); // ([a-z0-9]+)
paramValues.add(m3.group(3)); // ([^\"\\s']+)
}
String paramName, paramValue;
for (int ii = 0; ii < paramNames.size(); ii++)
{
paramName = paramNames.get(ii).toLowerCase();
paramValue = paramValues.get(ii);
// debug( "paramName='" + paramName + "'" );
// debug( "paramValue='" + paramValue + "'" );
// debug( "allowed? " + vAllowed.get( name ).contains( paramName ) );
if (allowedAttribute(name, paramName))
{
if (inArray(paramName, vProtocolAtts))
{
paramValue = processParamProtocol(paramValue);
}
params.append(' ').append(paramName).append("=\\\"").append(paramValue).append("\"");
}
}
if (inArray(name, vSelfClosingTags))
{
ending = " /";
}
if (inArray(name, vNeedClosingTags))
{
ending = "";
}
if (ending == null || ending.length() < 1)
{
if (vTagCounts.containsKey(name))
{
vTagCounts.put(name, vTagCounts.get(name) + 1);
}
else
{
vTagCounts.put(name, 1);
}
}
else
{
ending = " /";
}
return "<" + name + params + ending + ">";
}
else
{
return "";
}
}
// comments
m = P_COMMENT.matcher(s);
if (!stripComment && m.find())
{
return "<" + m.group() + ">";
}
return "";
}
private String processParamProtocol(String s)
{
s = decodeEntities(s);
final Matcher m = P_PROTOCOL.matcher(s);
if (m.find())
{
final String protocol = m.group(1);
if (!inArray(protocol, vAllowedProtocols))
{
// bad protocol, turn into local anchor link instead
s = "#" + s.substring(protocol.length() + 1);
if (s.startsWith("#//"))
{
s = "#" + s.substring(3);
}
}
}
return s;
}
private String decodeEntities(String s)
{
StringBuffer buf = new StringBuffer();
Matcher m = P_ENTITY.matcher(s);
while (m.find())
{
final String match = m.group(1);
final int decimal = Integer.decode(match).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
}
m.appendTail(buf);
s = buf.toString();
buf = new StringBuffer();
m = P_ENTITY_UNICODE.matcher(s);
while (m.find())
{
final String match = m.group(1);
final int decimal = Integer.valueOf(match, 16).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
}
m.appendTail(buf);
s = buf.toString();
buf = new StringBuffer();
m = P_ENCODE.matcher(s);
while (m.find())
{
final String match = m.group(1);
final int decimal = Integer.valueOf(match, 16).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
}
m.appendTail(buf);
s = buf.toString();
s = validateEntities(s);
return s;
}
private String validateEntities(final String s)
{
StringBuffer buf = new StringBuffer();
// validate entities throughout the string
Matcher m = P_VALID_ENTITIES.matcher(s);
while (m.find())
{
final String one = m.group(1); // ([^&;]*)
final String two = m.group(2); // (?=(;|&|$))
m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two)));
}
m.appendTail(buf);
return encodeQuotes(buf.toString());
}
private String encodeQuotes(final String s)
{
if (encodeQuotes)
{
StringBuffer buf = new StringBuffer();
Matcher m = P_VALID_QUOTES.matcher(s);
while (m.find())
{
final String one = m.group(1); // (>|^)
final String two = m.group(2); // ([^<]+?)
final String three = m.group(3); // (<|$)
// 不替换双引号为&quot;防止json格式无效 regexReplace(P_QUOTE, "&quot;", two)
m.appendReplacement(buf, Matcher.quoteReplacement(one + two + three));
}
m.appendTail(buf);
return buf.toString();
}
else
{
return s;
}
}
private String checkEntity(final String preamble, final String term)
{
return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&amp;" + preamble;
}
private boolean isValidEntity(final String entity)
{
return inArray(entity, vAllowedEntities);
}
private static boolean inArray(final String s, final String[] array)
{
for (String item : array)
{
if (item != null && item.equals(s))
{
return true;
}
}
return false;
}
private boolean allowed(final String name)
{
return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed);
}
private boolean allowedAttribute(final String name, final String paramName)
{
return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName));
}
}

View File

@ -1,21 +1,19 @@
package com.ruoyi.common.core.utils.ip; package com.ruoyi.common.core.utils.ip;
import com.ruoyi.common.core.utils.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
import com.ruoyi.common.core.utils.StringUtils;
/** /**
* IP * IP
* *
* @author ruoyi * @author ruoyi
*/ */
public class IpUtils public class IpUtils {
{ public static String getIpAddr(HttpServletRequest request) {
public static String getIpAddr(HttpServletRequest request) if (request == null) {
{
if (request == null)
{
return null; return null;
} }
@ -23,51 +21,42 @@ public class IpUtils
// X-Forwarded-ForSquid 服务代理 // X-Forwarded-ForSquid 服务代理
String ipAddresses = request.getHeader("X-Forwarded-For"); String ipAddresses = request.getHeader("X-Forwarded-For");
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
{
// Proxy-Client-IPapache 服务代理 // Proxy-Client-IPapache 服务代理
ipAddresses = request.getHeader("Proxy-Client-IP"); ipAddresses = request.getHeader("Proxy-Client-IP");
} }
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
{
// WL-Proxy-Client-IPweblogic 服务代理 // WL-Proxy-Client-IPweblogic 服务代理
ipAddresses = request.getHeader("WL-Proxy-Client-IP"); ipAddresses = request.getHeader("WL-Proxy-Client-IP");
} }
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
{
// HTTP_CLIENT_IP有些代理服务器 // HTTP_CLIENT_IP有些代理服务器
ipAddresses = request.getHeader("HTTP_CLIENT_IP"); ipAddresses = request.getHeader("HTTP_CLIENT_IP");
} }
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
{
// X-Real-IPnginx服务代理 // X-Real-IPnginx服务代理
ipAddresses = request.getHeader("X-Real-IP"); ipAddresses = request.getHeader("X-Real-IP");
} }
// 有些网络通过多层代理那么获取到的ip就会有多个一般都是通过逗号,分割开来并且第一个ip为客户端的真实IP // 有些网络通过多层代理那么获取到的ip就会有多个一般都是通过逗号,分割开来并且第一个ip为客户端的真实IP
if (ipAddresses != null && ipAddresses.length() != 0) if (ipAddresses != null && ipAddresses.length() != 0) {
{
ip = ipAddresses.split(",")[0]; ip = ipAddresses.split(",")[0];
} }
// 还是不能获取到最后再通过request.getRemoteAddr();获取 // 还是不能获取到最后再通过request.getRemoteAddr();获取
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
{
ip = request.getRemoteAddr(); ip = request.getRemoteAddr();
} }
return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip; return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
} }
public static boolean internalIp(String ip) public static boolean internalIp(String ip) {
{
byte[] addr = textToNumericFormatV4(ip); byte[] addr = textToNumericFormatV4(ip);
return internalIp(addr) || "127.0.0.1".equals(ip); return internalIp(addr) || "127.0.0.1".equals(ip);
} }
private static boolean internalIp(byte[] addr) private static boolean internalIp(byte[] addr) {
{ if (StringUtils.isNull(addr) || addr.length < 2) {
if (StringUtils.isNull(addr) || addr.length < 2)
{
return true; return true;
} }
final byte b0 = addr[0]; final byte b0 = addr[0];
@ -81,18 +70,15 @@ public class IpUtils
// 192.168.x.x/16 // 192.168.x.x/16
final byte SECTION_5 = (byte) 0xC0; final byte SECTION_5 = (byte) 0xC0;
final byte SECTION_6 = (byte) 0xA8; final byte SECTION_6 = (byte) 0xA8;
switch (b0) switch (b0) {
{
case SECTION_1: case SECTION_1:
return true; return true;
case SECTION_2: case SECTION_2:
if (b1 >= SECTION_3 && b1 <= SECTION_4) if (b1 >= SECTION_3 && b1 <= SECTION_4) {
{
return true; return true;
} }
case SECTION_5: case SECTION_5:
switch (b1) switch (b1) {
{
case SECTION_6: case SECTION_6:
return true; return true;
} }
@ -107,24 +93,20 @@ public class IpUtils
* @param text IPv4 * @param text IPv4
* @return byte * @return byte
*/ */
public static byte[] textToNumericFormatV4(String text) public static byte[] textToNumericFormatV4(String text) {
{ if (text.length() == 0) {
if (text.length() == 0)
{
return null; return null;
} }
byte[] bytes = new byte[4]; byte[] bytes = new byte[4];
String[] elements = text.split("\\.", -1); String[] elements = text.split("\\.", -1);
try try {
{
long l; long l;
int i; int i;
switch (elements.length) switch (elements.length) {
{
case 1: case 1:
l = Long.parseLong(elements[0]); l = Long.parseLong(elements[0]);
if ((l < 0L) || (l > 4294967295L)){ if ((l < 0L) || (l > 4294967295L)) {
return null; return null;
} }
bytes[0] = (byte) (int) (l >> 24 & 0xFF); bytes[0] = (byte) (int) (l >> 24 & 0xFF);
@ -147,8 +129,7 @@ public class IpUtils
bytes[3] = (byte) (int) (l & 0xFF); bytes[3] = (byte) (int) (l & 0xFF);
break; break;
case 3: case 3:
for (i = 0; i < 2; ++i) for (i = 0; i < 2; ++i) {
{
l = Integer.parseInt(elements[i]); l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L)) { if ((l < 0L) || (l > 255L)) {
return null; return null;
@ -163,8 +144,7 @@ public class IpUtils
bytes[3] = (byte) (int) (l & 0xFF); bytes[3] = (byte) (int) (l & 0xFF);
break; break;
case 4: case 4:
for (i = 0; i < 4; ++i) for (i = 0; i < 4; ++i) {
{
l = Integer.parseInt(elements[i]); l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L)) { if ((l < 0L) || (l > 255L)) {
return null; return null;
@ -175,34 +155,24 @@ public class IpUtils
default: default:
return null; return null;
} }
} } catch (NumberFormatException e) {
catch (NumberFormatException e)
{
return null; return null;
} }
return bytes; return bytes;
} }
public static String getHostIp() public static String getHostIp() {
{ try {
try
{
return InetAddress.getLocalHost().getHostAddress(); return InetAddress.getLocalHost().getHostAddress();
} } catch (UnknownHostException e) {
catch (UnknownHostException e)
{
} }
return "127.0.0.1"; return "127.0.0.1";
} }
public static String getHostName() public static String getHostName() {
{ try {
try
{
return InetAddress.getLocalHost().getHostName(); return InetAddress.getLocalHost().getHostName();
} } catch (UnknownHostException e) {
catch (UnknownHostException e)
{
} }
return "未知"; return "未知";
} }

View File

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

View File

@ -1,45 +1,35 @@
package com.ruoyi.common.core.utils.reflect; package com.ruoyi.common.core.utils.reflect;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.DateUtils; import lombok.AccessLevel;
import org.apache.commons.lang3.StringUtils; import lombok.NoArgsConstructor;
import org.apache.commons.lang3.Validate;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.*; import java.lang.reflect.Method;
import java.util.Date;
/** /**
* . getter/setter, 访, , Class, AOP. * . getter/setter, 访, , Class, AOP.
* *
* @author ruoyi * @author Lion Li
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class ReflectUtils extends ReflectUtil @NoArgsConstructor(access = AccessLevel.PRIVATE)
{ public class ReflectUtils extends ReflectUtil {
private static final String SETTER_PREFIX = "set"; private static final String SETTER_PREFIX = "set";
private static final String GETTER_PREFIX = "get"; private static final String GETTER_PREFIX = "get";
private static final String CGLIB_CLASS_SEPARATOR = "$$";
private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class);
/** /**
* Getter. * Getter.
* .. * ..
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <E> E invokeGetter(Object obj, String propertyName) public static <E> E invokeGetter(Object obj, String propertyName) {
{
Object object = obj; Object object = obj;
for (String name : StringUtils.split(propertyName, ".")) for (String name : StringUtils.split(propertyName, ".")) {
{
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name); String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); object = invoke(object, getterMethodName);
} }
return (E) object; return (E) object;
} }
@ -48,314 +38,19 @@ public class ReflectUtils extends ReflectUtil
* Setter, * Setter,
* .. * ..
*/ */
public static <E> void invokeSetter(Object obj, String propertyName, E value) public static <E> void invokeSetter(Object obj, String propertyName, E value) {
{
Object object = obj; Object object = obj;
String[] names = StringUtils.split(propertyName, "."); String[] names = StringUtils.split(propertyName, ".");
for (int i = 0; i < names.length; i++) for (int i = 0; i < names.length; i++) {
{ if (i < names.length - 1) {
if (i < names.length - 1)
{
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]); String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); object = invoke(object, getterMethodName);
} } else {
else
{
String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]); String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
invokeMethodByName(object, setterMethodName, new Object[] { value }); Method method = getMethodByName(object.getClass(), setterMethodName);
invoke(object, method, value);
} }
} }
} }
/**
* , private/protected.
* 使getAccessibleMethod()Method.
* +
*/
@SuppressWarnings("unchecked")
public static <E> E invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
final Object[] args)
{
if (obj == null || methodName == null)
{
return null;
}
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null)
{
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
return null;
}
try
{
return (E) method.invoke(obj, args);
}
catch (Exception e)
{
String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
throw convertReflectionExceptionToUnchecked(msg, e);
}
}
/**
* , private/protected
* 使getAccessibleMethodByName()Method.
*
*/
@SuppressWarnings("unchecked")
public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args)
{
Method method = getAccessibleMethodByName(obj, methodName, args.length);
if (method == null)
{
// 如果为空不报错,直接返回空。
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
return null;
}
try
{
// 类型转换(将参数数据类型转换为目标方法参数类型)
Class<?>[] cs = method.getParameterTypes();
for (int i = 0; i < cs.length; i++)
{
if (args[i] != null && !args[i].getClass().equals(cs[i]))
{
if (cs[i] == String.class)
{
args[i] = Convert.toStr(args[i]);
if (StringUtils.endsWith((String) args[i], ".0"))
{
args[i] = StringUtils.substringBefore((String) args[i], ".0");
}
}
else if (cs[i] == Integer.class)
{
args[i] = Convert.toInt(args[i]);
}
else if (cs[i] == Long.class)
{
args[i] = Convert.toLong(args[i]);
}
else if (cs[i] == Double.class)
{
args[i] = Convert.toDouble(args[i]);
}
else if (cs[i] == Float.class)
{
args[i] = Convert.toFloat(args[i]);
}
else if (cs[i] == Date.class)
{
if (args[i] instanceof String)
{
args[i] = DateUtils.parseDate(args[i]);
}
else
{
args[i] = DateUtil.getJavaDate((Double) args[i]);
}
}
else if (cs[i] == boolean.class || cs[i] == Boolean.class)
{
args[i] = Convert.toBool(args[i]);
}
}
}
return (E) method.invoke(obj, args);
}
catch (Exception e)
{
String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
throw convertReflectionExceptionToUnchecked(msg, e);
}
}
/**
* , DeclaredField, 访.
* Object, null.
*/
public static Field getAccessibleField(final Object obj, final String fieldName)
{
// 为空不报错。直接返回 null
if (obj == null)
{
return null;
}
Validate.notBlank(fieldName, "fieldName can't be blank");
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass())
{
try
{
Field field = superClass.getDeclaredField(fieldName);
makeAccessible(field);
return field;
}
catch (NoSuchFieldException e)
{
continue;
}
}
return null;
}
/**
* , DeclaredMethod,访.
* Object, null.
* +
* . 使Method,Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethod(final Object obj, final String methodName,
final Class<?>... parameterTypes)
{
// 为空不报错。直接返回 null
if (obj == null)
{
return null;
}
Validate.notBlank(methodName, "methodName can't be blank");
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass())
{
try
{
Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
makeAccessible(method);
return method;
}
catch (NoSuchMethodException e)
{
continue;
}
}
return null;
}
/**
* , DeclaredMethod,访.
* Object, null.
*
* . 使Method,Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum)
{
// 为空不报错。直接返回 null
if (obj == null)
{
return null;
}
Validate.notBlank(methodName, "methodName can't be blank");
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass())
{
Method[] methods = searchType.getDeclaredMethods();
for (Method method : methods)
{
if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum)
{
makeAccessible(method);
return method;
}
}
}
return null;
}
/**
* private/protectedpublicJDKSecurityManager
*/
public static void makeAccessible(Method method)
{
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible())
{
method.setAccessible(true);
}
}
/**
* private/protectedpublicJDKSecurityManager
*/
public static void makeAccessible(Field field)
{
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
|| Modifier.isFinal(field.getModifiers())) && !field.isAccessible())
{
field.setAccessible(true);
}
}
/**
* , Class,
* , Object.class.
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> getClassGenricType(final Class clazz)
{
return getClassGenricType(clazz, 0);
}
/**
* , Class.
* , Object.class.
*/
public static Class getClassGenricType(final Class clazz, final int index)
{
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType))
{
logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0)
{
logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length);
return Object.class;
}
if (!(params[index] instanceof Class))
{
logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class;
}
return (Class) params[index];
}
public static Class<?> getUserClass(Object instance)
{
if (instance == null)
{
throw new RuntimeException("Instance must not be null");
}
Class clazz = instance.getClass();
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR))
{
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && !Object.class.equals(superClass))
{
return superClass;
}
}
return clazz;
}
/**
* checked exceptionunchecked exception.
*/
public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e)
{
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|| e instanceof NoSuchMethodException)
{
return new IllegalArgumentException(msg, e);
}
else if (e instanceof InvocationTargetException)
{
return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException());
}
return new RuntimeException(msg, e);
}
} }

View File

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

View File

@ -8,8 +8,7 @@ import com.ruoyi.common.core.utils.StringUtils;
* *
* @author ruoyi * @author ruoyi
*/ */
public class SqlUtil public class SqlUtil {
{
/** /**
* sql * sql
*/ */
@ -23,10 +22,8 @@ public class SqlUtil
/** /**
* *
*/ */
public static String escapeOrderBySql(String value) public static String escapeOrderBySql(String value) {
{ if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {
if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value))
{
throw new UtilException("参数不符合规范,不能进行查询"); throw new UtilException("参数不符合规范,不能进行查询");
} }
return value; return value;
@ -35,25 +32,20 @@ public class SqlUtil
/** /**
* order by * order by
*/ */
public static boolean isValidOrderBySql(String value) public static boolean isValidOrderBySql(String value) {
{
return value.matches(SQL_PATTERN); return value.matches(SQL_PATTERN);
} }
/** /**
* SQL * SQL
*/ */
public static void filterKeyword(String value) public static void filterKeyword(String value) {
{ if (StringUtils.isEmpty(value)) {
if (StringUtils.isEmpty(value))
{
return; return;
} }
String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|"); String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|");
for (int i = 0; i < sqlKeywords.length; i++) for (int i = 0; i < sqlKeywords.length; i++) {
{ if (StringUtils.indexOfIgnoreCase(value, sqlKeywords[i]) > -1) {
if (StringUtils.indexOfIgnoreCase(value, sqlKeywords[i]) > -1)
{
throw new UtilException("参数存在SQL注入风险"); throw new UtilException("参数存在SQL注入风险");
} }
} }

View File

@ -1,20 +1,13 @@
package com.ruoyi.common.core.web.controller; package com.ruoyi.common.core.web.controller;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.constant.HttpStatus; import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.PageUtils; import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.core.web.domain.AjaxResult; import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo; import com.ruoyi.common.core.web.page.TableDataInfo;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
/** /**
* web * web
@ -22,23 +15,20 @@ import com.ruoyi.common.core.web.page.TableDataInfo;
* @author ruoyi * @author ruoyi
*/ */
@Slf4j @Slf4j
public class BaseController public class BaseController {
{
/** /**
* *
*/ */
protected void startPage() protected void startPage() {
{
PageUtils.startPage(); PageUtils.startPage();
} }
/** /**
* *
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
protected TableDataInfo getDataTable(List<?> list) protected TableDataInfo getDataTable(List<?> list) {
{
TableDataInfo rspData = new TableDataInfo(); TableDataInfo rspData = new TableDataInfo();
rspData.setCode(HttpStatus.SUCCESS); rspData.setCode(HttpStatus.SUCCESS);
rspData.setRows(list); rspData.setRows(list);
@ -53,8 +43,7 @@ public class BaseController
* @param rows * @param rows
* @return * @return
*/ */
protected AjaxResult toAjax(int rows) protected AjaxResult toAjax(int rows) {
{
return rows > 0 ? AjaxResult.success() : AjaxResult.error(); return rows > 0 ? AjaxResult.success() : AjaxResult.error();
} }
@ -64,40 +53,35 @@ public class BaseController
* @param result * @param result
* @return * @return
*/ */
protected AjaxResult toAjax(boolean result) protected AjaxResult toAjax(boolean result) {
{
return result ? success() : error(); return result ? success() : error();
} }
/** /**
* *
*/ */
public AjaxResult success() public AjaxResult success() {
{
return AjaxResult.success(); return AjaxResult.success();
} }
/** /**
* *
*/ */
public AjaxResult error() public AjaxResult error() {
{
return AjaxResult.error(); return AjaxResult.error();
} }
/** /**
* *
*/ */
public AjaxResult success(String message) public AjaxResult success(String message) {
{
return AjaxResult.success(message); return AjaxResult.success(message);
} }
/** /**
* *
*/ */
public AjaxResult error(String message) public AjaxResult error(String message) {
{
return AjaxResult.error(message); return AjaxResult.error(message);
} }
} }

View File

@ -1,42 +1,46 @@
package com.ruoyi.common.core.web.domain; package com.ruoyi.common.core.web.domain;
import java.util.HashMap;
import com.ruoyi.common.core.constant.HttpStatus; import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.StringUtils; import com.ruoyi.common.core.utils.StringUtils;
import java.util.HashMap;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public class AjaxResult extends HashMap<String, Object> public class AjaxResult extends HashMap<String, Object> {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 状态码 */ /**
*
*/
public static final String CODE_TAG = "code"; public static final String CODE_TAG = "code";
/** 返回内容 */ /**
*
*/
public static final String MSG_TAG = "msg"; public static final String MSG_TAG = "msg";
/** 数据对象 */ /**
*
*/
public static final String DATA_TAG = "data"; public static final String DATA_TAG = "data";
/** /**
* AjaxResult 使 * AjaxResult 使
*/ */
public AjaxResult() public AjaxResult() {
{
} }
/** /**
* AjaxResult * AjaxResult
* *
* @param code * @param code
* @param msg * @param msg
*/ */
public AjaxResult(int code, String msg) public AjaxResult(int code, String msg) {
{
super.put(CODE_TAG, code); super.put(CODE_TAG, code);
super.put(MSG_TAG, msg); super.put(MSG_TAG, msg);
} }
@ -45,15 +49,13 @@ public class AjaxResult extends HashMap<String, Object>
* AjaxResult * AjaxResult
* *
* @param code * @param code
* @param msg * @param msg
* @param data * @param data
*/ */
public AjaxResult(int code, String msg, Object data) public AjaxResult(int code, String msg, Object data) {
{
super.put(CODE_TAG, code); super.put(CODE_TAG, code);
super.put(MSG_TAG, msg); super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data)) if (StringUtils.isNotNull(data)) {
{
super.put(DATA_TAG, data); super.put(DATA_TAG, data);
} }
} }
@ -66,8 +68,7 @@ public class AjaxResult extends HashMap<String, Object>
* @return * @return
*/ */
@Override @Override
public AjaxResult put(String key, Object value) public AjaxResult put(String key, Object value) {
{
super.put(key, value); super.put(key, value);
return this; return this;
} }
@ -77,8 +78,7 @@ public class AjaxResult extends HashMap<String, Object>
* *
* @return * @return
*/ */
public static AjaxResult success() public static AjaxResult success() {
{
return AjaxResult.success("操作成功"); return AjaxResult.success("操作成功");
} }
@ -87,8 +87,7 @@ public class AjaxResult extends HashMap<String, Object>
* *
* @return * @return
*/ */
public static AjaxResult success(Object data) public static AjaxResult success(Object data) {
{
return AjaxResult.success("操作成功", data); return AjaxResult.success("操作成功", data);
} }
@ -98,20 +97,18 @@ public class AjaxResult extends HashMap<String, Object>
* @param msg * @param msg
* @return * @return
*/ */
public static AjaxResult success(String msg) public static AjaxResult success(String msg) {
{
return AjaxResult.success(msg, null); return AjaxResult.success(msg, null);
} }
/** /**
* *
* *
* @param msg * @param msg
* @param data * @param data
* @return * @return
*/ */
public static AjaxResult success(String msg, Object data) public static AjaxResult success(String msg, Object data) {
{
return new AjaxResult(HttpStatus.SUCCESS, msg, data); return new AjaxResult(HttpStatus.SUCCESS, msg, data);
} }
@ -120,8 +117,7 @@ public class AjaxResult extends HashMap<String, Object>
* *
* @return * @return
*/ */
public static AjaxResult error() public static AjaxResult error() {
{
return AjaxResult.error("操作失败"); return AjaxResult.error("操作失败");
} }
@ -131,20 +127,18 @@ public class AjaxResult extends HashMap<String, Object>
* @param msg * @param msg
* @return * @return
*/ */
public static AjaxResult error(String msg) public static AjaxResult error(String msg) {
{
return AjaxResult.error(msg, null); return AjaxResult.error(msg, null);
} }
/** /**
* *
* *
* @param msg * @param msg
* @param data * @param data
* @return * @return
*/ */
public static AjaxResult error(String msg, Object data) public static AjaxResult error(String msg, Object data) {
{
return new AjaxResult(HttpStatus.ERROR, msg, data); return new AjaxResult(HttpStatus.ERROR, msg, data);
} }
@ -152,11 +146,10 @@ public class AjaxResult extends HashMap<String, Object>
* *
* *
* @param code * @param code
* @param msg * @param msg
* @return * @return
*/ */
public static AjaxResult error(int code, String msg) public static AjaxResult error(int code, String msg) {
{
return new AjaxResult(code, msg, null); return new AjaxResult(code, msg, null);
} }
} }

View File

@ -1,10 +1,11 @@
package com.ruoyi.common.core.web.domain; package com.ruoyi.common.core.web.domain;
import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import lombok.Data;
/** /**
* Entity * Entity
@ -12,35 +13,46 @@ import lombok.Data;
* @author ruoyi * @author ruoyi
*/ */
@Data @Data
public class BaseEntity implements Serializable public class BaseEntity implements Serializable {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 搜索值 */ /**
*
*/
private String searchValue; private String searchValue;
/** 创建者 */ /**
*
*/
private String createBy; private String createBy;
/** 创建时间 */ /**
*
*/
private Date createTime; private Date createTime;
/** 更新者 */ /**
*
*/
private String updateBy; private String updateBy;
/** 更新时间 */ /**
*
*/
private Date updateTime; private Date updateTime;
/** 备注 */ /**
*
*/
private String remark; private String remark;
/** 请求参数 */ /**
*
*/
private Map<String, Object> params; private Map<String, Object> params;
public Map<String, Object> getParams() public Map<String, Object> getParams() {
{ if (params == null) {
if (params == null)
{
params = new HashMap<>(); params = new HashMap<>();
} }
return params; return params;

View File

@ -1,6 +1,7 @@
package com.ruoyi.common.core.web.domain; package com.ruoyi.common.core.web.domain;
import lombok.*; import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -12,23 +13,32 @@ import java.util.List;
*/ */
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public class TreeEntity extends BaseEntity public class TreeEntity extends BaseEntity {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 父菜单名称 */ /**
*
*/
private String parentName; private String parentName;
/** 父菜单ID */ /**
* ID
*/
private Long parentId; private Long parentId;
/** 显示顺序 */ /**
*
*/
private Integer orderNum; private Integer orderNum;
/** 祖级列表 */ /**
*
*/
private String ancestors; private String ancestors;
/** 子部门 */ /**
*
*/
private List<?> children = new ArrayList<>(); private List<?> children = new ArrayList<>();
} }

View File

@ -9,53 +9,53 @@ import lombok.Data;
* @author ruoyi * @author ruoyi
*/ */
@Data @Data
public class PageDomain public class PageDomain {
{ /**
/** 当前记录起始索引 */ *
*/
private Integer pageNum; private Integer pageNum;
/** 每页显示记录数 */ /**
*
*/
private Integer pageSize; private Integer pageSize;
/** 排序列 */ /**
*
*/
private String orderByColumn; private String orderByColumn;
/** 排序的方向desc或者asc */ /**
* descasc
*/
private String isAsc = "asc"; private String isAsc = "asc";
/** 分页参数合理化 */ /**
*
*/
private Boolean reasonable = true; private Boolean reasonable = true;
public String getOrderBy() public String getOrderBy() {
{ if (StringUtils.isEmpty(orderByColumn)) {
if (StringUtils.isEmpty(orderByColumn))
{
return ""; return "";
} }
return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc; return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc;
} }
public void setIsAsc(String isAsc) public void setIsAsc(String isAsc) {
{ if (StringUtils.isNotEmpty(isAsc)) {
if (StringUtils.isNotEmpty(isAsc))
{
// 兼容前端排序类型 // 兼容前端排序类型
if ("ascending".equals(isAsc)) if ("ascending".equals(isAsc)) {
{
isAsc = "asc"; isAsc = "asc";
} } else if ("descending".equals(isAsc)) {
else if ("descending".equals(isAsc))
{
isAsc = "desc"; isAsc = "desc";
} }
this.isAsc = isAsc; this.isAsc = isAsc;
} }
} }
public Boolean getReasonable() public Boolean getReasonable() {
{ if (StringUtils.isNull(reasonable)) {
if (StringUtils.isNull(reasonable))
{
return Boolean.TRUE; return Boolean.TRUE;
} }
return reasonable; return reasonable;

View File

@ -13,30 +13,36 @@ import java.util.List;
*/ */
@Data @Data
@NoArgsConstructor @NoArgsConstructor
public class TableDataInfo implements Serializable public class TableDataInfo implements Serializable {
{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** 总记录数 */ /**
*
*/
private long total; private long total;
/** 列表数据 */ /**
*
*/
private List<?> rows; private List<?> rows;
/** 消息状态码 */ /**
*
*/
private int code; private int code;
/** 消息内容 */ /**
*
*/
private String msg; private String msg;
/** /**
* *
* *
* @param list * @param list
* @param total * @param total
*/ */
public TableDataInfo(List<?> list, int total) public TableDataInfo(List<?> list, int total) {
{
this.rows = list; this.rows = list;
this.total = total; this.total = total;
} }

View File

@ -7,8 +7,7 @@ import com.ruoyi.common.core.utils.ServletUtils;
* *
* @author ruoyi * @author ruoyi
*/ */
public class TableSupport public class TableSupport {
{
/** /**
* *
*/ */
@ -37,8 +36,7 @@ public class TableSupport
/** /**
* *
*/ */
public static PageDomain getPageDomain() public static PageDomain getPageDomain() {
{
PageDomain pageDomain = new PageDomain(); PageDomain pageDomain = new PageDomain();
pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM)); pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM));
pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE)); pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE));
@ -48,8 +46,7 @@ public class TableSupport
return pageDomain; return pageDomain;
} }
public static PageDomain buildPageRequest() public static PageDomain buildPageRequest() {
{
return getPageDomain(); return getPageDomain();
} }
} }

View File

@ -13,13 +13,12 @@ import java.lang.annotation.Target;
* @author ruoyi * @author ruoyi
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER }) @Target(value = {ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Constraint(validatedBy = { XssValidator.class }) @Constraint(validatedBy = {XssValidator.class})
public @interface Xss public @interface Xss {
{
String message() String message()
default "不允许任何脚本运行"; default "不允许任何脚本运行";
Class<?>[] groups() default {}; Class<?>[] groups() default {};

View File

@ -10,18 +10,15 @@ import java.util.regex.Pattern;
* *
* @author ruoyi * @author ruoyi
*/ */
public class XssValidator implements ConstraintValidator<Xss, String> public class XssValidator implements ConstraintValidator<Xss, String> {
{
private final String HTML_PATTERN = "<(\\S*?)[^>]*>.*?|<.*? />"; private final String HTML_PATTERN = "<(\\S*?)[^>]*>.*?|<.*? />";
@Override @Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
{
return !containsHtml(value); return !containsHtml(value);
} }
public boolean containsHtml(String value) public boolean containsHtml(String value) {
{
Pattern pattern = Pattern.compile(HTML_PATTERN); Pattern pattern = Pattern.compile(HTML_PATTERN);
Matcher matcher = pattern.matcher(value); Matcher matcher = pattern.matcher(value);
return matcher.matches(); return matcher.matches();

View File

@ -1,10 +1,6 @@
package com.ruoyi.common.datascope.annotation; package com.ruoyi.common.datascope.annotation;
import java.lang.annotation.Documented; import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* *
@ -14,15 +10,15 @@ import java.lang.annotation.Target;
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Documented @Documented
public @interface DataScope public @interface DataScope {
{
/** /**
* *
*/ */
public String deptAlias() default ""; String deptAlias() default "";
/** /**
* *
*/ */
public String userAlias() default ""; String userAlias() default "";
} }

View File

@ -1,9 +1,5 @@
package com.ruoyi.common.datascope.aspect; package com.ruoyi.common.datascope.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.utils.StringUtils; import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.BaseEntity; import com.ruoyi.common.core.web.domain.BaseEntity;
import com.ruoyi.common.datascope.annotation.DataScope; import com.ruoyi.common.datascope.annotation.DataScope;
@ -11,6 +7,10 @@ import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysRole; import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser; import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser; import com.ruoyi.system.api.model.LoginUser;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/** /**
* *
@ -19,8 +19,7 @@ import com.ruoyi.system.api.model.LoginUser;
*/ */
@Aspect @Aspect
@Component @Component
public class DataScopeAspect public class DataScopeAspect {
{
/** /**
* *
*/ */
@ -52,22 +51,18 @@ public class DataScopeAspect
public static final String DATA_SCOPE = "dataScope"; public static final String DATA_SCOPE = "dataScope";
@Before("@annotation(controllerDataScope)") @Before("@annotation(controllerDataScope)")
public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable {
{
clearDataScope(point); clearDataScope(point);
handleDataScope(point, controllerDataScope); handleDataScope(point, controllerDataScope);
} }
protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope) protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope) {
{
// 获取当前的用户 // 获取当前的用户
LoginUser loginUser = SecurityUtils.getLoginUser(); LoginUser loginUser = SecurityUtils.getLoginUser();
if (StringUtils.isNotNull(loginUser)) if (StringUtils.isNotNull(loginUser)) {
{
SysUser currentUser = loginUser.getSysUser(); SysUser currentUser = loginUser.getSysUser();
// 如果是超级管理员,则不过滤数据 // 如果是超级管理员,则不过滤数据
if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) {
{
dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(), dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
controllerDataScope.userAlias()); controllerDataScope.userAlias());
} }
@ -78,57 +73,41 @@ public class DataScopeAspect
* *
* *
* @param joinPoint * @param joinPoint
* @param user * @param user
* @param deptAlias * @param deptAlias
* @param userAlias * @param userAlias
*/ */
public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) {
{
StringBuilder sqlString = new StringBuilder(); StringBuilder sqlString = new StringBuilder();
for (SysRole role : user.getRoles()) for (SysRole role : user.getRoles()) {
{
String dataScope = role.getDataScope(); String dataScope = role.getDataScope();
if (DATA_SCOPE_ALL.equals(dataScope)) if (DATA_SCOPE_ALL.equals(dataScope)) {
{
sqlString = new StringBuilder(); sqlString = new StringBuilder();
break; break;
} } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
else if (DATA_SCOPE_CUSTOM.equals(dataScope))
{
sqlString.append(StringUtils.format( sqlString.append(StringUtils.format(
" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias,
role.getRoleId())); role.getRoleId()));
} } else if (DATA_SCOPE_DEPT.equals(dataScope)) {
else if (DATA_SCOPE_DEPT.equals(dataScope))
{
sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId())); sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
} } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope))
{
sqlString.append(StringUtils.format( sqlString.append(StringUtils.format(
" OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )",
deptAlias, user.getDeptId(), user.getDeptId())); deptAlias, user.getDeptId(), user.getDeptId()));
} } else if (DATA_SCOPE_SELF.equals(dataScope)) {
else if (DATA_SCOPE_SELF.equals(dataScope)) if (StringUtils.isNotBlank(userAlias)) {
{
if (StringUtils.isNotBlank(userAlias))
{
sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId())); sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));
} } else {
else
{
// 数据权限为仅本人且没有userAlias别名不查询任何数据 // 数据权限为仅本人且没有userAlias别名不查询任何数据
sqlString.append(" OR 1=0 "); sqlString.append(" OR 1=0 ");
} }
} }
} }
if (StringUtils.isNotBlank(sqlString.toString())) if (StringUtils.isNotBlank(sqlString.toString())) {
{
Object params = joinPoint.getArgs()[0]; Object params = joinPoint.getArgs()[0];
if (StringUtils.isNotNull(params) && params instanceof BaseEntity) if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
{
BaseEntity baseEntity = (BaseEntity) params; BaseEntity baseEntity = (BaseEntity) params;
baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")"); baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
} }
@ -138,11 +117,9 @@ public class DataScopeAspect
/** /**
* sqlparams.dataScope * sqlparams.dataScope
*/ */
private void clearDataScope(final JoinPoint joinPoint) private void clearDataScope(final JoinPoint joinPoint) {
{
Object params = joinPoint.getArgs()[0]; Object params = joinPoint.getArgs()[0];
if (StringUtils.isNotNull(params) && params instanceof BaseEntity) if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
{
BaseEntity baseEntity = (BaseEntity) params; BaseEntity baseEntity = (BaseEntity) params;
baseEntity.getParams().put(DATA_SCOPE, ""); baseEntity.getParams().put(DATA_SCOPE, "");
} }

View File

@ -1,22 +1,18 @@
package com.ruoyi.common.datasource.annotation; package com.ruoyi.common.datasource.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.dynamic.datasource.annotation.DS;
import java.lang.annotation.*;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@Target({ ElementType.TYPE, ElementType.METHOD }) @Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Documented @Documented
@DS("master") @DS("master")
public @interface Master public @interface Master {
{
} }

View File

@ -1,22 +1,18 @@
package com.ruoyi.common.datasource.annotation; package com.ruoyi.common.datasource.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.dynamic.datasource.annotation.DS;
import java.lang.annotation.*;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@Target({ ElementType.TYPE, ElementType.METHOD }) @Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Documented @Documented
@DS("slave") @DS("slave")
public @interface Slave public @interface Slave {
{
} }

View File

@ -1,46 +1,41 @@
package com.ruoyi.common.log.annotation; package com.ruoyi.common.log.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.log.enums.BusinessType; import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.log.enums.OperatorType; import com.ruoyi.common.log.enums.OperatorType;
import java.lang.annotation.*;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*
*/ */
@Target({ ElementType.PARAMETER, ElementType.METHOD }) @Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Documented @Documented
public @interface Log public @interface Log {
{
/** /**
* *
*/ */
public String title() default ""; String title() default "";
/** /**
* *
*/ */
public BusinessType businessType() default BusinessType.OTHER; BusinessType businessType() default BusinessType.OTHER;
/** /**
* *
*/ */
public OperatorType operatorType() default OperatorType.MANAGE; OperatorType operatorType() default OperatorType.MANAGE;
/** /**
* *
*/ */
public boolean isSaveRequestData() default true; boolean isSaveRequestData() default true;
/** /**
* *
*/ */
public boolean isSaveResponseData() default true; boolean isSaveResponseData() default true;
} }

View File

@ -1,11 +1,14 @@
package com.ruoyi.common.log.aspect; package com.ruoyi.common.log.aspect;
import java.util.Collection;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.core.utils.JsonUtils; import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessStatus;
import com.ruoyi.common.log.service.AsyncLogService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysOperLog;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterReturning;
@ -16,14 +19,11 @@ import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.StringUtils; import javax.servlet.http.HttpServletRequest;
import com.ruoyi.common.core.utils.ip.IpUtils; import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.log.annotation.Log; import java.util.Collection;
import com.ruoyi.common.log.enums.BusinessStatus; import java.util.Map;
import com.ruoyi.common.log.service.AsyncLogService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysOperLog;
/** /**
* *
@ -33,8 +33,7 @@ import com.ruoyi.system.api.domain.SysOperLog;
@Slf4j @Slf4j
@Aspect @Aspect
@Component @Component
public class LogAspect public class LogAspect {
{
@Autowired @Autowired
private AsyncLogService asyncLogService; private AsyncLogService asyncLogService;
@ -45,8 +44,7 @@ public class LogAspect
* @param joinPoint * @param joinPoint
*/ */
@AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult") @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
{
handleLog(joinPoint, controllerLog, null, jsonResult); handleLog(joinPoint, controllerLog, null, jsonResult);
} }
@ -54,18 +52,15 @@ public class LogAspect
* *
* *
* @param joinPoint * @param joinPoint
* @param e * @param e
*/ */
@AfterThrowing(value = "@annotation(controllerLog)", throwing = "e") @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
{
handleLog(joinPoint, controllerLog, e, null); handleLog(joinPoint, controllerLog, e, null);
} }
protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
{ try {
try
{
// *========数据库日志=========*// // *========数据库日志=========*//
SysOperLog operLog = new SysOperLog(); SysOperLog operLog = new SysOperLog();
operLog.setStatus(BusinessStatus.SUCCESS.ordinal()); operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
@ -74,13 +69,11 @@ public class LogAspect
operLog.setOperIp(ip); operLog.setOperIp(ip);
operLog.setOperUrl(ServletUtils.getRequest().getRequestURI()); operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
String username = SecurityUtils.getUsername(); String username = SecurityUtils.getUsername();
if (StringUtils.isNotBlank(username)) if (StringUtils.isNotBlank(username)) {
{
operLog.setOperName(username); operLog.setOperName(username);
} }
if (e != null) if (e != null) {
{
operLog.setStatus(BusinessStatus.FAIL.ordinal()); operLog.setStatus(BusinessStatus.FAIL.ordinal());
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000)); operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
} }
@ -94,9 +87,7 @@ public class LogAspect
getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult); getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);
// 保存数据库 // 保存数据库
asyncLogService.saveSysLog(operLog); asyncLogService.saveSysLog(operLog);
} } catch (Exception exp) {
catch (Exception exp)
{
// 记录本地异常日志 // 记录本地异常日志
log.error("==前置通知异常=="); log.error("==前置通知异常==");
log.error("异常信息:{}", exp.getMessage()); log.error("异常信息:{}", exp.getMessage());
@ -107,12 +98,11 @@ public class LogAspect
/** /**
* Controller * Controller
* *
* @param log * @param log
* @param operLog * @param operLog
* @throws Exception * @throws Exception
*/ */
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception {
{
// 设置action动作 // 设置action动作
operLog.setBusinessType(log.businessType().ordinal()); operLog.setBusinessType(log.businessType().ordinal());
// 设置标题 // 设置标题
@ -120,14 +110,12 @@ public class LogAspect
// 设置操作人类别 // 设置操作人类别
operLog.setOperatorType(log.operatorType().ordinal()); operLog.setOperatorType(log.operatorType().ordinal());
// 是否需要保存request参数和值 // 是否需要保存request参数和值
if (log.isSaveRequestData()) if (log.isSaveRequestData()) {
{
// 获取参数的信息,传入到数据库中。 // 获取参数的信息,传入到数据库中。
setRequestValue(joinPoint, operLog); setRequestValue(joinPoint, operLog);
} }
// 是否需要保存response参数和值 // 是否需要保存response参数和值
if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) {
{
operLog.setJsonResult(StringUtils.substring(JsonUtils.toJsonString(jsonResult), 0, 2000)); operLog.setJsonResult(StringUtils.substring(JsonUtils.toJsonString(jsonResult), 0, 2000));
} }
} }
@ -138,11 +126,9 @@ public class LogAspect
* @param operLog * @param operLog
* @throws Exception * @throws Exception
*/ */
private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception {
{
String requestMethod = operLog.getRequestMethod(); String requestMethod = operLog.getRequestMethod();
if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
{
String params = argsArrayToString(joinPoint.getArgs()); String params = argsArrayToString(joinPoint.getArgs());
operLog.setOperParam(StringUtils.substring(params, 0, 2000)); operLog.setOperParam(StringUtils.substring(params, 0, 2000));
} }
@ -151,21 +137,14 @@ public class LogAspect
/** /**
* *
*/ */
private String argsArrayToString(Object[] paramsArray) private String argsArrayToString(Object[] paramsArray) {
{
StringBuilder params = new StringBuilder(); StringBuilder params = new StringBuilder();
if (paramsArray != null && paramsArray.length > 0) if (paramsArray != null && paramsArray.length > 0) {
{ for (Object o : paramsArray) {
for (Object o : paramsArray) if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
{ try {
if (StringUtils.isNotNull(o) && !isFilterObject(o))
{
try
{
params.append(JsonUtils.toJsonString(o)).append(" "); params.append(JsonUtils.toJsonString(o)).append(" ");
} } catch (Exception e) {
catch (Exception e)
{
} }
} }
} }
@ -180,26 +159,18 @@ public class LogAspect
* @return truefalse * @return truefalse
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public boolean isFilterObject(final Object o) public boolean isFilterObject(final Object o) {
{
Class<?> clazz = o.getClass(); Class<?> clazz = o.getClass();
if (clazz.isArray()) if (clazz.isArray()) {
{
return clazz.getComponentType().isAssignableFrom(MultipartFile.class); return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
} } else if (Collection.class.isAssignableFrom(clazz)) {
else if (Collection.class.isAssignableFrom(clazz))
{
Collection collection = (Collection) o; Collection collection = (Collection) o;
for (Object value : collection) for (Object value : collection) {
{
return value instanceof MultipartFile; return value instanceof MultipartFile;
} }
} } else if (Map.class.isAssignableFrom(clazz)) {
else if (Map.class.isAssignableFrom(clazz))
{
Map map = (Map) o; Map map = (Map) o;
for (Object value : map.entrySet()) for (Object value : map.entrySet()) {
{
Map.Entry entry = (Map.Entry) value; Map.Entry entry = (Map.Entry) value;
return entry.getValue() instanceof MultipartFile; return entry.getValue() instanceof MultipartFile;
} }

View File

@ -4,10 +4,8 @@ package com.ruoyi.common.log.enums;
* *
* *
* @author ruoyi * @author ruoyi
*
*/ */
public enum BusinessStatus public enum BusinessStatus {
{
/** /**
* *
*/ */

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