FebsUtil.java 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. package cc.mrbird.febs.common.utils;
  2. import cc.mrbird.febs.common.entity.CurrentUser;
  3. import cc.mrbird.febs.common.entity.constant.PageConstant;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.baomidou.mybatisplus.core.metadata.IPage;
  6. import com.fasterxml.jackson.databind.ObjectMapper;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.apache.commons.lang3.StringUtils;
  9. import org.springframework.core.io.buffer.DataBuffer;
  10. import org.springframework.http.HttpHeaders;
  11. import org.springframework.http.HttpStatus;
  12. import org.springframework.http.server.reactive.ServerHttpRequest;
  13. import org.springframework.http.server.reactive.ServerHttpResponse;
  14. import org.springframework.security.core.Authentication;
  15. import org.springframework.security.core.GrantedAuthority;
  16. import org.springframework.security.core.context.SecurityContextHolder;
  17. import org.springframework.security.oauth2.provider.OAuth2Authentication;
  18. import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
  19. import org.springframework.web.context.request.RequestContextHolder;
  20. import org.springframework.web.context.request.ServletRequestAttributes;
  21. import reactor.core.publisher.Mono;
  22. import javax.servlet.http.HttpServletRequest;
  23. import javax.servlet.http.HttpServletResponse;
  24. import java.io.IOException;
  25. import java.util.*;
  26. import java.util.regex.Matcher;
  27. import java.util.regex.Pattern;
  28. import java.util.stream.IntStream;
  29. /**
  30. * FEBS工具类
  31. *
  32. * @author MrBird
  33. */
  34. @Slf4j
  35. public class FebsUtil {
  36. /**
  37. * 驼峰转下划线
  38. *
  39. * @param value 待转换值
  40. * @return 结果
  41. */
  42. public static String camelToUnderscore(String value) {
  43. if (StringUtils.isBlank(value))
  44. return value;
  45. String[] arr = StringUtils.splitByCharacterTypeCamelCase(value);
  46. if (arr.length == 0)
  47. return value;
  48. StringBuilder result = new StringBuilder();
  49. IntStream.range(0, arr.length).forEach(i -> {
  50. if (i != arr.length - 1)
  51. result.append(arr[i]).append("_");
  52. else
  53. result.append(arr[i]);
  54. });
  55. return StringUtils.lowerCase(result.toString());
  56. }
  57. /**
  58. * 下划线转驼峰
  59. *
  60. * @param value 待转换值
  61. * @return 结果
  62. */
  63. public static String underscoreToCamel(String value) {
  64. StringBuilder result = new StringBuilder();
  65. String[] arr = value.split("_");
  66. for (String s : arr) {
  67. result.append((String.valueOf(s.charAt(0))).toUpperCase()).append(s.substring(1));
  68. }
  69. return result.toString();
  70. }
  71. /**
  72. * 判断是否为 ajax请求
  73. *
  74. * @param request HttpServletRequest
  75. * @return boolean
  76. */
  77. public static boolean isAjaxRequest(HttpServletRequest request) {
  78. return (request.getHeader("X-Requested-With") != null
  79. && "XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
  80. }
  81. /**
  82. * 正则校验
  83. *
  84. * @param regex 正则表达式字符串
  85. * @param value 要匹配的字符串
  86. * @return 正则校验结果
  87. */
  88. public static boolean match(String regex, String value) {
  89. Pattern pattern = Pattern.compile(regex);
  90. Matcher matcher = pattern.matcher(value);
  91. return matcher.matches();
  92. }
  93. /**
  94. * 设置响应
  95. *
  96. * @param response HttpServletResponse
  97. * @param contentType content-type
  98. * @param status http状态码
  99. * @param value 响应内容
  100. * @throws IOException IOException
  101. */
  102. public static void makeResponse(HttpServletResponse response, String contentType,
  103. int status, Object value) throws IOException {
  104. response.setContentType(contentType);
  105. response.setStatus(status);
  106. response.getOutputStream().write(JSONObject.toJSONString(value).getBytes());
  107. }
  108. /**
  109. * 设置webflux模型响应
  110. *
  111. * @param response ServerHttpResponse
  112. * @param contentType content-type
  113. * @param status http状态码
  114. * @param value 响应内容
  115. * @return Mono<Void>
  116. */
  117. public static Mono<Void> makeWebFluxResponse(ServerHttpResponse response, String contentType,
  118. HttpStatus status, Object value) {
  119. response.setStatusCode(status);
  120. response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
  121. DataBuffer dataBuffer = response.bufferFactory().wrap(JSONObject.toJSONString(value).getBytes());
  122. return response.writeWith(Mono.just(dataBuffer));
  123. }
  124. /**
  125. * 封装前端分页表格所需数据
  126. *
  127. * @param pageInfo pageInfo
  128. * @return Map<String, Object>
  129. */
  130. public static Map<String, Object> getDataTable(IPage<?> pageInfo) {
  131. Map<String, Object> data = new HashMap<>();
  132. data.put(PageConstant.ROWS, pageInfo.getRecords());
  133. data.put(PageConstant.TOTAL, pageInfo.getTotal());
  134. return data;
  135. }
  136. /**
  137. * 获取HttpServletRequest
  138. *
  139. * @return HttpServletRequest
  140. */
  141. public static HttpServletRequest getHttpServletRequest() {
  142. return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
  143. }
  144. /**
  145. * 获取请求IP
  146. *
  147. * @return String IP
  148. */
  149. public static String getHttpServletRequestIpAddress() {
  150. HttpServletRequest request = getHttpServletRequest();
  151. String ip = request.getHeader("x-forwarded-for");
  152. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  153. ip = request.getHeader("Proxy-Client-IP");
  154. }
  155. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  156. ip = request.getHeader("WL-Proxy-Client-IP");
  157. }
  158. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  159. ip = request.getRemoteAddr();
  160. }
  161. return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
  162. }
  163. /**
  164. * 获取请求IP
  165. *
  166. * @param request ServerHttpRequest
  167. * @return String IP
  168. */
  169. public static String getServerHttpRequestIpAddress(ServerHttpRequest request) {
  170. HttpHeaders headers = request.getHeaders();
  171. String ip = headers.getFirst("x-forwarded-for");
  172. if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
  173. if (ip.contains(",")) {
  174. ip = ip.split(",")[0];
  175. }
  176. }
  177. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  178. ip = headers.getFirst("Proxy-Client-IP");
  179. }
  180. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  181. ip = headers.getFirst("WL-Proxy-Client-IP");
  182. }
  183. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  184. ip = headers.getFirst("HTTP_CLIENT_IP");
  185. }
  186. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  187. ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
  188. }
  189. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  190. ip = headers.getFirst("X-Real-IP");
  191. }
  192. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  193. ip = Objects.requireNonNull(request.getRemoteAddress()).getAddress().getHostAddress();
  194. }
  195. return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
  196. }
  197. /**
  198. * 判断是否包含中文
  199. *
  200. * @param value 内容
  201. * @return 结果
  202. */
  203. public static boolean containChinese(String value) {
  204. Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
  205. Matcher m = p.matcher(value);
  206. return m.find();
  207. }
  208. /**
  209. * 获取在线用户信息
  210. *
  211. * @return CurrentUser 当前用户信息
  212. */
  213. public static CurrentUser getCurrentUser() {
  214. try {
  215. LinkedHashMap<String, Object> authenticationDetails = getAuthenticationDetails();
  216. Object principal = authenticationDetails.get("principal");
  217. ObjectMapper mapper = new ObjectMapper();
  218. return mapper.readValue(mapper.writeValueAsString(principal), CurrentUser.class);
  219. } catch (Exception e) {
  220. log.error("获取当前用户信息失败", e);
  221. return null;
  222. }
  223. }
  224. /**
  225. * 获取当前用户名称
  226. *
  227. * @return String 用户名
  228. */
  229. public static String getCurrentUsername() {
  230. return (String) getOAuth2Authentication().getPrincipal();
  231. }
  232. /**
  233. * 获取当前用户权限集
  234. *
  235. * @return Collection<GrantedAuthority>权限集
  236. */
  237. public static Collection<GrantedAuthority> getCurrentUserAuthority() {
  238. return getOAuth2Authentication().getAuthorities();
  239. }
  240. /**
  241. * 获取当前令牌内容
  242. *
  243. * @return String 令牌内容
  244. */
  245. public static String getCurrentTokenValue() {
  246. OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) getOAuth2Authentication().getDetails();
  247. return details.getTokenValue();
  248. }
  249. private static OAuth2Authentication getOAuth2Authentication() {
  250. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  251. return (OAuth2Authentication) authentication;
  252. }
  253. @SuppressWarnings("all")
  254. private static LinkedHashMap<String, Object> getAuthenticationDetails() {
  255. return (LinkedHashMap<String, Object>) getOAuth2Authentication().getUserAuthentication().getDetails();
  256. }
  257. }