From 11533092e96526e0a2ae74b690d61a5cb1261e98 Mon Sep 17 00:00:00 2001 From: Larry-bird Date: Tue, 31 Dec 2024 00:41:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E9=83=A8=E5=88=86=E4=B8=9A?= =?UTF-8?q?=E5=8A=A1=E4=BB=A3=E7=A0=81=E5=92=8C=E5=B7=A5=E5=85=B7=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/misc.xml | 10 +- .idea/modules.xml | 8 - .../com/ruoyi/system/Enum/VideoTagEnum.java | 39 ++ .../system/Interceptor/LoginInterceptor.java | 40 ++ .../Interceptor/RefreshTokenInterceptor.java | 32 ++ .../system/adapter/port/package-info.java | 4 + .../repository/ActivityRepository.java | 81 ++++ .../adapter/repository/package-info.java | 4 + .../system/dao/IGroupBuyActivityDao.java | 20 + .../system/dao/IGroupBuyDiscountDao.java | 20 + .../java/com/ruoyi/system/dao/ISkuDao.java | 16 + .../ruoyi/system/dao/po/GroupBuyActivity.java | 58 +++ .../ruoyi/system/dao/po/GroupBuyDiscount.java | 71 +++ .../java/com/ruoyi/system/dao/po/Sku.java | 39 ++ .../system/gateway/dto/package-info.java | 1 + .../ruoyi/system/gateway/package-info.java | 4 + .../handler/CommonGlobalExceptionHandler.java | 27 ++ .../com/ruoyi/system/redis/package-info.java | 4 + .../java/com/ruoyi/system/util/AESUtil.java | 57 +++ .../com/ruoyi/system/util/BaseContext.java | 19 + .../java/com/ruoyi/system/util/EsUtil.java | 75 ++++ .../com/ruoyi/system/util/FastDFSUtil.java | 221 ++++++++++ .../com/ruoyi/system/util/FileTestUtils.java | 38 ++ .../java/com/ruoyi/system/util/HttpUtil.java | 404 ++++++++++++++++++ .../java/com/ruoyi/system/util/ImageUtil.java | 163 +++++++ .../java/com/ruoyi/system/util/IpUtil.java | 61 +++ .../com/ruoyi/system/util/JsonResponse.java | 61 +++ .../java/com/ruoyi/system/util/MD5Util.java | 64 +++ .../java/com/ruoyi/system/util/RSAUtil.java | 127 ++++++ .../com/ruoyi/system/util/RocketMQUtil.java | 30 ++ .../java/com/ruoyi/system/util/TokenUtil.java | 61 +++ .../java/com/ruoyi/system/util/Utilfast.java | 115 +++++ 32 files changed, 1965 insertions(+), 9 deletions(-) delete mode 100644 .idea/modules.xml create mode 100644 src/main/java/com/ruoyi/system/Enum/VideoTagEnum.java create mode 100644 src/main/java/com/ruoyi/system/Interceptor/LoginInterceptor.java create mode 100644 src/main/java/com/ruoyi/system/Interceptor/RefreshTokenInterceptor.java create mode 100644 src/main/java/com/ruoyi/system/adapter/port/package-info.java create mode 100644 src/main/java/com/ruoyi/system/adapter/repository/ActivityRepository.java create mode 100644 src/main/java/com/ruoyi/system/adapter/repository/package-info.java create mode 100644 src/main/java/com/ruoyi/system/dao/IGroupBuyActivityDao.java create mode 100644 src/main/java/com/ruoyi/system/dao/IGroupBuyDiscountDao.java create mode 100644 src/main/java/com/ruoyi/system/dao/ISkuDao.java create mode 100644 src/main/java/com/ruoyi/system/dao/po/GroupBuyActivity.java create mode 100644 src/main/java/com/ruoyi/system/dao/po/GroupBuyDiscount.java create mode 100644 src/main/java/com/ruoyi/system/dao/po/Sku.java create mode 100644 src/main/java/com/ruoyi/system/gateway/dto/package-info.java create mode 100644 src/main/java/com/ruoyi/system/gateway/package-info.java create mode 100644 src/main/java/com/ruoyi/system/handler/CommonGlobalExceptionHandler.java create mode 100644 src/main/java/com/ruoyi/system/redis/package-info.java create mode 100644 src/main/java/com/ruoyi/system/util/AESUtil.java create mode 100644 src/main/java/com/ruoyi/system/util/BaseContext.java create mode 100644 src/main/java/com/ruoyi/system/util/EsUtil.java create mode 100644 src/main/java/com/ruoyi/system/util/FastDFSUtil.java create mode 100644 src/main/java/com/ruoyi/system/util/FileTestUtils.java create mode 100644 src/main/java/com/ruoyi/system/util/HttpUtil.java create mode 100644 src/main/java/com/ruoyi/system/util/ImageUtil.java create mode 100644 src/main/java/com/ruoyi/system/util/IpUtil.java create mode 100644 src/main/java/com/ruoyi/system/util/JsonResponse.java create mode 100644 src/main/java/com/ruoyi/system/util/MD5Util.java create mode 100644 src/main/java/com/ruoyi/system/util/RSAUtil.java create mode 100644 src/main/java/com/ruoyi/system/util/RocketMQUtil.java create mode 100644 src/main/java/com/ruoyi/system/util/TokenUtil.java create mode 100644 src/main/java/com/ruoyi/system/util/Utilfast.java diff --git a/.idea/misc.xml b/.idea/misc.xml index 639900d..e2044d1 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,6 +1,14 @@ - + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 7ddf35f..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/src/main/java/com/ruoyi/system/Enum/VideoTagEnum.java b/src/main/java/com/ruoyi/system/Enum/VideoTagEnum.java new file mode 100644 index 0000000..607ff85 --- /dev/null +++ b/src/main/java/com/ruoyi/system/Enum/VideoTagEnum.java @@ -0,0 +1,39 @@ +package com.ruoyi.system.Enum; + +/** + * @author: Larry + * @Date: 2023 /12 /06 / 15:23 + * @Description: + */ +public enum VideoTagEnum { + ACTION(1, "鬼畜"), + COMEDY(2, "色情"), + DRAMA(3, "运动"), + ROMANCE(4, "火影忍者"); + + private int id; + private String type; + + VideoTagEnum(int id, String type) { + this.id = id; + this.type = type; + } + + public int getId() { + return id; + } + + public String getType() { + return type; + } + + public static VideoTagEnum getById(int id) { + for (VideoTagEnum tag : values()) { + if (tag.getId() == id) { + return tag; + } + } + throw new IllegalArgumentException("Invalid VideoTagEnum id: " + id); + } +} + diff --git a/src/main/java/com/ruoyi/system/Interceptor/LoginInterceptor.java b/src/main/java/com/ruoyi/system/Interceptor/LoginInterceptor.java new file mode 100644 index 0000000..b485bb3 --- /dev/null +++ b/src/main/java/com/ruoyi/system/Interceptor/LoginInterceptor.java @@ -0,0 +1,40 @@ +package com.ruoyi.system.Interceptor; + +import com.zy.util.BaseContext; +import com.zy.util.TokenUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Date; +import java.util.concurrent.TimeUnit; + +/** + * @author: Larry + * @Date: 2023 /11 /22 / 21:40 + * @Description: + */ +@Slf4j +@Component +public class LoginInterceptor implements HandlerInterceptor { + @Resource + RedisTemplate redisTemplate; + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String token = request.getHeader("token"); + log.info(token); + Long userId = TokenUtil.verifyToken(token); + if (userId > 0) { + BaseContext.setCurrentId(userId); + Date passTime = TokenUtil.getTokenExpirationTime(token); + log.info(passTime.toString()); + redisTemplate.opsForValue().set("token"+userId,passTime.toString(),1, TimeUnit.HOURS); + return true; + } + return false; + } +} diff --git a/src/main/java/com/ruoyi/system/Interceptor/RefreshTokenInterceptor.java b/src/main/java/com/ruoyi/system/Interceptor/RefreshTokenInterceptor.java new file mode 100644 index 0000000..61955bb --- /dev/null +++ b/src/main/java/com/ruoyi/system/Interceptor/RefreshTokenInterceptor.java @@ -0,0 +1,32 @@ +package com.ruoyi.system.Interceptor; + +import com.zy.util.TokenUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author: Larry + * @Date: 2023 /11 /23 / 8:40 + * @Description: + */ +@Component +@Slf4j +public class RefreshTokenInterceptor implements HandlerInterceptor { + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String token = request.getHeader("token"); + try { + Long id = TokenUtil.verifyToken(token); + TokenUtil.generateRefreshToken(id); + log.info("刷新成功"); + return true ; + } catch (Exception e) { + throw new RuntimeException(e); + } + + } +} diff --git a/src/main/java/com/ruoyi/system/adapter/port/package-info.java b/src/main/java/com/ruoyi/system/adapter/port/package-info.java new file mode 100644 index 0000000..a67ae85 --- /dev/null +++ b/src/main/java/com/ruoyi/system/adapter/port/package-info.java @@ -0,0 +1,4 @@ +/** + * 实现对外部的api调用,类的名称为 XxxPort 接口定义在 domain 中 + */ +package com.ruoyi.system.adapter.port; \ No newline at end of file diff --git a/src/main/java/com/ruoyi/system/adapter/repository/ActivityRepository.java b/src/main/java/com/ruoyi/system/adapter/repository/ActivityRepository.java new file mode 100644 index 0000000..ad0ef0e --- /dev/null +++ b/src/main/java/com/ruoyi/system/adapter/repository/ActivityRepository.java @@ -0,0 +1,81 @@ +package com.ruoyi.system.adapter.repository; + +import cn.bugstack.domain.activity.adapter.repository.IActivityRepository; +import cn.bugstack.domain.activity.model.valobj.GroupBuyActivityDiscountVO; +import cn.bugstack.domain.activity.model.valobj.SkuVO; +import cn.bugstack.infrastructure.dao.IGroupBuyActivityDao; +import cn.bugstack.infrastructure.dao.IGroupBuyDiscountDao; +import cn.bugstack.infrastructure.dao.ISkuDao; +import cn.bugstack.infrastructure.dao.po.GroupBuyActivity; +import cn.bugstack.infrastructure.dao.po.GroupBuyDiscount; +import cn.bugstack.infrastructure.dao.po.Sku; +import org.springframework.stereotype.Repository; + +import javax.annotation.Resource; + +/** + * @author Fuzhengwei bugstack.cn @小傅哥 + * @description 活动仓储 + * @create 2024-12-21 10:10 + */ +@Repository +public class ActivityRepository implements IActivityRepository { + + @Resource + private IGroupBuyActivityDao groupBuyActivityDao; + @Resource + private IGroupBuyDiscountDao groupBuyDiscountDao; + + @Resource + private ISkuDao skuDao; + + @Override + public GroupBuyActivityDiscountVO queryGroupBuyActivityDiscountVO(String source, String channel) { + // 根据SC渠道值查询配置中最新的1个有效的活动 + GroupBuyActivity groupBuyActivityReq = new GroupBuyActivity(); + groupBuyActivityReq.setSource(source); + groupBuyActivityReq.setChannel(channel); + GroupBuyActivity groupBuyActivityRes = groupBuyActivityDao.queryValidGroupBuyActivity(groupBuyActivityReq); + + String discountId = groupBuyActivityRes.getDiscountId(); + + GroupBuyDiscount groupBuyDiscountRes = groupBuyDiscountDao.queryGroupBuyActivityDiscountByDiscountId(discountId); + GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount = GroupBuyActivityDiscountVO.GroupBuyDiscount.builder() + .discountName(groupBuyDiscountRes.getDiscountName()) + .discountDesc(groupBuyDiscountRes.getDiscountDesc()) + .discountType(groupBuyDiscountRes.getDiscountType()) + .marketPlan(groupBuyDiscountRes.getMarketPlan()) + .marketExpr(groupBuyDiscountRes.getMarketExpr()) + .tagId(groupBuyDiscountRes.getTagId()) + .build(); + + return GroupBuyActivityDiscountVO.builder() + .activityId(groupBuyActivityRes.getActivityId()) + .activityName(groupBuyActivityRes.getActivityName()) + .source(groupBuyActivityRes.getSource()) + .channel(groupBuyActivityRes.getChannel()) + .goodsId(groupBuyActivityRes.getGoodsId()) + .groupBuyDiscount(groupBuyDiscount) + .groupType(groupBuyActivityRes.getGroupType()) + .takeLimitCount(groupBuyActivityRes.getTakeLimitCount()) + .target(groupBuyActivityRes.getTarget()) + .validTime(groupBuyActivityRes.getValidTime()) + .status(groupBuyActivityRes.getStatus()) + .startTime(groupBuyActivityRes.getStartTime()) + .endTime(groupBuyActivityRes.getEndTime()) + .tagId(groupBuyActivityRes.getTagId()) + .tagScope(groupBuyActivityRes.getTagScope()) + .build(); + } + + @Override + public SkuVO querySkuByGoodsId(String goodsId) { + Sku sku = skuDao.querySkuByGoodsId(goodsId); + return SkuVO.builder() + .goodsId(sku.getGoodsId()) + .goodsName(sku.getGoodsName()) + .originalPrice(sku.getOriginalPrice()) + .build(); + } + +} diff --git a/src/main/java/com/ruoyi/system/adapter/repository/package-info.java b/src/main/java/com/ruoyi/system/adapter/repository/package-info.java new file mode 100644 index 0000000..537d212 --- /dev/null +++ b/src/main/java/com/ruoyi/system/adapter/repository/package-info.java @@ -0,0 +1,4 @@ +/** + * 仓储实现;用于实现 domain 中定义的仓储接口,如;IXxxRepository 在 Repository 中调用服务 + */ +package com.ruoyi.system.adapter.repository; \ No newline at end of file diff --git a/src/main/java/com/ruoyi/system/dao/IGroupBuyActivityDao.java b/src/main/java/com/ruoyi/system/dao/IGroupBuyActivityDao.java new file mode 100644 index 0000000..7bed518 --- /dev/null +++ b/src/main/java/com/ruoyi/system/dao/IGroupBuyActivityDao.java @@ -0,0 +1,20 @@ +package com.ruoyi.system.dao; + +import cn.bugstack.infrastructure.dao.po.GroupBuyActivity; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * @author Fuzhengwei bugstack.cn @小傅哥 + * @description 拼团活动Dao + * @create 2024-12-07 10:10 + */ +@Mapper +public interface IGroupBuyActivityDao { + + List queryGroupBuyActivityList(); + + GroupBuyActivity queryValidGroupBuyActivity(GroupBuyActivity groupBuyActivityReq); + +} diff --git a/src/main/java/com/ruoyi/system/dao/IGroupBuyDiscountDao.java b/src/main/java/com/ruoyi/system/dao/IGroupBuyDiscountDao.java new file mode 100644 index 0000000..be6c258 --- /dev/null +++ b/src/main/java/com/ruoyi/system/dao/IGroupBuyDiscountDao.java @@ -0,0 +1,20 @@ +package com.ruoyi.system.dao; + +import cn.bugstack.infrastructure.dao.po.GroupBuyDiscount; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * @author Fuzhengwei bugstack.cn @小傅哥 + * @description 折扣配置Dao + * @create 2024-12-07 10:10 + */ +@Mapper +public interface IGroupBuyDiscountDao { + + List queryGroupBuyDiscountList(); + + GroupBuyDiscount queryGroupBuyActivityDiscountByDiscountId(String discountId); + +} diff --git a/src/main/java/com/ruoyi/system/dao/ISkuDao.java b/src/main/java/com/ruoyi/system/dao/ISkuDao.java new file mode 100644 index 0000000..039509b --- /dev/null +++ b/src/main/java/com/ruoyi/system/dao/ISkuDao.java @@ -0,0 +1,16 @@ +package com.ruoyi.system.dao; + +import cn.bugstack.infrastructure.dao.po.Sku; +import org.apache.ibatis.annotations.Mapper; + +/** + * @author Fuzhengwei bugstack.cn @小傅哥 + * @description 商品查询 + * @create 2024-12-21 10:48 + */ +@Mapper +public interface ISkuDao { + + Sku querySkuByGoodsId(String goodsId); + +} diff --git a/src/main/java/com/ruoyi/system/dao/po/GroupBuyActivity.java b/src/main/java/com/ruoyi/system/dao/po/GroupBuyActivity.java new file mode 100644 index 0000000..07b02cb --- /dev/null +++ b/src/main/java/com/ruoyi/system/dao/po/GroupBuyActivity.java @@ -0,0 +1,58 @@ +package com.ruoyi.system.dao.po; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +/** + * @author Fuzhengwei bugstack.cn @小傅哥 + * @description 拼团活动 + * @create 2024-12-07 10:01 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class GroupBuyActivity { + + /** 自增 */ + private Long id; + /** 活动ID */ + private Long activityId; + /** 活动名称 */ + private String activityName; + /** 来源 */ + private String source; + /** 渠道 */ + private String channel; + /** 商品ID */ + private String goodsId; + /** 折扣ID */ + private String discountId; + /** 拼团方式(0自动成团、1达成目标拼团) */ + private Integer groupType; + /** 拼团次数限制 */ + private Integer takeLimitCount; + /** 拼团目标 */ + private Integer target; + /** 拼团时长(分钟) */ + private Integer validTime; + /** 活动状态(0创建、1生效、2过期、3废弃) */ + private Integer status; + /** 活动开始时间 */ + private Date startTime; + /** 活动结束时间 */ + private Date endTime; + /** 人群标签规则标识 */ + private String tagId; + /** 人群标签规则范围 */ + private String tagScope; + /** 创建时间 */ + private Date createTime; + /** 更新时间 */ + private Date updateTime; + +} diff --git a/src/main/java/com/ruoyi/system/dao/po/GroupBuyDiscount.java b/src/main/java/com/ruoyi/system/dao/po/GroupBuyDiscount.java new file mode 100644 index 0000000..2f25e34 --- /dev/null +++ b/src/main/java/com/ruoyi/system/dao/po/GroupBuyDiscount.java @@ -0,0 +1,71 @@ +package com.ruoyi.system.dao.po; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +/** + * @author Fuzhengwei bugstack.cn @小傅哥 + * @description 折扣配置 + * @create 2024-12-07 10:06 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class GroupBuyDiscount { + + /** + * 自增ID + */ + private Long id; + + /** + * 折扣ID + */ + private Integer discountId; + + /** + * 折扣标题 + */ + private String discountName; + + /** + * 折扣描述 + */ + private String discountDesc; + + /** + * 折扣类型(0:base、1:tag) + */ + private Byte discountType; + + /** + * 营销优惠计划(ZJ:直减、MJ:满减、N元购) + */ + private String marketPlan; + + /** + * 营销优惠表达式 + */ + private String marketExpr; + + /** + * 人群标签,特定优惠限定 + */ + private String tagId; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 更新时间 + */ + private Date updateTime; + +} diff --git a/src/main/java/com/ruoyi/system/dao/po/Sku.java b/src/main/java/com/ruoyi/system/dao/po/Sku.java new file mode 100644 index 0000000..6a55493 --- /dev/null +++ b/src/main/java/com/ruoyi/system/dao/po/Sku.java @@ -0,0 +1,39 @@ +package com.ruoyi.system.dao.po; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.util.Date; + +/** + * @author Fuzhengwei bugstack.cn @小傅哥 + * @description 商品信息 + * @create 2024-12-21 10:45 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class Sku { + + /** 自增 */ + private Long id; + /** 来源 */ + private String source; + /** 渠道 */ + private String channel; + /** 商品ID */ + private String goodsId; + /** 商品名称 */ + private String goodsName; + /** 原始价格 */ + private BigDecimal originalPrice; + /** 创建时间 */ + private Date createTime; + /** 更新时间 */ + private Date updateTime; + +} diff --git a/src/main/java/com/ruoyi/system/gateway/dto/package-info.java b/src/main/java/com/ruoyi/system/gateway/dto/package-info.java new file mode 100644 index 0000000..d05c6ec --- /dev/null +++ b/src/main/java/com/ruoyi/system/gateway/dto/package-info.java @@ -0,0 +1 @@ +package com.ruoyi.system.gateway.dto; \ No newline at end of file diff --git a/src/main/java/com/ruoyi/system/gateway/package-info.java b/src/main/java/com/ruoyi/system/gateway/package-info.java new file mode 100644 index 0000000..343bcb5 --- /dev/null +++ b/src/main/java/com/ruoyi/system/gateway/package-info.java @@ -0,0 +1,4 @@ +/** + * 定义http、rpc接口,调用外部。在 adapter 中调用这部分内容。 + */ +package com.ruoyi.system.gateway; \ No newline at end of file diff --git a/src/main/java/com/ruoyi/system/handler/CommonGlobalExceptionHandler.java b/src/main/java/com/ruoyi/system/handler/CommonGlobalExceptionHandler.java new file mode 100644 index 0000000..f681a23 --- /dev/null +++ b/src/main/java/com/ruoyi/system/handler/CommonGlobalExceptionHandler.java @@ -0,0 +1,27 @@ +package com.ruoyi.system.handler; +import com.zy.exception.ConditionException; +import com.zy.util.JsonResponse; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; + +@ControllerAdvice +@Order(Ordered.HIGHEST_PRECEDENCE) +public class CommonGlobalExceptionHandler { + + @ExceptionHandler(value = Exception.class) + @ResponseBody + public JsonResponse commonExceptionHandler(HttpServletRequest request, Exception e){ + String errorMsg = e.getMessage(); + if(e instanceof ConditionException){ + String errorCode = ((ConditionException)e).getCode(); + return new JsonResponse<>(errorCode, errorMsg); + }else{ + return new JsonResponse<>("500",errorMsg); + } + } +} diff --git a/src/main/java/com/ruoyi/system/redis/package-info.java b/src/main/java/com/ruoyi/system/redis/package-info.java new file mode 100644 index 0000000..719aebe --- /dev/null +++ b/src/main/java/com/ruoyi/system/redis/package-info.java @@ -0,0 +1,4 @@ +/** + * 提供redis链接配置 + */ +package com.ruoyi.system.redis; \ No newline at end of file diff --git a/src/main/java/com/ruoyi/system/util/AESUtil.java b/src/main/java/com/ruoyi/system/util/AESUtil.java new file mode 100644 index 0000000..2142299 --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/AESUtil.java @@ -0,0 +1,57 @@ +package com.ruoyi.system.util; + +import org.apache.tomcat.util.codec.binary.Base64; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; + +/** + * AES: Advanced Encryption Standard 高级加密标准 + * 最常见的对称加密算法,即加密和解密使用同样的密钥,加密结果可逆 + * 特点:加密速度非常快,适合经常发送数据的场合 + * + */ +public class AESUtil { + + private static final String KEY_ALGORITHM = "AES"; + + private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + + private final Cipher decryptCipher; + + private final Cipher encryptCipher; + + private final String seed; + + public AESUtil(String seed) throws Exception { + this.seed = seed; + decryptCipher = Cipher.getInstance(KEY_ALGORITHM); + encryptCipher = Cipher.getInstance(KEY_ALGORITHM); + decryptCipher.init(Cipher.DECRYPT_MODE, this.getSecretKey()); + encryptCipher.init(Cipher.ENCRYPT_MODE, this.getSecretKey()); + } + + public String decrypt(String content) throws Exception { + byte[] bytes = Base64.decodeBase64(content); + byte[] result = decryptCipher.doFinal(bytes); + return new String(result, StandardCharsets.UTF_8); + } + + public String encrypt(String content) throws Exception { + byte[] result = encryptCipher.doFinal(content.getBytes(StandardCharsets.UTF_8)); + return Base64.encodeBase64String(result); + } + + public SecretKey getSecretKey() throws Exception { + SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); + random.setSeed(seed.getBytes()); + KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM); + kg.init(128, random); + return kg.generateKey(); + } + + +} diff --git a/src/main/java/com/ruoyi/system/util/BaseContext.java b/src/main/java/com/ruoyi/system/util/BaseContext.java new file mode 100644 index 0000000..a4676e2 --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/BaseContext.java @@ -0,0 +1,19 @@ +package com.ruoyi.system.util; + +public class BaseContext { + + public static ThreadLocal threadLocal = new ThreadLocal<>(); + + public static void setCurrentId(Long id) { + threadLocal.set(id); + } + + public static Long getCurrentId() { + return threadLocal.get(); + } + + public static void removeCurrentId() { + threadLocal.remove(); + } + +} diff --git a/src/main/java/com/ruoyi/system/util/EsUtil.java b/src/main/java/com/ruoyi/system/util/EsUtil.java new file mode 100644 index 0000000..fb3f527 --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/EsUtil.java @@ -0,0 +1,75 @@ +package com.ruoyi.system.util; + +import org.elasticsearch.client.Request; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.RestClient; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.io.IOException; + +/** + * @author: Larry + * @Date: 2024 /10 /27 / 15:47 + * @Description: + */ +@Component +public class EsUtil { + @Resource + private RestClient restClient; + public boolean createIndex(String indexName) { + try { + // 构建创建索引的请求 + Request request = new Request("PUT", indexName); + // 设置索引的源数据,包括映射和设置 + String indexSettings = String.format( + "{\n" + + " \"settings\": {\n" + + " \"number_of_shards\": %d,\n" + + " \"number_of_replicas\": %d\n" + + " },\n" + + " \"mappings\": {\n" + + " \"properties\": {\n" + + " \"message\": {\n" + + " \"type\": \"text\"\n" + + " }\n" + + " }\n" + + " }\n" + + "}", 1, 0); + + request.setJsonEntity(indexSettings); + // 执行请求 + Response response = restClient.performRequest(request); + // 检查响应状态码 + return response.getStatusLine().getStatusCode() == 200; + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + /** + * 创建或更新Elasticsearch中的文档 + * @param index 索引名称 + * @param id 文档ID + * @param jsonDocument 要创建的文档内容,格式为JSON字符串 + * @return true 如果文档创建或更新成功,否则false + */ + public boolean createOrUpdateDocument(String index, String id, String jsonDocument) { + try { + // 构建请求 + Request request = new Request("PUT", index + "/_doc/" + id); + request.setJsonEntity(jsonDocument); + + // 执行请求 + restClient.performRequest(request); + + // 如果没有异常发生,我们可以认为文档创建或更新成功 + return true; + } catch (IOException e) { + // 打印异常信息 + e.printStackTrace(); + return false; + } + } + +} diff --git a/src/main/java/com/ruoyi/system/util/FastDFSUtil.java b/src/main/java/com/ruoyi/system/util/FastDFSUtil.java new file mode 100644 index 0000000..bc32410 --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/FastDFSUtil.java @@ -0,0 +1,221 @@ +package com.ruoyi.system.util; + +import com.github.tobato.fastdfs.domain.fdfs.FileInfo; +import com.github.tobato.fastdfs.domain.fdfs.MetaData; +import com.github.tobato.fastdfs.domain.fdfs.StorePath; +import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback; +import com.github.tobato.fastdfs.service.AppendFileStorageClient; +import com.github.tobato.fastdfs.service.FastFileStorageClient; +import com.zy.exception.ConditionException; +import io.netty.util.internal.StringUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.util.*; + +@Component +public class FastDFSUtil { + + @Autowired + private FastFileStorageClient fastFileStorageClient; + + @Autowired + private AppendFileStorageClient appendFileStorageClient; + + @Autowired + private RedisTemplate redisTemplate; + + private static final String PATH_KEY = "path-key:"; + + private static final String UPLOADED_SIZE_KEY = "uploaded-size-key:"; + + private static final String UPLOADED_NO_KEY = "uploaded-no-key:"; + + private static final String DEFAULT_GROUP = "group1"; + + private static final int SLICE_SIZE = 1024 * 1024 * 2; + + private String httpFdfsStorageAddr; + + public String getFileType(MultipartFile file){ + if(file == null){ + throw new ConditionException("非法文件!"); + } + String fileName = file.getOriginalFilename(); + int index = fileName.lastIndexOf("."); + return fileName.substring(index+1); + } + + //上传 + public String uploadCommonFile(MultipartFile file) throws Exception { + Set metaDataSet = new HashSet<>(); + String fileType = this.getFileType(file); + StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), fileType, metaDataSet); + return storePath.getPath(); + } + + public String uploadCommonFile(File file, String fileType) throws Exception { + Set metaDataSet = new HashSet<>(); + StorePath storePath = fastFileStorageClient.uploadFile(new FileInputStream(file), + file.length(), fileType, metaDataSet); + return storePath.getPath(); + } + + //上传可以断点续传的文件 + public String uploadAppenderFile(MultipartFile file) throws Exception{ + String fileType = this.getFileType(file); + StorePath storePath = appendFileStorageClient.uploadAppenderFile(DEFAULT_GROUP, file.getInputStream(), file.getSize(), fileType); + return storePath.getPath(); + } + + public void modifyAppenderFile(MultipartFile file, String filePath, long offset) throws Exception{ + appendFileStorageClient.modifyFile(DEFAULT_GROUP, filePath, file.getInputStream(), file.getSize(), offset); + } + //md5用来区分文件,形成一个唯一标识,方便redis记录 + public String uploadFileBySlices(MultipartFile file, String fileMd5, Integer sliceNo, Integer totalSliceNo) throws Exception { + if(file == null || sliceNo == null || totalSliceNo == null){ + throw new ConditionException("参数异常!"); + } + String pathKey = PATH_KEY + fileMd5; + String uploadedSizeKey = UPLOADED_SIZE_KEY + fileMd5; + String uploadedNoKey = UPLOADED_NO_KEY + fileMd5; + String uploadedSizeStr = redisTemplate.opsForValue().get(uploadedSizeKey); + //当前文件的大小,每次传完之后++ + Long uploadedSize = 0L; + if(!StringUtil.isNullOrEmpty(uploadedSizeStr)){ + uploadedSize = Long.valueOf(uploadedSizeStr); + } + if(sliceNo == 1){ //上传的是第一个分片 + String path = this.uploadAppenderFile(file); + if(StringUtil.isNullOrEmpty(path)){ + throw new ConditionException("上传失败!"); + } + redisTemplate.opsForValue().set(pathKey, path); + redisTemplate.opsForValue().set(uploadedNoKey, "1"); + }else{ + String filePath = redisTemplate.opsForValue().get(pathKey); + if(StringUtil.isNullOrEmpty(filePath)){ + throw new ConditionException("上传失败!"); + } + this.modifyAppenderFile(file, filePath, uploadedSize); + //将当前切片大小加1 + redisTemplate.opsForValue().increment(uploadedNoKey); + } + // 修改历史上传分片文件大小 + uploadedSize += file.getSize(); + redisTemplate.opsForValue().set(uploadedSizeKey, String.valueOf(uploadedSize)); + //如果所有分片全部上传完毕,则清空redis里面相关的key和value + String uploadedNoStr = redisTemplate.opsForValue().get(uploadedNoKey); + Integer uploadedNo = Integer.valueOf(uploadedNoStr); + String resultPath = ""; + if(uploadedNo.equals(totalSliceNo)){ + resultPath = redisTemplate.opsForValue().get(pathKey); + List keyList = Arrays.asList(uploadedNoKey, pathKey, uploadedSizeKey); + redisTemplate.delete(keyList); + } + return resultPath; + } + + public void convertFileToSlices(MultipartFile multipartFile) throws Exception{ + String fileType = this.getFileType(multipartFile); + //生成临时文件,将MultipartFile转为File + File file = this.multipartFileToFile(multipartFile); + //文件大小 + long fileLength = file.length(); + int count = 1; + //每完成一个分片的生成,文件大小加一个分片size + for(int i = 0; i < fileLength; i += SLICE_SIZE){ + //可以从文件任意位置操作文件(r表示只要读的权限) + RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); + //搜寻文件任意位置 + randomAccessFile.seek(i); + byte[] bytes = new byte[SLICE_SIZE]; + //获取分片文件实际的大小(可能有一定误差) + int len = randomAccessFile.read(bytes); + String path = "D:\\" + count + "." + fileType; + File slice = new File(path); + FileOutputStream fos = new FileOutputStream(slice); + fos.write(bytes, 0, len); + fos.close(); + randomAccessFile.close(); + count++; + } + //删除临时文件 + file.delete(); + } + + public File multipartFileToFile(MultipartFile multipartFile) throws Exception{ + String originalFileName = multipartFile.getOriginalFilename(); + String[] fileName = originalFileName.split("\\."); + File file = File.createTempFile(fileName[0], "." + fileName[1]); + multipartFile.transferTo(file); + return file; + } + + //删除 + public void deleteFile(String filePath){ + fastFileStorageClient.deleteFile(filePath); + } + + + + public void viewVideoOnlineBySlices(HttpServletRequest request, + HttpServletResponse response, + String path) throws Exception{ + FileInfo fileInfo = fastFileStorageClient.queryFileInfo(DEFAULT_GROUP, path); + long totalFileSize = fileInfo.getFileSize(); + String url = httpFdfsStorageAddr + path; + Enumeration headerNames = request.getHeaderNames(); + Map headers = new HashMap<>(); + while(headerNames.hasMoreElements()){ + String header = headerNames.nextElement(); + headers.put(header, request.getHeader(header)); + } + String rangeStr = request.getHeader("Range"); + String[] range; + if(StringUtil.isNullOrEmpty(rangeStr)){ + rangeStr = "bytes=0-" + (totalFileSize-1); + } + range = rangeStr.split("bytes=|-"); + long begin = 0; + if(range.length >= 2){ + begin = Long.parseLong(range[1]); + } + long end = totalFileSize-1; + if(range.length >= 3){ + end = Long.parseLong(range[2]); + } + long len = (end - begin) + 1; + String contentRange = "bytes " + begin + "-" + end + "/" + totalFileSize; + response.setHeader("Content-Range", contentRange); + response.setHeader("Accept-Ranges", "bytes"); + response.setHeader("Content-Type", "video/mp4"); + response.setContentLength((int)len); + response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); + HttpUtil.get(url, headers, response); + } + + public void downLoadFile(String url, String localPath) { + fastFileStorageClient.downloadFile(DEFAULT_GROUP, url, + new DownloadCallback() { + @Override + public String recv(InputStream ins) throws IOException { + File file = new File(localPath); + OutputStream os = new FileOutputStream(file); + int len = 0; + byte[] buffer = new byte[1024]; + while ((len = ins.read(buffer)) != -1) { + os.write(buffer, 0, len); + } + os.close(); + ins.close(); + return "success"; + } + }); + } +} diff --git a/src/main/java/com/ruoyi/system/util/FileTestUtils.java b/src/main/java/com/ruoyi/system/util/FileTestUtils.java new file mode 100644 index 0000000..2b5214a --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/FileTestUtils.java @@ -0,0 +1,38 @@ +package com.ruoyi.system.util; + +import org.apache.commons.io.FileUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; + +/** + * @author zhouquan + * @description 测试MultipartFile与File互转 + * @date 2023-03-12 17:31 + **/ +public class FileTestUtils { + + + /** + * MultipartFile转File + *

+ * 项目根路径创建临时文件,转换得到File,再删除临时文件 + * + * @param multipartFile + * @return + */ + public static File multiPartFileToFile(MultipartFile multipartFile) throws IOException { + + //获取文件名 + String originalFilename = multipartFile.getOriginalFilename(); + //获取默认定位到的当前用户目录("user.dir"),也就是当前应用的根路径 + String tempDir = System.getProperty("user.dir"); + //根目录下生成临时文件 + File file = new File(tempDir+File.separator+originalFilename); + FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file); + return file; + } + +} + diff --git a/src/main/java/com/ruoyi/system/util/HttpUtil.java b/src/main/java/com/ruoyi/system/util/HttpUtil.java new file mode 100644 index 0000000..dede1c6 --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/HttpUtil.java @@ -0,0 +1,404 @@ +package com.ruoyi.system.util; + +import com.alibaba.fastjson.JSONObject; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Map.Entry; + +/** + * Http请求工具类 + */ +public class HttpUtil { + + private static final String CONTENT_TYPE_JSON = "application/json"; + + private static final String CONTENT_TYPE_URL_ENCODED = "application/x-www-form-urlencoded"; + + private static final String REQUEST_METHOD_POST = "POST"; + + private static final String REQUEST_METHOD_GET = "GET"; + + private static final Integer CONNECT_TIME_OUT = 120000; + + /** + * http get请求 + * @param url 请求链接 + * @param params 请求参数 + */ + public static HttpResponse get(String url, Map params) throws Exception { + String getUrl = buildGetRequestParams(url, params); + URL urlObj = new URL(getUrl); + HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); + con.setDoInput(true); + con.setRequestMethod(REQUEST_METHOD_GET); + con.setConnectTimeout(CONNECT_TIME_OUT); + con.connect(); + BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); + int responseCode = con.getResponseCode(); + String response = writeResponse(responseCode,br); + br.close(); + String cookie = con.getHeaderField("Set-Cookie"); + con.disconnect(); + return new HttpResponse(responseCode,response, cookie); + } + + /** + * http get请求 可以配置请求头 + * @param url 请求链接 + * @param params 请求参数 + */ + public static HttpResponse get(String url, + Map params, + Map headers) throws Exception { + String getUrl = buildGetRequestParams(url, params); + URL urlObj = new URL(getUrl); + HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); + con.setDoInput(true); + con.setRequestMethod(REQUEST_METHOD_GET); + con.setRequestProperty("Content-Type", CONTENT_TYPE_JSON); + con.setConnectTimeout(CONNECT_TIME_OUT); + //设置请求头 + for(Entry entry : headers.entrySet()) { + String key = entry.getKey(); + String value = String.valueOf(entry.getValue()); + con.setRequestProperty(key, value); + } + con.connect(); + BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); + int responseCode = con.getResponseCode(); + String response = writeResponse(responseCode,br); + br.close(); + String cookie = con.getHeaderField("Set-Cookie"); + con.disconnect(); + return new HttpResponse(responseCode,response, cookie); + } + + /** + * http get请求 返回输出流 + * @param url 请求链接 + * @param headers 请求头 + * @param response 响应 + */ + public static OutputStream get(String url, + Map headers, + HttpServletResponse response) throws Exception { + URL urlObj = new URL(url); + HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); + con.setDoInput(true); + con.setRequestMethod(REQUEST_METHOD_GET); + con.setConnectTimeout(CONNECT_TIME_OUT); + for(Entry entry : headers.entrySet()) { + String key = entry.getKey(); + String value = String.valueOf(entry.getValue()); + con.setRequestProperty(key, value); + } + con.connect(); + BufferedInputStream bis = new BufferedInputStream(con.getInputStream()); + OutputStream os = response.getOutputStream(); + int responseCode = con.getResponseCode(); + byte[] buffer = new byte[1024]; + if(responseCode >=200 && responseCode <300) { + int i = bis.read(buffer); + while (( i != -1)) { + os.write(buffer,0,i); + i = bis.read(buffer); + } + bis.close(); + } + bis.close(); + con.disconnect(); + return os; + } + + /** + * http post请求,请求参数使用map进行封装 + * @param url 请求链接地址 + * @param params 请求参数 + */ + public static HttpResponse postJson(String url, Map params) throws Exception { + URL urlObj = new URL(url); + HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); + con.setDoOutput(true); + con.setDoInput(true); + con.setRequestProperty("Content-Type", CONTENT_TYPE_JSON); + con.setRequestMethod(REQUEST_METHOD_POST); + con.setConnectTimeout(CONNECT_TIME_OUT); + String json = JSONObject.toJSONString(params); + con.connect(); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream()); + outputStreamWriter.write(json); + outputStreamWriter.flush(); + BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); + int responseCode = con.getResponseCode(); + String response = writeResponse(responseCode,br); + outputStreamWriter.close(); + br.close(); + String cookie = con.getHeaderField("Set-Cookie"); + con.disconnect(); + return new HttpResponse(responseCode,response, cookie); + } + + /** + * http post请求,请求参数使用json字符串 + * @param url 请求链接地址 + */ + public static HttpResponse postJson(String url, String json) throws Exception { + URL urlObj = new URL(url); + HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); + con.setDoOutput(true); + con.setDoInput(true); + con.setRequestProperty("Content-Type", CONTENT_TYPE_JSON); + con.setRequestMethod(REQUEST_METHOD_POST); + con.setConnectTimeout(CONNECT_TIME_OUT); + con.connect(); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream()); + outputStreamWriter.write(json); + outputStreamWriter.flush(); + BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); + int responseCode = con.getResponseCode(); + String response = writeResponse(responseCode,br); + outputStreamWriter.close(); + br.close(); + String cookie = con.getHeaderField("Set-Cookie"); + con.disconnect(); + return new HttpResponse(responseCode,response, cookie); + } + + /** + * http post请求,请求参数使用json字符串, 可以配置请求头 + * @param url 请求链接地址 + * @param params 请求参数 + */ + public static HttpResponse postJson(String url, + Map params, + Map headers) throws Exception { + URL urlObj = new URL(url); + HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); + con.setDoOutput(true); + con.setDoInput(true); + con.setRequestProperty("Content-Type", CONTENT_TYPE_JSON); + //设置请求头 + for(Entry entry : headers.entrySet()) { + String key = entry.getKey(); + String value = String.valueOf(entry.getValue()); + con.setRequestProperty(key, value); + } + con.setRequestMethod(REQUEST_METHOD_POST); + con.setConnectTimeout(CONNECT_TIME_OUT); + String json = JSONObject.toJSONString(params); + con.connect(); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream()); + outputStreamWriter.write(json); + outputStreamWriter.flush(); + BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); + int responseCode = con.getResponseCode(); + String response = writeResponse(responseCode,br); + outputStreamWriter.close(); + br.close(); + String cookie = con.getHeaderField("Set-Cookie"); + con.disconnect(); + return new HttpResponse(responseCode,response, cookie); + } + + /** + * http post请求,请求参数形式为url-encoded + * @param url 请求链接地址 + * @param params 请求参数 + */ + public static HttpResponse postUrlEncoded(String url, + Map params) throws Exception { + URL urlObj = new URL(url); + HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); + con.setDoOutput(true); + con.setDoInput(true); + con.setRequestProperty("Content-Type", CONTENT_TYPE_URL_ENCODED); + con.setRequestMethod(REQUEST_METHOD_POST); + con.setConnectTimeout(CONNECT_TIME_OUT); + con.connect(); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream()); + String postParam = buildPostFormOrUrlEncodedParams(params); + outputStreamWriter.write(postParam); + outputStreamWriter.flush(); + BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); + int responseCode = con.getResponseCode(); + String response = writeResponse(responseCode,br); + outputStreamWriter.close(); + br.close(); + String cookie = con.getHeaderField("Set-Cookie"); + con.disconnect(); + return new HttpResponse(responseCode,response, cookie); + } + + /** + * http post请求,请求参数形式为form-data + * @param url 请求链接地址 + * @param params 请求参数 + */ + public static HttpResponse postFormData(String url, + Map params) throws Exception { + URL urlObj = new URL(url); + HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); + con.setDoOutput(true); + con.setDoInput(true); + con.setRequestMethod(REQUEST_METHOD_POST); + con.setConnectTimeout(CONNECT_TIME_OUT); + con.connect(); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream()); + String postParam = buildPostFormOrUrlEncodedParams(params); + outputStreamWriter.write(postParam); + outputStreamWriter.flush(); + BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); + int responseCode = con.getResponseCode(); + String response = writeResponse(responseCode,br); + outputStreamWriter.close(); + br.close(); + String cookie = con.getHeaderField("Set-Cookie"); + con.disconnect(); + return new HttpResponse(responseCode,response, cookie); + } + + /** + * http post请求,请求参数形式为form-data, 可以设置请求头 + * @param url 请求链接地址 + * @param params 请求参数 + */ + public static HttpResponse postFormData(String url, + Map params, + Map headers) throws Exception { + URL urlObj = new URL(url); + HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); + con.setDoOutput(true); + con.setDoInput(true); + con.setRequestMethod(REQUEST_METHOD_POST); + con.setConnectTimeout(CONNECT_TIME_OUT); + con.setRequestProperty("Content-Type", CONTENT_TYPE_URL_ENCODED); + //设置请求头 + for(Entry entry : headers.entrySet()) { + String key = entry.getKey(); + String value = String.valueOf(entry.getValue()); + con.setRequestProperty(key, value); + } + con.connect(); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream()); + String postParam = buildPostFormOrUrlEncodedParams(params); + outputStreamWriter.write(postParam); + outputStreamWriter.flush(); + BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); + int responseCode = con.getResponseCode(); + String response = writeResponse(responseCode,br); + outputStreamWriter.close(); + br.close(); + String cookie = con.getHeaderField("Set-Cookie"); + con.disconnect(); + return new HttpResponse(responseCode,response, cookie); + } + + private static String buildPostFormOrUrlEncodedParams(Map params) throws Exception { + StringBuilder postParamBuilder = new StringBuilder(); + if(params != null && !params.isEmpty()) { + for (Entry entry : params.entrySet()) { + if(entry.getValue() == null) { + continue; + } + String value = URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"); + postParamBuilder.append(entry.getKey()).append("=").append(value).append("&"); + } + postParamBuilder.deleteCharAt(postParamBuilder.length() - 1); + } + return postParamBuilder.toString(); + } + + + private static String buildGetRequestParams(String url, Map params) throws Exception { + StringBuilder sb = new StringBuilder(url); + if(params != null && !params.isEmpty()) { + sb.append("?"); + for (Entry entry : params.entrySet()) { + if(entry.getValue() == null) { + continue; + } + String value = URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"); + sb.append(entry.getKey()).append("=").append(value).append("&"); + } + sb.deleteCharAt(sb.length() - 1); + } + return sb.toString(); + } + + + private static String writeResponse(int responseCode, BufferedReader br) throws Exception { + StringBuilder responseSb = new StringBuilder(); + String response; + if(responseCode >=200 && responseCode <300) { + String line; + while ((line = br.readLine()) != null) { + responseSb.append(line).append("\n"); + } + response = responseSb.toString(); + br.close(); + }else { + response = responseSb.toString(); + } + return response; + } + + public static class HttpResponse { + + private int statusCode; + + private String body; + + private String cookie; + + public String getCookie() { + return cookie; + } + + public void setCookie(String cookie) { + this.cookie = cookie; + } + + public HttpResponse(int statusCode, String body){ + this.statusCode = statusCode; + this.body = body; + } + + public HttpResponse(int statusCode, String body, String cookie){ + this.statusCode = statusCode; + this.body = body; + this.cookie = cookie; + } + + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public boolean isSuccess(){ + return this.statusCode >= 200 && this.statusCode < 300; + } + + @Override + public String toString() { + return "{\n\tstatusCode:" + statusCode + ",\n\tbody:" + body + "}"; + } + + } +} diff --git a/src/main/java/com/ruoyi/system/util/ImageUtil.java b/src/main/java/com/ruoyi/system/util/ImageUtil.java new file mode 100644 index 0000000..2b75837 --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/ImageUtil.java @@ -0,0 +1,163 @@ +package com.ruoyi.system.util;//package com.zy.util; +// +//import com.alibaba.fastjson.JSONObject; +//import io.netty.util.internal.StringUtil; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.beans.factory.annotation.Value; +//import org.springframework.data.redis.core.RedisTemplate; +//import org.springframework.stereotype.Component; +// +//import javax.imageio.ImageIO; +//import javax.swing.*; +//import java.awt.*; +//import java.awt.image.BufferedImage; +//import java.io.*; +//import java.net.HttpURLConnection; +//import java.net.URL; +//import java.util.Base64; +//import java.util.HashMap; +//import java.util.Map; +// +// +//@Component +//public class ImageUtil { +// +// @Autowired +// private RedisTemplate redisTemplate; +// +// private static final String BAIDU_TOKEN_KEY = "baidu-access-token"; +// +// @Value("${baidu.develop.auth.url}") +// private String authUrl; +// +// @Value("${baidu.develop.clientId}") +// private String clientId; +// +// @Value("${baidu.develop.clientSecret}") +// private String clientSecret; +// +// @Value("${baidu.develop.splitBody.url}") +// private String splitBodyUrl; +// +// public BufferedImage getBodyOutline(BufferedImage image, InputStream inputStream) throws Exception { +// //调用百度api进行人像分割 +// String base64 = this.bodySeg(inputStream); +// JSONObject resultJson = JSONObject.parseObject(base64); +// //将结果转换为黑白剪影(二值图) +// return this.convert(resultJson.getString("labelmap"), image.getWidth(), image.getHeight()); +// } +// +// public String bodySeg(InputStream inputStream) throws Exception{ +// System.out.println("开始请求百度人体分割api"); +// long start = System.currentTimeMillis(); +// String imgStr = this.convertFileToBase64(inputStream); +// String accessToken = redisTemplate.opsForValue().get(BAIDU_TOKEN_KEY); +// if(StringUtil.isNullOrEmpty(accessToken)){ +// accessToken = this.getAuth(); +// redisTemplate.opsForValue().set(BAIDU_TOKEN_KEY, accessToken); +// } +// Map params = new HashMap<>(); +// params.put("image", imgStr); +// splitBodyUrl += "?access_token=" + accessToken; +// HttpUtil.HttpResponse result = HttpUtil.postUrlEncoded(splitBodyUrl, params); +// System.out.println("请求结束,总时间(s)为:" +( (System.currentTimeMillis() - start)/ 1000F)); +// return result.getBody(); +// } +// +// /** +// * 灰度图转为纯黑白图 +// */ +// public BufferedImage convert(String labelmapBase64, int realWidth, int realHeight) { +// try { +// byte[] bytes = Base64.getDecoder().decode(labelmapBase64); +// InputStream is = new ByteArrayInputStream(bytes); +// BufferedImage image = ImageIO.read(is); +// BufferedImage newImage = resize(image, realWidth, realHeight); +// BufferedImage grayImage = new BufferedImage(realWidth, realHeight, BufferedImage.TYPE_BYTE_BINARY); +// for (int i = 0; i < realWidth; i++) { +// for (int j = 0; j < realHeight; j++) { +// int rgb = newImage.getRGB(i, j); +// grayImage.setRGB(i, j, rgb * 255); //将像素存入缓冲区 +// } +// } +// return grayImage; +// } catch (IOException e) { +// e.printStackTrace(); +// } +// return null; +// } +// +// public static BufferedImage resize(BufferedImage img, int newW, int newH) { +// Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH); +// BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB); +// Graphics2D g2d = dimg.createGraphics(); +// g2d.drawImage(tmp, 0, 0, null); +// g2d.dispose(); +// return dimg; +// } +// +// public String convertFileToBase64(InputStream inputStream) { +// byte[] data = null; +// // 读取图片字节数组 +// try { +// data = new byte[inputStream.available()]; +// inputStream.read(data); +// inputStream.close(); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// // 对字节数组进行Base64编码,得到Base64编码的字符串 +//// BASE64Encoder encoder = new BASE64Encoder(); +//// return encoder.encode(data); +// return org.apache.commons.codec.binary.Base64.encodeBase64String(data); +// } +// +// /** +// * 百度获取Token +// */ +// private String getAuth() throws Exception{ +// // 获取token地址 +// StringBuilder sb = new StringBuilder(authUrl); +// sb.append("?grant_type=client_credentials").append("&client_id=" + clientId).append("&client_secret=" + clientSecret); +// URL realUrl = new URL(sb.toString()); +// // 打开和URL之间的连接 +// HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); +// connection.setRequestMethod("GET"); +// connection.connect(); +// // 定义 BufferedReader输入流来读取URL的响应 +// BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); +// String result = ""; +// String line; +// while ((line = in.readLine()) != null) { +// result += line; +// } +// JSONObject jsonObject = JSONObject.parseObject(result); +// return jsonObject.getString("access_token"); +// } +// +// public void transferAlpha(File file, File outputFile) throws Exception{ +// InputStream is = new FileInputStream(file); +// Image image = ImageIO.read(is); +// ImageIcon imageIcon = new ImageIcon(image); +// BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(), +// BufferedImage.TYPE_4BYTE_ABGR); +// Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); +// g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver()); +// int alpha = 0; +// for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) { +// for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) { +// int rgb = bufferedImage.getRGB(j2, j1); +// int R = (rgb & 0xff0000) >> 16; +// int G = (rgb & 0xff00) >> 8; +// int B = (rgb & 0xff); +// if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) { +// rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff); +// } +// bufferedImage.setRGB(j2, j1, rgb); +// } +// } +// g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver()); +// // 输出文件 +// ImageIO.write(bufferedImage, "png", outputFile); +// } +//} diff --git a/src/main/java/com/ruoyi/system/util/IpUtil.java b/src/main/java/com/ruoyi/system/util/IpUtil.java new file mode 100644 index 0000000..1cea8df --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/IpUtil.java @@ -0,0 +1,61 @@ +package com.ruoyi.system.util; + +import javax.servlet.http.HttpServletRequest; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.util.Enumeration; + +/** + * IP工具类 + */ +public class IpUtil { + + public static String getIP(HttpServletRequest httpServletRequest) { + String ip = httpServletRequest.getHeader("X-Forwarded-For"); + if (ip != null && !"".equals(ip.trim())) { + int index = ip.indexOf(","); + if (index != -1) { + ip = ip.substring(0, index); + } + return ip; + } else { + ip = httpServletRequest.getHeader("X-Real-IP"); + if (ip == null || "".equals(ip.trim())) { + ip = httpServletRequest.getRemoteAddr(); + } + return ip; + } + } + + public static String getLocalAddress() { + try { + InetAddress candidateAddress = null; + Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); + while (ifaces.hasMoreElements()) { + NetworkInterface iface = ifaces.nextElement(); + Enumeration inetAddrs = iface.getInetAddresses(); + + while (inetAddrs.hasMoreElements()) { + InetAddress inetAddr = inetAddrs.nextElement(); + if (!inetAddr.isLoopbackAddress()) { + if (inetAddr.isSiteLocalAddress()) { + return inetAddr.getHostAddress(); + } + + if (candidateAddress == null) { + candidateAddress = inetAddr; + } + } + } + } + if (candidateAddress != null) { + return candidateAddress.getHostAddress(); + } else { + InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); + return jdkSuppliedAddress.getHostAddress(); + } + } catch (Exception var5) { + return "unkown"; + } + } +} \ No newline at end of file diff --git a/src/main/java/com/ruoyi/system/util/JsonResponse.java b/src/main/java/com/ruoyi/system/util/JsonResponse.java new file mode 100644 index 0000000..95d2fcc --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/JsonResponse.java @@ -0,0 +1,61 @@ +package com.ruoyi.system.util; + +public class JsonResponse { + + private String code; + + private String msg; + + private T data; + + public JsonResponse(String code, String msg){ + this.code = code; + this.msg = msg; + } + + public JsonResponse(T data){ + this.data = data; + msg = "成功"; + code = "0"; + } + + public static JsonResponse success(){ + return new JsonResponse<>(null); + } + + public static JsonResponse success(String data){ + return new JsonResponse<>(data); + } + + public static JsonResponse fail(){ + return new JsonResponse<>("1", "失败"); + } + + public static JsonResponse fail(String code, String msg){ + return new JsonResponse<>(code, msg); + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } +} diff --git a/src/main/java/com/ruoyi/system/util/MD5Util.java b/src/main/java/com/ruoyi/system/util/MD5Util.java new file mode 100644 index 0000000..891d5ea --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/MD5Util.java @@ -0,0 +1,64 @@ +package com.ruoyi.system.util; + +import org.apache.commons.codec.digest.DigestUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; + +/** + * MD5加密 + * 单向加密算法 + * 特点:加密速度快,不需要秘钥,但是安全性不高,需要搭配随机盐值使用 + * + */ +public class MD5Util { + + public static String sign(String content, String salt, String charset) { + content = content + salt; + return DigestUtils.md5Hex(getContentBytes(content, charset)); + } + + public static boolean verify(String content, String sign, String salt, String charset) { + content = content + salt; + String mysign = DigestUtils.md5Hex(getContentBytes(content, charset)); + return mysign.equals(sign); + } + + private static byte[] getContentBytes(String content, String charset) { + if (!"".equals(charset)) { + try { + return content.getBytes(charset); + } catch (UnsupportedEncodingException var3) { + throw new RuntimeException("MD5签名过程中出现错误,指定的编码集错误"); + } + } else { + return content.getBytes(); + } + } + + //获取文件md5加密后的字符串 + public static String getFileMD5(MultipartFile file) throws Exception { + InputStream fis = file.getInputStream(); + //用字节输出流对文件进行输出 + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int byteRead; + //while读取文件内容 + while((byteRead = fis.read(buffer)) > 0){ + baos.write(buffer, 0, byteRead); + } + fis.close(); + //对文件字节流进行md5加密 + //本质:对字节数组进行md5加密,然后返回一个字符串 + return DigestUtils.md5Hex(baos.toByteArray()); + } + + public static void main(String[] args) { + String charset = "UTF-8"; + String jm = sign("12345","test",charset); + System.out.println( sign("12345","test",charset)); + + } +} \ No newline at end of file diff --git a/src/main/java/com/ruoyi/system/util/RSAUtil.java b/src/main/java/com/ruoyi/system/util/RSAUtil.java new file mode 100644 index 0000000..4ed0332 --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/RSAUtil.java @@ -0,0 +1,127 @@ +package com.ruoyi.system.util; + +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.Cipher; +import java.nio.charset.StandardCharsets; +import java.security.*; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +/** + * RSA加密 + * 非对称加密,有公钥和私钥之分,公钥用于数据加密,私钥用于数据解密。加密结果可逆 + * 公钥一般提供给外部进行使用,私钥需要放置在服务器端保证安全性。 + * 特点:加密安全性很高,但是加密速度较慢 + * + */ +public class RSAUtil { + + private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQk33iNdA8Iey7J6XrBsidqn6u8EDLWPHsfEUgLQ3qiTikhPKDTzZkpAfU/O0x6NvSKa7Dp0+uqWT3vnW1De0+3u8mCYdVfOdH94VG4xg5U5UrRJei8HhPiXuvKQ+6NBtebCCW5adZ4pBgOiU14cJLhVmm+dYiLo3IDD5LqrlomQIDAQAB"; + + private static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJCTfeI10Dwh7LsnpesGyJ2qfq7wQMtY8ex8RSAtDeqJOKSE8oNPNmSkB9T87THo29IprsOnT66pZPe+dbUN7T7e7yYJh1V850f3hUbjGDlTlStEl6LweE+Je68pD7o0G15sIJblp1nikGA6JTXhwkuFWab51iIujcgMPkuquWiZAgMBAAECgYA1UT9mciQWWQh9yNRmhXzssFjB2TZ8B5RIe1fe0t7D9NEf0yvAgzDzEo8U3CX5dv/CVL7vxr8bEbt7phCwsa8hJiLEOr7hLZaJzXVTbvfqb91oCZGNkqDQ3NJfGBMVgUmltEYF2Bbk3U0NDyat+Gu54tRd2OH+adJYKsD0XYeDBQJBAN5FE8E04A4FA1q8mQbVTSVJDYIEJwOrdC0r3iZ7za5CyXGk+br8pFalRePFaksRGdN32+mYhDKVNrNHspAObVMCQQCmhBsD+xiWrmpnrzeIfCW1cX8qRC3/RMkq0ACw3l6YedNFdN2Tb5WsRHmcbCI9y8mfLHiG/X1R+zHZKG67EKjjAkAmvAkGSY2mQ89i160fWLq5/bIh71FRPWbgnF15fWfJr4/lgyeWI4MMKn80g2nTrSZACQpE+jRHkGNY+OywWCNLAkEAli5nvztkfeJpDYK2b16pE/B9ZL2BTs3XMcnQFbU5VAPsTKSOgz8MmwZXOIE+kMWP3wPY4McXlC0eVGFnHUh1SQJAeAl3RPk+XbZDMYfPkStRJwocG9Ap+88mwTgR1I7uPzZ1aM84/WsQskiVMXv2SZLmMWvYtnhIKosL6IACp2AcDA=="; + + public static void main(String[] args) throws Exception{ + String str = RSAUtil.encrypt("123456"); + System.out.println(str); + } + + public static String getPublicKeyStr(){ + return PUBLIC_KEY; + } + + public static RSAPublicKey getPublicKey() throws Exception { + byte[] decoded = Base64.decodeBase64(PUBLIC_KEY); + return (RSAPublicKey) KeyFactory.getInstance("RSA") + .generatePublic(new X509EncodedKeySpec(decoded)); + } + + public static RSAPrivateKey getPrivateKey() throws Exception { + byte[] decoded = Base64.decodeBase64(PRIVATE_KEY); + return (RSAPrivateKey) KeyFactory.getInstance("RSA") + .generatePrivate(new PKCS8EncodedKeySpec(decoded)); + } + + public static RSAKey generateKeyPair() throws NoSuchAlgorithmException { + KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); + keyPairGen.initialize(1024, new SecureRandom()); + KeyPair keyPair = keyPairGen.generateKeyPair(); + RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded())); + String privateKeyString = new String(Base64.encodeBase64(privateKey.getEncoded())); + return new RSAKey(privateKey, privateKeyString, publicKey, publicKeyString); + } + + public static String encrypt(String source) throws Exception { + byte[] decoded = Base64.decodeBase64(PUBLIC_KEY); + RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA") + .generatePublic(new X509EncodedKeySpec(decoded)); + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(1, rsaPublicKey); + return Base64.encodeBase64String(cipher.doFinal(source.getBytes(StandardCharsets.UTF_8))); + } + + public static Cipher getCipher() throws Exception { + byte[] decoded = Base64.decodeBase64(PRIVATE_KEY); + RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) KeyFactory.getInstance("RSA") + .generatePrivate(new PKCS8EncodedKeySpec(decoded)); + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(2, rsaPrivateKey); + return cipher; + } + + public static String decrypt(String text) throws Exception { + Cipher cipher = getCipher(); + byte[] inputByte = Base64.decodeBase64(text.getBytes(StandardCharsets.UTF_8)); + return new String(cipher.doFinal(inputByte)); + } + + public static class RSAKey { + private RSAPrivateKey privateKey; + private String privateKeyString; + private RSAPublicKey publicKey; + public String publicKeyString; + + public RSAKey(RSAPrivateKey privateKey, String privateKeyString, RSAPublicKey publicKey, String publicKeyString) { + this.privateKey = privateKey; + this.privateKeyString = privateKeyString; + this.publicKey = publicKey; + this.publicKeyString = publicKeyString; + } + + public RSAPrivateKey getPrivateKey() { + return this.privateKey; + } + + public void setPrivateKey(RSAPrivateKey privateKey) { + this.privateKey = privateKey; + } + + public String getPrivateKeyString() { + return this.privateKeyString; + } + + public void setPrivateKeyString(String privateKeyString) { + this.privateKeyString = privateKeyString; + } + + public RSAPublicKey getPublicKey() { + return this.publicKey; + } + + public void setPublicKey(RSAPublicKey publicKey) { + this.publicKey = publicKey; + } + + public String getPublicKeyString() { + return this.publicKeyString; + } + + public void setPublicKeyString(String publicKeyString) { + this.publicKeyString = publicKeyString; + } + } +} \ No newline at end of file diff --git a/src/main/java/com/ruoyi/system/util/RocketMQUtil.java b/src/main/java/com/ruoyi/system/util/RocketMQUtil.java new file mode 100644 index 0000000..06734ac --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/RocketMQUtil.java @@ -0,0 +1,30 @@ +package com.ruoyi.system.util; + +import org.apache.rocketmq.client.producer.DefaultMQProducer; +import org.apache.rocketmq.client.producer.SendCallback; +import org.apache.rocketmq.client.producer.SendResult; +import org.apache.rocketmq.common.message.Message; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RocketMQUtil { + + public static void syncSendMsg(DefaultMQProducer producer, Message msg) throws Exception{ + SendResult result = producer.send(msg); + System.out.println(result); + } + + public static void asyncSendMsg(DefaultMQProducer producer, Message msg) throws Exception{ + producer.send(msg, new SendCallback() { + @Override + public void onSuccess(SendResult sendResult) { + Logger logger = LoggerFactory.getLogger(RocketMQUtil.class); + logger.info("异步发送消息成功,消息id:" + sendResult.getMsgId()); + } + @Override + public void onException(Throwable e) { + e.printStackTrace(); + } + }); + } +} diff --git a/src/main/java/com/ruoyi/system/util/TokenUtil.java b/src/main/java/com/ruoyi/system/util/TokenUtil.java new file mode 100644 index 0000000..6354483 --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/TokenUtil.java @@ -0,0 +1,61 @@ +package com.ruoyi.system.util; + + +import com.auth0.jwt.JWT; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.TokenExpiredException; +import com.auth0.jwt.interfaces.DecodedJWT; +import com.auth0.jwt.interfaces.JWTVerifier; +import com.zy.exception.ConditionException; + +import java.util.Calendar; +import java.util.Date; + +public class TokenUtil { + + private static final String ISSUER = "签发者"; + public static Date getTokenExpirationTime(String token) { + DecodedJWT jwt = JWT.decode(token); + return jwt.getExpiresAt(); + } + + public static String generateToken(Long userId) throws Exception{ + Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey()); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.HOUR, 10); + return JWT.create().withKeyId(String.valueOf(userId)) + .withIssuer(ISSUER) + .withExpiresAt(calendar.getTime()) + .sign(algorithm); + } + + public static String generateRefreshToken(Long userId) throws Exception{ + Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey()); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.HOUR, 1); + return JWT.create().withKeyId(String.valueOf(userId)) + .withIssuer(ISSUER) + .withExpiresAt(calendar.getTime()) + .sign(algorithm); + } + + public static Long verifyToken(String token){ + try{ + Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey()); + JWTVerifier verifier = JWT.require(algorithm).build(); + DecodedJWT jwt = verifier.verify(token); + String userId = jwt.getKeyId(); + return Long.valueOf(userId); + }catch (TokenExpiredException e){ + throw new ConditionException("555","token过期!"); + }catch (Exception e){ + throw new ConditionException("非法用户token!"); + } + + + } + + +} diff --git a/src/main/java/com/ruoyi/system/util/Utilfast.java b/src/main/java/com/ruoyi/system/util/Utilfast.java new file mode 100644 index 0000000..92bc398 --- /dev/null +++ b/src/main/java/com/ruoyi/system/util/Utilfast.java @@ -0,0 +1,115 @@ +package com.ruoyi.system.util; + +import com.github.tobato.fastdfs.domain.conn.FdfsWebServer; +import com.github.tobato.fastdfs.domain.fdfs.StorePath; +import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray; +import com.github.tobato.fastdfs.service.FastFileStorageClient; +import org.apache.commons.io.FilenameUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; + +import java.io.*; +import java.nio.charset.StandardCharsets; + +/** + * @author: Larry + * @Date: 2023 /12 /05 / 13:04 + * @Description: + */ +@Component +public class Utilfast { + @Autowired + private FastFileStorageClient storageClient; + + @Autowired + private FdfsWebServer fdfsWebServer; + + /** + * 上传文件 + * + * @return 文件访问地址 + * @throws IOException + */ + public String upload(MultipartFile multipartFile) throws Exception { + String extName = FilenameUtils.getExtension(multipartFile.getOriginalFilename()); + StorePath storePath = storageClient.uploadImageAndCrtThumbImage(multipartFile.getInputStream(), multipartFile.getSize(), extName, null); + + return storePath.getFullPath(); + } + + /** + * 上传文件 + * @param file 文件对象 + * @return 文件访问地址 + * @throws IOException + */ + public String uploadFile(File file) throws IOException { + FileInputStream inputStream = new FileInputStream (file); + StorePath storePath = storageClient.uploadFile(inputStream,file.length(), FilenameUtils.getExtension(file.getName()),null); + inputStream.close(); + return getResAccessUrl(storePath); + } + /** + * 带输入流形式的文件上传 + * + * @param is + * @param size + * @param fileName + * @return + */ + public String uploadFileStream(InputStream is, long size, String fileName) { + StorePath path = storageClient.uploadFile(is, size, fileName, null); + return getResAccessUrl(path); + } + + /** + * 将一段字符串生成一个文件上传 + * @param content 文件内容 + * @param fileExtension + * @return + */ + public String uploadFile(String content, String fileExtension) { + byte[] buff = content.getBytes(StandardCharsets.UTF_8); + ByteArrayInputStream stream = new ByteArrayInputStream(buff); + StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null); + return getResAccessUrl(storePath); + } + + // 封装图片完整URL地址 + private String getResAccessUrl(StorePath storePath) { + String fileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath(); + return fileUrl; + } + + /** + * 下载文件 + * @param fileUrl 文件url + * @return + */ + public byte[] download(String fileUrl) { + String group = fileUrl.substring(0, fileUrl.indexOf("/")); + String path = fileUrl.substring(fileUrl.indexOf("/") + 1); + byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray()); + return bytes; + } + + /** + * 删除文件 + * @param fileUrl 文件访问地址 + * @return + */ +// public void deleteFile(String fileUrl) { +// if (StringUtils.isEmpty(fileUrl)) { +// return; +// } +// try { +// StorePath storePath = StorePath.praseFromUrl(fileUrl); +// storageClient.deleteFile(storePath.getGroup(), storePath.getPath()); +// } catch (FdfsUnsupportStorePathException e) { +// logger.warn(e.getMessage()); +// } +// } + + } +