提交部分业务代码和工具类

pull/2/head
Larry-bird 8 months ago
parent 329b4456b9
commit 11533092e9

@ -1,6 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17 (2)" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ruoyi-study.iml" filepath="$PROJECT_DIR$/.idea/ruoyi-study.iml" />
</modules>
</component>
</project>

@ -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);
}
}

@ -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<String,String> 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;
}
}

@ -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);
}
}
}

@ -0,0 +1,4 @@
/**
* api XxxPort domain
*/
package com.ruoyi.system.adapter.port;

@ -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();
}
}

@ -0,0 +1,4 @@
/**
* domain IXxxRepository Repository
*/
package com.ruoyi.system.adapter.repository;

@ -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<GroupBuyActivity> queryGroupBuyActivityList();
GroupBuyActivity queryValidGroupBuyActivity(GroupBuyActivity groupBuyActivityReq);
}

@ -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<GroupBuyDiscount> queryGroupBuyDiscountList();
GroupBuyDiscount queryGroupBuyActivityDiscountByDiscountId(String discountId);
}

@ -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);
}

@ -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;
}

@ -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:base1:tag
*/
private Byte discountType;
/**
* ZJ:MJ:N
*/
private String marketPlan;
/**
*
*/
private String marketExpr;
/**
*
*/
private String tagId;
/**
*
*/
private Date createTime;
/**
*
*/
private Date updateTime;
}

@ -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;
}

@ -0,0 +1 @@
package com.ruoyi.system.gateway.dto;

@ -0,0 +1,4 @@
/**
* httprpc adapter
*/
package com.ruoyi.system.gateway;

@ -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<String> 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);
}
}
}

@ -0,0 +1,4 @@
/**
* redis
*/
package com.ruoyi.system.redis;

@ -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();
}
}

@ -0,0 +1,19 @@
package com.ruoyi.system.util;
public class BaseContext {
public static ThreadLocal<Long> 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();
}
}

@ -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;
}
}
}

@ -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<String, String> 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<MetaData> 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<MetaData> 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<String> 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<String> headerNames = request.getHeaderNames();
Map<String, Object> 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<String>() {
@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";
}
});
}
}

@ -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 MultipartFileFile
* @date 2023-03-12 17:31
**/
public class FileTestUtils {
/**
* MultipartFileFile
* <p>
* 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;
}
}

@ -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<String, Object> 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<String, Object> params,
Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> params,
Map<String, Object> 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<String, Object> 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 posturl-encoded
* @param url
* @param params
*/
public static HttpResponse postUrlEncoded(String url,
Map<String, Object> 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 postform-data
* @param url
* @param params
*/
public static HttpResponse postFormData(String url,
Map<String, Object> 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 postform-data
* @param url
* @param params
*/
public static HttpResponse postFormData(String url,
Map<String, Object> params,
Map<String, Object> 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<String, Object> 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<String, Object> params) throws Exception {
StringBuilder postParamBuilder = new StringBuilder();
if(params != null && !params.isEmpty()) {
for (Entry<String, Object> 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<String, Object> params) throws Exception {
StringBuilder sb = new StringBuilder(url);
if(params != null && !params.isEmpty()) {
sb.append("?");
for (Entry<String, Object> 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 + "}";
}
}
}

@ -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<String, String> 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<String, Object> 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);
// }
//}

@ -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<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
while (ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();
Enumeration<InetAddress> 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";
}
}
}

@ -0,0 +1,61 @@
package com.ruoyi.system.util;
public class JsonResponse<T> {
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<String> success(){
return new JsonResponse<>(null);
}
public static JsonResponse<String> success(String data){
return new JsonResponse<>(data);
}
public static JsonResponse<String> fail(){
return new JsonResponse<>("1", "失败");
}
public static JsonResponse<String> 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;
}
}

@ -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));
}
}

@ -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;
}
}
}

@ -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();
}
});
}
}

@ -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");
}
}
}

@ -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());
// }
// }
}
Loading…
Cancel
Save