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