You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

566 lines
19 KiB

  1. package com.simple.utils;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.io.UnsupportedEncodingException;
  5. import java.math.BigDecimal;
  6. import java.net.URLDecoder;
  7. import java.net.URLEncoder;
  8. import java.text.NumberFormat;
  9. import java.text.ParseException;
  10. import java.text.SimpleDateFormat;
  11. import java.util.*;
  12. import java.util.regex.Matcher;
  13. import java.util.regex.Pattern;
  14. /**
  15. * @author Stormeye
  16. * @since 2018.08.09
  17. */
  18. public final class Utility {
  19. private final static Logger logger = LoggerFactory.getLogger(Utility.class);
  20. // @Autowired
  21. // private ReloadableResourceBundleMessageSource messageSource;
  22. public static String generateUUID() {
  23. return UUID.randomUUID().toString();
  24. }
  25. public static String generate32UUID() {
  26. return UUID.randomUUID().toString().replaceAll("-", "");
  27. }
  28. public static boolean isEmpty(CharSequence str) {
  29. if (str == null || str.length() == 0)
  30. return true;
  31. else
  32. return false;
  33. }
  34. public static boolean isBlank(CharSequence str) {
  35. int strLen;
  36. if (str == null || (strLen = str.length()) == 0) {
  37. return true;
  38. }
  39. for (int i = 0; i < strLen; i++) {
  40. if ((Character.isWhitespace(str.charAt(i)) == false)) {
  41. return false;
  42. }
  43. }
  44. return true;
  45. }
  46. /**
  47. * format time to "yyyy-MM-dd"
  48. * @param time
  49. * @return
  50. */
  51. public static String formatTime(int time){
  52. long t = time * 1000l;
  53. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  54. String ret = formatter.format(new Date(t));
  55. return ret;
  56. }
  57. /**
  58. * format timestamp to "yyyy-MM-dd HH:mm:ss"
  59. * @param time
  60. * @return
  61. */
  62. public static String formatTimestamp(int time){
  63. long t = time * 1000l;
  64. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  65. String ret = formatter.format(new Date(t));
  66. return ret;
  67. }
  68. /**
  69. * getSimpleRegionModel the day end time by given the time point
  70. * e.g. given timePoint is "2015.5.13 13:45:32", the returned day end time is "2015.5.13 23:59:59"
  71. * @param timePoint
  72. * @return
  73. */
  74. public static int getDayEndTime(int timePoint){
  75. Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
  76. long theTime = ((long)timePoint)*1000;
  77. calendar.setTimeInMillis(theTime);
  78. int year = calendar.get(Calendar.YEAR);
  79. int month = calendar.get(Calendar.MONTH);
  80. int day = calendar.get(Calendar.DAY_OF_MONTH);
  81. int hour = calendar.get(Calendar.HOUR_OF_DAY);
  82. int minute = calendar.get(Calendar.MINUTE);
  83. int second = calendar.get(Calendar.SECOND);
  84. calendar.clear();
  85. calendar.set(year, month, day, 23, 59, 59);
  86. int ret = (int)(calendar.getTimeInMillis()/1000);
  87. return ret;
  88. }
  89. public static int getDayStartTime(int timePoint) {
  90. Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
  91. long theTime = ((long)timePoint)*1000;
  92. calendar.setTimeInMillis(theTime);
  93. int year = calendar.get(Calendar.YEAR);
  94. int month = calendar.get(Calendar.MONTH);
  95. int day = calendar.get(Calendar.DAY_OF_MONTH);
  96. int hour = calendar.get(Calendar.HOUR_OF_DAY);
  97. int minute = calendar.get(Calendar.MINUTE);
  98. int second = calendar.get(Calendar.SECOND);
  99. calendar.clear();
  100. calendar.set(year, month, day, 0, 0, 0);
  101. int ret = (int)(calendar.getTimeInMillis()/1000);
  102. return ret;
  103. }
  104. public static int getLastHourEndTime(int timePoint) {
  105. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd-HH");
  106. String curHour = sf.format(System.currentTimeMillis());
  107. int ret = timePoint;
  108. try {
  109. ret = (int)((sf.parse(curHour).getTime())/1000);
  110. } catch(ParseException ex) {
  111. ex.printStackTrace();
  112. }
  113. return ret - 1;
  114. }
  115. /**
  116. * Encrypt plain text
  117. * @param plainText
  118. * @return encrypted string for cvn2
  119. */
  120. public static String encryptText(String plainText) {
  121. return plainText;
  122. }
  123. /**
  124. * Decrypt to plain text
  125. * @param decryptedText
  126. * @return encrypted string for cvn2
  127. */
  128. public static String decryptedText(String decryptedText) {
  129. return decryptedText;
  130. }
  131. /**
  132. * Mask the bankcard Number, e.g. 18911113927 to 189******3927
  133. * @param idCardNo
  134. * @return masked phone number
  135. */
  136. public static String maskIdCard(String idCardNo) {
  137. if(isEmpty(idCardNo) || idCardNo.length() < 18) {
  138. return idCardNo;
  139. }
  140. return idCardNo.substring(0,4) + "**" + idCardNo.substring(6, 12) + "***" + idCardNo.substring(15, 18);
  141. }
  142. /**
  143. * Mask the bankcard Number, e.g. 18911113927 to 189******3927
  144. * @param bankCardNo
  145. * @return masked phone number
  146. */
  147. public static String maskBankCard(String bankCardNo) {
  148. if(bankCardNo.length() <= 8) {
  149. return bankCardNo;
  150. }
  151. return bankCardNo.substring(0,4) + "******" + bankCardNo.substring(bankCardNo.length() - 4, bankCardNo.length());
  152. }
  153. /**
  154. * Mask the user name, e.g.
  155. * @param userName
  156. * @return masked phone number
  157. */
  158. public static String maskUserName(String userName) {
  159. switch (userName.length()) {
  160. case 0:
  161. case 1:
  162. return "*";
  163. default:
  164. return userName.replaceAll(".", "*").replaceFirst(".$",userName.substring(userName.length() - 1));
  165. }
  166. }
  167. public static String maskPhoneNum(String phoneNum) {
  168. if(phoneNum==null || phoneNum.length() < 4) {
  169. return phoneNum;
  170. }
  171. return phoneNum.substring(0,3) + "****" + phoneNum.substring(phoneNum.length() - 4, phoneNum.length());
  172. }
  173. /**
  174. * Convert current time into int type. used for create_time/update time
  175. * @param
  176. * @return timestamp
  177. */
  178. public static int getCurrentTimeStamp() {
  179. if(debugCurrentTimeStamp == 0) {
  180. return (int) (System.currentTimeMillis() / 1000);
  181. }else {
  182. return debugCurrentTimeStamp;
  183. }
  184. }
  185. public static int convertDate2TimeStamp(Date date) {
  186. return (int) (date.getTime() / 1000);
  187. }
  188. private static int debugCurrentTimeStamp = 0;
  189. /**
  190. * For test purpose, getCurrentTimeStamp will return the timestamp if non-zero.
  191. * @param
  192. * @return timestamp
  193. */
  194. public static void setDebugCurrentTimeStamp(int timeStamp) {
  195. debugCurrentTimeStamp = timeStamp;
  196. }
  197. public static String generateInvitationCode(Set<String> existingCode){
  198. int invitationCode = (int)((Math.random()*9+1)*100000);
  199. if(existingCode != null){
  200. while(existingCode.contains(String.valueOf(invitationCode))){
  201. invitationCode++;
  202. if(invitationCode>=999999){
  203. invitationCode = (int)((Math.random()*9+1)*100000);
  204. }
  205. }
  206. }
  207. return String.valueOf(invitationCode);
  208. }
  209. public static String generateOrderId(String gid) {
  210. if (null == gid) {
  211. return "";
  212. }
  213. return "SDLC" + gid.replaceAll("-", "");
  214. }
  215. public static String getDataFormatString(int currentSec) {
  216. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  217. return sf.format(((long) currentSec) * 1000);
  218. }
  219. public static String getDataFormatString2(int currentSec) {
  220. SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
  221. return sf.format(((long) currentSec) * 1000);
  222. }
  223. public static String getDataFormatString3(Date date) {
  224. SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
  225. return sf.format(date);
  226. }
  227. public static String convertDecimal2PercentRate(BigDecimal rate) {
  228. NumberFormat percent = NumberFormat.getPercentInstance();
  229. percent.setMaximumFractionDigits(1);
  230. return percent.format(rate.setScale(3, BigDecimal.ROUND_DOWN));
  231. }
  232. public static String convertLineFeedCharacter(String msg){
  233. if(msg == null || msg.isEmpty()){
  234. return "";
  235. }
  236. msg = msg.replace("\\\\n", "\\n");
  237. return msg;
  238. }
  239. public static int getSimpleDayEndTime(int timePoint){
  240. Calendar ca = new GregorianCalendar();
  241. ca.setTime(new Date(((long) timePoint) * 1000));
  242. ca.set(Calendar.HOUR_OF_DAY, 23);
  243. ca.set(Calendar.MINUTE, 59);
  244. ca.set(Calendar.SECOND, 59);
  245. long ret = ca.getTime().getTime()/1000;
  246. return (int) ret;
  247. }
  248. public static String urlEncodeUTF8(String s) {
  249. try {
  250. return URLEncoder.encode(s, "UTF-8");
  251. } catch (UnsupportedEncodingException e) {
  252. throw new UnsupportedOperationException(e);
  253. }
  254. }
  255. public static String urlDecodeUTF8(String s) {
  256. try {
  257. return URLDecoder.decode(s, "UTF-8");
  258. } catch (UnsupportedEncodingException e) {
  259. throw new UnsupportedOperationException(e);
  260. }
  261. }
  262. public static int dateStringToTimeStamp(String dateStr){
  263. int timeStamp = 0;
  264. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  265. try {
  266. Date date = sdf.parse(dateStr);
  267. timeStamp= (int) (date.getTime()/1000);
  268. } catch (ParseException e) {
  269. logger.error("dateStringToTimeStamp exception = {}", e);
  270. }
  271. return timeStamp;
  272. }
  273. public static int dateStringToTimeStamp(String dateStr,String format){
  274. int timeStamp = 0;
  275. SimpleDateFormat sdf = new SimpleDateFormat(format);
  276. try {
  277. Date date = sdf.parse(dateStr);
  278. timeStamp= (int) (date.getTime()/1000);
  279. } catch (ParseException e) {
  280. logger.error("dateStringToTimeStamp exception = {}", e);
  281. }
  282. return timeStamp;
  283. }
  284. public static Object convert(Object object, Class<?> type) {
  285. if (object instanceof Number) {
  286. Number number = (Number) object;
  287. if (type.equals(byte.class) || type.equals(Byte.class)) {
  288. return number.byteValue();
  289. }
  290. if (type.equals(short.class) || type.equals(Short.class)) {
  291. return number.shortValue();
  292. }
  293. if (type.equals(int.class) || type.equals(Integer.class)) {
  294. return number.intValue();
  295. }
  296. if (type.equals(long.class) || type.equals(Long.class)) {
  297. return number.longValue();
  298. }
  299. if (type.equals(float.class) || type.equals(Float.class)) {
  300. return number.floatValue();
  301. }
  302. if (type.equals(double.class) || type.equals(Double.class)) {
  303. return number.doubleValue();
  304. }
  305. }
  306. return object;
  307. }
  308. public static int getFirstDayByDate(final Date date) {
  309. Calendar instance = Calendar.getInstance();
  310. instance.setTime(date);
  311. instance.set(instance.get(Calendar.YEAR), instance.get(Calendar.MONTH), 1, 0, 0, 0);
  312. int ret = (int) (instance.getTimeInMillis()/1000);
  313. return ret;
  314. }
  315. public static boolean decimalEqualsScale2(BigDecimal one , BigDecimal two) {
  316. if (one == null || two == null) {
  317. return false;
  318. }
  319. final BigDecimal o1 = one.setScale(2 , BigDecimal.ROUND_DOWN);
  320. final BigDecimal o2 = two.setScale(2 , BigDecimal.ROUND_DOWN);
  321. return o1.compareTo(o2) == 0;
  322. }
  323. public static int decimalCompareScale2(BigDecimal one , BigDecimal two) {
  324. if (one == null || two == null) {
  325. return -1;
  326. }
  327. final BigDecimal o1 = one.setScale(2 , BigDecimal.ROUND_DOWN);
  328. final BigDecimal o2 = two.setScale(2 , BigDecimal.ROUND_DOWN);
  329. return o1.compareTo(o2);
  330. }
  331. public static BigDecimal setScale2RoundDown(BigDecimal one) {
  332. if (one == null) {
  333. return null;
  334. }
  335. return one.setScale(2, BigDecimal.ROUND_DOWN);
  336. }
  337. public static boolean isNumeric(String str){
  338. Pattern pattern = Pattern.compile("[0-9]*");
  339. Matcher isNum = pattern.matcher(str);
  340. if( !isNum.matches() ){
  341. return false;
  342. }
  343. return true;
  344. }
  345. public static String dateFormat(Date date, String pattern) {
  346. SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  347. return sdf.format(date);
  348. }
  349. public static int getCurrentWeekStartTime(int dayTime) {
  350. Calendar currentDate = Calendar.getInstance();
  351. currentDate.setTime(new Date(dayTime * 1000L));
  352. currentDate.setFirstDayOfWeek(Calendar.MONDAY);
  353. currentDate.set(Calendar.HOUR_OF_DAY, 0);
  354. currentDate.set(Calendar.MINUTE, 0);
  355. currentDate.set(Calendar.SECOND, 0);
  356. currentDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
  357. return (int)(currentDate.getTimeInMillis() / 1000L);
  358. }
  359. public static int getCurrentWeekEndTime(int dayTime) {
  360. Calendar currentDate = Calendar.getInstance();
  361. currentDate.setTime(new Date(dayTime * 1000L));
  362. currentDate.setFirstDayOfWeek(Calendar.MONDAY);
  363. currentDate.set(Calendar.HOUR_OF_DAY, 23);
  364. currentDate.set(Calendar.MINUTE, 59);
  365. currentDate.set(Calendar.SECOND, 59);
  366. currentDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
  367. return (int)(currentDate.getTimeInMillis() / 1000L);
  368. }
  369. public static int getCurrentMonthStartTime(int dayTime) {
  370. Calendar currentDate = Calendar.getInstance();
  371. currentDate.setTime(new Date(dayTime * 1000L));
  372. currentDate.set(Calendar.HOUR_OF_DAY, 0);
  373. currentDate.set(Calendar.MINUTE, 0);
  374. currentDate.set(Calendar.SECOND, 0);
  375. currentDate.set(Calendar.DAY_OF_MONTH, currentDate
  376. .getActualMinimum(Calendar.DAY_OF_MONTH));
  377. return (int)(currentDate.getTimeInMillis() / 1000L);
  378. }
  379. public static int getCurrentMonthEndTime(int dayTime) {
  380. Calendar currentDate = Calendar.getInstance();
  381. currentDate.setTime(new Date(dayTime * 1000L));
  382. currentDate.set(Calendar.HOUR_OF_DAY, 23);
  383. currentDate.set(Calendar.MINUTE, 59);
  384. currentDate.set(Calendar.SECOND, 59);
  385. currentDate.set(Calendar.DAY_OF_MONTH, currentDate
  386. .getActualMaximum(Calendar.DAY_OF_MONTH));
  387. return (int)(currentDate.getTimeInMillis() / 1000L);
  388. }
  389. /**
  390. * format time to "yyyy-MM-dd"
  391. * @param time
  392. * @return
  393. */
  394. public static String formatTimeYYMMDDHH(int time){
  395. long t = time * 1000l;
  396. SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHH");
  397. String ret = formatter.format(new Date(t));
  398. return ret;
  399. }
  400. public static String formatTimeMMDD(int time){
  401. long t = time * 1000l;
  402. SimpleDateFormat formatter = new SimpleDateFormat("MMdd");
  403. String ret = formatter.format(new Date(t));
  404. return ret;
  405. }
  406. public static String formatTimeMMDotDD(int time) {
  407. long t = time * 1000l;
  408. SimpleDateFormat formatter = new SimpleDateFormat("MM.dd");
  409. String ret = formatter.format(new Date(t));
  410. return ret;
  411. }
  412. public static String formatTimeYmdHm(int time) {
  413. long t = time * 1000l;
  414. SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
  415. String ret = formatter.format(new Date(t));
  416. return ret;
  417. }
  418. public static int getDayByType(int time, int type) {
  419. long t = time * 1000L;
  420. Calendar calendar = Calendar.getInstance();
  421. calendar.setTime(new Date(t));
  422. return calendar.get(type);
  423. }
  424. public static int addTime(int time , int type , int nums) {
  425. long t = time * 1000L;
  426. Calendar calendar = Calendar.getInstance();
  427. calendar.setTime(new Date(t));
  428. calendar.add(type, nums);
  429. return (int)(calendar.getTimeInMillis() / 1000L);
  430. }
  431. public static BigDecimal convertCoord2Decimal(Integer coordLat) {
  432. return new BigDecimal(coordLat).divide(new BigDecimal(100000), 5, BigDecimal.ROUND_HALF_DOWN);
  433. }
  434. public static BigDecimal convertScale(Double amount) {
  435. return amount != null ? new BigDecimal(amount).setScale(1,BigDecimal.ROUND_HALF_DOWN) : BigDecimal.ZERO;
  436. }
  437. public static String convertLevel(String level) {
  438. if (level != null && level.matches("\\d+(.\\d+)?")) {
  439. return new BigDecimal(level)
  440. .multiply(new BigDecimal(2.0))
  441. .setScale(1, BigDecimal.ROUND_HALF_UP).toString();
  442. }
  443. return level;
  444. }
  445. public static String getUTFString(String content) {
  446. try {
  447. return new String(content.getBytes("ISO-8859-1"), "utf-8");
  448. } catch (UnsupportedEncodingException e) {
  449. e.printStackTrace();
  450. }
  451. return "";
  452. }
  453. /**
  454. * 金额 分转换元(精确到2位小数)
  455. * @param money (单位分)
  456. * @return
  457. */
  458. public static BigDecimal getAmount(Integer money) {
  459. return new BigDecimal(money).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);
  460. }
  461. public static String getDataFormatStringYYYYMMDDHHmmss(int currentSec) {
  462. SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
  463. return sf.format(((long) currentSec) * 1000);
  464. }
  465. public static String getDataFormatStringYYYYMMDDHHmmss(Date currentDate) {
  466. SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
  467. return sf.format(currentDate);
  468. }
  469. public static Date getDateFromString(String timeEnd) throws ParseException {
  470. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  471. return sdf.parse(timeEnd);
  472. }
  473. public static String getOrderNo() {
  474. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  475. String dateStr = sdf.format(new Date());
  476. return dateStr.substring(0,4)+dateStr.substring(5,7)+dateStr.substring(8,10)+dateStr.substring(11,13)+dateStr.substring(14,16)+dateStr.substring(17,19)+RandomUtils.getNum(5);
  477. }
  478. /**
  479. * 金额 分转换元(精确到1位小数)
  480. * @param money (单位角)
  481. * @return
  482. */
  483. public static String getAmountStr(Integer money) {
  484. return new BigDecimal(money).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN).toString();
  485. }
  486. /**
  487. * format time to "yyyyMMdd"
  488. * @param time
  489. * @return
  490. */
  491. public static String formatTimeYmd(int time){
  492. long t = time * 1000l;
  493. SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
  494. String ret = formatter.format(new Date(t));
  495. return ret;
  496. }
  497. }