refactor: 优化部分工具类的使用

This commit is contained in:
Charles7c 2023-12-01 21:32:32 +08:00
parent a34070ffed
commit 0ac21fc6cb
15 changed files with 17 additions and 503 deletions

View File

@ -37,11 +37,12 @@ import org.springframework.web.multipart.MaxUploadSizeExceededException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import top.charles7c.continew.admin.common.util.StreamUtils;
import top.charles7c.continew.admin.common.util.holder.LogContextHolder;
import top.charles7c.continew.starter.core.constant.StringConstants;
import top.charles7c.continew.starter.core.util.ExceptionUtils;
import top.charles7c.continew.starter.extension.crud.exception.BadRequestException;
import top.charles7c.continew.starter.extension.crud.exception.BusinessException;
@ -74,7 +75,8 @@ public class GlobalExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
public R constraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
log.warn("请求地址 [{}],参数验证失败。", request.getRequestURI(), e);
String errorMsg = StreamUtils.join(e.getConstraintViolations(), ConstraintViolation::getMessage, "");
String errorMsg =
CollUtil.join(e.getConstraintViolations(), StringConstants.CHINESE_COMMA, ConstraintViolation::getMessage);
LogContextHolder.setErrorMsg(errorMsg);
return R.fail(HttpStatus.BAD_REQUEST.value(), errorMsg);
}
@ -85,7 +87,8 @@ public class GlobalExceptionHandler {
@ExceptionHandler(BindException.class)
public R handleBindException(BindException e, HttpServletRequest request) {
log.warn("请求地址 [{}],参数验证失败。", request.getRequestURI(), e);
String errorMsg = StreamUtils.join(e.getAllErrors(), DefaultMessageSourceResolvable::getDefaultMessage, "");
String errorMsg = CollUtil.join(e.getAllErrors(), StringConstants.CHINESE_COMMA,
DefaultMessageSourceResolvable::getDefaultMessage);
LogContextHolder.setErrorMsg(errorMsg);
return R.fail(HttpStatus.BAD_REQUEST.value(), errorMsg);
}

View File

@ -1,84 +0,0 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.continew.admin.common.util;
import java.io.File;
import java.time.LocalDateTime;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
/**
* 文件工具类
*
* @author Zheng JieELADMIN
* @author Charles7c
* @since 2023/1/2 21:34
*/
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FileUtils {
/**
* 上传文件
*
* @param multipartFile
* 源文件对象
* @param filePath
* 文件路径
* @param isKeepOriginalFilename
* 是否保留原文件名
* @return 目标文件对象
*/
public static File upload(MultipartFile multipartFile, String filePath, boolean isKeepOriginalFilename) {
String originalFilename = multipartFile.getOriginalFilename();
String extensionName = FileNameUtil.extName(originalFilename);
String fileName;
if (isKeepOriginalFilename) {
fileName = String.format("%s-%s.%s", FileNameUtil.getPrefix(originalFilename),
DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATETIME_MS_PATTERN), extensionName);
} else {
fileName = String.format("%s.%s", IdUtil.fastSimpleUUID(), extensionName);
}
try {
String pathname = filePath + fileName;
File dest = new File(pathname).getCanonicalFile();
// 如果父路径不存在自动创建
if (!dest.getParentFile().exists()) {
if (!dest.getParentFile().mkdirs()) {
log.error("Create upload file parent path failed.");
}
}
// 文件写入
multipartFile.transferTo(dest);
return dest;
} catch (Exception e) {
log.error("Upload file occurred an error: {}. fileName: {}.", e.getMessage(), fileName, e);
}
return null;
}
}

View File

@ -1,78 +0,0 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.continew.admin.common.util;
import java.util.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
/**
* Servlet 工具类
*
* @author Charles7c
* @since 2022/12/23 20:00
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ServletUtils {
/**
* 获取请求对象
*
* @return /
*/
public static HttpServletRequest getRequest() {
return getServletRequestAttributes().getRequest();
}
/**
* 获取响应对象
*
* @return /
*/
public static HttpServletResponse getResponse() {
return getServletRequestAttributes().getResponse();
}
/**
* 获取浏览器及其版本信息
*
* @param request
* 请求对象
* @return 浏览器及其版本信息
*/
public static String getBrowser(HttpServletRequest request) {
if (null == request) {
return null;
}
UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
return userAgent.getBrowser().getName() + " " + userAgent.getVersion();
}
private static ServletRequestAttributes getServletRequestAttributes() {
return (ServletRequestAttributes)Objects.requireNonNull(RequestContextHolder.getRequestAttributes());
}
}

View File

@ -1,60 +0,0 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.continew.admin.common.util;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import cn.hutool.core.collection.CollUtil;
import top.charles7c.continew.starter.core.constant.StringConstants;
/**
* Stream 工具类
*
* @author Lion Li<a href="https://gitee.com/dromara/RuoYi-Vue-Plus">RuoYi-Vue-Plus</a>
* @author Charles7c
* @since 2022/12/22 19:51
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StreamUtils {
/**
* 将集合中的指定字段使用分隔符拼接成字符串
*
* @param collection
* 集合
* @param function
* 字段方法
* @param delimiter
* 分隔符
* @param <E>
* /
* @return 拼接结果
*/
public static <E> String join(Collection<E> collection, Function<E, String> function, CharSequence delimiter) {
if (CollUtil.isEmpty(collection)) {
return StringConstants.EMPTY;
}
return collection.stream().map(function).filter(Objects::nonNull).collect(Collectors.joining(delimiter));
}
}

View File

@ -1,53 +0,0 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.continew.admin.common.util;
import java.util.Map;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
/**
* 模板工具类
*
* @author Charles7c
* @since 2023/1/13 20:37
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TemplateUtils {
private static final String TEMPLATE_PARENT_PATH = "templates";
/**
* 将模板与绑定参数融合后返回为字符串
*
* @param bindingMap
* 绑定的参数此Map中的参数会替换模板中的变量
* @return 融合后的内容
*/
public static String render(String templatePath, Map<?, ?> bindingMap) {
TemplateEngine engine =
TemplateUtil.createEngine(new TemplateConfig(TEMPLATE_PARENT_PATH, TemplateConfig.ResourceMode.CLASSPATH));
Template template = engine.getTemplate(templatePath);
return template.render(bindingMap);
}
}

View File

@ -1,43 +0,0 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.continew.admin.common.util;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import cn.hutool.http.HttpUtil;
/**
* URLUniform Resource Locator统一资源定位符相关工具类
*
* @author Charles7c
* @since 2023/3/20 21:27
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class URLUtils {
/**
* 提供的 URL 是否为 HTTP URL协议包括"http""https"
*
* @param url
* URL
* @return 是否为 HTTP URL
*/
public static boolean isHttpUrl(String url) {
return HttpUtil.isHttp(url) || HttpUtil.isHttps(url);
}
}

View File

@ -32,10 +32,10 @@ import cn.hutool.extra.spring.SpringUtil;
import top.charles7c.continew.admin.common.constant.CacheConstants;
import top.charles7c.continew.admin.common.model.dto.LogContext;
import top.charles7c.continew.admin.common.model.dto.LoginUser;
import top.charles7c.continew.admin.common.util.ServletUtils;
import top.charles7c.continew.admin.common.util.holder.LogContextHolder;
import top.charles7c.continew.starter.core.util.ExceptionUtils;
import top.charles7c.continew.starter.core.util.IpUtils;
import top.charles7c.continew.starter.core.util.ServletUtils;
import top.charles7c.continew.starter.extension.crud.base.CommonUserService;
/**

View File

@ -53,7 +53,6 @@ import cn.hutool.json.JSONUtil;
import top.charles7c.continew.admin.auth.model.req.AccountLoginReq;
import top.charles7c.continew.admin.common.constant.SysConstants;
import top.charles7c.continew.admin.common.model.dto.LogContext;
import top.charles7c.continew.admin.common.util.ServletUtils;
import top.charles7c.continew.admin.common.util.helper.LoginHelper;
import top.charles7c.continew.admin.common.util.holder.LogContextHolder;
import top.charles7c.continew.admin.monitor.annotation.Log;
@ -64,6 +63,7 @@ import top.charles7c.continew.admin.system.service.UserService;
import top.charles7c.continew.starter.core.constant.StringConstants;
import top.charles7c.continew.starter.core.util.ExceptionUtils;
import top.charles7c.continew.starter.core.util.IpUtils;
import top.charles7c.continew.starter.core.util.ServletUtils;
import top.charles7c.continew.starter.extension.crud.model.resp.R;
/**

View File

@ -41,7 +41,6 @@ import top.charles7c.continew.admin.common.constant.CacheConstants;
import top.charles7c.continew.admin.common.constant.FileConstants;
import top.charles7c.continew.admin.common.constant.SysConstants;
import top.charles7c.continew.admin.common.enums.DisEnableStatusEnum;
import top.charles7c.continew.admin.common.util.FileUtils;
import top.charles7c.continew.admin.common.util.SecureUtils;
import top.charles7c.continew.admin.common.util.helper.LoginHelper;
import top.charles7c.continew.admin.system.mapper.UserMapper;
@ -58,6 +57,7 @@ import top.charles7c.continew.admin.system.service.UserRoleService;
import top.charles7c.continew.admin.system.service.UserService;
import top.charles7c.continew.starter.core.constant.StringConstants;
import top.charles7c.continew.starter.core.util.ExceptionUtils;
import top.charles7c.continew.starter.core.util.FileUploadUtils;
import top.charles7c.continew.starter.extension.crud.base.BaseServiceImpl;
import top.charles7c.continew.starter.extension.crud.base.CommonUserService;
import top.charles7c.continew.starter.extension.crud.util.validate.CheckUtils;
@ -172,7 +172,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserRes
// 上传新头像
UserDO user = super.getById(id);
String avatarPath = localStorageProperties.getPath().getAvatar();
File newAvatarFile = FileUtils.upload(avatarFile, avatarPath, false);
File newAvatarFile = FileUploadUtils.upload(avatarFile, avatarPath, false);
CheckUtils.throwIfNull(newAvatarFile, "上传头像失败");
assert null != newAvatarFile;
// 更新用户头像

View File

@ -42,7 +42,6 @@ import cn.hutool.core.util.StrUtil;
import cn.hutool.db.meta.Column;
import cn.hutool.system.SystemUtil;
import top.charles7c.continew.admin.common.util.TemplateUtils;
import top.charles7c.continew.admin.tool.config.properties.GeneratorProperties;
import top.charles7c.continew.admin.tool.config.properties.GeneratorProperties.TemplateConfig;
import top.charles7c.continew.admin.tool.mapper.FieldConfigMapper;
@ -53,9 +52,10 @@ import top.charles7c.continew.admin.tool.model.query.TableQuery;
import top.charles7c.continew.admin.tool.model.req.GenConfigReq;
import top.charles7c.continew.admin.tool.model.resp.TableResp;
import top.charles7c.continew.admin.tool.service.GeneratorService;
import top.charles7c.continew.admin.tool.util.MetaUtils;
import top.charles7c.continew.admin.tool.util.Table;
import top.charles7c.continew.starter.core.constant.StringConstants;
import top.charles7c.continew.starter.core.util.TemplateUtils;
import top.charles7c.continew.starter.core.util.db.MetaUtils;
import top.charles7c.continew.starter.core.util.db.Table;
import top.charles7c.continew.starter.extension.crud.enums.QueryTypeEnum;
import top.charles7c.continew.starter.extension.crud.exception.BusinessException;
import top.charles7c.continew.starter.extension.crud.model.query.PageQuery;

View File

@ -1,99 +0,0 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.continew.admin.tool.util;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.sql.DataSource;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.meta.Column;
import cn.hutool.db.meta.MetaUtil;
/**
* 数据库元数据信息工具类
*
* @author Charles7c
* @since 2023/4/26 21:39
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MetaUtils {
/**
* 获取所有表信息
*
* @param dataSource
* 数据源
* @return 表信息列表
*/
public static List<Table> getTables(DataSource dataSource) throws SQLException {
return getTables(dataSource, null);
}
/**
* 获取所有表信息
*
* @param dataSource
* 数据源
* @param tableName
* 表名称
* @return 表信息列表
*/
public static List<Table> getTables(DataSource dataSource, String tableName) throws SQLException {
String querySql = "SHOW TABLE STATUS";
List<Entity> tableEntityList;
Db db = Db.use(dataSource);
if (StrUtil.isNotBlank(tableName)) {
tableEntityList = db.query(String.format("%s WHERE NAME = ?", querySql), tableName);
} else {
tableEntityList = db.query(querySql);
}
List<Table> tableList = new ArrayList<>(tableEntityList.size());
for (Entity tableEntity : tableEntityList) {
Table table = new Table(tableEntity.getStr("NAME"));
table.setComment(tableEntity.getStr("COMMENT"));
table.setEngine(tableEntity.getStr("ENGINE"));
table.setCharset(tableEntity.getStr("COLLATION"));
table.setCreateTime(DateUtil.toLocalDateTime(tableEntity.getDate("CREATE_TIME")));
table.setUpdateTime(DateUtil.toLocalDateTime(tableEntity.getDate("UPDATE_TIME")));
tableList.add(table);
}
return tableList;
}
/**
* 获取所有列信息
*
* @param dataSource
* 数据源
* @param tableName
* 表名称
* @return 列信息列表
*/
public static Collection<Column> getColumns(DataSource dataSource, String tableName) {
cn.hutool.db.meta.Table table = MetaUtil.getTableMeta(dataSource, tableName);
return table.getColumns();
}
}

View File

@ -1,72 +0,0 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.continew.admin.tool.util;
import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
/**
* 数据库表信息
*
* @author Charles7c
* @since 2023/4/26 21:41
*/
@Getter
@Setter
public class Table implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 表名称
*/
private String tableName;
/**
* 注释
*/
private String comment;
/**
* 存储引擎
*/
private String engine;
/**
* 字符集
*/
private String charset;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 修改时间
*/
private LocalDateTime updateTime;
public Table(String tableName) {
this.tableName = tableName;
}
}

View File

@ -50,10 +50,10 @@ import top.charles7c.continew.admin.common.config.properties.CaptchaProperties;
import top.charles7c.continew.admin.common.constant.CacheConstants;
import top.charles7c.continew.admin.common.constant.RegexConstants;
import top.charles7c.continew.admin.common.model.resp.CaptchaResp;
import top.charles7c.continew.admin.common.util.TemplateUtils;
import top.charles7c.continew.starter.cache.redisson.util.RedisUtils;
import top.charles7c.continew.starter.captcha.graphic.autoconfigure.GraphicCaptchaProperties;
import top.charles7c.continew.starter.core.autoconfigure.project.ProjectProperties;
import top.charles7c.continew.starter.core.util.TemplateUtils;
import top.charles7c.continew.starter.extension.crud.model.resp.R;
import top.charles7c.continew.starter.extension.crud.util.validate.CheckUtils;
import top.charles7c.continew.starter.messaging.mail.util.MailUtils;

View File

@ -45,7 +45,6 @@ import cn.hutool.core.util.StrUtil;
import top.charles7c.continew.admin.common.config.properties.LocalStorageProperties;
import top.charles7c.continew.admin.common.constant.CacheConstants;
import top.charles7c.continew.admin.common.model.resp.LabelValueResp;
import top.charles7c.continew.admin.common.util.FileUtils;
import top.charles7c.continew.admin.monitor.annotation.Log;
import top.charles7c.continew.admin.system.model.query.DeptQuery;
import top.charles7c.continew.admin.system.model.query.MenuQuery;
@ -54,6 +53,7 @@ import top.charles7c.continew.admin.system.model.query.RoleQuery;
import top.charles7c.continew.admin.system.model.resp.RoleResp;
import top.charles7c.continew.admin.system.service.*;
import top.charles7c.continew.starter.core.autoconfigure.project.ProjectProperties;
import top.charles7c.continew.starter.core.util.FileUploadUtils;
import top.charles7c.continew.starter.extension.crud.base.IBaseEnum;
import top.charles7c.continew.starter.extension.crud.model.query.SortQuery;
import top.charles7c.continew.starter.extension.crud.model.resp.R;
@ -89,7 +89,7 @@ public class CommonController {
Long maxSizeInMb = localStorageProperties.getMaxSizeInMb();
CheckUtils.throwIf(file.getSize() > maxSizeInMb * 1024 * 1024, "请上传小于 {}MB 的文件", maxSizeInMb);
String filePath = localStorageProperties.getPath().getFile();
File newFile = FileUtils.upload(file, filePath, false);
File newFile = FileUploadUtils.upload(file, filePath, false);
CheckUtils.throwIfNull(newFile, "上传文件失败");
assert null != newFile;
return R.ok("上传成功", newFile.getName());

View File

@ -26,11 +26,11 @@ import org.springframework.web.bind.annotation.RestController;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import top.charles7c.continew.admin.common.util.URLUtils;
import top.charles7c.continew.admin.system.model.query.MenuQuery;
import top.charles7c.continew.admin.system.model.req.MenuReq;
import top.charles7c.continew.admin.system.model.resp.MenuResp;
import top.charles7c.continew.admin.system.service.MenuService;
import top.charles7c.continew.starter.core.util.URLUtils;
import top.charles7c.continew.starter.extension.crud.annotation.CrudRequestMapping;
import top.charles7c.continew.starter.extension.crud.base.BaseController;
import top.charles7c.continew.starter.extension.crud.base.ValidateGroup;