CommonUtil.java 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. package com.template.common.utils;
  2. import com.auth0.jwt.JWT;
  3. import com.auth0.jwt.interfaces.Claim;
  4. import com.auth0.jwt.interfaces.DecodedJWT;
  5. import com.template.model.pojo.RepairAdmin;
  6. import com.template.model.pojo.SmartDataSourceLog;
  7. import com.template.model.result.CommonResult;
  8. import lombok.extern.slf4j.Slf4j;
  9. import javax.servlet.http.HttpServletRequest;
  10. import java.net.InetAddress;
  11. import java.net.UnknownHostException;
  12. import java.security.MessageDigest;
  13. import java.time.LocalDate;
  14. import java.time.LocalDateTime;
  15. import java.time.LocalTime;
  16. import java.util.*;
  17. import java.util.regex.Matcher;
  18. import java.util.regex.Pattern;
  19. /**
  20. * 公共工具类
  21. **/
  22. @Slf4j
  23. public class CommonUtil {
  24. /**
  25. * 检测客户端参数
  26. *
  27. * @param code 状态码
  28. * @param object 对象
  29. * @return 返回类型
  30. */
  31. public static Map<String, Object> getReturnMap(String code, Object object) {
  32. Map<String, Object> returnMap = new HashMap<>();
  33. returnMap.put("code", code);
  34. returnMap.put("msg", object);
  35. return returnMap;
  36. }
  37. /**
  38. * 生成日志对象
  39. *
  40. * @param str 字符串
  41. * @param httpServletRequest 请求对象
  42. * @return 返回对象
  43. */
  44. public static SmartDataSourceLog generateLog(String str, HttpServletRequest httpServletRequest) {
  45. String serverIp = null;
  46. try {
  47. serverIp = InetAddress.getLocalHost().getHostAddress();
  48. } catch (UnknownHostException e) {
  49. throw new RuntimeException(e);
  50. }
  51. String clientIp = httpServletRequest.getRemoteAddr();
  52. String token = httpServletRequest.getHeader("Authorization");
  53. String account;
  54. if (token != null) {
  55. Map<String, Claim> map = JWT.decode(token).getClaims();
  56. account = map.get("account").asString();
  57. } else {
  58. account = "";
  59. }
  60. String[] splitArr = str.split("\\|");
  61. SmartDataSourceLog smartDataSourceLog = new SmartDataSourceLog();
  62. smartDataSourceLog.setLogActionName(splitArr[0]);
  63. smartDataSourceLog.setLogActionHost(serverIp);
  64. smartDataSourceLog.setLogActionModule(splitArr[1]);
  65. smartDataSourceLog.setLogActionBusiness(splitArr[2]);
  66. smartDataSourceLog.setLogActionPeople(account);
  67. smartDataSourceLog.setLogActionRemote(clientIp);
  68. smartDataSourceLog.setLogActionClass(splitArr[3]);
  69. return smartDataSourceLog;
  70. }
  71. public static String getNumberFromString(String string) {
  72. Pattern pattern = Pattern.compile("\\d+");
  73. Matcher matcher = pattern.matcher(string);
  74. if (matcher.find()) {
  75. return matcher.group();
  76. }
  77. return null;
  78. }
  79. /**
  80. * 获取ip
  81. *
  82. * @param request
  83. * @return
  84. */
  85. public static String getIpAddr(HttpServletRequest request) {
  86. String ipAddress = null;
  87. try {
  88. ipAddress = request.getHeader("x-forwarded-for");
  89. System.out.println("x-forwarded-for=" + ipAddress);
  90. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  91. ipAddress = request.getHeader("Proxy-Client-IP");
  92. System.out.println("Proxy-Client-IP=" + ipAddress);
  93. }
  94. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  95. ipAddress = request.getHeader("WL-Proxy-Client-IP");
  96. System.out.println("WL-Proxy-Client-IP=" + ipAddress);
  97. }
  98. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  99. ipAddress = request.getRemoteAddr();
  100. System.out.println("getRemoteAddr=" + ipAddress);
  101. if (ipAddress.equals("127.0.0.1")) {
  102. // 根据网卡取本机配置的IP
  103. InetAddress inet = null;
  104. try {
  105. inet = InetAddress.getLocalHost();
  106. } catch (UnknownHostException e) {
  107. e.printStackTrace();
  108. }
  109. ipAddress = inet.getHostAddress();
  110. System.out.println("getHostAddress=" + ipAddress);
  111. }
  112. }
  113. // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  114. if (ipAddress != null && ipAddress.length() > 15) {
  115. // "***.***.***.***".length()
  116. // = 15
  117. if (ipAddress.indexOf(",") > 0) {
  118. ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
  119. }
  120. }
  121. } catch (Exception e) {
  122. ipAddress = "";
  123. }
  124. return ipAddress;
  125. }
  126. /**
  127. * 获取全部请求头
  128. *
  129. * @param request
  130. * @return
  131. */
  132. public static Map<String, String> getAllRequestHeader(HttpServletRequest request) {
  133. Enumeration<String> headerNames = request.getHeaderNames();
  134. Map<String, String> map = new HashMap<>();
  135. while (headerNames.hasMoreElements()) {
  136. String key = headerNames.nextElement();
  137. //根据名称获取请求头的值
  138. String value = request.getHeader(key);
  139. map.put(key, value);
  140. }
  141. return map;
  142. }
  143. /**
  144. * MD5加密
  145. *
  146. * @param data
  147. * @return
  148. */
  149. public static String MD5(String data) {
  150. try {
  151. MessageDigest md = MessageDigest.getInstance("MD5");
  152. byte[] array = md.digest(data.getBytes("UTF-8"));
  153. StringBuilder sb = new StringBuilder();
  154. for (byte item : array) {
  155. sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
  156. }
  157. return sb.toString().toUpperCase();
  158. } catch (Exception exception) {
  159. }
  160. return null;
  161. }
  162. /**
  163. * 获取验证码随机数
  164. *
  165. * @param length
  166. * @return
  167. */
  168. public static String getRandomCode(int length) {
  169. String sources = "0123456789";
  170. Random random = new Random();
  171. StringBuilder sb = new StringBuilder();
  172. for (int j = 0; j < length; j++) {
  173. sb.append(sources.charAt(random.nextInt(9)));
  174. }
  175. return sb.toString();
  176. }
  177. /**
  178. * 获取当前时间戳
  179. *
  180. * @return
  181. */
  182. public static long getCurrentTimestamp() {
  183. return System.currentTimeMillis();
  184. }
  185. /**
  186. * 生成uuid
  187. *
  188. * @return
  189. */
  190. public static String generateUUID() {
  191. return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
  192. }
  193. /**
  194. * 获取随机长度的串
  195. *
  196. * @param length
  197. * @return
  198. */
  199. private static final String ALL_CHAR_NUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  200. public static String getStringNumRandom(int length) {
  201. //生成随机数字和字母,
  202. Random random = new Random();
  203. StringBuilder saltString = new StringBuilder(length);
  204. for (int i = 1; i <= length; ++i) {
  205. saltString.append(ALL_CHAR_NUM.charAt(random.nextInt(ALL_CHAR_NUM.length())));
  206. }
  207. return saltString.toString();
  208. }
  209. /**
  210. * LocalDate 拼接时间转成 LocalDateTime
  211. *
  212. * @param localDate
  213. * @param timeStr HH:mm:ss
  214. * @return
  215. */
  216. public static LocalDateTime localDateToTime(LocalDate localDate, String timeStr) {
  217. LocalTime time = LocalTime.parse(timeStr);
  218. return LocalDateTime.of(localDate.getYear(), localDate.getMonth(), localDate.getDayOfMonth(),
  219. time.getHour(), time.getMinute(), time.getSecond());
  220. }
  221. }