CommonUtil.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. package com.minpay.common.util;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4. import java.math.BigDecimal;
  5. import java.sql.Timestamp;
  6. import java.text.DecimalFormat;
  7. import java.text.ParseException;
  8. import java.text.SimpleDateFormat;
  9. import java.util.ArrayList;
  10. import java.util.Calendar;
  11. import java.util.Date;
  12. import java.util.HashMap;
  13. import java.util.List;
  14. import java.util.Map;
  15. import java.util.Random;
  16. import java.util.regex.Matcher;
  17. import java.util.regex.Pattern;
  18. import javax.servlet.http.HttpServletRequest;
  19. import org.apache.commons.lang.StringUtils;
  20. public class CommonUtil {
  21. private final static double EARTH_RADIUS = 6378.137;
  22. public static boolean isMatches(String str, String matcher){
  23. Pattern pattern = Pattern.compile(matcher);
  24. Matcher isMatches = pattern.matcher(str);
  25. if( !isMatches.matches() ){
  26. return false;
  27. }
  28. return true;
  29. }
  30. public static boolean isMoney(String str)
  31. {
  32. java.util.regex.Pattern pattern=java.util.regex.Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
  33. java.util.regex.Matcher match=pattern.matcher(str);
  34. if(match.matches()==false)
  35. {
  36. return false;
  37. }
  38. else
  39. {
  40. return true;
  41. }
  42. }
  43. /**
  44. * 格式化金额
  45. *
  46. * @param str
  47. * @return
  48. */
  49. public static String formatCurrency(String str) {
  50. if(isEmpty(str)) {
  51. return "0";
  52. }
  53. return new DecimalFormat(",###.##").format((new BigDecimal(str)).doubleValue());
  54. }
  55. /**
  56. * obj to String
  57. *
  58. * @param obj
  59. * @return
  60. */
  61. public static String objToString(Object pObject) {
  62. String strValue = "";
  63. try {
  64. strValue = pObject.toString();
  65. } catch (Exception e) {
  66. strValue = "";
  67. }
  68. if ("null".equals(strValue)) {
  69. strValue = "";
  70. }
  71. return strValue;
  72. }
  73. /**
  74. *
  75. * @param pObject
  76. * @return
  77. */
  78. public static BigDecimal objToBigDecimal(final Object pObject) {
  79. BigDecimal result = null;
  80. String str = "";
  81. if (pObject != null) {
  82. str = pObject.toString();
  83. } else {
  84. str = "";
  85. }
  86. try {
  87. if ("".equals(str)) {
  88. return new BigDecimal(0);
  89. } else {
  90. result = new BigDecimal(str);
  91. }
  92. } catch (NumberFormatException e) {
  93. return BigDecimal.ZERO;
  94. }
  95. // result = result.setScale(2, RoundingMode.HALF_UP);
  96. return result;
  97. }
  98. public static int objToint(final Object pObject) {
  99. int intReturn = 0;
  100. int intIndex = 0;
  101. try {
  102. if (pObject != null && !("".equals(pObject.toString().trim()))) {
  103. String strObject = pObject.toString().trim();
  104. intIndex = strObject.indexOf(".");
  105. if (intIndex == -1) {
  106. intReturn = new Integer(strObject).intValue();
  107. } else {
  108. intReturn = new Integer(strObject.substring(0, intIndex))
  109. .intValue();
  110. }
  111. } else {
  112. intReturn = 0;
  113. }
  114. } catch (Exception e) {
  115. intReturn = 0;
  116. }
  117. return intReturn;
  118. }
  119. public static boolean isEmpty(String str) {
  120. if (str == null
  121. || "".equals(str)
  122. || "null".equals(str)
  123. || "undefined".equals(str)) {
  124. return true;
  125. }
  126. return false;
  127. }
  128. public static boolean isNotEmpty(String str) {
  129. return !isEmpty(str);
  130. }
  131. /**
  132. * str1 加上 str2
  133. *
  134. * @param str1
  135. * @param str2
  136. * @return
  137. */
  138. public static String add(String str1, String str2) {
  139. return objToString(objToBigDecimal(str1).add(objToBigDecimal(str2)));
  140. }
  141. /**
  142. * str1 减去 str2
  143. *
  144. * @param str1
  145. * @param str2
  146. * @return
  147. */
  148. public static String subtract(String str1, String str2) {
  149. return objToString(objToBigDecimal(str1)
  150. .subtract(objToBigDecimal(str2)));
  151. }
  152. /**
  153. * 比较
  154. *
  155. * @param str1
  156. * @param str2
  157. * @return 0 : str1 == str2 1 : str1 > str2 -1 : str1 < str2
  158. */
  159. public static int compare(String str1, String str2) {
  160. if (str1 == null || "".equals(str1) || "null".equals(str1)) {
  161. str1 = "0";
  162. }
  163. if (str2 == null || "".equals(str2) || "null".equals(str2)) {
  164. str2 = "0";
  165. }
  166. BigDecimal big1 = new BigDecimal(str1);
  167. BigDecimal big2 = new BigDecimal(str2);
  168. int iRet = big1.compareTo(big2);
  169. if (iRet > 0) {
  170. return 1;
  171. } else if (iRet < 0) {
  172. return -1;
  173. }
  174. return 0;
  175. }
  176. /**
  177. * 相除
  178. *
  179. * @param str1
  180. * @param str2
  181. * @return
  182. */
  183. public static String divide(String str1, String str2) {
  184. if (str1 == null || "".equals(str1) || "null".equals(str1)) {
  185. str1 = "0";
  186. }
  187. if (str2 == null || "".equals(str2) || "null".equals(str2)) {
  188. str2 = "0";
  189. }
  190. BigDecimal big1 = new BigDecimal(str1);
  191. big1.setScale(2, BigDecimal.ROUND_HALF_DOWN);
  192. BigDecimal big2 = new BigDecimal(str2);
  193. big2.setScale(2, BigDecimal.ROUND_HALF_DOWN);
  194. BigDecimal iRet = big1.divide(big2, 4, BigDecimal.ROUND_HALF_DOWN);
  195. return iRet.setScale(2, BigDecimal.ROUND_HALF_DOWN).toString();
  196. }
  197. public static String divide(String str1, String str2, int pointWs) {
  198. if (str1 == null || "".equals(str1) || "null".equals(str1)) {
  199. str1 = "0";
  200. }
  201. if (str2 == null || "".equals(str2) || "null".equals(str2)) {
  202. str2 = "0";
  203. }
  204. if (CommonUtil.compare(str2, "0") == 0) {
  205. return "0";
  206. }
  207. BigDecimal big1 = new BigDecimal(str1);
  208. BigDecimal big2 = new BigDecimal(str2);
  209. BigDecimal iRet = big1.divide(big2, pointWs, BigDecimal.ROUND_HALF_UP);
  210. return objToString(iRet);
  211. }
  212. /**
  213. * 相乘
  214. *
  215. * @param str1
  216. * @param str2
  217. * @return
  218. */
  219. public static String multiply(String str1, String str2) {
  220. if (str1 == null || "".equals(str1) || "null".equals(str1)) {
  221. str1 = "0";
  222. }
  223. if (str2 == null || "".equals(str2) || "null".equals(str2)) {
  224. str2 = "0";
  225. }
  226. BigDecimal big1 = new BigDecimal(str1);
  227. BigDecimal big2 = new BigDecimal(str2);
  228. BigDecimal iRet = big1.multiply(big2);
  229. return iRet.toString();
  230. }
  231. public static String multiply(String str1, String str2, int pointWs) {
  232. return objToString(objToBigDecimal(multiply(str1, str2)).setScale(pointWs, BigDecimal.ROUND_HALF_UP));
  233. }
  234. /**
  235. * 生成15位随机码
  236. *
  237. * @return
  238. */
  239. public static String getCode() {
  240. Random random = new Random();
  241. String sRand = "";
  242. for (int i = 0; i < 15; i++) {
  243. String rand = String.valueOf(random.nextInt(10));
  244. sRand += rand;
  245. }
  246. return sRand;
  247. }
  248. /**
  249. * getting ip address from remote request
  250. *
  251. * @author shihh
  252. * @param request
  253. * request object
  254. * @return String request ip address
  255. */
  256. public static String getRequestIpAddr(HttpServletRequest request) {
  257. String ip = request.getHeader("x-forwarded-for");
  258. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  259. ip = request.getHeader("Proxy-Client-IP");
  260. }
  261. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  262. ip = request.getHeader("WL-Proxy-Client-IP");
  263. }
  264. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  265. ip = request.getRemoteAddr();
  266. }
  267. return ip;
  268. }
  269. /**
  270. * getting the current time of system
  271. *
  272. * @author shihh
  273. * @param format
  274. * time format
  275. * @return String time is formatted
  276. */
  277. public static String getSystemTime(String format) {
  278. String systemTime = null;
  279. try {
  280. SimpleDateFormat df = new SimpleDateFormat(format);// 设置日期格式
  281. systemTime = df.format(new Date());
  282. } catch (Exception ex) {
  283. return systemTime;
  284. }
  285. return systemTime;
  286. }
  287. /**
  288. * getting value of source string that is separated by some separator by key
  289. * if there is any error , return null for example: it return string "merry"
  290. * when invoking the function getVauleBySeparator
  291. * ("username=merry&sex=f","username","&","=");
  292. *
  293. * @author shihh
  294. * @param src
  295. * @param key
  296. * @param outSeparator
  297. * @param innerSeparator
  298. * @return String
  299. */
  300. public static String getVauleBySeparator(String src, String key,
  301. String outSeparator, String innerSeparator) {
  302. String ret = null;
  303. if (isEmpty(src) || isEmpty(key) || isEmpty(innerSeparator)
  304. || isEmpty(outSeparator))
  305. return ret;
  306. int keyPos = src.indexOf(key);
  307. if (keyPos < 0) {
  308. return ret;
  309. }
  310. int inSepPos = src.indexOf(innerSeparator, keyPos + key.length() - 1);
  311. int ouSepPos = src.indexOf(outSeparator, inSepPos + 1);
  312. if (ouSepPos == -1)
  313. ret = src.substring(inSepPos + 1);
  314. else
  315. ret = src.substring(inSepPos + 1, ouSepPos);
  316. return ret;
  317. }
  318. public static String timeFormat(String time, String format) {
  319. String systemTime = null;
  320. try {
  321. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  322. Date date = sdf.parse(time);
  323. SimpleDateFormat todf = new SimpleDateFormat(format);// 设置日期格式
  324. systemTime = todf.format(date);
  325. } catch (Exception ex) {
  326. return systemTime;
  327. }
  328. return systemTime;
  329. }
  330. /**
  331. * 格式化日期
  332. * @param time
  333. * @param format
  334. * @return
  335. */
  336. public static String dateFormat(String time, String format) {
  337. String systemTime = null;
  338. try {
  339. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
  340. Date date = sdf.parse(time);
  341. SimpleDateFormat todf = new SimpleDateFormat(format);// 设置日期格式
  342. systemTime = todf.format(date);
  343. } catch (Exception ex) {
  344. return systemTime;
  345. }
  346. return systemTime;
  347. }
  348. /**
  349. * getting special format's date string
  350. *
  351. * @author shihh
  352. * @param format
  353. * time format
  354. * @return String time is formatted
  355. */
  356. public static String getFmtDateString(Date date, String format) {
  357. String dateStr = null;
  358. try {
  359. SimpleDateFormat df = new SimpleDateFormat(format);// 设置日期格式
  360. dateStr = df.format(date);
  361. } catch (Exception ex) {
  362. return dateStr;
  363. }
  364. return dateStr;
  365. }
  366. /**
  367. * judge if an element be contained in array
  368. *
  369. * @author shihh
  370. * @param
  371. * @return boolean
  372. */
  373. public static boolean isContainInArray(String element, String[] array) {
  374. boolean isContain = false;
  375. for (String subElement : array) {
  376. if (subElement.equals(element)) {
  377. isContain = true;
  378. break;
  379. }
  380. }
  381. return isContain;
  382. }
  383. /**
  384. * 比较时间差,time1-time2,time1>time2返回正数,time1<time2返回负数
  385. * 返回Long数组【】,Long[6]=周差,Long
  386. * [5]=年差,Long[4]=月差,Long[3]=日差,Long[2]=时差,Long[1]=分差,Long[0]=秒差 暂不考虑周差
  387. * 月只比较月数的差值,如2012年12月31日与2013年1月1日,计算结果为相差1月 年按月的基数基数按,每相差12个月为1年。
  388. *
  389. * @param time1
  390. * 要笔记哦的时间1,格式yyyyMMddHHmmss
  391. * @param time2
  392. * 要笔记哦的时间2,格式yyyyMMddHHmmss
  393. * @return
  394. */
  395. public static long[] getTD(String time1, String time2) {
  396. Calendar cal1 = Calendar.getInstance();
  397. Calendar cal2 = Calendar.getInstance();
  398. SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
  399. Date date1 = null;
  400. Date date2 = null;
  401. try {
  402. date1 = df.parse(time1);
  403. cal1.setTime(date1);
  404. date2 = df.parse(time2);
  405. cal2.setTime(date2);
  406. } catch (ParseException e) {
  407. e.printStackTrace();
  408. return null;
  409. }
  410. long l = date1.getTime() - date2.getTime();
  411. long day = l / (24 * 60 * 60 * 1000);
  412. long hour = (l / (60 * 60 * 1000));
  413. long min = ((l / (60 * 1000)));
  414. long s = (l / 1000);
  415. int yeardiff = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
  416. int month = 0;
  417. if (yeardiff > 1) {// time1>time2,相差超过2年的除了要计算time1和time2的月差距,还要加上中间间隔年数的月差距
  418. month = (cal1.get(Calendar.MONTH) + 1)
  419. + (11 - cal2.get(Calendar.MONTH)) + (yeardiff - 1) * 12;
  420. } else if (yeardiff < -1) {// time1<time2,相差超过2年的除了要计算time1和time2的月差距,还要加上中间间隔年数的月差距
  421. month = -((11 - cal1.get(Calendar.MONTH)) + (cal2
  422. .get(Calendar.MONTH) + 1)) + (yeardiff + 1) * 12;
  423. } else if (yeardiff == 1) {// time1>time2,相差1年的除了只计算time1和time2的月差距
  424. month = (cal1.get(Calendar.MONTH) + 1)
  425. + (11 - cal2.get(Calendar.MONTH));
  426. } else if (yeardiff == -1) {// time1<time2,相差1年的除了只计算time1和time2的月差距
  427. month = (11 - cal1.get(Calendar.MONTH))
  428. + (cal2.get(Calendar.MONTH) + 1);
  429. month = -month;
  430. } else if (yeardiff == 0) {// 同年份的比较只需计算月差即可
  431. month = cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
  432. }
  433. int time1monthmax = cal1.getActualMaximum(Calendar.DATE);// time1当月最大天数
  434. int time2monthmax = cal2.getActualMaximum(Calendar.DATE);// time2当月最大天数
  435. int monthmax = 30;
  436. boolean wholeMonthDiff = false;
  437. // 计算两个日期之间是否正好相差了一个整月,由于二月存在其特殊性,暂时按两个月是否相差30天来计算。
  438. if (month > 0) {
  439. wholeMonthDiff = time1monthmax - cal1.get(Calendar.DAY_OF_MONTH)
  440. + cal2.get(Calendar.DAY_OF_MONTH) > monthmax;
  441. if (!wholeMonthDiff) {
  442. month--;
  443. }
  444. } else {
  445. wholeMonthDiff = time2monthmax - cal2.get(Calendar.DAY_OF_MONTH)
  446. + cal1.get(Calendar.DAY_OF_MONTH) > monthmax;
  447. month++;
  448. }
  449. long[] td = new long[7];
  450. td[0] = s;
  451. td[1] = min;
  452. td[2] = hour;
  453. td[3] = day;
  454. td[4] = month;
  455. td[5] = month / 12;
  456. td[6] = day / 7;
  457. return td;
  458. }
  459. /**
  460. * return
  461. *
  462. * @author shihh
  463. * @param double d
  464. * latitude or longitude
  465. * @return double
  466. */
  467. private static double rad(double d)
  468. {
  469. return d * Math.PI / 180.0;
  470. }
  471. /**
  472. * return distance between two points
  473. *
  474. * @author shihh
  475. * @param lat1 - 纬度
  476. * @param lng1 - 经度
  477. * @param lat2 - 纬度
  478. * @param lng2 - 经度
  479. * @return double
  480. */
  481. public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
  482. {
  483. double radLat1 = rad(lat1);
  484. double radLat2 = rad(lat2);
  485. double a = radLat1 - radLat2;
  486. double b = rad(lng1) - rad(lng2);
  487. double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
  488. Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
  489. s = s * EARTH_RADIUS;
  490. //s = Math.round(s * 10000) / 10000;
  491. return s;
  492. }
  493. /**
  494. *
  495. * @param i 0代表不增加,0+1 都代表增加几天
  496. * @return
  497. */
  498. public static Timestamp getSystemTime(int i){
  499. Timestamp ts = new Timestamp(new Date().getTime());
  500. if(i > 0){
  501. Calendar c = Calendar.getInstance();
  502. c.add(Calendar.DATE,i);
  503. ts.setTime(c.getTimeInMillis());
  504. return ts;
  505. }else{
  506. return ts;
  507. }
  508. }
  509. /**
  510. * 截取+补位
  511. * @param str 原始字符串
  512. * @param maxLength 最大长度
  513. * @param rightPad true :右边补位, false:左边补位
  514. * @return
  515. */
  516. public static String padAndSub(String str, int maxLength, boolean rightPad) {
  517. str = StringUtils.substring(str, 0, maxLength - 1);
  518. if(rightPad) {
  519. str = StringUtils.rightPad(str, maxLength, "");
  520. }
  521. else {
  522. str = StringUtils.leftPad(str, maxLength, "");
  523. }
  524. return str;
  525. }
  526. /**
  527. * 银行卡掩码
  528. * @param sCardNo 银行卡号
  529. * @return
  530. */
  531. public static String getYanMaCardNo (String sCardNo) {
  532. String sYaMa = "****************************************";
  533. if (sCardNo==null || sCardNo.equals("")) {
  534. return sCardNo;
  535. } else {
  536. int iLength = sCardNo.length();
  537. if (iLength>4) {
  538. // 截取前4位
  539. String str1 = sCardNo.substring(0, 4);
  540. // 截取后4位
  541. String str2=sCardNo.substring(iLength-4, iLength);
  542. // 截取掩码
  543. String sYaMa1=sYaMa.substring(0,iLength-8);
  544. // 组合
  545. return str1+sYaMa1+str2;
  546. } else {
  547. return sCardNo;
  548. }
  549. }
  550. }
  551. /**
  552. * 根据List转成IN的sql
  553. * @param strLst
  554. * @return
  555. */
  556. public static String listToStr4InSql(List<String> strLst) {
  557. StringBuffer sb = new StringBuffer();
  558. for(String val : strLst) {
  559. sb.append("'");
  560. sb.append(val);
  561. sb.append("',");
  562. }
  563. if(sb.length() > 0) {
  564. return sb.substring(0, sb.length()-1);
  565. }
  566. return "";
  567. }
  568. public static Map<String, String> copyMap(Map<String, String> map) {
  569. Map<String, String> cMap = new HashMap<String, String>();
  570. for(String key : map.keySet()){
  571. String value = map.get(key);
  572. cMap.put(key, value);
  573. }
  574. return cMap;
  575. }
  576. public static List<String> getIdFromList(List<?> list, String idName) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
  577. List<String> resList = new ArrayList<String>();
  578. for (Object object : list) {
  579. if (object instanceof Map) {
  580. Map<String,String> map = (Map<String,String>)object;
  581. if (!resList.contains(map.get(idName))) {
  582. resList.add(map.get(idName));
  583. }
  584. } else {
  585. Class tClass = object.getClass();
  586. Method mapGet = tClass.getDeclaredMethod("get"+toUpper(idName));
  587. if (!resList.contains((String)mapGet.invoke(object))) {
  588. resList.add((String)mapGet.invoke(object));
  589. }
  590. }
  591. }
  592. return resList;
  593. }
  594. public static String toUpper(String str) {
  595. return str.substring(0,1).toUpperCase()+str.substring(1);
  596. }
  597. /**
  598. * 去除回车空格等
  599. * 注:\n 回车(\u000a) \t 水平制表符(\u0009) \r 换行(\u000d)
  600. * @param str
  601. * @return
  602. */
  603. public static String replaceSTRN(String str) {
  604. Pattern p = Pattern.compile("\\t|\r|\n");
  605. Matcher m = p.matcher(str);
  606. str = m.replaceAll("");
  607. return str;
  608. }
  609. /**
  610. * 指定日期的前/后几个月
  611. * @param num 正数(后),负数(前)
  612. * @param date
  613. * @return
  614. * @throws ParseException
  615. */
  616. public static String addMonth (int num,String date) throws ParseException{
  617. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
  618. Date dt = sdf.parse(date);
  619. Calendar rightNow = Calendar.getInstance();
  620. rightNow.setTime(dt);
  621. rightNow.add(Calendar.MONTH, num);
  622. Date dt1 = rightNow.getTime();
  623. String reStr = sdf.format(dt1);
  624. return reStr;
  625. }
  626. }