StringUtils.java 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /*
  2. * Copyright 2019-2020 Zheng Jie
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package me.zhengjie.utils;
  17. import cn.hutool.http.HttpUtil;
  18. import cn.hutool.json.JSONObject;
  19. import cn.hutool.json.JSONUtil;
  20. import lombok.extern.slf4j.Slf4j;
  21. import me.zhengjie.config.ElAdminProperties;
  22. import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
  23. import net.dreamlu.mica.ip2region.core.IpInfo;
  24. import nl.basjes.parse.useragent.UserAgent;
  25. import nl.basjes.parse.useragent.UserAgentAnalyzer;
  26. import javax.servlet.http.HttpServletRequest;
  27. import java.net.InetAddress;
  28. import java.net.NetworkInterface;
  29. import java.net.UnknownHostException;
  30. import java.util.Calendar;
  31. import java.util.Date;
  32. import java.util.Enumeration;
  33. /**
  34. * @author Zheng Jie
  35. * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
  36. */
  37. @Slf4j
  38. public class StringUtils extends org.apache.commons.lang3.StringUtils {
  39. private static final char SEPARATOR = '_';
  40. private static final String UNKNOWN = "unknown";
  41. /**
  42. * 注入bean
  43. */
  44. private final static Ip2regionSearcher IP_SEARCHER = SpringContextHolder.getBean(Ip2regionSearcher.class);
  45. private static final UserAgentAnalyzer USER_AGENT_ANALYZER = UserAgentAnalyzer
  46. .newBuilder()
  47. .hideMatcherLoadStats()
  48. .withCache(10000)
  49. .withField(UserAgent.AGENT_NAME_VERSION)
  50. .build();
  51. /**
  52. * 驼峰命名法工具
  53. *
  54. * @return toCamelCase(" hello_world ") == "helloWorld"
  55. * toCapitalizeCamelCase("hello_world") == "HelloWorld"
  56. * toUnderScoreCase("helloWorld") = "hello_world"
  57. */
  58. public static String toCamelCase(String s) {
  59. if (s == null) {
  60. return null;
  61. }
  62. s = s.toLowerCase();
  63. StringBuilder sb = new StringBuilder(s.length());
  64. boolean upperCase = false;
  65. for (int i = 0; i < s.length(); i++) {
  66. char c = s.charAt(i);
  67. if (c == SEPARATOR) {
  68. upperCase = true;
  69. } else if (upperCase) {
  70. sb.append(Character.toUpperCase(c));
  71. upperCase = false;
  72. } else {
  73. sb.append(c);
  74. }
  75. }
  76. return sb.toString();
  77. }
  78. /**
  79. * 驼峰命名法工具
  80. *
  81. * @return toCamelCase(" hello_world ") == "helloWorld"
  82. * toCapitalizeCamelCase("hello_world") == "HelloWorld"
  83. * toUnderScoreCase("helloWorld") = "hello_world"
  84. */
  85. public static String toCapitalizeCamelCase(String s) {
  86. if (s == null) {
  87. return null;
  88. }
  89. s = toCamelCase(s);
  90. return s.substring(0, 1).toUpperCase() + s.substring(1);
  91. }
  92. /**
  93. * 驼峰命名法工具
  94. *
  95. * @return toCamelCase(" hello_world ") == "helloWorld"
  96. * toCapitalizeCamelCase("hello_world") == "HelloWorld"
  97. * toUnderScoreCase("helloWorld") = "hello_world"
  98. */
  99. static String toUnderScoreCase(String s) {
  100. if (s == null) {
  101. return null;
  102. }
  103. StringBuilder sb = new StringBuilder();
  104. boolean upperCase = false;
  105. for (int i = 0; i < s.length(); i++) {
  106. char c = s.charAt(i);
  107. boolean nextUpperCase = true;
  108. if (i < (s.length() - 1)) {
  109. nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
  110. }
  111. if ((i > 0) && Character.isUpperCase(c)) {
  112. if (!upperCase || !nextUpperCase) {
  113. sb.append(SEPARATOR);
  114. }
  115. upperCase = true;
  116. } else {
  117. upperCase = false;
  118. }
  119. sb.append(Character.toLowerCase(c));
  120. }
  121. return sb.toString();
  122. }
  123. /**
  124. * 获取ip地址
  125. */
  126. public static String getIp(HttpServletRequest request) {
  127. String ip = request.getHeader("x-forwarded-for");
  128. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  129. ip = request.getHeader("Proxy-Client-IP");
  130. }
  131. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  132. ip = request.getHeader("WL-Proxy-Client-IP");
  133. }
  134. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  135. ip = request.getRemoteAddr();
  136. }
  137. String comma = ",";
  138. String localhost = "127.0.0.1";
  139. if (ip.contains(comma)) {
  140. ip = ip.split(",")[0];
  141. }
  142. if (localhost.equals(ip)) {
  143. // 获取本机真正的ip地址
  144. try {
  145. ip = InetAddress.getLocalHost().getHostAddress();
  146. } catch (UnknownHostException e) {
  147. log.error(e.getMessage(), e);
  148. }
  149. }
  150. return ip;
  151. }
  152. /**
  153. * 根据ip获取详细地址
  154. */
  155. public static String getCityInfo(String ip) {
  156. if (ElAdminProperties.ipLocal) {
  157. return getLocalCityInfo(ip);
  158. } else {
  159. return getHttpCityInfo(ip);
  160. }
  161. }
  162. /**
  163. * 根据ip获取详细地址
  164. */
  165. public static String getHttpCityInfo(String ip) {
  166. String api = String.format(ElAdminConstant.Url.IP_URL, ip);
  167. JSONObject object = JSONUtil.parseObj(HttpUtil.get(api));
  168. return object.get("addr", String.class);
  169. }
  170. /**
  171. * 根据ip获取详细地址
  172. */
  173. public static String getLocalCityInfo(String ip) {
  174. IpInfo ipInfo = IP_SEARCHER.memorySearch(ip);
  175. if(ipInfo != null){
  176. return ipInfo.getAddress();
  177. }
  178. return null;
  179. }
  180. public static String getBrowser(HttpServletRequest request) {
  181. UserAgent.ImmutableUserAgent userAgent = USER_AGENT_ANALYZER.parse(request.getHeader("User-Agent"));
  182. return userAgent.get(UserAgent.AGENT_NAME_VERSION).getValue();
  183. }
  184. /**
  185. * 获得当天是周几
  186. */
  187. public static String getWeekDay() {
  188. String[] weekDays = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  189. Calendar cal = Calendar.getInstance();
  190. cal.setTime(new Date());
  191. int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
  192. if (w < 0) {
  193. w = 0;
  194. }
  195. return weekDays[w];
  196. }
  197. /**
  198. * 获取当前机器的IP
  199. *
  200. * @return /
  201. */
  202. public static String getLocalIp() {
  203. try {
  204. InetAddress candidateAddress = null;
  205. // 遍历所有的网络接口
  206. for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
  207. NetworkInterface anInterface = interfaces.nextElement();
  208. // 在所有的接口下再遍历IP
  209. for (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses(); inetAddresses.hasMoreElements();) {
  210. InetAddress inetAddr = inetAddresses.nextElement();
  211. // 排除loopback类型地址
  212. if (!inetAddr.isLoopbackAddress()) {
  213. if (inetAddr.isSiteLocalAddress()) {
  214. // 如果是site-local地址,就是它了
  215. return inetAddr.getHostAddress();
  216. } else if (candidateAddress == null) {
  217. // site-local类型的地址未被发现,先记录候选地址
  218. candidateAddress = inetAddr;
  219. }
  220. }
  221. }
  222. }
  223. if (candidateAddress != null) {
  224. return candidateAddress.getHostAddress();
  225. }
  226. // 如果没有发现 non-loopback地址.只能用最次选的方案
  227. InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
  228. if (jdkSuppliedAddress == null) {
  229. return "";
  230. }
  231. return jdkSuppliedAddress.getHostAddress();
  232. } catch (Exception e) {
  233. return "";
  234. }
  235. }
  236. }