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

This commit is contained in:
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;
/**