sonarqube质量修复

This commit is contained in:
gaoqr
2024-10-09 12:04:54 +08:00
parent 2e96dd8173
commit 220d0ff28a
36 changed files with 242 additions and 513 deletions
@@ -12,38 +12,32 @@ import com.cf.imes.framework.common.exception.ErrorCode;
*
* @author 晨丰科技
*/
public interface GlobalErrorCodeConstants {
public class GlobalErrorCodeConstants {
ErrorCode SUCCESS = new ErrorCode(0, "成功");
public static final ErrorCode SUCCESS = new ErrorCode(0, "成功");
// ========== 客户端错误段 ==========
ErrorCode BAD_REQUEST = new ErrorCode(400, "请求参数不正确");
ErrorCode UNAUTHORIZED = new ErrorCode(401, "账号未登录");
ErrorCode FORBIDDEN = new ErrorCode(403, "没有该操作权限");
ErrorCode NOT_FOUND = new ErrorCode(404, "请求未找到");
ErrorCode METHOD_NOT_ALLOWED = new ErrorCode(405, "请求方法不正确");
ErrorCode LOCKED = new ErrorCode(423, "请求失败,请稍后重试"); // 并发请求,不允许
ErrorCode TOO_MANY_REQUESTS = new ErrorCode(429, "请求过于频繁,请稍后重试");
ErrorCode DATA_SOURCE_CODE_NOT_FOUND = new ErrorCode(430, "未传递数据源标识");
ErrorCode ORGAN_ID_NOT_FOUND = new ErrorCode(431, "未传组织标识");
public static final ErrorCode BAD_REQUEST = new ErrorCode(400, "请求参数不正确");
public static final ErrorCode UNAUTHORIZED = new ErrorCode(401, "账号未登录");
public static final ErrorCode FORBIDDEN = new ErrorCode(403, "没有该操作权限");
public static final ErrorCode NOT_FOUND = new ErrorCode(404, "请求未找到");
public static final ErrorCode METHOD_NOT_ALLOWED = new ErrorCode(405, "请求方法不正确");
public static final ErrorCode LOCKED = new ErrorCode(423, "请求失败,请稍后重试"); // 并发请求,不允许
public static final ErrorCode TOO_MANY_REQUESTS = new ErrorCode(429, "请求过于频繁,请稍后重试");
// ========== 服务端错误段 ==========
ErrorCode INTERNAL_SERVER_ERROR = new ErrorCode(500, "系统异常,请联系客服处理");
ErrorCode NOT_IMPLEMENTED = new ErrorCode(501, "功能未实现/未开启");
ErrorCode ERROR_CONFIGURATION = new ErrorCode(502, "错误的配置项");
public static final ErrorCode INTERNAL_SERVER_ERROR = new ErrorCode(500, "系统异常,请联系客服处理");
public static final ErrorCode NOT_IMPLEMENTED = new ErrorCode(501, "功能未实现/未开启");
// ES文档更新失败
ErrorCode ES_ERROR_UPDATE = new ErrorCode(503, "数据异常,请勿点击过快,请稍等再试");
public static final ErrorCode ES_ERROR_UPDATE = new ErrorCode(503, "数据异常,请勿点击过快,请稍等再试");
// ES文档删除失败
ErrorCode ES_ERROR_DELETE = new ErrorCode(504, "数据异常,请勿点击过快,请稍等再试");
ErrorCode DATA_EXCEPTION_ERROR = new ErrorCode(505, "数据异常,请联系客服处理");
public static final ErrorCode ES_ERROR_DELETE = new ErrorCode(504, "数据异常,请勿点击过快,请稍等再试");
public static final ErrorCode DATA_EXCEPTION_ERROR = new ErrorCode(505, "数据异常,请联系客服处理");
// ========== 自定义错误段 ==========
ErrorCode REPEATED_REQUESTS = new ErrorCode(900, "重复请求,请稍后重试"); // 重复请求
ErrorCode DEMO_DENY = new ErrorCode(901, "演示模式,禁止写操作");
ErrorCode UNKNOWN = new ErrorCode(999, "未知错误");
public static final ErrorCode REPEATED_REQUESTS = new ErrorCode(900, "重复请求,请稍后重试"); // 重复请求
public static final ErrorCode DEMO_DENY = new ErrorCode(901, "演示模式,禁止写操作");
}
@@ -34,6 +34,8 @@ public class JsonUtils {
private static ObjectMapper objectMapper = new ObjectMapper();
private static final String JSON_PARSE_ERROR_NOTIFICATION = "json parse err,json:{}";
static {
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
@@ -74,7 +76,7 @@ public class JsonUtils {
try {
return objectMapper.readValue(text, clazz);
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
log.error(JSON_PARSE_ERROR_NOTIFICATION, text, e);
throw new RuntimeException(e);
}
}
@@ -88,7 +90,7 @@ public class JsonUtils {
JsonNode pathNode = treeNode.path(path);
return objectMapper.readValue(pathNode.toString(), clazz);
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
log.error(JSON_PARSE_ERROR_NOTIFICATION, text, e);
throw new RuntimeException(e);
}
}
@@ -100,7 +102,7 @@ public class JsonUtils {
try {
return objectMapper.readValue(text, objectMapper.getTypeFactory().constructType(type));
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
log.error(JSON_PARSE_ERROR_NOTIFICATION, text, e);
throw new RuntimeException(e);
}
}
@@ -128,7 +130,7 @@ public class JsonUtils {
try {
return objectMapper.readValue(bytes, clazz);
} catch (IOException e) {
log.error("json parse err,json:{}", bytes, e);
log.error(JSON_PARSE_ERROR_NOTIFICATION, bytes, e);
throw new RuntimeException(e);
}
}
@@ -137,7 +139,7 @@ public class JsonUtils {
try {
return objectMapper.readValue(text, typeReference);
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
log.error(JSON_PARSE_ERROR_NOTIFICATION, text, e);
throw new RuntimeException(e);
}
}
@@ -149,7 +151,7 @@ public class JsonUtils {
try {
return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
log.error(JSON_PARSE_ERROR_NOTIFICATION, text, e);
throw new RuntimeException(e);
}
}
@@ -163,7 +165,7 @@ public class JsonUtils {
JsonNode pathNode = treeNode.path(path);
return objectMapper.readValue(pathNode.toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
log.error(JSON_PARSE_ERROR_NOTIFICATION, text, e);
throw new RuntimeException(e);
}
}
@@ -172,7 +174,7 @@ public class JsonUtils {
try {
return objectMapper.readTree(text);
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
log.error(JSON_PARSE_ERROR_NOTIFICATION, text, e);
throw new RuntimeException(e);
}
}
@@ -181,7 +183,7 @@ public class JsonUtils {
try {
return objectMapper.readTree(text);
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
log.error(JSON_PARSE_ERROR_NOTIFICATION, text, e);
throw new RuntimeException(e);
}
}
@@ -246,23 +248,26 @@ public class JsonUtils {
//设置解压缩的输入数据。
inflater.setInput(decode);
final byte[] bytes = new byte[256];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
try {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256)) {
//finished() 如果已到达压缩数据流的末尾,则返回true。
while (!inflater.finished()) {
//将字节解压缩到指定的缓冲区中。
int length = inflater.inflate(bytes);
outputStream.write(bytes, 0, length);
}
return outputStream.toString();
} catch (DataFormatException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
//关闭解压缩器并丢弃任何未处理的输入。
inflater.end();
}
return outputStream.toString();
}
@@ -34,14 +34,17 @@ public class OrganKafkaProducerInterceptor implements ProducerInterceptor<Object
@Override
public void onAcknowledgement(RecordMetadata metadata, Exception exception) {
// onAcknowledgement
}
@Override
public void close() {
// close
}
@Override
public void configure(Map<String, ?> configs) {
// configure
}
}
@@ -31,6 +31,7 @@ public class OrganRocketMQSendMessageHook implements SendMessageHook {
@Override
public void sendMessageAfter(SendMessageContext sendMessageContext) {
// sendMessageAfter
}
}
@@ -4,6 +4,7 @@ import com.cf.imes.framework.pay.core.client.exception.PayException;
import com.cf.imes.framework.pay.core.enums.order.PayOrderDisplayModeEnum;
import com.cf.imes.framework.pay.core.enums.order.PayOrderStatusRespEnum;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@@ -13,6 +14,7 @@ import java.time.LocalDateTime;
* @author 晨丰科技
*/
@Data
@NoArgsConstructor
public class PayOrderRespDTO {
/**
@@ -73,9 +75,6 @@ public class PayOrderRespDTO {
*/
private String channelErrorMsg;
public PayOrderRespDTO() {
}
/**
* 创建【WAITING】状态的订单返回
*/
@@ -1,8 +1,8 @@
package com.cf.imes.framework.pay.core.client.impl.weixin;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.cf.imes.framework.common.util.date.LocalDateTimeUtils;
import com.cf.imes.framework.pay.core.client.dto.order.PayOrderRespDTO;
import com.cf.imes.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
@@ -77,7 +77,7 @@ public class WxBarPayClient extends AbstractWxPayClient {
// 1. SYSTEMERROR:接口返回错误:请立即调用被扫订单结果查询API,查询当前订单状态,并根据订单的状态决定下一步的操作。
// 2. USERPAYING:用户支付中,需要输入密码:等待 5 秒,然后调用被扫订单结果查询 API,查询当前订单的不同状态,决定下一步的操作。
// 3. BANKERROR:银行系统异常:请立即调用被扫订单结果查询 API,查询当前订单的不同状态,决定下一步的操作。
if (!StrUtil.equalsAny(ex.getErrCode(), "SYSTEMERROR", "USERPAYING", "BANKERROR")) {
if (!CharSequenceUtil.equalsAny(ex.getErrCode(), "SYSTEMERROR", "USERPAYING", "BANKERROR")) {
throw ex;
}
// 等待 5 秒,继续下一轮重新发起支付
@@ -98,7 +98,7 @@ public class WxBarPayClient extends AbstractWxPayClient {
static String getAuthCode(PayOrderUnifiedReqDTO reqDTO) {
String authCode = MapUtil.getStr(reqDTO.getChannelExtras(), "authCode");
if (StrUtil.isEmpty(authCode)) {
if (CharSequenceUtil.isEmpty(authCode)) {
throw invalidParamException("支付请求的 authCode 不能为空!");
}
return authCode;
@@ -1,7 +1,7 @@
package com.cf.imes.framework.pay.core.client.impl.weixin;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.cf.imes.framework.pay.core.client.dto.order.PayOrderRespDTO;
import com.cf.imes.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
import com.cf.imes.framework.pay.core.enums.channel.PayChannelEnum;
@@ -71,7 +71,7 @@ public class WxPubPayClient extends AbstractWxPayClient {
static String getOpenid(PayOrderUnifiedReqDTO reqDTO) {
String openid = MapUtil.getStr(reqDTO.getChannelExtras(), "openid");
if (StrUtil.isEmpty(openid)) {
if (CharSequenceUtil.isEmpty(openid)) {
throw invalidParamException("支付请求的 openid 不能为空!");
}
return openid;
@@ -1,50 +0,0 @@
package com.cf.imes.framework.sms.core.enums;
import com.cf.imes.framework.common.exception.ErrorCode;
/**
* 短信框架的错误码枚举
*
* 短信框架,使用 2-001-000-000 段
*
* @author 晨丰科技
*/
public interface SmsFrameworkErrorCodeConstants {
ErrorCode SMS_UNKNOWN = new ErrorCode(2_001_000_000, "未知错误,需要解析");
// ========== 权限 / 限流等相关 2-001-000-100 ==========
ErrorCode SMS_PERMISSION_DENY = new ErrorCode(2_001_000_100, "没有发送短信的权限");
ErrorCode SMS_IP_DENY = new ErrorCode(2_001_000_100, "IP 不允许发送短信");
// 阿里云:将短信发送频率限制在正常的业务限流范围内。默认短信验证码:使用同一签名,对同一个手机号验证码,支持 1 条 / 分钟,5 条 / 小时,累计 10 条 / 天。
ErrorCode SMS_SEND_BUSINESS_LIMIT_CONTROL = new ErrorCode(2_001_000_102, "指定手机的发送限流");
// 阿里云:已经达到您在控制台设置的短信日发送量限额值。在国内消息设置 > 安全设置,修改发送总量阈值。
ErrorCode SMS_SEND_DAY_LIMIT_CONTROL = new ErrorCode(2_001_000_103, "每天的发送限流");
ErrorCode SMS_SEND_CONTENT_INVALID = new ErrorCode(2_001_000_104, "短信内容有敏感词");
// 腾讯云:为避免骚扰用户,营销短信只允许在8点到22点发送。
ErrorCode SMS_SEND_MARKET_LIMIT_CONTROL = new ErrorCode(2_001_000_105, "营销短信发送时间限制");
// ========== 模板相关 2-001-000-200 ==========
ErrorCode SMS_TEMPLATE_INVALID = new ErrorCode(2_001_000_200, "短信模板不合法"); // 包括短信模板不存在
ErrorCode SMS_TEMPLATE_PARAM_ERROR = new ErrorCode(2_001_000_201, "模板参数不正确");
// ========== 签名相关 2-001-000-300 ==========
ErrorCode SMS_SIGN_INVALID = new ErrorCode(2_001_000_300, "短信签名不可用");
// ========== 账户相关 2-001-000-400 ==========
ErrorCode SMS_ACCOUNT_MONEY_NOT_ENOUGH = new ErrorCode(2_001_000_400, "账户余额不足");
ErrorCode SMS_ACCOUNT_INVALID = new ErrorCode(2_001_000_401, "apiKey 不存在");
// ========== 其它相关 2-001-000-900 开头 ==========
ErrorCode SMS_API_PARAM_ERROR = new ErrorCode(2_001_000_900, "请求参数缺失");
ErrorCode SMS_MOBILE_INVALID = new ErrorCode(2_001_000_901, "手机格式不正确");
ErrorCode SMS_MOBILE_BLACK = new ErrorCode(2_001_000_902, "手机号在黑名单中");
ErrorCode SMS_APP_ID_INVALID = new ErrorCode(2_001_000_903, "SdkAppId不合法");
ErrorCode EXCEPTION = new ErrorCode(2_001_000_999, "调用异常");
}
@@ -1,28 +0,0 @@
package com.cf.imes.framework.captcha.core.enums;
/**
* 验证码 Redis Key 枚举类
*
* @author 晨丰科技
*/
public interface CaptchaRedisKeyConstants {
/**
* 验证码的请求限流
*
* KEY 格式:AJ.CAPTCHA.REQ.LIMIT-%s-%s
* VALUE 数据类型:String // 例如说:验证失败 5 次,get 接口锁定
* 过期时间:60 秒
*/
String AJ_CAPTCHA_REQ_LIMIT = "AJ.CAPTCHA.REQ.LIMIT-%s-%s";
/**
* 验证码的坐标
*
* KEY 格式:RUNNING:CAPTCHA:%s // AbstractCaptchaService.REDIS_CAPTCHA_KEY
* VALUE 数据类型:String // PointVO.class {"secretKey":"PP1w2Frr2KEejD2m","x":162,"y":5}
* 过期时间:120 秒
*/
String AJ_CAPTCHA_RUNNING = "RUNNING:CAPTCHA:%s";
}
@@ -2,9 +2,9 @@ package com.cf.imes.framework.desensitize.core.base.serializer;
import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.lang.Singleton;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.cf.imes.framework.desensitize.core.base.annotation.DesensitizeBy;
import com.cf.imes.framework.desensitize.core.base.handler.DesensitizationHandler;
import com.fasterxml.jackson.core.JsonGenerator;
@@ -53,7 +53,7 @@ public class StringDesensitizeSerializer extends StdSerializer<String> implement
@Override
@SuppressWarnings("unchecked")
public void serialize(String value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
if (StrUtil.isBlank(value)) {
if (CharSequenceUtil.isBlank(value)) {
gen.writeNull();
return;
}
@@ -1,7 +1,7 @@
package com.cf.imes.framework.file.core.client.s3;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.HttpUtil;
import com.cf.imes.framework.file.core.client.AbstractFileClient;
import io.minio.*;
@@ -29,7 +29,7 @@ public class S3FileClient extends AbstractFileClient<S3FileClientConfig> {
@Override
protected void doInit() {
// 补全 domain
if (StrUtil.isEmpty(config.getDomain())) {
if (CharSequenceUtil.isEmpty(config.getDomain())) {
config.setDomain(buildDomain());
}
// 初始化客户端
@@ -50,7 +50,7 @@ public class S3FileClient extends AbstractFileClient<S3FileClientConfig> {
if (HttpUtil.isHttp(config.getEndpoint()) || HttpUtil.isHttps(config.getEndpoint())) {
return config.getEndpoint();
}
return StrUtil.format("https://{}", config.getEndpoint());
return CharSequenceUtil.format("https://{}", config.getEndpoint());
}
/**
@@ -61,10 +61,10 @@ public class S3FileClient extends AbstractFileClient<S3FileClientConfig> {
private String buildDomain() {
// 如果已经是 http 或者 https,则不进行拼接.主要适配 MinIO
if (HttpUtil.isHttp(config.getEndpoint()) || HttpUtil.isHttps(config.getEndpoint())) {
return StrUtil.format("{}/{}", config.getEndpoint(), config.getBucket());
return CharSequenceUtil.format("{}/{}", config.getEndpoint(), config.getBucket());
}
// 阿里云、腾讯云、华为云都适合。七牛云比较特殊,必须有自定义域名
return StrUtil.format("https://{}.{}", config.getBucket(), config.getEndpoint());
return CharSequenceUtil.format("https://{}.{}", config.getBucket(), config.getEndpoint());
}
/**
@@ -75,13 +75,13 @@ public class S3FileClient extends AbstractFileClient<S3FileClientConfig> {
private String buildRegion() {
// 阿里云必须有 region,否则会报错
if (config.getEndpoint().contains(ENDPOINT_ALIYUN)) {
return StrUtil.subBefore(config.getEndpoint(), '.', false)
.replaceAll("-internal", "")// 去除内网 Endpoint 的后缀
.replaceAll("https://", "");
return CharSequenceUtil.subBefore(config.getEndpoint(), '.', false)
.replace("-internal", "")// 去除内网 Endpoint 的后缀
.replace("https://", "");
}
// 腾讯云必须有 region,否则会报错
if (config.getEndpoint().contains(ENDPOINT_TENCENT)) {
return StrUtil.subAfter(config.getEndpoint(), "cos.", false)
return CharSequenceUtil.subAfter(config.getEndpoint(), "cos.", false)
.replaceAll("." + ENDPOINT_TENCENT, ""); // 去除 Endpoint
}
return null;
@@ -1,6 +1,6 @@
package com.cf.imes.framework.file.core.client.s3;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.cf.imes.framework.file.core.client.FileClientConfig;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
@@ -68,7 +68,7 @@ public class S3FileClientConfig implements FileClientConfig {
@JsonIgnore
public boolean isDomainValid() {
// 如果是七牛,必须带有 domain
if (StrUtil.contains(endpoint, ENDPOINT_QINIU) && StrUtil.isEmpty(domain)) {
if (CharSequenceUtil.contains(endpoint, ENDPOINT_QINIU) && CharSequenceUtil.isEmpty(domain)) {
return false;
}
return true;
@@ -1,22 +0,0 @@
package com.cf.imes.framework.datasource.core.enums;
/**
* 对应于多数据源中不同数据源配置
*
* 通过在方法上,使用 {@link com.baomidou.dynamic.datasource.annotation.DS} 注解,设置使用的数据源。
* 注意,默认是 {@link #MASTER} 数据源
*
* 对应官方文档为 http://dynamic-datasource.com/guide/customize/Annotation.html
*/
public interface DataSourceEnum {
/**
* 主库,推荐使用 {@link com.baomidou.dynamic.datasource.annotation.Master} 注解
*/
String MASTER = "master";
/**
* 从库,推荐使用 {@link com.baomidou.dynamic.datasource.annotation.Slave} 注解
*/
String SLAVE = "slave";
}
@@ -67,6 +67,8 @@ public class ChenfengMybatisAutoConfiguration {
return new KingbaseKeyGenerator();
case DM:
return new DmKeyGenerator();
default:
throw new IllegalArgumentException(CharSequenceUtil.format("DbType{} 找不到合适的 IKeyGenerator 实现类", dbType));
}
}
// 找不到合适的 IKeyGenerator 实现类
@@ -86,6 +86,7 @@ public class IdTypeEnvironmentPostProcessor implements EnvironmentPostProcessor
case SQL_SERVER2005:
driverClass = "org.quartz.impl.jdbcjobstore.MSSQLDelegate";
break;
default:
}
// 设置 driverClass 变量
if (CharSequenceUtil.isNotEmpty(driverClass)) {
@@ -1,7 +1,7 @@
package com.cf.imes.framework.mybatis.core.type;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.text.CharSequenceUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
@@ -53,6 +53,6 @@ public class StringListTypeHandler implements TypeHandler<List<String>> {
if (value == null) {
return null;
}
return StrUtil.splitTrim(value, COMMA);
return CharSequenceUtil.splitTrim(value, COMMA);
}
}
@@ -1,19 +0,0 @@
package com.cf.imes.framework.lock4j.core;
/**
* Lock4j Redis Key 枚举类
*
* @author 晨丰科技
*/
public interface Lock4jRedisKeyConstants {
/**
* 分布式锁
*
* KEY 格式:lock4j:%s // 参数来自 DefaultLockKeyBuilder 类
* VALUE 数据格式:HASH // RLock.classRedisson 的 Lock 锁,使用 Hash 数据结构
* 过期时间:不固定
*/
String LOCK4J = "lock4j:%s";
}
@@ -1,7 +1,8 @@
package com.cf.imes.framework.redis.core;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
@@ -28,11 +29,11 @@ public class TimeoutRedisCacheManager extends RedisCacheManager {
@Override
protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
if (StrUtil.isEmpty(name)) {
if (CharSequenceUtil.isEmpty(name)) {
return super.createRedisCache(name, cacheConfig);
}
// 如果使用 # 分隔,大小不为 2,则说明不使用自定义过期时间
String[] names = StrUtil.splitToArray(name, SPLIT);
String[] names = CharSequenceUtil.splitToArray(name, SPLIT);
if (names.length != 2) {
return super.createRedisCache(name, cacheConfig);
}
@@ -40,7 +41,7 @@ public class TimeoutRedisCacheManager extends RedisCacheManager {
// 核心:通过修改 cacheConfig 的过期时间,实现自定义过期时间
if (cacheConfig != null) {
// 移除 # 后面的 : 以及后面的内容,避免影响解析
names[1] = StrUtil.subBefore(names[1], StrUtil.COLON, false);
names[1] = CharSequenceUtil.subBefore(names[1], StrPool.COLON, false);
// 解析时间
Duration duration = parseDuration(names[1]);
cacheConfig = cacheConfig.entryTtl(duration);
@@ -55,7 +56,7 @@ public class TimeoutRedisCacheManager extends RedisCacheManager {
* @return 过期时间 Duration
*/
private Duration parseDuration(String ttlStr) {
String timeUnit = StrUtil.subSuf(ttlStr, -1);
String timeUnit = CharSequenceUtil.subSuf(ttlStr, -1);
switch (timeUnit) {
case "d":
return Duration.ofDays(removeDurationSuffix(ttlStr));
@@ -77,7 +78,7 @@ public class TimeoutRedisCacheManager extends RedisCacheManager {
* @return 时间
*/
private Long removeDurationSuffix(String ttlStr) {
return NumberUtil.parseLong(StrUtil.sub(ttlStr, 0, ttlStr.length() - 1));
return NumberUtil.parseLong(CharSequenceUtil.sub(ttlStr, 0, ttlStr.length() - 1));
}
}
@@ -186,6 +186,7 @@ public class ChenfengWebSecurityConfigurerAdapter {
case DELETE:
result.putAll(HttpMethod.DELETE, urls);
break;
default:
}
});
}
@@ -1,7 +1,7 @@
package com.cf.imes.framework.security.core.filter;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.util.json.JsonUtils;
@@ -58,7 +58,7 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
if (loginUser == null) {
String token = SecurityFrameworkUtils.obtainAuthorization(request,
securityProperties.getTokenHeader(), securityProperties.getTokenParameter());
if (StrUtil.isNotEmpty(token)) {
if (CharSequenceUtil.isNotEmpty(token)) {
Integer userType = WebFrameworkUtils.getLoginUserType(request);
try {
// 1.1 基于 token 构建登录用户
@@ -135,7 +135,7 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
@SneakyThrows
private LoginUser buildLoginUserByHeader(HttpServletRequest request) {
String loginUserStr = request.getHeader(SecurityFrameworkUtils.LOGIN_USER_HEADER);
if(StrUtil.isNotEmpty(loginUserStr)) {
if(CharSequenceUtil.isNotEmpty(loginUserStr)) {
try {
loginUserStr = URLDecoder.decode(loginUserStr, StandardCharsets.UTF_8.name()); // 解码,解决中文乱码问题
return JsonUtils.parseObject(loginUserStr, LoginUser.class);
@@ -1,9 +1,9 @@
package com.cf.imes.framework.test.core.util;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.cf.imes.framework.common.enums.CommonStatusEnum;
import uk.co.jemos.podam.api.PodamFactory;
import uk.co.jemos.podam.api.PodamFactoryImpl;
@@ -46,7 +46,7 @@ public class RandomUtils {
return RandomUtil.randomEle(CommonStatusEnum.values()).getStatus();
}
// 如果是 type、status 结尾的字段,返回 tinyint 范围
if (StrUtil.endWithAnyIgnoreCase(attributeMetadata.getAttributeName(),
if (CharSequenceUtil.endWithAnyIgnoreCase(attributeMetadata.getAttributeName(),
"type", "status", "category", "scope", "result")) {
return RandomUtil.randomInt(0, TINYINT_MAX + 1);
}
@@ -55,7 +55,9 @@ public class CacheRequestBodyWrapper extends HttpServletRequestWrapper {
}
@Override
public void setReadListener(ReadListener readListener) {}
public void setReadListener(ReadListener readListener) {
// setReadListener
}
@Override
public int available() {
@@ -2,7 +2,7 @@ package com.cf.imes.framework.web.core.handler;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.cf.imes.framework.apilog.core.service.ApiErrorLog;
import com.cf.imes.framework.apilog.core.service.ApiErrorLogFrameworkService;
@@ -330,7 +330,7 @@ public class GlobalExceptionHandler {
"[微信公众号 cf-module-mp - 表结构未导入][参考 https://doc.iocoder.cn/mp/build/ 开启]");
}
// 4. 商城系统
if (StrUtil.containsAny(message, "product_", "promotion_", "trade_")) {
if (CharSequenceUtil.containsAny(message, "product_", "promotion_", "trade_")) {
log.error("[商城系统 cf-module-mall - 已禁用][参考 https://doc.iocoder.cn/mall/build/ 开启]");
return CommonResult.error(NOT_IMPLEMENTED.getCode(),
"[商城系统 cf-module-mall - 已禁用][参考 https://doc.iocoder.cn/mall/build/ 开启]");
@@ -1,7 +1,7 @@
package com.cf.imes.gateway.filter.grey;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.cf.imes.framework.common.util.collection.CollectionUtils;
import com.cf.imes.gateway.util.EnvUtils;
import com.alibaba.cloud.nacos.balancer.NacosBalancer;
@@ -66,10 +66,10 @@ public class GrayLoadBalancer implements ReactorServiceInstanceLoadBalancer {
// 筛选满足 version 条件的实例列表
String version = headers.getFirst(VERSION);
List<ServiceInstance> chooseInstances;
if (StrUtil.isEmpty(version)) {
if (CharSequenceUtil.isEmpty(version)) {
chooseInstances = instances;
} else {
chooseInstances = CollectionUtils.filterList(instances, instance -> version.equals(instance.getMetadata().get("version")));
chooseInstances = CollectionUtils.filterList(instances, instance -> version.equals(instance.getMetadata().get(VERSION)));
if (CollUtil.isEmpty(chooseInstances)) {
log.warn("[getInstanceResponse][serviceId({}) 没有满足版本({})的服务实例列表,直接使用所有服务实例列表]", serviceId, version);
chooseInstances = instances;
@@ -95,7 +95,7 @@ public class GrayLoadBalancer implements ReactorServiceInstanceLoadBalancer {
private List<ServiceInstance> filterTagServiceInstances(List<ServiceInstance> instances, HttpHeaders headers) {
// 情况一,没有 tag 时,直接返回
String tag = EnvUtils.getTag(headers);
if (StrUtil.isEmpty(tag)) {
if (CharSequenceUtil.isEmpty(tag)) {
return instances;
}
@@ -1,8 +1,8 @@
package com.cf.imes.gateway.util;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.http.HttpHeaders;
@@ -33,7 +33,7 @@ public class EnvUtils {
}
public static String getHostName() {
return StrUtil.blankToDefault(NetUtil.getLocalHostName(), IdUtil.fastSimpleUUID());
return CharSequenceUtil.blankToDefault(NetUtil.getLocalHostName(), IdUtil.fastSimpleUUID());
}
}
@@ -5,16 +5,10 @@ package com.cf.imes.module.infra.enums;
*
* @author 晨丰科技
*/
public interface DictTypeConstants {
public class DictTypeConstants {
public static final String API_ERROR_LOG_PROCESS_STATUS = "infra_api_error_log_process_status"; // API 错误日志的处理状态的枚举
String REDIS_TIMEOUT_TYPE = "infra_redis_timeout_type"; // Redis 超时类型
String JOB_STATUS = "infra_job_status"; // 定时任务状态的枚举
String JOB_LOG_STATUS = "infra_job_log_status"; // 定时任务日志状态的枚举
String API_ERROR_LOG_PROCESS_STATUS = "infra_api_error_log_process_status"; // API 错误日志的处理状态的枚举
String CONFIG_TYPE = "infra_config_type"; // 参数配置类型
String BOOLEAN_STRING = "infra_boolean_string"; // Boolean 是否类型
public static final String CONFIG_TYPE = "infra_config_type"; // 参数配置类型
public static final String BOOLEAN_STRING = "infra_boolean_string"; // Boolean 是否类型
}
@@ -7,68 +7,42 @@ import com.cf.imes.framework.common.exception.ErrorCode;
*
* infra 系统,使用 1-001-000-000 段
*/
public interface ErrorCodeConstants {
public class ErrorCodeConstants {
// ========== 参数配置 1-001-000-000 ==========
ErrorCode CONFIG_NOT_EXISTS = new ErrorCode(1_001_000_001, "参数配置不存在");
ErrorCode CONFIG_KEY_DUPLICATE = new ErrorCode(1_001_000_002, "参数配置 key 重复");
ErrorCode CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE = new ErrorCode(1_001_000_003, "不能删除类型为系统内置的参数配置");
ErrorCode CONFIG_GET_VALUE_ERROR_IF_VISIBLE = new ErrorCode(1_001_000_004, "获取参数配置失败,原因:不允许获取不可见配置");
// ========== 定时任务 1-001-001-000 ==========
ErrorCode JOB_NOT_EXISTS = new ErrorCode(1_001_001_000, "定时任务不存在");
ErrorCode JOB_HANDLER_EXISTS = new ErrorCode(1_001_001_001, "定时任务的处理器已经存在");
ErrorCode JOB_CHANGE_STATUS_INVALID = new ErrorCode(1_001_001_002, "只允许修改为开启或者关闭状态");
ErrorCode JOB_CHANGE_STATUS_EQUALS = new ErrorCode(1_001_001_003, "定时任务已经处于该状态,无需修改");
ErrorCode JOB_UPDATE_ONLY_NORMAL_STATUS = new ErrorCode(1_001_001_004, "只有开启状态的任务,才可以修改");
ErrorCode JOB_CRON_EXPRESSION_VALID = new ErrorCode(1_001_001_005, "CRON 表达式不正确");
public static final ErrorCode CONFIG_NOT_EXISTS = new ErrorCode(1_001_000_001, "参数配置不存在");
public static final ErrorCode CONFIG_KEY_DUPLICATE = new ErrorCode(1_001_000_002, "参数配置 key 重复");
public static final ErrorCode CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE = new ErrorCode(1_001_000_003, "不能删除类型为系统内置的参数配置");
public static final ErrorCode CONFIG_GET_VALUE_ERROR_IF_VISIBLE = new ErrorCode(1_001_000_004, "获取参数配置失败,原因:不允许获取不可见配置");
// ========== API 错误日志 1-001-002-000 ==========
ErrorCode API_ERROR_LOG_NOT_FOUND = new ErrorCode(1_001_002_000, "API 错误日志不存在");
ErrorCode API_ERROR_LOG_PROCESSED = new ErrorCode(1_001_002_001, "API 错误日志已处理");
public static final ErrorCode API_ERROR_LOG_NOT_FOUND = new ErrorCode(1_001_002_000, "API 错误日志不存在");
public static final ErrorCode API_ERROR_LOG_PROCESSED = new ErrorCode(1_001_002_001, "API 错误日志已处理");
// ========= 文件相关 1-001-003-000 =================
ErrorCode FILE_PATH_EXISTS = new ErrorCode(1_001_003_000, "文件路径已存在");
ErrorCode FILE_NOT_EXISTS = new ErrorCode(1_001_003_001, "文件不存在");
ErrorCode FILE_IS_EMPTY = new ErrorCode(1_001_003_002, "文件为空");
ErrorCode FILE_REMOVE_FAIL = new ErrorCode(1_001_003_003, "文件删除失败");
public static final ErrorCode FILE_NOT_EXISTS = new ErrorCode(1_001_003_001, "文件存在");
public static final ErrorCode FILE_IS_EMPTY = new ErrorCode(1_001_003_002, "文件为空");
public static final ErrorCode FILE_REMOVE_FAIL = new ErrorCode(1_001_003_003, "文件删除失败");
// ========== 代码生成器 1-001-004-000 ==========
ErrorCode CODEGEN_TABLE_EXISTS = new ErrorCode(1_003_001_000, "表定义已经存在");
ErrorCode CODEGEN_IMPORT_TABLE_NULL = new ErrorCode(1_003_001_001, "导入的表不存在");
ErrorCode CODEGEN_IMPORT_COLUMNS_NULL = new ErrorCode(1_003_001_002, "导入的字段不存在");
ErrorCode CODEGEN_TABLE_NOT_EXISTS = new ErrorCode(1_003_001_004, "表定义不存在");
ErrorCode CODEGEN_COLUMN_NOT_EXISTS = new ErrorCode(1_003_001_005, "字段义不存在");
ErrorCode CODEGEN_SYNC_COLUMNS_NULL = new ErrorCode(1_003_001_006, "同步的字段不存在");
ErrorCode CODEGEN_SYNC_NONE_CHANGE = new ErrorCode(1_003_001_007, "同步失败,不存在改变");
ErrorCode CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL = new ErrorCode(1_003_001_008, "数据库的表注释未填写");
ErrorCode CODEGEN_TABLE_INFO_COLUMN_COMMENT_IS_NULL = new ErrorCode(1_003_001_009, "数据库的表字段({})注释未填写");
ErrorCode CODEGEN_MASTER_TABLE_NOT_EXISTS = new ErrorCode(1_003_001_010, "主表(id={})定义不存在,请检查");
ErrorCode CODEGEN_SUB_COLUMN_NOT_EXISTS = new ErrorCode(1_003_001_011, "子表的字段(id={})不存在,请检查");
ErrorCode CODEGEN_MASTER_GENERATION_FAIL_NO_SUB_TABLE = new ErrorCode(1_003_001_012, "主表生成代码失败,原因:它没有子表");
ErrorCode CODEGEN_MASTER_GENERATION_FAIL_NO_SUB_COLUMN = new ErrorCode(1_003_001_013, "主表生成代码失败,原因:它的子表({})没有字段");
public static final ErrorCode CODEGEN_TABLE_EXISTS = new ErrorCode(1_003_001_000, "表定义已经存在");
public static final ErrorCode CODEGEN_IMPORT_TABLE_NULL = new ErrorCode(1_003_001_001, "导入的表不存在");
public static final ErrorCode CODEGEN_IMPORT_COLUMNS_NULL = new ErrorCode(1_003_001_002, "导入的字段不存在");
public static final ErrorCode CODEGEN_TABLE_NOT_EXISTS = new ErrorCode(1_003_001_004, "表定义不存在");
public static final ErrorCode CODEGEN_COLUMN_NOT_EXISTS = new ErrorCode(1_003_001_005, "字段义不存在");
public static final ErrorCode CODEGEN_SYNC_NONE_CHANGE = new ErrorCode(1_003_001_007, "同步失败,不存在改变");
public static final ErrorCode CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL = new ErrorCode(1_003_001_008, "数据库的表注释未填写");
public static final ErrorCode CODEGEN_TABLE_INFO_COLUMN_COMMENT_IS_NULL = new ErrorCode(1_003_001_009, "数据库的表字段({})注释未填写");
public static final ErrorCode CODEGEN_MASTER_TABLE_NOT_EXISTS = new ErrorCode(1_003_001_010, "主表(id={})定义不存在,请检查");
public static final ErrorCode CODEGEN_SUB_COLUMN_NOT_EXISTS = new ErrorCode(1_003_001_011, "子表的字段(id={})不存在,请检查");
public static final ErrorCode CODEGEN_MASTER_GENERATION_FAIL_NO_SUB_TABLE = new ErrorCode(1_003_001_012, "主表生成代码失败,原因:它没有子表");
// ========== 文件配置 1-001-006-000 ==========
ErrorCode FILE_CONFIG_NOT_EXISTS = new ErrorCode(1_001_006_000, "文件配置不存在");
ErrorCode FILE_CONFIG_DELETE_FAIL_MASTER = new ErrorCode(1_001_006_001, "该文件配置不允许删除,原因:它是主配置,删除会导致无法上传文件");
public static final ErrorCode FILE_CONFIG_NOT_EXISTS = new ErrorCode(1_001_006_000, "文件配置不存在");
public static final ErrorCode FILE_CONFIG_DELETE_FAIL_MASTER = new ErrorCode(1_001_006_001, "该文件配置不允许删除,原因:它是主配置,删除会导致无法上传文件");
// ========== 数据源配置 1-001-007-000 ==========
ErrorCode DATA_SOURCE_CONFIG_NOT_EXISTS = new ErrorCode(1_001_007_000, "数据源配置不存在");
ErrorCode DATA_SOURCE_CONFIG_NOT_OK = new ErrorCode(1_001_007_001, "数据源配置不正确,无法进行连接");
// ========== 数据源配置 1-001-107-000 ==========
ErrorCode DEMO_STUDENT_NOT_EXISTS = new ErrorCode(1_001_107_000, "学生不存在");
// ========== 学生 1-001-201-000 ==========
ErrorCode DEMO01_CONTACT_NOT_EXISTS = new ErrorCode(1_001_201_000, "示例联系人不存在");
ErrorCode DEMO02_CATEGORY_NOT_EXISTS = new ErrorCode(1_001_201_001, "示例分类不存在");
ErrorCode DEMO02_CATEGORY_EXITS_CHILDREN = new ErrorCode(1_001_201_002, "存在存在子示例分类,无法删除");
ErrorCode DEMO02_CATEGORY_PARENT_NOT_EXITS = new ErrorCode(1_001_201_003,"父级示例分类不存在");
ErrorCode DEMO02_CATEGORY_PARENT_ERROR = new ErrorCode(1_001_201_004, "不能设置自己为父示例分类");
ErrorCode DEMO02_CATEGORY_NAME_DUPLICATE = new ErrorCode(1_001_201_005, "已经存在该名字的示例分类");
ErrorCode DEMO02_CATEGORY_PARENT_IS_CHILD = new ErrorCode(1_001_201_006, "不能设置自己的子示例分类为父示例分类");
ErrorCode DEMO03_STUDENT_NOT_EXISTS = new ErrorCode(1_001_201_007, "学生不存在");
ErrorCode DEMO03_GRADE_NOT_EXISTS = new ErrorCode(1_001_201_008, "学生班级不存在");
ErrorCode DEMO03_GRADE_EXISTS = new ErrorCode(1_001_201_009, "学生班级已存在");
public static final ErrorCode DATA_SOURCE_CONFIG_NOT_EXISTS = new ErrorCode(1_001_007_000, "数据源配置不存在");
public static final ErrorCode DATA_SOURCE_CONFIG_NOT_OK = new ErrorCode(1_001_007_001, "数据源配置不正确,无法进行连接");
}
@@ -1,6 +1,6 @@
package com.cf.imes.module.infra.api.websocket;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.websocket.core.sender.WebSocketMessageSender;
import com.cf.imes.module.infra.api.websocket.dto.WebSocketSendReqDTO;
@@ -20,7 +20,7 @@ public class WebSocketSenderApiImpl implements WebSocketSenderApi {
@Override
public CommonResult<Boolean> send(WebSocketSendReqDTO message) {
if (StrUtil.isNotEmpty(message.getSessionId())) {
if (CharSequenceUtil.isNotEmpty(message.getSessionId())) {
webSocketMessageSender.send(message.getSessionId(),
message.getMessageType(), message.getMessageContent());
} else if (message.getUserType() != null && message.getUserId() != null) {
@@ -1,7 +1,7 @@
package com.cf.imes.module.infra.controller.admin.file;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.URLUtil;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.pojo.PageResult;
@@ -68,8 +68,8 @@ public class FileController {
HttpServletResponse response,
@PathVariable("configId") Long configId) throws Exception {
// 获取请求的路径
String path = StrUtil.subAfter(request.getRequestURI(), "/get/", false);
if (StrUtil.isEmpty(path)) {
String path = CharSequenceUtil.subAfter(request.getRequestURI(), "/get/", false);
if (CharSequenceUtil.isEmpty(path)) {
throw new IllegalArgumentException("结尾的 path 路径必须传递");
}
// 解码,解决中文路径的问题 https://gitee.com/zhijiantianya/ruoyi-vue-pro/pulls/807/
@@ -1,6 +1,6 @@
package com.cf.imes.module.infra.convert.redis;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.cf.imes.module.infra.controller.admin.redis.vo.RedisMonitorRespVO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@@ -18,9 +18,9 @@ public interface RedisConvert {
.commandStats(new ArrayList<>(commandStats.size())).build();
commandStats.forEach((key, value) -> {
respVO.getCommandStats().add(RedisMonitorRespVO.CommandStat.builder()
.command(StrUtil.subAfter((String) key, "cmdstat_", false))
.calls(Long.valueOf(StrUtil.subBetween((String) value, "calls=", ",")))
.usec(Long.valueOf(StrUtil.subBetween((String) value, "usec=", ",")))
.command(CharSequenceUtil.subAfter((String) key, "cmdstat_", false))
.calls(Long.valueOf(CharSequenceUtil.subBetween((String) value, "calls=", ",")))
.usec(Long.valueOf(CharSequenceUtil.subBetween((String) value, "usec=", ",")))
.build());
});
return respVO;
@@ -1,7 +1,7 @@
package com.cf.imes.module.infra.service.codegen;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.module.infra.controller.admin.codegen.vo.CodegenCreateListReqVO;
@@ -110,14 +110,14 @@ public class CodegenServiceImpl implements CodegenService {
if (tableInfo == null) {
throw exception(CODEGEN_IMPORT_TABLE_NULL);
}
if (StrUtil.isEmpty(tableInfo.getComment())) {
if (CharSequenceUtil.isEmpty(tableInfo.getComment())) {
throw exception(CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL);
}
if (CollUtil.isEmpty(tableInfo.getFields())) {
throw exception(CODEGEN_IMPORT_COLUMNS_NULL);
}
tableInfo.getFields().forEach(field -> {
if (StrUtil.isEmpty(field.getComment())) {
if (CharSequenceUtil.isEmpty(field.getComment())) {
throw exception(CODEGEN_TABLE_INFO_COLUMN_COMMENT_IS_NULL, field.getName());
}
});
@@ -1,8 +1,8 @@
package com.cf.imes.module.infra.service.codegen.inner;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.cf.imes.framework.mybatis.core.dataobject.BaseDO;
import com.cf.imes.module.infra.convert.codegen.CodegenConvert;
import com.cf.imes.module.infra.dal.dataobject.codegen.CodegenColumnDO;
@@ -118,7 +118,7 @@ public class CodegenBuilder {
// 驼峰 + 首字母大写;第一步,第一个 _ 前缀的后面,作为 class 名字;第二步,驼峰命名
table.setClassName(upperFirst(toCamelCase(subAfter(tableName, '_', false))));
// 去除结尾的表,作为类描述
table.setClassComment(StrUtil.removeSuffixIgnoreCase(table.getTableComment(), ""));
table.setClassComment(CharSequenceUtil.removeSuffixIgnoreCase(table.getTableComment(), ""));
table.setTemplateType(CodegenTemplateTypeEnum.ONE.getType());
}
@@ -152,7 +152,7 @@ public class CodegenBuilder {
&& !column.getPrimaryKey()); // 对于主键,列表过滤不需要传递
// 处理 listOperationCondition 字段
COLUMN_LIST_OPERATION_CONDITION_MAPPINGS.entrySet().stream()
.filter(entry -> StrUtil.endWithIgnoreCase(column.getJavaField(), entry.getKey()))
.filter(entry -> CharSequenceUtil.endWithIgnoreCase(column.getJavaField(), entry.getKey()))
.findFirst().ifPresent(entry -> column.setListOperationCondition(entry.getValue().getCondition()));
if (column.getListOperationCondition() == null) {
column.setListOperationCondition(CodegenColumnListConditionEnum.EQ.getCondition());
@@ -164,7 +164,7 @@ public class CodegenBuilder {
private void processColumnUI(CodegenColumnDO column) {
// 基于后缀进行匹配
COLUMN_HTML_TYPE_MAPPINGS.entrySet().stream()
.filter(entry -> StrUtil.endWithIgnoreCase(column.getJavaField(), entry.getKey()))
.filter(entry -> CharSequenceUtil.endWithIgnoreCase(column.getJavaField(), entry.getKey()))
.findFirst().ifPresent(entry -> column.setHtmlType(entry.getValue().getType()));
// 如果是 Boolean 类型时,设置为 radio 类型.
if (Boolean.class.getSimpleName().equals(column.getJavaType())) {
@@ -187,32 +187,32 @@ public class CodegenBuilder {
*/
private void processColumnExample(CodegenColumnDO column) {
// id、price、count 等可能是整数的后缀
if (StrUtil.endWithAnyIgnoreCase(column.getJavaField(), "id", "price", "count")) {
if (CharSequenceUtil.endWithAnyIgnoreCase(column.getJavaField(), "id", "price", "count")) {
column.setExample(String.valueOf(randomInt(1, Short.MAX_VALUE)));
return;
}
// name
if (StrUtil.endWithIgnoreCase(column.getJavaField(), "name")) {
if (CharSequenceUtil.endWithIgnoreCase(column.getJavaField(), "name")) {
column.setExample(randomEle(new String[]{"张三", "李四", "王五", "赵六", "晨丰"}));
return;
}
// status
if (StrUtil.endWithAnyIgnoreCase(column.getJavaField(), "status", "type")) {
if (CharSequenceUtil.endWithAnyIgnoreCase(column.getJavaField(), "status", "type")) {
column.setExample(randomEle(new String[]{"1", "2"}));
return;
}
// url
if (StrUtil.endWithIgnoreCase(column.getColumnName(), "url")) {
if (CharSequenceUtil.endWithIgnoreCase(column.getColumnName(), "url")) {
column.setExample("https://www.cf.com");
return;
}
// reason
if (StrUtil.endWithIgnoreCase(column.getColumnName(), "reason")) {
if (CharSequenceUtil.endWithIgnoreCase(column.getColumnName(), "reason")) {
column.setExample(randomEle(new String[]{"不喜欢", "不对", "不好", "不香"}));
return;
}
// description、memo、remark
if (StrUtil.endWithAnyIgnoreCase(column.getColumnName(), "description", "memo", "remark")) {
if (CharSequenceUtil.endWithAnyIgnoreCase(column.getColumnName(), "description", "memo", "remark")) {
column.setExample(randomEle(new String[]{"你猜", "随便", "你说的对"}));
return;
}
@@ -2,12 +2,11 @@ package com.cf.imes.module.infra.service.codegen.inner;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.engine.velocity.VelocityEngine;
import cn.hutool.system.SystemUtil;
import com.cf.imes.framework.common.exception.util.ServiceExceptionUtil;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.pojo.PageParam;
@@ -57,6 +56,16 @@ import static cn.hutool.core.text.CharSequenceUtil.*;
@Component
public class CodegenEngine {
private static final String INDEX_VUE = "views/index.vue";
private static final String MODULE_INDEX_VUE = "views/${table.moduleName}/${table.businessName}/index.vue";
private static final String FORM_VUE = "views/form.vue";
private static final String MODULE_FORM_VUE = "views/${table.moduleName}/${table.businessName}/${simpleClassName}Form.vue";
private static final String MODULE_COMPONENTS_FORM_VUE = "views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}Form.vue";
private static final String MODULE_COMPONENTS_LIST_VUE = "views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}List.vue";
private static final String API_TS = "api/api.ts";
private static final String API_INDEX_TS = "api/${table.moduleName}/${table.businessName}/index.ts";
private static final String SUB_INDEX = "subIndex";
/**
* 后端的模板配置
*
@@ -102,57 +111,57 @@ public class CodegenEngine {
*/
private static final Table<Integer, String, String> FRONT_TEMPLATES = ImmutableTable.<Integer, String, String>builder()
// Vue2 标准模版
.put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/index.vue"),
vueFilePath("views/${table.moduleName}/${table.businessName}/index.vue"))
.put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath(INDEX_VUE),
vueFilePath(MODULE_INDEX_VUE))
.put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("api/api.js"),
vueFilePath("api/${table.moduleName}/${table.businessName}/index.js"))
.put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/form.vue"),
vueFilePath("views/${table.moduleName}/${table.businessName}/${simpleClassName}Form.vue"))
.put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath(FORM_VUE),
vueFilePath(MODULE_FORM_VUE))
.put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/components/form_sub_normal.vue"), // 特殊:主子表专属逻辑
vueFilePath("views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}Form.vue"))
vueFilePath(MODULE_COMPONENTS_FORM_VUE))
.put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/components/form_sub_inner.vue"), // 特殊:主子表专属逻辑
vueFilePath("views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}Form.vue"))
vueFilePath(MODULE_COMPONENTS_FORM_VUE))
.put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/components/form_sub_erp.vue"), // 特殊:主子表专属逻辑
vueFilePath("views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}Form.vue"))
vueFilePath(MODULE_COMPONENTS_FORM_VUE))
.put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/components/list_sub_inner.vue"), // 特殊:主子表专属逻辑
vueFilePath("views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}List.vue"))
vueFilePath(MODULE_COMPONENTS_LIST_VUE))
.put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/components/list_sub_erp.vue"), // 特殊:主子表专属逻辑
vueFilePath("views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}List.vue"))
vueFilePath(MODULE_COMPONENTS_LIST_VUE))
// Vue3 标准模版
.put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/index.vue"),
vue3FilePath("views/${table.moduleName}/${table.businessName}/index.vue"))
.put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/form.vue"),
vue3FilePath("views/${table.moduleName}/${table.businessName}/${simpleClassName}Form.vue"))
.put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath(INDEX_VUE),
vue3FilePath(MODULE_INDEX_VUE))
.put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath(FORM_VUE),
vue3FilePath(MODULE_FORM_VUE))
.put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/components/form_sub_normal.vue"), // 特殊:主子表专属逻辑
vue3FilePath("views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}Form.vue"))
vue3FilePath(MODULE_COMPONENTS_FORM_VUE))
.put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/components/form_sub_inner.vue"), // 特殊:主子表专属逻辑
vue3FilePath("views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}Form.vue"))
vue3FilePath(MODULE_COMPONENTS_FORM_VUE))
.put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/components/form_sub_erp.vue"), // 特殊:主子表专属逻辑
vue3FilePath("views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}Form.vue"))
vue3FilePath(MODULE_COMPONENTS_FORM_VUE))
.put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/components/list_sub_inner.vue"), // 特殊:主子表专属逻辑
vue3FilePath("views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}List.vue"))
vue3FilePath(MODULE_COMPONENTS_LIST_VUE))
.put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/components/list_sub_erp.vue"), // 特殊:主子表专属逻辑
vue3FilePath("views/${table.moduleName}/${table.businessName}/components/${subSimpleClassName}List.vue"))
.put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("api/api.ts"),
vue3FilePath("api/${table.moduleName}/${table.businessName}/index.ts"))
vue3FilePath(MODULE_COMPONENTS_LIST_VUE))
.put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath(API_TS),
vue3FilePath(API_INDEX_TS))
// Vue3 Schema 模版
.put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/data.ts"),
vue3FilePath("views/${table.moduleName}/${table.businessName}/${classNameVar}.data.ts"))
.put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/index.vue"),
vue3FilePath("views/${table.moduleName}/${table.businessName}/index.vue"))
.put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/form.vue"),
vue3FilePath("views/${table.moduleName}/${table.businessName}/${simpleClassName}Form.vue"))
.put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("api/api.ts"),
vue3FilePath("api/${table.moduleName}/${table.businessName}/index.ts"))
.put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath(INDEX_VUE),
vue3FilePath(MODULE_INDEX_VUE))
.put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath(FORM_VUE),
vue3FilePath(MODULE_FORM_VUE))
.put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath(API_TS),
vue3FilePath(API_INDEX_TS))
// Vue3 vben 模版
.put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/data.ts"),
vue3FilePath("views/${table.moduleName}/${table.businessName}/${classNameVar}.data.ts"))
.put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/index.vue"),
vue3FilePath("views/${table.moduleName}/${table.businessName}/index.vue"))
.put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/form.vue"),
.put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath(INDEX_VUE),
vue3FilePath(MODULE_INDEX_VUE))
.put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath(FORM_VUE),
vue3FilePath("views/${table.moduleName}/${table.businessName}/${simpleClassName}Modal.vue"))
.put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("api/api.ts"),
vue3FilePath("api/${table.moduleName}/${table.businessName}/index.ts"))
.put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath(API_TS),
vue3FilePath(API_INDEX_TS))
.build();
@Resource
@@ -290,10 +299,10 @@ public class CodegenEngine {
// 逐个生成
for (int i = 0; i < subTables.size(); i++) {
bindingMap.put("subIndex", i);
bindingMap.put(SUB_INDEX, i);
generateCode(result, vmPath, filePath, bindingMap);
}
bindingMap.remove("subIndex");
bindingMap.remove(SUB_INDEX);
}
/**
@@ -307,26 +316,26 @@ public class CodegenEngine {
*/
private String prettyCode(String content) {
// Vue 界面:去除字段后面多余的 , 逗号,解决前端的 Pretty 代码格式检查的报错
content = content.replaceAll(",\n}", "\n}").replaceAll(",\n }", "\n }");
content = content.replace(",\n}", "\n}").replace(",\n }", "\n }");
// Vue 界面:去除多的 dateFormatter,只有一个的情况下,说明没使用到
if (StrUtil.count(content, "dateFormatter") == 1) {
if (CharSequenceUtil.count(content, "dateFormatter") == 1) {
content = StrUtils.removeLineContains(content, "dateFormatter");
}
// Vue2 界面:修正 $refs
if (StrUtil.count(content, "this.refs") >= 1) {
if (CharSequenceUtil.count(content, "this.refs") >= 1) {
content = content.replace("this.refs", "this.$refs");
}
// Vue 界面:去除多的 dict 相关,只有一个的情况下,说明没使用到
if (StrUtil.count(content, "getIntDictOptions") == 1) {
if (CharSequenceUtil.count(content, "getIntDictOptions") == 1) {
content = content.replace("getIntDictOptions, ", "");
}
if (StrUtil.count(content, "getStrDictOptions") == 1) {
if (CharSequenceUtil.count(content, "getStrDictOptions") == 1) {
content = content.replace("getStrDictOptions, ", "");
}
if (StrUtil.count(content, "getBoolDictOptions") == 1) {
if (CharSequenceUtil.count(content, "getBoolDictOptions") == 1) {
content = content.replace("getBoolDictOptions, ", "");
}
if (StrUtil.count(content, "DICT_TYPE.") == 0) {
if (CharSequenceUtil.count(content, "DICT_TYPE.") == 0) {
content = StrUtils.removeLineContains(content, "DICT_TYPE");
}
return content;
@@ -412,29 +421,29 @@ public class CodegenEngine {
@SuppressWarnings("unchecked")
private String formatFilePath(String filePath, Map<String, Object> bindingMap) {
filePath = StrUtil.replace(filePath, "${basePackage}",
getStr(bindingMap, "basePackage").replaceAll("\\.", "/"));
filePath = StrUtil.replace(filePath, "${classNameVar}",
filePath = CharSequenceUtil.replace(filePath, "${basePackage}",
getStr(bindingMap, "basePackage").replace("\\.", "/"));
filePath = CharSequenceUtil.replace(filePath, "${classNameVar}",
getStr(bindingMap, "classNameVar"));
filePath = StrUtil.replace(filePath, "${simpleClassName}",
filePath = CharSequenceUtil.replace(filePath, "${simpleClassName}",
getStr(bindingMap, "simpleClassName"));
// sceneEnum 包含的字段
CodegenSceneEnum sceneEnum = (CodegenSceneEnum) bindingMap.get("sceneEnum");
filePath = StrUtil.replace(filePath, "${sceneEnum.prefixClass}", sceneEnum.getPrefixClass());
filePath = StrUtil.replace(filePath, "${sceneEnum.basePackage}", sceneEnum.getBasePackage());
filePath = CharSequenceUtil.replace(filePath, "${sceneEnum.prefixClass}", sceneEnum.getPrefixClass());
filePath = CharSequenceUtil.replace(filePath, "${sceneEnum.basePackage}", sceneEnum.getBasePackage());
// table 包含的字段
CodegenTableDO table = (CodegenTableDO) bindingMap.get("table");
filePath = StrUtil.replace(filePath, "${table.moduleName}", table.getModuleName());
filePath = StrUtil.replace(filePath, "${table.businessName}", table.getBusinessName());
filePath = StrUtil.replace(filePath, "${table.className}", table.getClassName());
filePath = CharSequenceUtil.replace(filePath, "${table.moduleName}", table.getModuleName());
filePath = CharSequenceUtil.replace(filePath, "${table.businessName}", table.getBusinessName());
filePath = CharSequenceUtil.replace(filePath, "${table.className}", table.getClassName());
// 特殊:主子表专属逻辑
Integer subIndex = (Integer) bindingMap.get("subIndex");
Integer subIndex = (Integer) bindingMap.get(SUB_INDEX);
if (subIndex != null) {
CodegenTableDO subTable = ((List<CodegenTableDO>) bindingMap.get("subTables")).get(subIndex);
filePath = StrUtil.replace(filePath, "${subTable.moduleName}", subTable.getModuleName());
filePath = StrUtil.replace(filePath, "${subTable.businessName}", subTable.getBusinessName());
filePath = StrUtil.replace(filePath, "${subTable.className}", subTable.getClassName());
filePath = StrUtil.replace(filePath, "${subSimpleClassName}",
filePath = CharSequenceUtil.replace(filePath, "${subTable.moduleName}", subTable.getModuleName());
filePath = CharSequenceUtil.replace(filePath, "${subTable.businessName}", subTable.getBusinessName());
filePath = CharSequenceUtil.replace(filePath, "${subTable.className}", subTable.getClassName());
filePath = CharSequenceUtil.replace(filePath, "${subSimpleClassName}",
((List<String>) bindingMap.get("subSimpleClassNames")).get(subIndex));
}
return filePath;
@@ -1,41 +0,0 @@
package com.cf.imes.module.infra.service;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.generator.query.DefaultQuery;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class DefaultDatabaseQueryTest {
public static void main(String[] args) {
// DataSourceConfig dataSourceConfig = new DataSourceConfig.Builder("jdbc:oracle:thin:@127.0.0.1:1521:xe",
// "root", "123456").build();
DataSourceConfig dataSourceConfig = new DataSourceConfig.Builder("jdbc:postgresql://127.0.0.1:5432/ruoyi-vue-pro",
"root", "123456").build();
// StrategyConfig strategyConfig = new StrategyConfig.Builder().build();
ConfigBuilder builder = new ConfigBuilder(null, dataSourceConfig, null, null, null, null);
DefaultQuery query = new DefaultQuery(builder);
long time = System.currentTimeMillis();
List<TableInfo> tableInfos = query.queryTables();
assertNotEquals(0, tableInfos.size());
for (TableInfo tableInfo : tableInfos) {
if (StrUtil.startWithAny(tableInfo.getName().toLowerCase(), "act_", "flw_", "qrtz_")) {
continue;
}
System.out.println(String.format("CREATE SEQUENCE %s_seq MINVALUE 1;", tableInfo.getName()));
// System.out.println(String.format("DELETE FROM %s WHERE deleted = '1';", tableInfo.getName()));
}
System.out.println(tableInfos.size());
System.out.println(System.currentTimeMillis() - time);
}
}
@@ -1,47 +1,45 @@
package com.cf.imes.module.executor.util;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.cf.imes.module.executor.dal.dataobject.order.OrderDO;
import com.cf.imes.module.executor.util.fileConversion.admin.files.excel.OrderPlateImportExcelVO;
import org.apache.poi.ss.usermodel.Workbook;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.util.ResourceUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* excel 文件写入
*/
@Slf4j
public class ExcelWriterUtil {
// 写excel
public static void write(HttpServletResponse response,
Map<String, Object> orderMap,
List<OrderPlateImportExcelVO> list,
String filePathErr) throws IOException {
String filePathErr) {
ServletOutputStream outputStream = null;
ExcelWriter excelWriter = null;
//输入流
InputStream inputStream = ResourceUtils.getURL(filePathErr).openStream();
ServletOutputStream outputStream = response.getOutputStream();
try (InputStream inputStream = ResourceUtils.getURL(filePathErr).openStream()){
outputStream = response.getOutputStream();
//设置输出流和模板信息
ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
excelWriter = EasyExcelFactory.write(outputStream).withTemplate(inputStream).build();
WriteSheet writeSheet = EasyExcelFactory.writerSheet().build();
//开启自动换行,自动换行表示每次写入一条list数据是都会重新生成一行空行,此选项默认是关闭的,需要提前设置为true
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
@@ -65,112 +63,14 @@ public class ExcelWriterUtil {
excelWriter.fill(list, fillConfig, writeSheet);
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//关流
excelWriter.finish();
inputStream.close();
outputStream.close();
}
// 写excel
public static void writeErr(HttpServletResponse response,
String err,
String filePathErr) throws IOException {
//输入流
InputStream inputStream = ResourceUtils.getURL(filePathErr).openStream();
ServletOutputStream outputStream = response.getOutputStream();
//设置输出流和模板信息
ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
//准备单组和数据
Map<String, String> map = new HashMap<>();
map.put("err", err);
excelWriter.fill(map, writeSheet);
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//关流
excelWriter.finish();
inputStream.close();
outputStream.close();
}
public static void exportExcelZip(HttpServletResponse response, Map<OrderDO, Object> map, String filePathErr, String type) throws IOException {
ServletOutputStream outputStream = response.getOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
try {
for (Map.Entry<OrderDO, Object> entry : map.entrySet()) {
OrderDO k = entry.getKey();
Object value = entry.getValue();
// 创建ExcelWriter并填充数据
InputStream inputStream = ResourceUtils.getURL(filePathErr).openStream();
ExcelWriter excelWriter = EasyExcel.write(outputStream)
.withTemplate(inputStream)
.excelType(ExcelTypeEnum.XLS)
.build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
// 填充订单数据
excelWriter.fill(fillOrderData(k), writeSheet);
// 填充列表数据
excelWriter.fill(value, fillConfig(), writeSheet);
// 写入ZipOutputStream
ZipEntry zipEntry = new ZipEntry(type + "_" + k.getId() + ".xls");
zipOutputStream.putNextEntry(zipEntry);
Workbook workbook = excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
workbook.write(zipOutputStream);
excelWriter.finish(); // 关闭ExcelWriter
// 关闭输入流
inputStream.close();
}
} catch (IOException e) {
log.error("文件【{}】写入异常", filePathErr, e);
} finally {
// 关闭流
zipOutputStream.close();
outputStream.close();
}
}
public static void exportExcel(HttpServletResponse response,
OrderDO orderDO,
List<OrderPlateImportExcelVO> list,
String filePathErr,
String type) throws IOException {
//输入流
InputStream inputStream = ResourceUtils.getURL(filePathErr+ File.separator + type).openStream();
ServletOutputStream outputStream = response.getOutputStream();
//设置输出流和模板信息
ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
//开启自动换行,自动换行表示每次写入一条list数据是都会重新生成一行空行,此选项默认是关闭的,需要提前设置为true
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
//准备单组和数据
Map<String, String> mapOrder = fillOrderData(orderDO);
excelWriter.fill(mapOrder, writeSheet);
//列表
excelWriter.fill(list, fillConfig, writeSheet);
//设置文件名的编码格式,防止文件名乱码
String fileName = URLEncoder.encode(type.replace("模板",String.valueOf(orderDO.getId())), "UTF-8");
//固定写法,设置响应头
response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//关流
excelWriter.finish();
inputStream.close();
outputStream.close();
IOUtils.closeQuietly(excelWriter);
IOUtils.closeQuietly(outputStream);
}
}
// 填充订单数据
@@ -166,12 +166,14 @@ public class VoiceServiceImpl implements VoiceService{
public void zipFiles(String fileNames, String zipOutName) throws IOException {
WritableByteChannel writableByteChannel = null;
ByteBuffer buffer = ByteBuffer.allocate(2048);
FileInputStream fileInputStream = null;
FileChannel fileChannel = null;
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipOutName))) {
writableByteChannel = Channels.newChannel(zipOutputStream);
File source = new File(fileNames);
zipOutputStream.putNextEntry(new ZipEntry(source.getName()));
fileChannel = new FileInputStream(fileNames).getChannel();
fileInputStream = new FileInputStream(fileNames);
fileChannel = fileInputStream.getChannel();
while (fileChannel.read(buffer) != -1) {
//更新缓存区位置
buffer.flip();
@@ -190,6 +192,7 @@ public class VoiceServiceImpl implements VoiceService{
} finally {
IOUtils.closeQuietly(writableByteChannel);
IOUtils.closeQuietly(fileChannel);
IOUtils.closeQuietly(fileInputStream);
buffer.clear();
}
}