工具类
JSON转换 - JSONUtils.java

1 package com.demo.utils; 2 3 import com.fasterxml.jackson.core.JsonProcessingException; 4 import com.fasterxml.jackson.databind.ObjectMapper; 5 import org.apache.commons.lang3.StringUtils; 6 import org.json.JSONArray; 7 import org.json.JSONObject; 8 import org.slf4j.Logger; 9 import org.slf4j.LoggerFactory; 10 11 import java.io.IOException; 12 13 public class JSONUtils { 14 15 private static final Logger logger = LoggerFactory.getLogger(JSONUtils.class); 16 17 private JSONUtils() { 18 } 19 20 public static JSONObject parseJSONObject(String json) { 21 try { 22 return new JSONObject(json); 23 } catch (Exception e) { 24 logger.error("parse JSONObject error!", e); 25 } 26 return null; 27 } 28 29 public static JSONArray parseJSONArray(String jsonArray) { 30 try { 31 return new JSONArray(jsonArray); 32 } catch (Exception e) { 33 logger.error("parse parseJSONArray error!", e); 34 } 35 return null; 36 } 37 38 public static String getString(JSONObject obj, String name) { 39 String value = ""; 40 try { 41 value = obj.getString(name); 42 } catch (Exception e) { 43 logger.error("JSONObject get String value error!", e); 44 } 45 return value; 46 } 47 48 public static Long getLong(JSONObject obj, String name) { 49 Long value = 0L; 50 try { 51 value = obj.getLong(name); 52 } catch (Exception e) { 53 logger.error("JSONObject get Long value error!", e); 54 } 55 return value; 56 } 57 58 public static JSONArray getJSONArray(JSONObject obj, String name) { 59 try { 60 return obj.getJSONArray(name); 61 } catch (Exception e) { 62 logger.error("JSONObject get JSONArray value error!", e); 63 } 64 return null; 65 } 66 67 public static String toJson(Object obj) { 68 if (obj == null) { 69 return ""; 70 } 71 ObjectMapper mapper = new ObjectMapper(); 72 try { 73 return mapper.writeValueAsString(obj); 74 } catch (JsonProcessingException e) { 75 logger.error("JSONUtils to String error!", e); 76 } 77 return ""; 78 } 79 80 public static <T> T fromJson(String json, Class<T> clazz) { 81 if (StringUtils.isBlank(json)) return null; 82 ObjectMapper mapper = new ObjectMapper(); 83 try { 84 return mapper.readValue(json, clazz); 85 } catch (IOException e) { 86 logger.error("JSONUtils fromJson error!", e); 87 } 88 return null; 89 } 90 91 92 public static <T> T fromJsonWithoutErr(String json, Class<T> clazz) { 93 ObjectMapper mapper = new ObjectMapper(); 94 try { 95 return mapper.readValue(json, clazz); 96 } catch (IOException ignored) { 97 } 98 return null; 99 } 100 101 /** 102 * 取字符串值 调用toString方法 103 * 104 * @param v 对象 105 * @param dv 默认值 106 * @return 107 */ 108 String strValue(Object v, String dv) { 109 if (v != null && v instanceof String) 110 return StringUtils.isBlank(v.toString()) ? dv : v.toString(); 111 return v == null ? dv : v.toString(); 112 } 113 }View Code
Data时间 - DataUtils.java

1 package com.demo.utils; 2 3 import freemarker.template.utility.NullArgumentException; 4 import org.apache.commons.lang3.StringUtils; 5 import org.slf4j.Logger; 6 import org.slf4j.LoggerFactory; 7 8 import java.text.ParseException; 9 import java.text.SimpleDateFormat; 10 import java.util.Calendar; 11 import java.util.Date; 12 import java.util.GregorianCalendar; 13 import java.util.Set; 14 15 /** 16 * 日期转换工具 17 * 18 */ 19 public class DateUtils { 20 21 private static final Logger logger = LoggerFactory.getLogger(DateUtils.class); 22 23 public static final int TIME_SECOND = 1000; 24 25 public static final int TIME_MINUTE = 60 * TIME_SECOND; 26 27 public static final int TIME_HOUR = 60 * TIME_MINUTE; 28 29 public static final int TIME_DAY = 24 * TIME_HOUR; 30 31 public enum Pattern { 32 YEAR("yyyy"), // 33 MONTH("MM"), // 34 DAY("dd"), // 35 HOUR("HH"), // 36 MINUTE("mm"), // 37 SECOND("ss"), // 38 YEAR_MONTH("yyyy/MM"), // 39 YEAR_MONTH_SHORT("yyyyMM"), // 40 YEAR_MONTH_CN("yyyy-MM"), // 41 DATE_CN("yyyy-MM-dd"), // 42 DATE_EN("yyyy/MM/dd"), // 43 DATE_SHORT("yyyyMMdd"), // 44 TIME_FULL("HH:mm:ss"), // 45 TIME_SHORT("HHmmss"), // 46 TIME_HM("HH:mm"), // 47 TIME_HM_S("HHmm"), // 48 DATETIME_YMDHM_CN("yyyy-MM-dd HH:mm"), // 49 DATETIME_SHORT("yyyyMMddHHmmss"), // 50 DATETIME_FULL_SHORT("yyyyMMddHHmmssSSS"), // 51 DATETIME_CN("yyyy-MM-dd HH:mm:ss"), // 52 DATETIME_EN("yyyy/MM/dd HH:mm:ss"); 53 54 private final String value; 55 56 private Pattern(String value) { 57 this.value = value; 58 } 59 60 public String getValue() { 61 return value; 62 } 63 } 64 65 protected static final String[] WEEK_CN = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; 66 protected static final String[] WEEK_CN_SHORT = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"}; 67 68 /** 69 * 获日期取周中文名称 70 * 71 * @param date 72 * @return 73 */ 74 public static String getWeek(Date date) { 75 Calendar cal = Calendar.getInstance(); 76 cal.setTime(date); 77 int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1; 78 if (week_index < 0) { 79 week_index = 0; 80 } 81 return WEEK_CN[week_index]; 82 } 83 84 /** 85 * 获工作是取周中文名称 86 * 87 * @param week 88 * @return 89 */ 90 public static String getWeek(final Integer week) { 91 int index_week = 0; 92 if (week != null && week >= 0 && week <= 6) { 93 index_week = week; 94 } 95 return WEEK_CN[index_week]; 96 } 97 98 /** 99 * 获工作是取周中文名称 100 * 101 * @param week 102 * @return 103 */ 104 public static String getWeekShort(final Integer week) { 105 int index_week = 0; 106 if (week != null && week >= 0 && week <= 6) { 107 index_week = week; 108 } 109 return WEEK_CN_SHORT[index_week]; 110 } 111 112 113 /** 114 * Return the current date 115 * 116 * @return - DATE<br> 117 */ 118 public static Date currDateTime() { 119 Calendar cal = Calendar.getInstance(); 120 return cal.getTime(); 121 } 122 123 /** 124 * Return the current date 125 * 126 * @return - DATE<br> 127 */ 128 public static Date currDateTimeCN() { 129 Date date = currDateTime(); 130 String dateStr = format(Pattern.DATETIME_CN, date); 131 return parseDateTime(dateStr); 132 } 133 134 /** 135 * Return the current date string 136 * 137 * @return - 产生的日期字符串<br> 138 */ 139 public static String getCurrentDateStr() { 140 Calendar cal = Calendar.getInstance(); 141 Date currDate = cal.getTime(); 142 return format(currDate); 143 } 144 145 /** 146 * Return the current date in the specified format 147 * 148 * @return 149 */ 150 public static String getCurrentDateTimeStr() { 151 Calendar cal = Calendar.getInstance(); 152 Date currDate = cal.getTime(); 153 154 return formatTime(currDate); 155 } 156 157 public static Date parse(final Pattern pattern, String dateValue) { 158 if (dateValue == null) { 159 return null; 160 } 161 SimpleDateFormat dateFormat = new SimpleDateFormat(pattern.getValue()); 162 163 try { 164 return dateFormat.parse(dateValue); 165 } catch (ParseException e) { 166 logger.error(DateUtils.class.getSimpleName(), e); 167 } 168 169 return null; 170 171 } 172 173 /** 174 * Parse a string and return a date timestamp 175 * 176 * @param timestamp 177 * @return 178 * @throws Exception 179 */ 180 public static Date parse(Long timestamp) { 181 return new Date(timestamp); 182 } 183 184 /** 185 * Parse a string and return a date value 186 * 187 * @param dateValue 188 * @return 189 * @throws Exception 190 */ 191 public static Date parseDate(String dateValue) { 192 return parse(Pattern.DATE_CN, dateValue); 193 } 194 195 /** 196 * Parse a strign and return a datetime value 197 * 198 * @param dateValue 199 * @return 200 */ 201 public static Date parseDateTime(String dateValue) { 202 return parse(Pattern.DATETIME_CN, dateValue); 203 } 204 205 /** 206 * String转换Date("yyyy-MM-dd HH:mm") 207 * 208 * @param dateValue 209 * @return 210 */ 211 public static Date parseDateTimeHM(String dateValue) { 212 return parse(Pattern.DATETIME_YMDHM_CN, dateValue); 213 } 214 215 /** 216 * 将Timestamp类型的日期转换为系统参数定义的格式的字符串。 217 * 218 * @param datetime 需要转换的日期。 219 * @return 转换后符合给定格式的日期字符串 220 */ 221 public static String format(Date datetime) { 222 return format(Pattern.DATE_CN, datetime); 223 } 224 225 /** 226 * 将Timestamp类型的日期转换为系统参数定义的格式的字符串。 227 * 228 * @param datetime 需要转换的日期。 229 * @return 转换后符合给定格式的日期字符串 230 */ 231 public static String formatTime(Date datetime) { 232 return format(Pattern.DATETIME_CN, datetime); 233 } 234 235 public static String formatTimeYMDHM(Date dateTime) { 236 return format(Pattern.DATETIME_YMDHM_CN, dateTime); 237 } 238 239 /** 240 * 将Date类型的日期转换为系统参数定义的格式的字符串。 241 * 242 * @param pattern 243 * @param datetime 244 * @return 245 */ 246 public static String format(final Pattern pattern, Date datetime) { 247 if (datetime == null) 248 return null; 249 SimpleDateFormat dateFormat = new SimpleDateFormat(pattern.getValue()); 250 return dateFormat.format(datetime); 251 } 252 253 /** 254 * 取得指定日期N天后的日期 255 * 256 * @param date 257 * @param days 258 * @return 259 */ 260 public static Date addDays(Date date, int days) { 261 Calendar cal = Calendar.getInstance(); 262 cal.setTime(date); 263 264 cal.add(Calendar.DAY_OF_MONTH, days); 265 266 return cal.getTime(); 267 } 268 269 /** 270 * 计算两个日期之间相差的天数 271 * 272 * @param date1 273 * @param date2 274 * @return 275 */ 276 public static int daysBetween(Date date1, Date date2) { 277 Calendar cal = Calendar.getInstance(); 278 cal.setTime(date1); 279 long time1 = cal.getTimeInMillis(); 280 cal.setTime(date2); 281 long time2 = cal.getTimeInMillis(); 282 long betweenDays = (time2 - time1) / (1000 * 3600 * 24); 283 284 return Integer.parseInt(String.valueOf(betweenDays)); 285 } 286 287 /** 288 * 计算当前日期相对于"1977-12-01"的天数 289 * 290 * @param date 291 * @return 292 */ 293 public static long getRelativeDays(Date date) { 294 Date relativeDate = DateUtils.parse(Pattern.DATE_CN, "1977-12-01"); 295 296 return DateUtils.daysBetween(relativeDate, date); 297 } 298 299 public static Date getDateBeforTwelveMonth() { 300 String date = ""; 301 Calendar calendar = Calendar.getInstance(); 302 calendar.setTime(currDateTime()); 303 int year = calendar.get(Calendar.YEAR) - 1; 304 int month = calendar.get(Calendar.MONTH) + 1; 305 if (month > 9) { 306 date = String.valueOf(year) + "-" + month + "-01"; 307 } else { 308 date = String.valueOf(year) + "-0" + month + "-01"; 309 } 310 311 return parseDate(date); 312 } 313 314 /** 315 * 传入时间字符串,加一天后返回Date 316 * 317 * @param date 时间 格式 YYYY-MM-DD 318 * @return 319 */ 320 public static Date addDate(String date) { 321 if (date == null) { 322 return null; 323 } 324 325 Date tempDate = parse(Pattern.DATE_CN, date); 326 String year = format(Pattern.YEAR, tempDate); 327 String month = format(Pattern.MONTH, tempDate); 328 String day = format(Pattern.DAY, tempDate); 329 330 GregorianCalendar calendar = new GregorianCalendar(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day)); 331 332 calendar.add(GregorianCalendar.DATE, 1); 333 return calendar.getTime(); 334 } 335 336 public static Integer getOfType(Date date, int type) { 337 if (date == null) { 338 return null; 339 } 340 Calendar c = Calendar.getInstance(); 341 c.setTime(date); 342 int t = Calendar.YEAR; 343 switch (type) { 344 case Calendar.MONTH: 345 t = Calendar.MONTH; 346 return c.get(t) + 1; 347 case Calendar.DATE: 348 t = Calendar.DATE; 349 break; 350 case Calendar.HOUR: 351 t = Calendar.HOUR; 352 break; 353 case Calendar.MINUTE: 354 t = Calendar.MINUTE; 355 break; 356 case Calendar.SECOND: 357 t = Calendar.SECOND; 358 break; 359 case Calendar.DAY_OF_WEEK: 360 t = Calendar.DAY_OF_WEEK; 361 break; 362 case Calendar.DAY_OF_WEEK_IN_MONTH: 363 t = Calendar.DAY_OF_WEEK_IN_MONTH; 364 break; 365 default: 366 break; 367 } 368 return c.get(t); 369 } 370 371 public static Date getFirstDayOfMouth(Date date) { 372 if (date == null) { 373 return null; 374 } 375 Calendar c = Calendar.getInstance(); 376 c.setTime(date); 377 c.set(Calendar.DAY_OF_MONTH, 1); 378 c.set(Calendar.HOUR_OF_DAY, 0); 379 c.set(Calendar.MINUTE, 0); 380 c.set(Calendar.SECOND, 0); 381 c.set(Calendar.MILLISECOND, 0); 382 return c.getTime(); 383 } 384 385 /** 386 * 时间去掉时分秒(yyy-MM-dd 00:00:00.000) 387 * 388 * @param dateTime 389 * @return 390 */ 391 public static Date clearTime(Date dateTime) { 392 if (dateTime == null) { 393 return null; 394 } 395 Calendar c = Calendar.getInstance(); 396 c.setTime(dateTime); 397 c.set(Calendar.HOUR_OF_DAY, 0); 398 c.set(Calendar.MINUTE, 0); 399 c.set(Calendar.SECOND, 0); 400 c.set(Calendar.MILLISECOND, 0); 401 return c.getTime(); 402 } 403 404 /** 405 * 时间去掉毫秒(yyy-MM-dd HH:mm:ss.000) 406 * 407 * @param dateTime 408 * @return 409 */ 410 public static Date clearTimeMS(Date dateTime) { 411 if (dateTime == null) { 412 return null; 413 } 414 Calendar c = Calendar.getInstance(); 415 c.setTime(dateTime); 416 c.set(Calendar.MILLISECOND, 0); 417 return c.getTime(); 418 } 419 420 /** 421 * 日期最后一刻(yyy-MM-dd 23:59:59.999) 422 * 423 * @param dateTime 424 * @return 425 */ 426 public static Date endTime(Date dateTime) { 427 if (dateTime == null) { 428 return null; 429 } 430 Calendar c = Calendar.getInstance(); 431 c.setTime(dateTime); 432 c.set(Calendar.HOUR_OF_DAY, 23); 433 c.set(Calendar.MINUTE, 59); 434 c.set(Calendar.SECOND, 59); 435 c.set(Calendar.MILLISECOND, 999); 436 return c.getTime(); 437 } 438 439 public static Date addHours(Date date, int hours) { 440 Calendar cal = Calendar.getInstance(); 441 cal.setTime(date); 442 cal.add(Calendar.HOUR_OF_DAY, hours); 443 return cal.getTime(); 444 } 445 446 public static Date addMinutes(Date date, int minutes) { 447 Calendar cal = Calendar.getInstance(); 448 cal.setTime(date); 449 cal.add(Calendar.MINUTE, minutes); 450 return cal.getTime(); 451 } 452 453 /** 454 * 计算两个日期之间的工作日数 455 * 456 * @param start 开始日期 457 * @param end 结束日期 458 * @param workday 适用工作日(1周日2周一3周二4周三5周四6周五7周六) 459 * @return 工作日数 460 */ 461 public static int workdays(Date start, Date end, Set<Integer> workday) { 462 if (start == null || end == null) { 463 throw new NullArgumentException("start ro end date is require!"); 464 } 465 Calendar cal = Calendar.getInstance(); 466 cal.setTime(start); 467 int count = 0; 468 while (cal.getTime().before(addDays(end, 1))) { 469 if (workday.contains(getOfType(cal.getTime(), Calendar.DAY_OF_WEEK))) { 470 count++; 471 } 472 cal.add(Calendar.DAY_OF_MONTH, 1); 473 } 474 return count; 475 } 476 477 /** 478 * 计算两个日期之间的工作日数 479 * 480 * @param start 开始日期 481 * @param end 结束日期 482 * @param workday 适用工作日(1周日2周一3周二4周三5周四6周五7周六) 483 * @return 工作日数 484 */ 485 public static int workdays(Date start, Date end, String workday) { 486 if (start == null || end == null) { 487 throw new NullArgumentException("start ro end date is require!"); 488 } 489 Calendar cal = Calendar.getInstance(); 490 cal.setTime(start); 491 int count = 0; 492 while (cal.getTime().before(addDays(end, 1))) { 493 Integer tmp = getOfType(cal.getTime(), Calendar.DAY_OF_WEEK); 494 if (tmp != null && workday.contains(tmp.toString())) { 495 count++; 496 } 497 cal.add(Calendar.DAY_OF_MONTH, 1); 498 } 499 return count; 500 } 501 502 /** 503 * 1234567转中文 504 * 505 * @param workday 506 * @param separator 分割符 507 * @return 508 */ 509 public static String convertWorkdays(String workday, String separator) { 510 return convertWorkdays(workday, separator, "zh_cn_short"); 511 } 512 513 /** 514 * 1234567转中文 515 * 516 * @param workday 517 * @param separator 分割符 518 * @param nameType 中文(全、简写) 519 * @return 520 */ 521 public static String convertWorkdays(String workday, String separator, String nameType) { 522 if (StringUtils.isBlank(workday)) { 523 return "-"; 524 } 525 StringBuilder sb = new StringBuilder(); 526 for (int i = 0; i < workday.length(); i++) { 527 if (sb.length() > 0) { 528 sb.append(separator); 529 } 530 String day = String.valueOf(workday.charAt(i)); 531 if (StringUtils.isNumeric(day)) { 532 if ("zh_cn".equals(nameType)) { 533 sb.append(DateUtils.getWeek(Integer.valueOf(day))); 534 } else if ("zh_cn_short".equals(nameType)) { 535 sb.append(DateUtils.getWeekShort(Integer.valueOf(day))); 536 } 537 } 538 } 539 return sb.toString(); 540 } 541 542 /** 543 * 时间偏移 544 * 545 * @param date 时间 546 * @param offsetDay 天数 547 * @param offsetMin 分钟数 548 * @return 跨越天数(以0点为准) 549 */ 550 public static int calcOffset(Date date, int offsetDay, int offsetMin) { 551 // Date date = DateUtils.parse(Pattern.TIME_HM_S, hm); 552 if (date == null) return 0; 553 Calendar cal = Calendar.getInstance(); 554 cal.setTime(date); 555 Date d0 = cal.getTime(); 556 Date d1 = addDays(date, offsetDay); 557 Date d2 = addMinutes(d1, offsetMin); 558 Date d3 = d1.after(d2) ? d1 : d2; 559 d3 = clearTime(d3); 560 int n = 0; 561 do { 562 d3 = addDays(d3, -1); 563 if (d3.after(d0) && !d2.before(d3)) { 564 n++; 565 } 566 } while (d3.after(d0)); 567 return n; 568 } 569 570 /** 571 * 分钟偏移 572 * 573 * @param date 时间 574 * @param offsetDay 天数 575 * @param offsetMin 分钟数 576 * @return 577 */ 578 public static Date moveMinute(Date date, int offsetDay, int offsetMin) { 579 if (date == null) return null; 580 Date d1 = addDays(date, offsetDay); 581 Date d2 = addMinutes(d1, offsetMin); 582 return addDays(d2, -offsetDay); 583 } 584 585 /** 586 * 分钟偏移 587 * 588 * @param hm 时分 589 * @param offsetDay 天数 590 * @param offsetMin 分钟数 591 * @return 592 */ 593 public static String moveMinute(String hm, int offsetDay, int offsetMin) { 594 Date date = DateUtils.parse(Pattern.TIME_HM_S, hm); 595 if (date == null) return null; 596 // logger.info("{}|{}|{}", formatTime(d1), formatTime(d2), formatTime(d3)); 597 return format(Pattern.TIME_HM_S, moveMinute(date, offsetDay, offsetMin)); 598 } 599 600 601 /** 602 * 两个日期取小值 603 * 604 * @param date1 605 * @param date2 606 * @return 607 */ 608 public static Date min(Date date1, Date date2) { 609 if (date1 == null) return date2; 610 else if (date2 == null) return date1; 611 else if (date1.after(date2)) return date2; 612 return date1; 613 } 614 615 /** 616 * 两个日期取大值 617 * 618 * @param date1 619 * @param date2 620 * @return 621 */ 622 public static Date max(Date date1, Date date2) { 623 if (date1 == null) return date2; 624 else if (date2 == null) return date1; 625 else if (date1.before(date2)) return date2; 626 return date1; 627 } 628 629 /** 630 * <p>Title: exchangeDate</p> 631 * <p>Description: </p> 632 * 633 * @param nyr 取年月日 634 * @param sfm 取时分 635 * @return 636 */ 637 public static Date exchangeDate(Date nyr, Date sfm) { 638 Date date = new Date(); 639 try { 640 String sfmStr = format(Pattern.TIME_HM, sfm); 641 String nyrStr = format(nyr); 642 date = parse(Pattern.DATETIME_YMDHM_CN, nyrStr + " " + sfmStr); 643 } catch (Exception e) { 644 } 645 return date; 646 } 647 648 public static String exchangeString(Date nyr, Date sfm) { 649 Date date = new Date(); 650 try { 651 String sfmStr = format(Pattern.TIME_HM, sfm); 652 String nyrStr = format(nyr); 653 return nyrStr + " " + sfmStr; 654 } catch (Exception e) { 655 } 656 return formatTimeYMDHM(date); 657 } 658 659 }View Code
System系统 - SystemUtil.java

1 package com.sf.shiva.trtms.ground.core.utils; 2 3 import java.net.InetAddress; 4 import java.net.NetworkInterface; 5 import java.net.UnknownHostException; 6 import java.util.Enumeration; 7 import java.util.Properties; 8 9 10 import org.slf4j.Logger; 11 import org.slf4j.LoggerFactory; 12 13 14 public class SystemUtil { 15 16 17 private static Logger LOG = LoggerFactory.getLogger(SystemUtil.class); 18 19 20 /** 21 * 返回本机IP的字符串形式 22 * 23 * @return 24 * @throws Exception 25 */ 26 public static String getLocalIp() throws Exception { 27 InetAddress inetAddress; 28 29 30 inetAddress = getSystemLocalIP(); 31 if (null != inetAddress) { 32 String ip = inetAddress.getHostAddress(); 33 LOG.info("获取的本机IP为{}", ip); 34 return ip; 35 } 36 throw new Exception("获取ip失败"); 37 } 38 39 40 /** 41 * 获取本机ip的InetAddress形式 42 * 43 * @return 44 * @throws Exception 45 */ 46 private static InetAddress getSystemLocalIP() throws Exception { 47 48 49 InetAddress inetAddress; 50 String osName = getSystemOsName(); 51 if ("Windows".compareToIgnoreCase(osName) < 0) { 52 inetAddress = getWinLocalIp(); 53 } else { 54 inetAddress = getUnixLocalIp(); 55 } 56 return inetAddress; 57 } 58 59 60 /** 61 * 获取类Unix系统的IP 62 * 63 * @return 64 * @throws Exception 65 */ 66 private static InetAddress getUnixLocalIp() throws Exception { 67 Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); 68 if (null == netInterfaces) { 69 throw new Exception("获取类Unix系统的IP失败"); 70 } 71 InetAddress ip = null; 72 while (netInterfaces.hasMoreElements()) { 73 NetworkInterface ni = netInterfaces.nextElement(); 74 if (ni.isUp()) { 75 Enumeration<InetAddress> addressEnumeration = ni.getInetAddresses(); 76 while (addressEnumeration.hasMoreElements()) { 77 ip = addressEnumeration.nextElement(); 78 if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) { 79 return ip; 80 } 81 } 82 } 83 } 84 throw new Exception("获取类Unix系统的IP失败"); 85 } 86 87 88 /** 89 * 获取window系统的ip,貌似不会返回null 90 * 91 * @return 92 * @throws UnknownHostException 93 */ 94 private static InetAddress getWinLocalIp() throws UnknownHostException { 95 InetAddress inetAddress = InetAddress.getLocalHost(); 96 return inetAddress; 97 } 98 99 100 /** 101 * 获取操作系统名称 102 * 103 * @return 104 */ 105 private static String getSystemOsName() { 106 Properties props = System.getProperties(); 107 String osName = props.getProperty("os.name"); 108 return osName; 109 } 110 111 112 /** 113 * 获取内存信息 114 * 115 * @return 116 */ 117 public static final String getRamInfo() { 118 Runtime rt = Runtime.getRuntime(); 119 return "RAM:" + rt.totalMemory()/1024/1024 + "MB total," + rt.freeMemory()/1024/1024 + "MB free."; 120 } 121 122 123 public static void main(String[] args) { 124 try { 125 getLocalIp(); 126 } catch (Exception e) { 127 LOG.error("failed"); 128 } 129 } 130 }View Code
MySql加解密 - MySqlCryptoUtils.java

1 package com.sf.shiva.trtms.ground.core.utils; 2 3 import com.sf.shiva.trtms.ground.core.error.UnsupportedRuntimeException; 4 import org.apache.commons.codec.binary.Hex; 5 import org.slf4j.Logger; 6 import org.slf4j.LoggerFactory; 7 8 import javax.crypto.Cipher; 9 import javax.crypto.spec.SecretKeySpec; 10 import java.io.UnsupportedEncodingException; 11 12 public class MySqlCryptoUtils { 13 14 private static final Logger logger = LoggerFactory.getLogger(MySqlCryptoUtils.class); 15 16 private MySqlCryptoUtils() { 17 } 18 19 /** 20 * AES-密钥 21 * 22 * @param key--密钥串 23 * @param encoding--编码 24 * @return 25 */ 26 private static SecretKeySpec generateMySQLAESKey(final String key, final String encoding) { 27 try { 28 final byte[] finalKey = new byte[16]; 29 int i = 0; 30 for (byte b : key.getBytes(encoding)) 31 finalKey[i++ % 16] ^= b; 32 return new SecretKeySpec(finalKey, "AES"); 33 } catch (UnsupportedEncodingException e) { 34 throw new UnsupportedRuntimeException(e); 35 } 36 } 37 38 /** 39 * 字符串AES加密(mysql) 40 * 41 * @param src-- 需要加密的字符串 42 * @param key-- 密钥 43 * @return 44 */ 45 public static String mysqlEncryptToHex(String src, String key) { 46 String encryptString = null; 47 try { 48 Cipher encryptCipher = Cipher.getInstance("AES"); 49 SecretKeySpec secretKeySpec = generateMySQLAESKey(key, "UTF-8");// 密钥 50 encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); 51 52 byte[] bytes = encryptCipher.doFinal(src.getBytes()); 53 encryptString = new String(Hex.encodeHex(bytes)); 54 } catch (Exception e) { 55 logger.error("The MySqlCrypto.mysqlDecryptToHex Exception!", e); 56 } 57 return encryptString; 58 } 59 60 /** 61 * 字符串AES解密(mysql) 62 * 63 * @param value--加密后的十六进制字符串 64 * @param key-- 密钥 65 * @return 66 */ 67 public static String mysqlDecryptToHex(String value, String key) { 68 String decryptString = null; 69 try { 70 Cipher decryptCipher = Cipher.getInstance("AES"); 71 SecretKeySpec secretKeySpec = generateMySQLAESKey(key, "UTF-8");// 密钥 72 decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec); 73 74 byte[] bytes = Hex.decodeHex(value.toCharArray()); 75 bytes = decryptCipher.doFinal(bytes); 76 decryptString = new String(bytes); 77 } catch (Exception e) { 78 logger.error("The MySqlCrypto.mysqlDecryptToHex Exception!", e); 79 } 80 return decryptString; 81 } 82 }View Code

1 package com.sf.shiva.trtms.ground.core.error; 2 3 /** 4 * 不支持-运行时异常 5 * 6 */ 7 public class UnsupportedRuntimeException extends GrdRuntimeException { 8 9 /** 10 * 不用的 11 */ 12 private static final long serialVersionUID = 1L; 13 14 public UnsupportedRuntimeException() { 15 super("Unsupported Runtime Exception!"); 16 } 17 18 public UnsupportedRuntimeException(Throwable e) { 19 super("Unsupported Runtime Exception!", e); 20 } 21 22 public UnsupportedRuntimeException(String code, String msg) { 23 super(msg); 24 this.code = code; 25 } 26 }UnsupportedRuntimeException Code
SQLUtils - SQLUtils.java

1 package com.sf.shiva.trtms.ground.core.utils; 2 3 import java.util.regex.Pattern; 4 5 public class SQLUtils { 6 7 private SQLUtils() { 8 } 9 10 private final static String[] patternList = {".*(update|UPDATE) .*(set|SET) .*", ".*(delete|DELETE_PLAN) .*(from|FROM) .*", ".*(drop|DROP) .*", ".*(alter|ALTER) .*(table|TABLE) .*", ".*(truncate|TRUNCATE) .*"}; 11 12 public static boolean isSelectSql(String sql) { 13 if ( org.apache.commons.lang3.StringUtils.isBlank(sql)) { 14 return false; 15 } 16 for (String pattern : patternList) { 17 boolean ok = Pattern.matches(pattern, sql); 18 if (ok) return false; 19 } 20 return true; 21 } 22 23 public enum Type { 24 SELECT, UPDATE, CREATE, DELETE, UNKNOW, DROP, ALTER, TRUNCATE 25 } 26 27 public static Type parseType(String sql) { 28 String tmp = org.apache.commons.lang3.StringUtils.trim(sql); 29 String[] lines = tmp.split("\n"); 30 String sqlStart = ""; 31 if (lines.length <= 1) { 32 sqlStart = tmp; 33 } else { 34 int i = 0; 35 for (String line : lines) { 36 if ( org.apache.commons.lang3.StringUtils.isBlank(line)) { 37 continue; 38 } 39 if (line.startsWith("/*")) { 40 i = 1; 41 } else if (i == 0 && !line.startsWith("-- ") && !line.startsWith("#")) { 42 sqlStart = line; 43 break; 44 } else if (line.startsWith("*/")) { 45 i = 0; 46 } 47 } 48 } 49 50 if (sqlStart.startsWith("select") || sqlStart.startsWith("SELECT")) { 51 return Type.SELECT; 52 } else if (sqlStart.startsWith("update") || sqlStart.startsWith("UPDATE")) { 53 return Type.UPDATE; 54 } else if (sqlStart.startsWith("create") || sqlStart.startsWith("CREATE")) { 55 return Type.CREATE; 56 } else if (sqlStart.startsWith("delete") || sqlStart.startsWith("DELETE_PLAN")) { 57 return Type.DELETE; 58 } else if (sqlStart.startsWith("drop") || sqlStart.startsWith("DROP")) { 59 return Type.DROP; 60 } else if (sqlStart.startsWith("alter") || sqlStart.startsWith("ALTER")) { 61 return Type.ALTER; 62 } else if (sqlStart.startsWith("truncate") || sqlStart.startsWith("TRUNCATE")) { 63 return Type.TRUNCATE; 64 } 65 return Type.UNKNOW; 66 } 67 }View Code
MapUtil请求URL - MapUtil.java

1 /* 2 * Copyright (c) 2017, S.F. Express Inc. All rights reserved. 3 */ 4 package com.sf.shiva.trtms.ground.core.utils; 5 6 import org.dom4j.Document; 7 import org.dom4j.DocumentException; 8 import org.dom4j.DocumentHelper; 9 import org.dom4j.Element; 10 import org.json.JSONObject; 11 import org.slf4j.LoggerFactory; 12 13 import java.io.BufferedReader; 14 import java.io.IOException; 15 import java.io.InputStreamReader; 16 import java.io.UnsupportedEncodingException; 17 import java.net.URL; 18 import java.net.URLConnection; 19 import java.net.URLEncoder; 20 21 22 /** 23 * 请求url操作工具类 24 */ 25 public class MapUtil { 26 private static org.slf4j.Logger logger = LoggerFactory.getLogger(MapUtil.class); 27 28 //请求url获取string字符串 29 public static String loadUrl(String url) { 30 StringBuilder json = new StringBuilder(); 31 BufferedReader in = null; 32 try { 33 URL server = new URL(url); 34 URLConnection yc = server.openConnection(); 35 yc.setRequestProperty("accept", "*/*"); 36 yc.setRequestProperty("connection", "Keep-Alive"); 37 //建立连接 38 yc.connect(); 39 40 in = new BufferedReader(new InputStreamReader( 41 yc.getInputStream(), "utf-8"));//防止乱码 42 String inputLine = null; 43 while ((inputLine = in.readLine()) != null) { 44 json.append(inputLine); 45 } 46 } catch (IOException e) { 47 logger.error("An anomaly occurs in the analysis of latitude and longitude:{}", e.getMessage()); 48 } finally { 49 IOUtils.close(in); 50 } 51 return json.toString(); 52 } 53 54 //解析获取json数据 55 public static String getKey(String url, String key) { 56 JSONObject obj = new JSONObject(url); 57 return obj.getString(key); 58 } 59 60 61 /** 62 * 拼装解析经纬度url 63 * 64 * @param citys 省市 省市之间用,分割,还要判断市是否有/,如有,取第一个市 65 * @return 66 * @params url 图吧url 67 */ 68 public static String convertCityUrl(String url, String citys) { 69 StringBuffer sb = new StringBuffer(url); 70 String[] cs = citys.split(","); 71 String province = cs[0]; 72 String city = cs[1]; 73 if (city.contains("/")) { 74 city = city.split("/")[0]; 75 } 76 try { 77 sb.append("/geocoding/getLatLonByAddress.json?encode=UTF-8&customer=2").append("&keyword=").append(URLEncoder.encode(province + city, "UTF-8")); 78 sb.append("&city=").append(URLEncoder.encode(city, "UTF-8")); 79 80 } catch (UnsupportedEncodingException e) { 81 return null; 82 } 83 return sb.toString(); 84 } 85 86 /** 87 * 拼装根据经纬度获取距离的url 88 * 89 * @param oriLatLon 始发城市经纬度 如 19.232,123.232 90 * @param destLatLon 目的城市经纬度 91 * @param mid :['0', "地址到地址"], ['1', "网点到网点"],['2', "地址到网点"],['3', "网点到地址"],['4', "车辆当前位置到网点"] 92 * @param style : ['0', "最快路线"],['1', "最短路线"], ['6', "避开高速"],['3', "步行"] 93 * @return 94 * @params url 图吧url 95 */ 96 public static String convertDistanceUrl(String url, String oriLatLon, String destLatLon, String mid, int style) { 97 StringBuffer sb = new StringBuffer(url); 98 sb.append("/route/getDriveByLatLon.xml?customer=2&encode=UTF-8"); 99 sb.append("&orig=").append(oriLatLon).append("&dest=").append(destLatLon); 100 if (mid != null && !"".equals(mid)) { 101 sb.append("&mid=").append(mid); 102 } 103 sb.append("&style=").append(style).append("&inGb=g02&outGb=g02"); 104 return sb.toString(); 105 } 106 107 //根据经纬度解析xml获取距离 108 public static String getDistance(String xml) { 109 String value = null; 110 try { 111 Document doc = DocumentHelper.parseText(xml); 112 Element root = doc.getRootElement(); 113 value = root.elementText("distance"); 114 } catch (DocumentException e) { 115 return null; 116 } 117 return value; 118 } 119 120 }View Code
BaseResult接口返回 - aseResult.java

1 package com.sf.shiva.trtms.ground.core.http; 2 3 import java.io.Serializable; 4 import java.util.ArrayList; 5 import java.util.Collection; 6 7 public class BaseResult<T> implements Serializable { 8 9 private int status = 0; 10 private String code; 11 private String msg; 12 13 private Collection<T> records = new ArrayList<>(); 14 15 public BaseResult() { 16 } 17 18 public BaseResult(T record) { 19 this.status = 1; 20 this.records = new ArrayList<>(); 21 this.records.add(record); 22 } 23 24 public BaseResult(Collection<T> records) { 25 if (records != null && !records.isEmpty()) { 26 this.status = 1; 27 this.records = records; 28 } 29 } 30 31 public Collection<T> getRecords() { 32 return records; 33 } 34 35 public void setRecords(Collection<T> records) { 36 if (records != null && !records.isEmpty()) { 37 this.status = 1; 38 this.records = records; 39 } 40 } 41 42 public int getStatus() { 43 return status; 44 } 45 46 public void setStatus(int status) { 47 this.status = status; 48 } 49 50 public String getCode() { 51 return code; 52 } 53 54 public void setCode(String code) { 55 this.code = code; 56 } 57 58 public String getMsg() { 59 return msg; 60 } 61 62 public void setMsg(String msg) { 63 this.msg = msg; 64 } 65 66 67 public boolean isSuccess() { 68 return status == 1; 69 } 70 71 public boolean isEmpty() { 72 return records == null || records.isEmpty(); 73 } 74 75 public T get() { 76 if (isEmpty()) { 77 return null; 78 } 79 return records.iterator().next(); 80 } 81 }View Code
PlatformUtils获取本机IP - PlatformUtils.java

1 package com.sf.shiva.trtms.ground.core.utils; 2 3 import org.slf4j.Logger; 4 import org.slf4j.LoggerFactory; 5 6 import java.net.InetAddress; 7 import java.net.NetworkInterface; 8 import java.net.SocketException; 9 import java.net.UnknownHostException; 10 11 public class PlatformUtils { 12 13 private static final Logger LOG = LoggerFactory.getLogger(PlatformUtils.class); 14 15 private PlatformUtils() { 16 } 17 18 /** 19 * 获取本机器的IP地址 20 * 21 * @return 22 */ 23 public static String getLocalHostIp() { 24 try { 25 InetAddress addr = InetAddress.getLocalHost(); 26 return addr.getHostAddress(); 27 } catch (UnknownHostException e) { 28 LOG.error("getLocalHostIp()", e); 29 return "N/A"; 30 } 31 } 32 33 /** 34 * 获取本机器的MAC地址 35 * 36 * @return 37 * @throws Exception 38 */ 39 public static String getLocalHostMac() { 40 try { 41 InetAddress inetAddress = InetAddress.getLocalHost(); 42 NetworkInterface networkInterface = NetworkInterface.getByInetAddress(inetAddress); 43 StringBuilder sb = new StringBuilder(); 44 // 获取网卡,获取地址 45 byte[] mac = networkInterface.getHardwareAddress(); 46 for (int i = 0; i < mac.length; i++) { 47 if (i != 0) { 48 sb.append(":"); 49 } 50 // 字节转换为整数 51 int temp = mac[i] & 0xff; 52 String str = Integer.toHexString(temp); 53 if (str.length() == 1) { 54 sb.append("0" + str); 55 } else { 56 sb.append(str); 57 } 58 } 59 return sb.toString().toUpperCase(); 60 } catch (UnknownHostException | SocketException ue) { 61 LOG.error("getLocalHostMac()", ue); 62 return "N/A"; 63 } 64 } 65 }View Code

更多精彩