Skip to content

Commit

Permalink
添加断言工具类,简化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
tangllty committed Dec 20, 2023
1 parent 21daaf4 commit 9566a23
Show file tree
Hide file tree
Showing 10 changed files with 256 additions and 66 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.tang.commons.exception;

/**
* 断言异常
*
* @author Tang
*/
public class AssertException extends RuntimeException {

@java.io.Serial
private static final long serialVersionUID = 1953209867997857028L;

public AssertException() {
}

public AssertException(String message) {
super(message);
}

public AssertException(Throwable cause) {
super(cause);
}

public AssertException(String message, Throwable cause) {
super(message, cause);
}

}
182 changes: 182 additions & 0 deletions tang-commons/src/main/java/com/tang/commons/utils/Assert.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
package com.tang.commons.utils;

import java.util.Objects;
import java.util.function.Supplier;

import com.tang.commons.exception.AssertException;

/**
* 断言工具类,符合条件时抛出异常
*
* @author Tang
*/
public class Assert {

private Assert() {
}

/**
* 表达式为 True 时抛出异常
*
* @param expression 表达式
*/
public static void isTrue(boolean expression) {
isTrue(expression, "表达式为 True");
}

/**
* 表达式为 True 时抛出异常
*
* @param expression 表达式
* @param message 异常信息
*/
public static void isTrue(boolean expression, String message) {
isTrue(expression, new AssertException(message));
}

/**
* 表达式为 True 时抛出异常
*
* @param expression 表达式
* @param cause 异常
*/
public static void isTrue(boolean expression, RuntimeException cause) {
isTrue(expression, () -> cause);
}

/**
* 表达式为 True 时抛出异常
*
* @param expression 表达式
* @param cause 异常
*/
public static void isTrue(boolean expression, Supplier<? extends RuntimeException> cause) {
if (expression) {
throw cause.get();
}
}

/**
* 表达式为 False 时抛出异常
*
* @param expression 表达式
*/
public static void isFalse(boolean expression) {
isFalse(expression, "表达式为 False");
}

/**
* 表达式为 False 时抛出异常
*
* @param expression 表达式
* @param message 异常信息
*/
public static void isFalse(boolean expression, String message) {
isFalse(expression, new AssertException(message));
}

/**
* 表达式为 False 时抛出异常
*
* @param expression 表达式
* @param cause 异常
*/
public static void isFalse(boolean expression, RuntimeException cause) {
isFalse(expression, () -> cause);
}

/**
* 表达式为 False 时抛出异常
*
* @param expression 表达式
* @param cause 异常
*/
public static void isFalse(boolean expression, Supplier<? extends RuntimeException> cause) {
if (!expression) {
throw cause.get();
}
}

/**
* 对象为 Null 时抛出异常
*
* @param object 对象
*/
public static void isNull(Object object) {
isNull(object, "对象为 Null");
}

/**
* 对象为 Null 时抛出异常
*
* @param object 对象
* @param message 异常信息
*/
public static void isNull(Object object, String message) {
isNull(object, new AssertException(message));
}

/**
* 对象为 Null 时抛出异常
*
* @param object 对象
* @param cause 异常
*/
public static void isNull(Object object, RuntimeException cause) {
isNull(object, () -> cause);
}

/**
* 对象为 Null 时抛出异常
*
* @param object 对象
* @param cause 异常
*/
public static void isNull(Object object, Supplier<? extends RuntimeException> cause) {
if (Objects.isNull(object)) {
throw cause.get();
}
}

/**
* 对象不为 Null 时抛出异常
*
* @param object 对象
*/
public static void nonNull(Object object) {
nonNull(object, "对象不为 Null");
}

/**
* 对象不为 Null 时抛出异常
*
* @param object 对象
* @param message 异常信息
*/
public static void nonNull(Object object, String message) {
nonNull(object, new AssertException(message));
}

/**
* 对象不为 Null 时抛出异常
*
* @param object 对象
* @param cause 异常
*/
public static void nonNull(Object object, RuntimeException cause) {
nonNull(object, () -> cause);
}

/**
* 对象不为 Null 时抛出异常
*
* @param object 对象
* @param cause 异常
*/
public static void nonNull(Object object, Supplier<? extends RuntimeException> cause) {
if (Objects.nonNull(object)) {
throw cause.get();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ private SqlUtils() {
* 检查字符,防止注入绕过
*/
public static String escapeOrderBySql(String value) {
if (StringUtils.isNotBlank(value) && !isValidOrderBySql(value)) {
throw new UtilsException("查询失败, 参数不符合规范");
}
Assert.isTrue(StringUtils.isNotBlank(value) && !isValidOrderBySql(value), new UtilsException("查询失败, 参数不符合规范"));
return value;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,24 +84,24 @@ public static String uploadAvatar(MultipartFile avatar) {
*/
private static String upload(MultipartFile file, String path) {
var fileName = getFileName(file);
if (fileName.length() > MAX_FILE_NAME_LENGTH) {
throw new MaxFileNameLengthException("上传失败, 文件名最大长度为: " + MAX_FILE_NAME_LENGTH);
}
if (file.getSize() > MAX_FILE_SIZE) {
throw new MaxFileSizeException("上传失败, 文件最大大小为: " + ByteUtils.getSize(MAX_FILE_SIZE));
}

Assert.isTrue(fileName.length() > MAX_FILE_NAME_LENGTH, new MaxFileNameLengthException("上传失败, 文件名最大长度为: " + MAX_FILE_NAME_LENGTH));
Assert.isTrue(file.getSize() > MAX_FILE_SIZE, new MaxFileSizeException("上传失败, 文件最大大小为: " + ByteUtils.getSize(MAX_FILE_SIZE)));

fileName = System.currentTimeMillis() + "_" + fileName;
var destDir = new File(path);
if (!destDir.exists()) {
destDir.mkdirs();
}
var filePath = destDir + File.separator + fileName;
var dest = new File(filePath);

try {
file.transferTo(dest);
} catch (IllegalStateException | IOException e) {
LOGGER.error("上传文件失败, 文件路径: {}, 文件大小: {}", filePath, ByteUtils.getSize(file.getSize()), e);
}

filePath = filePath.replace("\\", "/");
if (LOGGER.isInfoEnabled()) {
LOGGER.info("上传文件成功, 文件路径: {}, 文件大小: {}", filePath, ByteUtils.getSize(file.getSize()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import java.time.temporal.ChronoUnit;
import java.util.Locale;

import com.tang.commons.utils.Assert;

/**
* 日期工具类
*
Expand Down Expand Up @@ -41,9 +43,7 @@ public static String getChatTime(LocalDateTime localDateTime, boolean is12HourFo
var monday = now.with(DayOfWeek.MONDAY).truncatedTo(ChronoUnit.DAYS);
var sunday = monday.plusDays(6);

if (localDateTime.toLocalDate().isAfter(now.toLocalDate())) {
throw new IllegalArgumentException("Chat time cannot be later than now");
}
Assert.isTrue(localDateTime.toLocalDate().isAfter(now.toLocalDate()), new IllegalArgumentException("Chat time cannot be later than now"));

var pattern = new StringBuilder();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.tang.commons.utils.id;

import com.tang.commons.utils.Assert;

/**
* 雪花算法
*
Expand Down Expand Up @@ -84,12 +86,9 @@ public class Snowflake {
* @param machineId 机器标识
*/
public Snowflake(long dataCenterId, long machineId) {
if (dataCenterId > MAX_DATA_CENTER_NUM || dataCenterId < 0) {
throw new IllegalArgumentException("Data center ID can't be greater than MAX_DATA_CENTER_NUM or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("Machine ID can't be greater than MAX_MACHINE_NUM or less than 0");
}
Assert.isTrue(dataCenterId > MAX_DATA_CENTER_NUM || dataCenterId < 0, new IllegalArgumentException("Data center ID can't be greater than MAX_DATA_CENTER_NUM or less than 0"));
Assert.isTrue(machineId > MAX_MACHINE_NUM || machineId < 0, new IllegalArgumentException("Machine ID can't be greater than MAX_MACHINE_NUM or less than 0"));

this.dataCenterId = dataCenterId;
this.machineId = machineId;
}
Expand All @@ -101,10 +100,8 @@ public Snowflake(long dataCenterId, long machineId) {
*/
public synchronized long nextId() {
long currentTimestamp = getTimestamp();
if (currentTimestamp < lastTimestamp) {
// 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过,抛出非法异常
throw new IllegalArgumentException("Clock moved backwards. Refusing to generate id");
}
// 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过,抛出非法异常
Assert.isTrue(currentTimestamp < lastTimestamp, new IllegalArgumentException("Clock moved backwards. Refusing to generate id"));

// 如果是同一时间生成的,则进行毫秒内序列
if (currentTimestamp == lastTimestamp) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import com.tang.commons.exception.file.FileNotExistException;
import com.tang.commons.exception.file.FileTypeMismatchException;
import com.tang.commons.model.SysDictDataModel;
import com.tang.commons.utils.Assert;
import com.tang.commons.utils.DictUtils;
import com.tang.commons.utils.LogUtils;

Expand All @@ -61,15 +62,19 @@ private ExcelUtils() {
* @return 数据
*/
public static <T> List<T> importExcel(Class<T> clazz, MultipartFile file) {
if (Objects.isNull(file)) {
Assert.isNull(file, () -> {
LOGGER.error("导入失败, 文件为空");
throw new FileNotExistException("导入失败, 文件为空");
}
return new FileNotExistException("导入失败, 文件为空");
});
var fileName = file.getOriginalFilename();
if (Objects.isNull(fileName) || !fileName.endsWith(FileType.EXCEL_2007)) {
Assert.isNull(fileName, () -> {
LOGGER.error("导入失败, 文件名为空");
return new FileNotExistException("导入失败, 文件名为空");
});
Assert.isFalse(fileName.endsWith(FileType.EXCEL_2007), () -> {
LOGGER.error("导入失败, 只支持 Excel 2007 及以上版本");
throw new FileTypeMismatchException("导入失败, 只支持 Excel 2007 及以上版本");
}
return new FileTypeMismatchException("导入失败, 只支持 Excel 2007 及以上版本");
});

var list = new ArrayList<T>();
var fields = getFields(clazz);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import com.tang.commons.exception.user.IllegalLoginTypeException;
import com.tang.commons.model.LoginModel;
import com.tang.commons.model.UserModel;
import com.tang.commons.utils.Assert;
import com.tang.commons.utils.LogUtils;
import com.tang.commons.utils.RedisUtils;
import com.tang.commons.utils.StringUtils;
Expand Down Expand Up @@ -123,13 +124,8 @@ public void verifyCaptcha(LoginModel loginModel) {

var captcha = redisUtils.get(CachePrefix.CAPTCHA + loginModel.getCaptcha().getId());

if (Objects.isNull(captcha)) {
throw new CaptchaException("验证码已过期");
}

if (!captcha.equals(loginModel.getCaptcha().getText())) {
throw new CaptchaException("验证码错误");
}
Assert.isNull(captcha, new CaptchaException("验证码已过期"));
Assert.isFalse(captcha.equals(loginModel.getCaptcha().getText()), new CaptchaException("验证码错误"));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import com.tang.commons.model.SysDeptModel;
import com.tang.commons.model.SysUserModel;
import com.tang.commons.model.UserModel;
import com.tang.commons.utils.Assert;
import com.tang.commons.utils.SecurityUtils;
import com.tang.framework.web.service.TokenService;
import com.tang.system.entity.SysUser;
Expand Down Expand Up @@ -59,18 +60,10 @@ public AuthenticationService(SysRoleService roleService, SysMenuService menuServ
*/
public UserModel createUserModel(SysUser user, String password, String account, String loginType) {
try {
if (Objects.isNull(user)) {
throw new UserNotFoundException("用户不存在");
}
if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
throw new PasswordMismatchException("密码错误");
}
if (user.getStatus().equals(Status.DISABLED)) {
throw new DisabledException("账号已停用");
}
if (user.getDelFlag().equals(Status.DELETED)) {
throw new DeletedException("账号已删除");
}
Assert.isNull(user, new UserNotFoundException("用户不存在"));
Assert.isFalse(SecurityUtils.matchesPassword(password, user.getPassword()), new PasswordMismatchException("密码错误"));
Assert.isTrue(user.getStatus().equals(Status.DISABLED), new DisabledException("账号已停用"));
Assert.isTrue(user.getDelFlag().equals(Status.DELETED),new DeletedException("账号已删除"));
} catch (RuntimeException e) {
logLoginService.recordLoginInfo(Objects.isNull(user) ? null : user.getUserId(), tokenService.getUserAgent(), account, loginType, false, e.getMessage());
throw e;
Expand Down
Loading

0 comments on commit 9566a23

Please sign in to comment.