CommonUtil.java 8.2 KB

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