Tools.java 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 byte[] getMd5(String str) {
  62. try {
  63. MessageDigest md = MessageDigest.getInstance("MD5");
  64. md.update(str.getBytes("utf-8"));
  65. return md.digest();
  66. } catch (Exception e) {
  67. System.out.println(e);
  68. }
  69. return null;
  70. }
  71. public static byte[] getSha1(String str){
  72. try {
  73. MessageDigest md = MessageDigest.getInstance("SHA-1");
  74. md.update(str.getBytes("utf-8"));
  75. return md.digest();
  76. } catch (Exception e) {
  77. System.out.println(e);
  78. }
  79. return null;
  80. }
  81. public static byte[] getHmacSha1(String str, String key){
  82. try {
  83. byte[] data=key.getBytes("utf-8");
  84. //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
  85. SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
  86. //生成一个指定 Mac 算法 的 Mac 对象
  87. Mac mac = Mac.getInstance("HmacSHA1");
  88. //用给定密钥初始化 Mac 对象
  89. mac.init(secretKey);
  90. byte[] text = str.getBytes("utf-8");
  91. //完成 Mac 操作
  92. return mac.doFinal(text);
  93. } catch (NoSuchAlgorithmException e) {
  94. e.printStackTrace();
  95. } catch (UnsupportedEncodingException e) {
  96. e.printStackTrace();
  97. } catch (InvalidKeyException e) {
  98. e.printStackTrace();
  99. }
  100. return null;
  101. }
  102. public static String byteArrayToHexString(byte[] b) {
  103. String ret = "";
  104. for (int i = 0; i < b.length; i++) {
  105. String hex = Integer.toHexString(b[i] & 255);
  106. if (hex.length() == 1) {
  107. hex = '0' + hex;
  108. }
  109. ret += hex;
  110. }
  111. return ret;
  112. }
  113. /**
  114. * @param bytes
  115. * @return
  116. */
  117. public static byte[] decodeBase64(final byte[] bytes) {
  118. return Base64.decodeBase64(bytes);
  119. }
  120. /**
  121. * @param str
  122. * @return
  123. */
  124. public static byte[] decodeBase64(final String str) {
  125. return Base64.decodeBase64(str.getBytes());
  126. }
  127. /**
  128. * 二进制数据编码为BASE64字符串
  129. *
  130. * @param bytes
  131. * @return
  132. * @throws Exception
  133. */
  134. public static String encodeBase64(final byte[] bytes) {
  135. return new String(Base64.encodeBase64(bytes));
  136. }
  137. public static String encodeBase64(final String str) {
  138. return encodeBase64(str.getBytes());
  139. }
  140. //求两个字符串数组的并集,利用set的元素唯一性
  141. public static <T> Collection<T> union(Collection<T> arr1, Collection<T> arr2) {
  142. Set<T> set = new HashSet<T>();
  143. set.addAll(arr1);
  144. set.addAll(arr2);
  145. return set;
  146. }
  147. //求两个数组的交集
  148. public static <T> Collection<T> intersect(Collection<T> arr1, Collection<T> arr2) {
  149. Map<T, Boolean> map = new HashMap<T, Boolean>();
  150. LinkedList<T> list = new LinkedList<T>();
  151. for (T str : arr1) {
  152. if (!map.containsKey(str)) {
  153. map.put(str, Boolean.FALSE);
  154. }
  155. }
  156. for (T str : arr2) {
  157. if (map.containsKey(str)) {
  158. map.put(str, Boolean.TRUE);
  159. }
  160. }
  161. for (Map.Entry<T, Boolean> e : map.entrySet()) {
  162. if (e.getValue().equals(Boolean.TRUE)) {
  163. list.add(e.getKey());
  164. }
  165. }
  166. return list;
  167. }
  168. //求两个数组的差集: 第一个不在第二个中的元素
  169. public static <T> Collection<T> minus(Collection<T> arr1, Collection<T> arr2) {
  170. LinkedList<T> list = new LinkedList<T>();
  171. list.addAll(arr1);
  172. for (T str : arr2) {
  173. if (list.contains(str)) {
  174. list.remove(str);
  175. }
  176. }
  177. return list;
  178. }
  179. public static String joinIds(Collection ids) {
  180. List<String> list = new ArrayList<>();
  181. // logger.debug("join:{}", ids);
  182. if(ids == null || ids.size() == 0) return "";
  183. for (Object id : ids) {
  184. list.add(id.toString());
  185. }
  186. return String.join(",", list);
  187. }
  188. public static Collection<Long> splitIds(String ids){
  189. List<Long> l = new ArrayList<>();
  190. // logger.debug("split:{}", ids);
  191. if(ids == null || ids.length() == 0) return l;
  192. String[] list = ids.split(",");
  193. for(String s:list){
  194. l.add(Long.valueOf(s));
  195. }
  196. return l;
  197. }
  198. public static String getClientIp(HttpServletRequest request){
  199. String ipAddress = request.getHeader("x-forwarded-for");
  200. if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  201. ipAddress = request.getRemoteAddr();
  202. }
  203. //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  204. if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
  205. if(ipAddress.indexOf(",")>0){
  206. ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
  207. }
  208. }
  209. return ipAddress;
  210. }
  211. public static Date today(){
  212. Calendar calendar = Calendar.getInstance();
  213. calendar.setTime(new Date());
  214. calendar.set(Calendar.HOUR_OF_DAY, 0);
  215. calendar.set(Calendar.MINUTE, 0);
  216. calendar.set(Calendar.SECOND, 0);
  217. return calendar.getTime();
  218. }
  219. public static Date addDate(Date date, int day){
  220. Calendar c = Calendar.getInstance();
  221. c.setTime(date);
  222. c.add(Calendar.DAY_OF_YEAR, day);
  223. return date;
  224. }
  225. public static TreeMap<String, String> parseXml(String xml) {
  226. Document document = null;
  227. TreeMap<String, String> packageMap = new TreeMap<>();
  228. try {
  229. document = DocumentHelper.parseText(xml);
  230. } catch (DocumentException ex) {
  231. return null;
  232. }
  233. Element rootElement = document.getRootElement();
  234. for (Element element : (List<Element>) rootElement.elements()) {
  235. packageMap.put(element.getName(), element.getText());
  236. }
  237. return packageMap;
  238. }
  239. }