CommonUtil.java 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. package com.backendsys.utils;
  2. import java.io.IOException;
  3. import java.net.*;
  4. import java.security.MessageDigest;
  5. import java.text.SimpleDateFormat;
  6. import java.time.LocalDateTime;
  7. import java.time.format.DateTimeFormatter;
  8. import java.util.Date;
  9. import java.util.Random;
  10. import java.util.UUID;
  11. import cn.hutool.core.date.DateUtil;
  12. import com.backendsys.exception.CustException;
  13. import jakarta.servlet.http.HttpServletRequest;
  14. import org.springframework.stereotype.Component;
  15. @Component
  16. public class CommonUtil {
  17. //@Autowired
  18. //private static TokenUtil tokenService;
  19. // 以上引用会报错:
  20. // Cannot invoke \"com.backendsys.modules.common.KLingAiConfig.Security.utils.TokenUtil.getTokenInfo(jakarta.servlet.http.HttpServletRequest)\" because \"com.backendsys.utils.CommonUtil.tokenService\" is null
  21. // 工具类无法直接用,得写 set 方法,如下:
  22. //private static TokenUtil tokenService;
  23. //@Autowired
  24. //public void setTokenService(TokenUtil tokenService) {
  25. // this.tokenService = tokenService;
  26. //}
  27. /**
  28. * 获取自身 ip
  29. * @param request
  30. */
  31. public static String getIpAddr(HttpServletRequest request) {
  32. String ipAddress = null;
  33. try {
  34. ipAddress = request.getHeader("x-forwarded-for");
  35. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  36. ipAddress = request.getHeader("Proxy-Client-IP");
  37. }
  38. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  39. ipAddress = request.getHeader("WL-Proxy-Client-IP");
  40. }
  41. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  42. ipAddress = request.getRemoteAddr();
  43. if (ipAddress.equals("127.0.0.1")) {
  44. // 根据网卡取本机配置的IP
  45. InetAddress inet = null;
  46. try {
  47. inet = InetAddress.getLocalHost();
  48. } catch (UnknownHostException e) {
  49. e.printStackTrace();
  50. }
  51. ipAddress = inet.getHostAddress();
  52. }
  53. }
  54. // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  55. if (ipAddress != null && ipAddress.length() > 15) {
  56. // "***.***.***.***".length()
  57. // = 15
  58. if (ipAddress.indexOf(",") > 0) {
  59. ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
  60. }
  61. }
  62. } catch (Exception e) {
  63. ipAddress = "";
  64. }
  65. return ipAddress;
  66. }
  67. /**
  68. * MD5
  69. */
  70. public static String MD5(String data) {
  71. try {
  72. java.security.MessageDigest md = MessageDigest.getInstance("MD5");
  73. byte[] array = md.digest(data.getBytes("UTF-8"));
  74. StringBuilder sb = new StringBuilder();
  75. for (byte item : array) {
  76. sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
  77. }
  78. return sb.toString().toUpperCase();
  79. } catch (Exception exception) {
  80. }
  81. return null;
  82. }
  83. /**
  84. * (并发有可能会重复)
  85. * 生成一个随机订单编码 ([prefix]-时间戳-3位随机数)
  86. * 例如:OR-3322113441-323
  87. */
  88. public static String generateRandomOrderCode(String prefix) {
  89. Random random = new Random();
  90. String randomNumber = String.format("%03d", random.nextInt(1000));
  91. String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
  92. return prefix + "-" + timestamp + "-" + randomNumber;
  93. }
  94. /**
  95. * (唯一UUID) 生成一个随机订单编码
  96. */
  97. public static String generateUniqueRandomOrderCode(String prefix) {
  98. String uuid = UUID.randomUUID().toString().replaceAll("-", "");
  99. return prefix + "-" + uuid.toUpperCase();
  100. }
  101. /**
  102. * 快速获得当前时间 (yyyy-MM-dd HH:mm:ss)
  103. */
  104. public static String getCurrentTime() {
  105. // 获取当前时间并格式化为 "yyyy-MM-DD HH:mm:ss" 的格式
  106. return DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
  107. }
  108. /**
  109. * 生成新的文件名 (基于当前日期时间 及 后缀名)
  110. */
  111. public static String generateFilename(String suffix) {
  112. String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
  113. // 检查suffix是否以点开头,如果没有,则添加一个点
  114. String fileSuffix = (suffix != null && !suffix.startsWith(".")) ? "." + suffix : suffix;
  115. String newFileName = timeStamp + fileSuffix;
  116. return newFileName;
  117. }
  118. /**
  119. * 根据远程地址,获得文件大小
  120. */
  121. public static Long getRemoteFileSize(String remote_url) {
  122. try {
  123. URL url = new URL(remote_url);
  124. // 获得文件元数据
  125. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  126. // 设置请求方法为HEAD,这样一般不会下载文件内容,只获取响应头
  127. connection.setRequestMethod("HEAD");
  128. // 连接到服务器
  129. connection.connect();
  130. // 获取响应头中的Content-Length属性,即文件的大小
  131. int contentLength = connection.getContentLength();
  132. return (long) contentLength;
  133. } catch (MalformedURLException e) {
  134. throw new CustException(e.getMessage());
  135. } catch (ProtocolException e) {
  136. throw new RuntimeException(e);
  137. } catch (IOException e) {
  138. throw new RuntimeException(e);
  139. }
  140. }
  141. }