Tools.java 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package com.nuliji.tools;
  2. import org.apache.commons.codec.binary.Base64;
  3. import org.dom4j.Document;
  4. import org.dom4j.DocumentException;
  5. import org.dom4j.DocumentHelper;
  6. import org.dom4j.Element;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import javax.crypto.Mac;
  10. import javax.crypto.SecretKey;
  11. import javax.crypto.spec.SecretKeySpec;
  12. import javax.servlet.http.HttpServletRequest;
  13. import java.io.UnsupportedEncodingException;
  14. import java.security.InvalidKeyException;
  15. import java.security.MessageDigest;
  16. import java.security.NoSuchAlgorithmException;
  17. import java.util.*;
  18. /**
  19. * Created by gaojie on 2017/11/9.
  20. */
  21. public class Tools {
  22. private static final Logger logger = LoggerFactory.getLogger(Tools.class);
  23. protected static Random random = new Random();
  24. public static String stringMD5(String str) {
  25. return byteArrayToHexString(getMd5(str));
  26. }
  27. public static String stringSha1(String str) {
  28. return byteArrayToHexString(getSha1(str));
  29. }
  30. public static int getRandom() {
  31. return random.nextInt(999999)%900000+100000;
  32. }
  33. public static String getRandomString(int length){
  34. String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  35. Random random=new Random();
  36. StringBuffer sb=new StringBuffer();
  37. for(int i=0;i<length;i++){
  38. int number=random.nextInt(62);
  39. sb.append(str.charAt(number));
  40. }
  41. return sb.toString();
  42. }
  43. /**
  44. * 取得指定月份的最大天数
  45. *
  46. * @param date 月份,格式yyyy-MM
  47. * @return
  48. */
  49. public static int getMonthDays(String date) {
  50. Calendar calendar = Calendar.getInstance();
  51. calendar.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)));
  52. calendar.set(Calendar.MONTH, Integer.parseInt(date.substring(5, 7)) - 1);
  53. int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
  54. return maxDay;
  55. }
  56. public static int getDayOfMonth(Date date) {
  57. Calendar calendar = Calendar.getInstance();
  58. calendar.setTime(date);
  59. return calendar.get(Calendar.DAY_OF_MONTH);
  60. }
  61. public static int getDayOfWeek(Date date){
  62. Calendar calendar = Calendar.getInstance();
  63. calendar.setTime(date);
  64. return calendar.get(Calendar.DAY_OF_WEEK);
  65. }
  66. public static byte[] getMd5(String str) {
  67. try {
  68. MessageDigest md = MessageDigest.getInstance("MD5");
  69. md.update(str.getBytes("utf-8"));
  70. return md.digest();
  71. } catch (Exception e) {
  72. System.out.println(e);
  73. }
  74. return null;
  75. }
  76. public static byte[] getSha1(String str){
  77. try {
  78. MessageDigest md = MessageDigest.getInstance("SHA-1");
  79. md.update(str.getBytes("utf-8"));
  80. return md.digest();
  81. } catch (Exception e) {
  82. System.out.println(e);
  83. }
  84. return null;
  85. }
  86. public static byte[] getHmacSha1(String str, String key){
  87. try {
  88. byte[] data=key.getBytes("utf-8");
  89. //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
  90. SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
  91. //生成一个指定 Mac 算法 的 Mac 对象
  92. Mac mac = Mac.getInstance("HmacSHA1");
  93. //用给定密钥初始化 Mac 对象
  94. mac.init(secretKey);
  95. byte[] text = str.getBytes("utf-8");
  96. //完成 Mac 操作
  97. return mac.doFinal(text);
  98. } catch (NoSuchAlgorithmException e) {
  99. e.printStackTrace();
  100. } catch (UnsupportedEncodingException e) {
  101. e.printStackTrace();
  102. } catch (InvalidKeyException e) {
  103. e.printStackTrace();
  104. }
  105. return null;
  106. }
  107. public static String byteArrayToHexString(byte[] b) {
  108. String ret = "";
  109. for (int i = 0; i < b.length; i++) {
  110. String hex = Integer.toHexString(b[i] & 255);
  111. if (hex.length() == 1) {
  112. hex = '0' + hex;
  113. }
  114. ret += hex;
  115. }
  116. return ret;
  117. }
  118. /**
  119. * @param bytes
  120. * @return
  121. */
  122. public static byte[] decodeBase64(final byte[] bytes) {
  123. return Base64.decodeBase64(bytes);
  124. }
  125. /**
  126. * @param str
  127. * @return
  128. */
  129. public static byte[] decodeBase64(final String str) {
  130. return Base64.decodeBase64(str.getBytes());
  131. }
  132. /**
  133. * 二进制数据编码为BASE64字符串
  134. *
  135. * @param bytes
  136. * @return
  137. * @throws Exception
  138. */
  139. public static String encodeBase64(final byte[] bytes) {
  140. return new String(Base64.encodeBase64(bytes));
  141. }
  142. public static String encodeBase64(final String str) {
  143. return encodeBase64(str.getBytes());
  144. }
  145. //求两个字符串数组的并集,利用set的元素唯一性
  146. public static <T> Collection<T> union(Collection<T> arr1, Collection<T> arr2) {
  147. Set<T> set = new HashSet<T>();
  148. set.addAll(arr1);
  149. set.addAll(arr2);
  150. return set;
  151. }
  152. //求两个数组的交集
  153. public static <T> Collection<T> intersect(Collection<T> arr1, Collection<T> arr2) {
  154. Map<T, Boolean> map = new HashMap<T, Boolean>();
  155. LinkedList<T> list = new LinkedList<T>();
  156. for (T str : arr1) {
  157. if (!map.containsKey(str)) {
  158. map.put(str, Boolean.FALSE);
  159. }
  160. }
  161. for (T str : arr2) {
  162. if (map.containsKey(str)) {
  163. map.put(str, Boolean.TRUE);
  164. }
  165. }
  166. for (Map.Entry<T, Boolean> e : map.entrySet()) {
  167. if (e.getValue().equals(Boolean.TRUE)) {
  168. list.add(e.getKey());
  169. }
  170. }
  171. return list;
  172. }
  173. //求两个数组的差集: 第一个不在第二个中的元素
  174. public static <T> Collection<T> minus(Collection<T> arr1, Collection<T> arr2) {
  175. LinkedList<T> list = new LinkedList<T>();
  176. list.addAll(arr1);
  177. for (T str : arr2) {
  178. if (list.contains(str)) {
  179. list.remove(str);
  180. }
  181. }
  182. return list;
  183. }
  184. public static String joinIds(Collection ids) {
  185. List<String> list = new ArrayList<>();
  186. // logger.debug("join:{}", ids);
  187. if(ids == null || ids.size() == 0) return "";
  188. for (Object id : ids) {
  189. list.add(id.toString());
  190. }
  191. return String.join(",", list);
  192. }
  193. public static Collection<Long> splitIds(String ids){
  194. List<Long> l = new ArrayList<>();
  195. // logger.debug("split:{}", ids);
  196. if(ids == null || ids.length() == 0) return l;
  197. String[] list = ids.split(",");
  198. for(String s:list){
  199. l.add(Long.valueOf(s));
  200. }
  201. return l;
  202. }
  203. public static String getClientIp(HttpServletRequest request){
  204. String ipAddress = request.getHeader("x-forwarded-for");
  205. if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  206. ipAddress = request.getRemoteAddr();
  207. }
  208. //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  209. if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
  210. if(ipAddress.indexOf(",")>0){
  211. ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
  212. }
  213. }
  214. return ipAddress;
  215. }
  216. public static Date today(){
  217. Calendar calendar = Calendar.getInstance();
  218. calendar.setTime(new Date());
  219. calendar.set(Calendar.HOUR_OF_DAY, 0);
  220. calendar.set(Calendar.MINUTE, 0);
  221. calendar.set(Calendar.SECOND, 0);
  222. return calendar.getTime();
  223. }
  224. public static int year(Date date){
  225. Calendar calendar = Calendar.getInstance();
  226. calendar.setTime(date);
  227. return calendar.get(Calendar.YEAR);
  228. }
  229. public static Date addDate(Date date, int day){
  230. Calendar c = Calendar.getInstance();
  231. c.setTime(date);
  232. c.add(Calendar.DAY_OF_YEAR, day);
  233. return c.getTime();
  234. }
  235. public static Date addMonth(Date date, int month){
  236. Calendar c = Calendar.getInstance();
  237. c.setTime(date);
  238. c.add(Calendar.MONTH, month);
  239. return c.getTime();
  240. }
  241. public static Date addYear(Date date, int year){
  242. Calendar c = Calendar.getInstance();
  243. c.setTime(date);
  244. c.add(Calendar.YEAR, year);
  245. return c.getTime();
  246. }
  247. public static TreeMap<String, String> parseXml(String xml) {
  248. Document document = null;
  249. TreeMap<String, String> packageMap = new TreeMap<>();
  250. try {
  251. document = DocumentHelper.parseText(xml);
  252. } catch (DocumentException ex) {
  253. return null;
  254. }
  255. Element rootElement = document.getRootElement();
  256. for (Element element : (List<Element>) rootElement.elements()) {
  257. packageMap.put(element.getName(), element.getText());
  258. }
  259. return packageMap;
  260. }
  261. }