- 日期工具类DateUtil.java提供日期计算的相关静态方法
- 接口调用工具类HttpClientUtil.java提供调用外部接口的公共方法
- 加密工具类GenMD5Util.java提供了将制定字符串加密成MD5的方法
- 公共方法抽象工具类CommonUtil.java提供了对工单表增删改查的公共方法
- 获取Bean实例工具类SpringContextUtil.java提供了根据bean id获取Bean实例的方法
- 实体Bean和JSON转换工具类JsonToBeanUtil.java提供了json和bean相互转换的方法
- 流程工具类FlowUtil.java提供了字符串转换和解析response的常用方法
- 文件上传工具类FileUpLoadUtil.java封装了上传的公共方法
- 工具类CookieUtil.java提供了常用的操纵缓存的方法
- 表格Excel转换实体Bean工具类ExcelUtil.java提供了文件导入导出的方法
- 复用$control.setTemplate("web:orderOptList.vm")实现日志记录
- JDK反射提供抽象参数类实现动态加载
- api auth授权机制保证外部调用接口的安全性
1.日期工具类DateUtil.java提供了常用的日期计算方法,涉及SimpleDateFormat、Calendar、Date三个类,附上代码:
1 package com.alibaba.tboss.util; 2 3 import java.math.BigDecimal; 4 import java.text.DateFormat; 5 import java.text.SimpleDateFormat; 6 import java.util.Calendar; 7 import java.util.Date; 8 import java.util.GregorianCalendar; 9 import java.util.Locale; 10 11 import org.apache.commons.lang3.StringUtils; 12 13 import com.alibaba.common.lang.StringUtil; 14 import com.alibaba.nonda.json.ParseException; 15 16 public class DateUtil { 17 18 public static final String DATE_FORMAT = "yyyy-MM-dd"; 19 public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; 20 public static final String DATETIME = "yyyyMMddHHmmss"; 21 22 /** 23 * 计算两个日期之间相差的天数 24 * 25 * @param smdate 较小的时间 26 * @param bdate 较大的时间 27 * @return 相差天数 28 * @throws ParseException 29 * @throws Exception 30 */ 31 public static int daysBetween(Date smdate, Date bdate) { 32 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 33 try { 34 smdate = sdf.parse(sdf.format(smdate)); 35 bdate = sdf.parse(sdf.format(bdate)); 36 } catch (java.text.ParseException e) { 37 e.printStackTrace(); 38 } 39 Calendar cal = Calendar.getInstance(); 40 cal.setTime(smdate); 41 long time1 = cal.getTimeInMillis(); 42 cal.setTime(bdate); 43 long time2 = cal.getTimeInMillis(); 44 long between_days = (time2 - time1) / (1000 * 3600 * 24); 45 return new BigDecimal(String.valueOf(between_days)).abs().intValue(); 46 } 47 48 /** 49 * @description 将时间字符串转化为Date 50 * @author Anan 51 * @time 2013年7月26日 下午7:50:32 52 * @param time 时间字符串 53 * @param formatStr 时间格式 如"2013-7-26 19:52:47"、"2013-7-26" 54 * @return 55 */ 56 public static Date toDate(String time, String formatStr) { 57 Date date = null; 58 DateFormat dateFormat = new SimpleDateFormat(formatStr); 59 try { 60 date = dateFormat.parse(time); 61 } catch (java.text.ParseException e) { 62 e.printStackTrace(); 63 } 64 return date; 65 } 66 67 public static Date toDatebyday(String time, String formatStr) { 68 Date date = null; 69 DateFormat dateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH); 70 try { 71 date = dateFormat.parse(time); 72 } catch (java.text.ParseException e) { 73 e.printStackTrace(); 74 } 75 return date; 76 } 77 78 public static String toDatebydaytoString(String time, String formatStr) throws java.text.ParseException { 79 Date date = null; 80 String dateString = ""; 81 DateFormat dateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH); 82 83 date = dateFormat.parse(time); 84 dateString = formateDate(date); 85 86 return dateString; 87 } 88 89 public static Date toDatebytime(Date time, String formatStr) throws java.text.ParseException { 90 Date date = null; 91 String dateString = ""; 92 DateFormat dateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH); 93 94 dateString = formateDate(time); 95 date = toDate(dateString); 96 97 return date; 98 } 99 100 /** 101 * @description 将日期转化为字符串 102 * @author Anan 103 * @time 2013年7月30日 下午4:32:30 104 * @param date 105 * @param formatStr 106 * @return 107 */ 108 public static String toString(Date date, String formatStr) { 109 if (null == date || StringUtils.isBlank(formatStr)) return ""; 110 SimpleDateFormat sdf = new SimpleDateFormat(formatStr); 111 return sdf.format(date); 112 } 113 114 /** 115 * @description 将年月日转化为日期 116 * @author Anan 117 * @time 2013年7月30日 下午5:00:33 118 * @param year 119 * @param month 120 * @param day 121 * @return 122 * @throws java.text.ParseException 123 */ 124 public static Date toDate(int year, int month, int day) throws java.text.ParseException { 125 Date date = null; 126 Calendar calender = Calendar.getInstance(); 127 calender.set(Calendar.YEAR, year); 128 calender.set(Calendar.MONTH, month - 1); 129 calender.set(Calendar.DATE, day); 130 calender.set(Calendar.HOUR_OF_DAY, 0); 131 calender.set(Calendar.MINUTE, 0); 132 calender.set(Calendar.SECOND, 0); 133 date = calender.getTime(); 134 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 135 date = sdf.parse(sdf.format(date)); 136 return date; 137 } 138 139 /** 140 * @description 结束日期属于开始日期后的第几个月的日期 141 * @author Anan 142 * @time 2013年8月27日 下午10:00:33 143 * @param startDate 开始日期 144 * @param endDate 结束日期 145 * @return 146 */ 147 public static int monthsFromStartDate(Date startDate, Date endDate) { 148 int result = 0; 149 Date temp = null; 150 startDate = toDate(toString(startDate, "yyyy-MM-dd"), "yyyy-MM-dd"); 151 endDate = toDate(toString(endDate, "yyyy-MM-dd"), "yyyy-MM-dd"); 152 // 开始日期 大于 结束日期 两个日期互换 例如: startDate 2013-05-21 endDate = 2013-04-20 153 if (startDate.after(endDate)) { 154 temp = startDate; 155 startDate = endDate; 156 endDate = temp; 157 } 158 Date tempEndDate1 = null; 159 Date tempEndDate2 = null; 160 int a = getDayOfMonth(startDate); 161 int b = getDayOfMonth(endDate); 162 int c = a - b; 163 Calendar c1 = Calendar.getInstance(); 164 Calendar c2 = Calendar.getInstance(); 165 c1.setTime(startDate); 166 c2.setTime(endDate); 167 c2.set(Calendar.DAY_OF_MONTH, a); 168 tempEndDate2 = c2.getTime(); 169 int i = 0; 170 while (true) { 171 tempEndDate1 = addToMonth(startDate, i); 172 if (tempEndDate1.compareTo(tempEndDate2) == 0) { 173 result = i; 174 break; 175 } 176 i++; 177 if (i == 999999999) {// 防止死循环 178 break; 179 } 180 } 181 if (c < 0) { 182 result = result + 1; 183 } 184 return result; 185 } 186 187 /** 188 * 获取开始时间与结束时间之间间隔的月数 189 * 190 * @author yansong 191 * @param startDate 192 * @param endDate 193 * @return 194 */ 195 public static int monthsBetween(Date startDate, Date endDate) { 196 int iMonth = 0; 197 try { 198 Calendar objCalendarDateStart = Calendar.getInstance(); 199 objCalendarDateStart.setTime(startDate); 200 Calendar objCalendarDateEnd = Calendar.getInstance(); 201 objCalendarDateEnd.setTime(endDate); 202 if (objCalendarDateEnd.equals(objCalendarDateStart) || objCalendarDateStart.after(objCalendarDateEnd)) { 203 return 0; 204 } else { 205 if (objCalendarDateEnd.get(Calendar.YEAR) > objCalendarDateStart.get(Calendar.YEAR)) { 206 iMonth = (objCalendarDateEnd.get(Calendar.YEAR) - objCalendarDateStart.get(Calendar.YEAR)) * 12 207 + objCalendarDateEnd.get(Calendar.MONTH) - objCalendarDateStart.get(Calendar.MONTH); 208 } else { 209 iMonth = objCalendarDateEnd.get(Calendar.MONTH) - objCalendarDateStart.get(Calendar.MONTH); 210 } 211 } 212 213 } catch (Exception e) { 214 e.printStackTrace(); 215 } 216 return iMonth; 217 } 218 219 /** 220 * 获取输入日期所在月份的第一天 221 * 222 * @author yansong 223 * @param date 224 * @return 225 */ 226 public static Date getFristDateForCurrentMonth(Date date) { 227 Calendar cal = Calendar.getInstance(); 228 cal.setTime(date); 229 cal.set(GregorianCalendar.DAY_OF_MONTH, 1); 230 231 return cal.getTime(); 232 } 233 234 /** 235 * 获取输入日期所在月份的最后一天 236 * 237 * @author yansong 238 * @param date 239 * @return 240 */ 241 public static Date getLastDateForCurrentMonth(Date date) { 242 Calendar cal = Calendar.getInstance(); 243 cal.setTime(date); 244 245 cal.set(Calendar.DATE, 1); 246 cal.roll(Calendar.DATE, -1); 247 248 return cal.getTime(); 249 } 250 251 /** 252 * @description 获取某年某月的第一天 253 * @author Anan 254 * @time 2013年7月30日 下午4:27:53 255 * @param year 某年 256 * @param month 某月 257 * @return 258 */ 259 public static Date getMonthBegin(int year, int month) { 260 Date _month_begin = null; 261 Calendar calender = Calendar.getInstance(); 262 calender.set(Calendar.YEAR, year); 263 calender.set(Calendar.MONTH, month - 1); 264 calender.set(Calendar.DATE, 1);// 把日期设置为当月第一天 265 calender.set(Calendar.HOUR_OF_DAY, 0); 266 calender.set(Calendar.MINUTE, 0); 267 calender.set(Calendar.SECOND, 0); 268 _month_begin = calender.getTime(); 269 return _month_begin; 270 } 271 272 /** 273 * @description 获取某年某月的最后一天 274 * @author Anan 275 * @time 2013年7月30日 下午4:28:59 276 * @param year 某年 277 * @param month 某月 278 * @return 279 */ 280 public static Date getMonthEnd(int year, int month) { 281 Date month_end = null; 282 Calendar calender = Calendar.getInstance(); 283 calender.set(Calendar.YEAR, year); 284 calender.set(Calendar.MONTH, month - 1); 285 calender.set(Calendar.DATE, 1);// 把日期设置为当月第一天 286 calender.roll(Calendar.DATE, -1);// 日期回滚一天,也就是最后一天 287 calender.set(Calendar.HOUR_OF_DAY, 0); 288 calender.set(Calendar.MINUTE, 0); 289 calender.set(Calendar.SECOND, 0); 290 month_end = calender.getTime(); 291 return month_end; 292 } 293 294 /** 295 * @description 得到指定月的天数 296 * @author Anan 297 * @time 2013年7月30日 下午4:48:00 298 * @param year 某年 299 * @param month 某月 300 * @return 301 */ 302 public static int getMonthLastDay(int year, int month) { 303 Calendar calender = Calendar.getInstance(); 304 calender.set(Calendar.YEAR, year); 305 calender.set(Calendar.MONTH, month - 1); 306 calender.set(Calendar.DATE, 1);// 把日期设置为当月第一天 307 calender.roll(Calendar.DATE, -1);// 日期回滚一天,也就是最后一天 308 int maxDate = calender.get(Calendar.DATE); 309 return maxDate; 310 } 311 312 /** 313 * @description 得到当前日期月的天数 314 * @author Anan 315 * @time 2013年9月1日 下午1:01:44 316 * @param date 317 * @return 318 */ 319 public static int getMonthLastDay(Date date) { 320 Calendar calender = Calendar.getInstance(); 321 calender.setTime(date); 322 calender.set(Calendar.DATE, 1);// 把日期设置为当月第一天 323 calender.roll(Calendar.DATE, -1);// 日期回滚一天,也就是最后一天 324 int maxDate = calender.get(Calendar.DATE); 325 return maxDate; 326 } 327 328 /** 329 * @description 得到日期中的月份 330 * @author William 331 * @time 2013年10月24日 下午1:01:44 332 * @param date 333 * @return 334 */ 335 public static int getMonth(Date date) { 336 Calendar calendar = Calendar.getInstance(); 337 calendar.setTime(date); 338 return calendar.get(Calendar.MONTH); 339 } 340 341 /** 342 * @description 当月的第几天 343 * @author Anan 344 * @time 2013年8月22日 下午9:24:30 345 * @param date 346 * @return 347 */ 348 public static int getDayOfMonth(Date date) { 349 Calendar cal = Calendar.getInstance(); 350 cal.setTime(date); 351 return cal.get(Calendar.DAY_OF_MONTH); 352 } 353 354 /** 355 * @description 获得当前日期 + N个月 之后的日期 356 * @author Anan 357 * @time 2013年8月23日 上午12:26:53 358 * @param oldDate 359 * @param n 360 * @return 361 */ 362 public static Date addToMonth(Date oldDate, int n) { 363 Date newDate = null; 364 Calendar calOld = Calendar.getInstance(); 365 calOld.setTime(oldDate); 366 int month = calOld.get(Calendar.MONTH); 367 Calendar calNew = Calendar.getInstance(); 368 calNew.setTime(oldDate); 369 calNew.set(Calendar.MONTH, n + month); 370 newDate = calNew.getTime(); 371 return newDate; 372 } 373 374 /** 375 * @description 获得当前日期 减去 N月 之后的日期 376 * @author Anan 377 * @time 2013年9月1日 上午12:26:53 378 * @param oldDate 379 * @param n 380 * @return 381 */ 382 public static Date removeMonths(Date oldDate, int n) { 383 Date newDate = null; 384 Calendar calOld = Calendar.getInstance(); 385 calOld.setTime(oldDate); 386 int month = calOld.get(Calendar.MONTH); 387 Calendar calNew = Calendar.getInstance(); 388 calNew.setTime(oldDate); 389 calNew.set(Calendar.MONTH, month - n); 390 newDate = calNew.getTime(); 391 return newDate; 392 } 393 394 /** 395 * @description 获得当前日期 减去 N天 之后的日期 396 * @author Anan 397 * @time 2013年8月23日 上午12:26:53 398 * @param oldDate 399 * @param n 400 * @return 401 */ 402 public static Date removeDays(Date oldDate, int n) { 403 Date newDate = null; 404 Calendar calOld = Calendar.getInstance(); 405 calOld.setTime(oldDate); 406 int day = calOld.get(Calendar.DAY_OF_YEAR); 407 Calendar calNew = Calendar.getInstance(); 408 calNew.setTime(oldDate); 409 calNew.set(Calendar.DAY_OF_YEAR, day - n); 410 newDate = calNew.getTime(); 411 return newDate; 412 } 413 414 /** 415 * @description 获得当前日期 加上 N天 之后的日期 416 * @author Anan 417 * @time 2013年8月23日 上午12:26:53 418 * @param oldDate 419 * @param n 420 * @return 421 */ 422 public static Date addDays(Date oldDate, int n) { 423 Date newDate = null; 424 Calendar calOld = Calendar.getInstance(); 425 calOld.setTime(oldDate); 426 int day = calOld.get(Calendar.DAY_OF_YEAR); 427 Calendar calNew = Calendar.getInstance(); 428 calNew.setTime(oldDate); 429 calNew.set(Calendar.DAY_OF_YEAR, day + n); 430 newDate = calNew.getTime(); 431 return newDate; 432 } 433 434 /** 435 * @description 获取两个年份之间的差值 436 * @author Anan 437 * @time 2013年8月23日 上午2:28:29 438 * @param startDate 439 * @param endDate 440 * @return 441 */ 442 public static int yearsBetween(Date startDate, Date endDate) { 443 int iYears = 0; 444 Calendar calS = Calendar.getInstance(); 445 calS.setTime(startDate); 446 Calendar calE = Calendar.getInstance(); 447 calE.setTime(endDate); 448 int i = startDate.compareTo(endDate); 449 if (i == 1) { 450 iYears = calS.get(Calendar.YEAR) - calE.get(Calendar.YEAR); 451 } else if (i == -1) { 452 iYears = calE.get(Calendar.YEAR) - calS.get(Calendar.YEAR); 453 } 454 return iYears; 455 } 456 457 /** 458 * @param date 日期 459 * @param offset 偏移量,0为周日 单位为日 460 * @return WeekOfYear 461 */ 462 public static int getWeekOfYear(Date date, int offset) { 463 Calendar calendar = Calendar.getInstance(); 464 calendar.setTimeInMillis(date.getTime() - offset * 24 * 3600 * 1000L); 465 return calendar.get(Calendar.WEEK_OF_YEAR); 466 } 467 468 // public static void main(String[] args) { 469 // Date now = toDate("2013-1-12", "yyyy-MM-dd"); 470 // System.out.println(DateUtil.toString(DateUtil.addDays(now, 2),"yyyy-MM-dd")); 471 // } 472 473 /** 474 * 标准格式化date 475 * 476 * @param date 477 * @return 478 */ 479 public static String formateDate(Date date) { 480 if (date == null) { 481 return StringUtil.EMPTY_STRING; 482 } 483 484 return new SimpleDateFormat(DATE_FORMAT).format(date); 485 } 486 487 /** 488 * 标准格式化datetime 489 * 490 * @param date 491 * @return 492 */ 493 public static String formateDatetime(Date date) { 494 if (date == null) { 495 return StringUtil.EMPTY_STRING; 496 } 497 498 return new SimpleDateFormat(DATETIME_FORMAT).format(date); 499 } 500 501 /** 502 * 按照"yyyy-MM-dd"的格式转换日期字符串为Date类型 503 * 504 * @param dateStr 日期字符串 505 * @return 506 */ 507 public static Date toDate(String dateStr) { 508 Date date = null; 509 DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); 510 try { 511 date = dateFormat.parse(dateStr); 512 } catch (java.text.ParseException e) { 513 return null; 514 } 515 return date; 516 } 517 518 public static Date toDateTimes(String dateStr) { 519 520 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); 521 String result = null; 522 Date date = null; 523 try { 524 Date strToDate = sdf.parse(dateStr); 525 result = toString(strToDate, DATETIME_FORMAT); 526 date = toDate(result, DATETIME_FORMAT); 527 } catch (java.text.ParseException e) { 528 // TODO Auto-generated catch block 529 e.printStackTrace(); 530 } 531 return date; 532 533 } 534 535 public static String toDateTimeCompara(String dateStr) { 536 537 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); 538 String result = null; 539 540 try { 541 Date strToDate = sdf.parse(dateStr); 542 result = toString(strToDate, DATETIME_FORMAT); 543 544 } catch (java.text.ParseException e) { 545 // TODO Auto-generated catch block 546 e.printStackTrace(); 547 } 548 return result; 549 550 } 551 552 /** 553 * 按照"yyyy-MM-dd HH:mm:ss"的格式转换日期时间字符串为Date类型 554 * 555 * @param dateTimeStr 日期时间字符串 556 * @return 557 */ 558 public static Date toDateTime(String dateTimeStr) { 559 Date date = null; 560 DateFormat dateFormat = new SimpleDateFormat(DATETIME_FORMAT); 561 try { 562 date = dateFormat.parse(dateTimeStr); 563 } catch (java.text.ParseException e) { 564 return null; 565 } 566 return date; 567 } 568 569 public static String transferLongToDate(Long millSec) { 570 571 SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_FORMAT); 572 573 Date date = new Date(millSec); 574 575 return sdf.format(date); 576 577 } 578 579 /** 580 * 校验日期格式是否满足yyyyMMddHHmmss这种格式 581 * 582 * @param time 583 * @return 584 */ 585 public static boolean checkValidDate(String time) { 586 boolean ret = true; 587 try { 588 int year = new Integer(time.substring(0, 4)).intValue(); 589 int month = new Integer(time.substring(4, 6)).intValue(); 590 int date = new Integer(time.substring(6, 8)).intValue(); 591 int hourOfDay = new Integer(time.substring(8, 10)).intValue(); 592 int minute = new Integer(time.substring(10, 12)).intValue(); 593 int second = new Integer(time.substring(12, 14)).intValue(); 594 Calendar cal = Calendar.getInstance(); 595 cal.setLenient(false); // 允许严格检查日期格式 596 cal.set(year, month - 1, date); 597 cal.set(year, month - 1, date, hourOfDay, minute, second); 598 cal.getTime();// 该方法调用就会抛出异常 599 } catch (Exception e) { 600 e.printStackTrace(); 601 ret = false; 602 } 603 return ret; 604 } 605 606 public static void main(String[] args) { 607 String format = "20150819202020"; 608 String datestr = "09090909090909"; 609 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); 610 System.out.println("456" + checkValidDate(datestr)); 611 System.out.println("789" + toDateTimes(datestr)); 612 System.out.println("123" + toString(toDateTimes(datestr), DATETIME_FORMAT)); 613 try { 614 Date strToDate = sdf.parse(format); 615 String result = toString(strToDate, DATETIME_FORMAT); 616 System.out.println("strToDate" + strToDate); 617 System.out.println("strToDate" + result); 618 619 } catch (java.text.ParseException e) { 620 // TODO Auto-generated catch block 621 e.printStackTrace(); 622 } 623 624 } 625 626 /** 627 * 获得指定日期的后一天 628 * 629 * @param specifiedDay 630 * @return 631 */ 632 public static Date getSpecifiedDayAfter(Date date) { 633 Calendar c = Calendar.getInstance(); 634 635 c.setTime(date); 636 int day = c.get(Calendar.DATE); 637 c.set(Calendar.DATE, day + 1); 638 639 String dayAfter = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()); 640 Date newdate = toDate(dayAfter); 641 return newdate; 642 } 643 }
2.工具类HttpClientUtil.java提供了系统调用外部接口的公共方法,包括post、get方法,以及对于HTTPS协议的支持。在httpPostWithJson方法中流的关闭采用了传统的方法,如果项目的JDK版本在1.7之上,可以采用try...with...resources来关闭流。
package com.alibaba.tboss.util; 2 3 import java.io.BufferedReader; 4 import java.io.DataOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.InputStreamReader; 8 import java.io.UnsupportedEncodingException; 9 import java.net.HttpURLConnection; 10 import java.net.MalformedURLException; 11 import java.net.URL; 12 import java.util.ArrayList; 13 import java.util.List; 14 import java.util.Map; 15 16 import javax.net.ssl.SSLContext; 17 import javax.net.ssl.TrustManager; 18 import javax.net.ssl.X509TrustManager; 19 20 import org.apache.commons.lang.StringUtils; 21 import org.apache.http.HttpEntity; 22 import org.apache.http.HttpResponse; 23 import org.apache.http.NameValuePair; 24 import org.apache.http.client.HttpClient; 25 import org.apache.http.client.entity.UrlEncodedFormEntity; 26 import org.apache.http.client.methods.HttpGet; 27 import org.apache.http.client.methods.HttpPost; 28 import org.apache.http.conn.scheme.Scheme; 29 import org.apache.http.conn.ssl.SSLSocketFactory; 30 import org.apache.http.entity.StringEntity; 31 import org.apache.http.impl.client.DefaultHttpClient; 32 import org.apache.http.message.BasicNameValuePair; 33 import org.apache.http.util.EntityUtils; 34 import org.slf4j.Logger; 35 import org.slf4j.LoggerFactory; 36 37 import com.alibaba.fastjson.JSONObject; 38 import com.alibaba.fasttext.sec.url.SSRFChecker; 39 40 public class HttpClientUtil { 41 42 private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); 43 44 public static String httpPostWithJson(String ecUrl, String params) { 45 BufferedReader reader = null; 46 HttpURLConnection connection = null; 47 try { 48 URL url = new URL(ecUrl); 49 connection = (HttpURLConnection) url.openConnection(); 50 // 创建连接 51 connection.setDoOutput(true); 52 connection.setDoInput(true); 53 connection.setRequestMethod("POST"); 54 connection.setUseCaches(false); 55 connection.setInstanceFollowRedirects(true); 56 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 57 connection.connect(); 58 59 // POST请求 60 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 61 out.writeBytes(params); 62 out.flush(); 63 out.close(); 64 65 // 读取响应 66 reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 67 String lines; 68 StringBuffer sb = new StringBuffer(""); 69 while ((lines = reader.readLine()) != null) { 70 lines = new String(lines.getBytes(), "utf-8"); 71 sb.append(lines); 72 } 73 return sb.toString(); 74 } catch (MalformedURLException e) { 75 logger.error("httpPostWithJsonMalformedURLException error", e); 76 e.printStackTrace(); 77 } catch (UnsupportedEncodingException e) { 78 logger.error("httpPostWithJsonUnsupportedEncodingException error", e); 79 e.printStackTrace(); 80 } catch (IOException e) { 81 logger.error("httpPostWithJsonIOException error", e); 82 e.printStackTrace(); 83 } finally { 84 try { 85 if (null != reader) { 86 reader.close(); 87 } 88 if (null != connection) { 89 connection.disconnect(); 90 } 91 } catch (IOException e) { 92 e.printStackTrace(); 93 } 94 } 95 return null; 96 } 97 98 public static String HttpPostWithJsonByHttpClient(String url, String json) { 99 HttpClient client = new DefaultHttpClient(); 100 HttpPost post = new HttpPost(url); 101 try { 102 StringEntity s = new StringEntity(json); 103 s.setContentEncoding("UTF-8"); 104 s.setContentType("application/json"); 105 post.setEntity(s); 106 107 HttpResponse response = client.execute(post); 108 // 读取内容 109 String result = extractContent(response); 110 return result; 111 } catch (Exception e) { 112 logger.error("HttpPostWithJsonByHttpClientException error", e); 113 return null; 114 } 115 } 116 117 public static String httpPostRequest(String url, Map<String, String> params) throws Exception { 118 HttpClient httpclient = new DefaultHttpClient(); 119 HttpPost httpPost = new HttpPost(url); 120 httpPost.setHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8"); 121 List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 122 for (String key : params.keySet()) { 123 parameters.add(new BasicNameValuePair(key, params.get(key))); 124 } 125 // 创建UrlEncodedFormEntity对象 126 UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, "UTF-8"); 127 httpPost.setEntity(formEntiry); 128 129 HttpResponse response = httpclient.execute(httpPost); 130 String html = extractContent(response); 131 return html; 132 } 133 134 public static String httpGetRequest(String url) throws Exception { 135 HttpClient httpclient = new DefaultHttpClient(); 136 137 // 使用安全包进行检查是否安全 138 SSRFChecker ssrfChecker = SSRFChecker.instance; 139 if (!ssrfChecker.checkUrlWithoutConnection(url)) { 140 logger.error("HttpClientUtils SSRFCheck Errors ", url); 141 throw new RuntimeException("SSRFChecker fail, url=[" + url + "]"); 142 } 143 144 HttpPost httpGet = new HttpPost(url); 145 httpGet.setHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8"); 146 // 创建UrlEncodedFormEntity对象 147 HttpResponse response = httpclient.execute(httpGet); 148 String html = extractContent(response); 149 return html; 150 } 151 152 private static String extractContent(HttpResponse response) throws Exception { 153 String htmStr = null; 154 if (response.getStatusLine().getStatusCode() == 200) { 155 if (response != null) { 156 HttpEntity entity = response.getEntity(); 157 InputStream ins = entity.getContent(); 158 BufferedReader br = new BufferedReader(new InputStreamReader(ins, "UTF-8")); 159 StringBuffer sbf = new StringBuffer(); 160 String line = null; 161 while ((line = br.readLine()) != null) { 162 sbf.append(line); 163 } 164 // 处理内容 165 htmStr = sbf.toString(); 166 } 167 } 168 return htmStr; 169 } 170 171 /** 172 * 实现HTTPS的API访问 173 * 174 * @param sn 175 * @param nodegroup 176 * @param traceInfo 177 * @return 178 */ 179 public static boolean httpsPostRequest(String url, Map<String, Object> params) { 180 181 DefaultHttpClient httpClient = new DefaultHttpClient(); 182 try { 183 TrustManager easyTrustManager = new X509TrustManager() { 184 185 @Override 186 public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) 187 throws java.security.cert.CertificateException { 188 } 189 190 @Override 191 public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) 192 throws java.security.cert.CertificateException { 193 } 194 195 @Override 196 public java.security.cert.X509Certificate[] getAcceptedIssuers() { 197 return new java.security.cert.X509Certificate[0]; // To change body of implemented methods use File 198 // | Settings | File Templates. 199 } 200 }; 201 202 SSLContext sslcontext = SSLContext.getInstance("TLS"); 203 sslcontext.init(null, new TrustManager[] { easyTrustManager }, null); 204 SSLSocketFactory sf = new SSLSocketFactory(sslcontext); 205 Scheme sch = new Scheme("https", 443, sf); 206 httpClient.getConnectionManager().getSchemeRegistry().register(sch); 207 208 HttpPost httpPost = new HttpPost(url); 209 List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 210 for (String key : params.keySet()) { 211 if (params.get(key) != null) { 212 parameters.add(new BasicNameValuePair(key, params.get(key).toString())); 213 } 214 } 215 UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, "UTF-8"); 216 217 httpPost.setEntity(formEntiry); 218 219 HttpResponse response = httpClient.execute(httpPost); 220 HttpEntity entity = response.getEntity(); 221 String content = EntityUtils.toString(entity); 222 if (content != null) { 223 JSONObject jo = JSONObject.parseObject(content); 224 if (jo.getBooleanValue("content")) { 225 return true; 226 } 227 } 228 return false; 229 } catch (Exception e) { 230 throw new RuntimeException(e.getMessage(), e); 231 } finally { 232 httpClient.getConnectionManager().shutdown(); 233 } 234 } 235 236 public static JSONObject httpsPostRequestString(String url, Map<String, Object> params) { 237 238 DefaultHttpClient httpClient = new DefaultHttpClient(); 239 String content = ""; 240 try { 241 TrustManager easyTrustManager = new X509TrustManager() { 242 243 @Override 244 public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) 245 throws java.security.cert.CertificateException { 246 } 247 248 @Override 249 public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) 250 throws java.security.cert.CertificateException { 251 } 252 253 @Override 254 public java.security.cert.X509Certificate[] getAcceptedIssuers() { 255 return new java.security.cert.X509Certificate[0]; // To change body of implemented methods use File 256 // | Settings | File Templates. 257 } 258 }; 259 260 SSLContext sslcontext = SSLContext.getInstance("TLS"); 261 sslcontext.init(null, new TrustManager[] { easyTrustManager }, null); 262 SSLSocketFactory sf = new SSLSocketFactory(sslcontext); 263 Scheme sch = new Scheme("https", 443, sf); 264 httpClient.getConnectionManager().getSchemeRegistry().register(sch); 265 266 HttpPost httpPost = new HttpPost(url); 267 List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 268 for (String key : params.keySet()) { 269 if (params.get(key) != null) { 270 parameters.add(new BasicNameValuePair(key, params.get(key).toString())); 271 } 272 } 273 UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, "UTF-8"); 274 275 httpPost.setEntity(formEntiry); 276 277 HttpResponse response = httpClient.execute(httpPost); 278 HttpEntity entity = response.getEntity(); 279 content = EntityUtils.toString(entity); 280 if (content != null) { 281 JSONObject jo = JSONObject.parseObject(content); 282 return jo; 283 } 284 return null; 285 } catch (Exception e) { 286 logger.error("httpsPostRequestString [url={},params={},response={}] error:", url, 287 JSONObject.toJSONString(params), content, e); 288 throw new RuntimeException(e.getMessage(), e); 289 } finally { 290 httpClient.getConnectionManager().shutdown(); 291 } 292 } 293 294 public static String httpsGetByHttpclient(String url, String authorization) { 295 296 DefaultHttpClient httpClient = new DefaultHttpClient(); 297 try { 298 TrustManager easyTrustManager = new X509TrustManager() { 299 300 @Override 301 public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) 302 throws java.security.cert.CertificateException { 303 } 304 305 @Override 306 public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) 307 throws java.security.cert.CertificateException { 308 } 309 310 @Override 311 public java.security.cert.X509Certificate[] getAcceptedIssuers() { 312 return new java.security.cert.X509Certificate[0]; // To change body of implemented methods use File 313 // | Settings | File Templates. 314 } 315 }; 316 317 SSLContext sslcontext = SSLContext.getInstance("TLS"); 318 sslcontext.init(null, new TrustManager[] { easyTrustManager }, null); 319 SSLSocketFactory sf = new SSLSocketFactory(sslcontext); 320 Scheme sch = new Scheme("https", 443, sf); 321 httpClient.getConnectionManager().getSchemeRegistry().register(sch); 322 323 // 使用安全包进行检查是否安全 324 SSRFChecker ssrfChecker = SSRFChecker.instance; 325 if (!ssrfChecker.checkUrlWithoutConnection(url)) { 326 logger.error("HttpClientUtils SSRFCheck Errors ", url); 327 throw new RuntimeException("SSRFChecker fail, url=[" + url + "]"); 328 } 329 330 HttpGet httpGet = new HttpGet(url); 331 httpGet.setHeader("Authorization", authorization); 332 333 HttpResponse response = httpClient.execute(httpGet); 334 String content = extractContent(response); 335 if (StringUtils.isBlank(content)) { 336 return ""; 337 } 338 return content; 339 } catch (Exception e) { 340 throw new RuntimeException(e.getMessage(), e); 341 } finally { 342 httpClient.getConnectionManager().shutdown(); 343 } 344 } 345 346 /** 347 * https post 方式,包含Authorization认证 348 * 349 * @param url 350 * @param params 351 * @param authorization 352 * @return 353 */ 354 public static String httpsPostByHttpclient(String url, Map<String, Object> params, String authorization) { 355 DefaultHttpClient httpClient = new DefaultHttpClient(); 356 try { 357 TrustManager easyTrustManager = new X509TrustManager() { 358 359 @Override 360 public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) 361 throws java.security.cert.CertificateException { 362 } 363 364 @Override 365 public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) 366 throws java.security.cert.CertificateException { 367 } 368 369 @Override 370 public java.security.cert.X509Certificate[] getAcceptedIssuers() { 371 return new java.security.cert.X509Certificate[0]; // To change body of implemented methods use File 372 // | Settings | File Templates. 373 } 374 }; 375 376 SSLContext sslcontext = SSLContext.getInstance("TLS"); 377 sslcontext.init(null, new TrustManager[] { easyTrustManager }, null); 378 SSLSocketFactory sf = new SSLSocketFactory(sslcontext); 379 Scheme sch = new Scheme("https", 443, sf); 380 httpClient.getConnectionManager().getSchemeRegistry().register(sch); 381 382 HttpPost httpPost = new HttpPost(url); 383 httpPost.setHeader("Authorization", authorization); 384 List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 385 for (String key : params.keySet()) { 386 if (params.get(key) != null) { 387 parameters.add(new BasicNameValuePair(key, params.get(key).toString())); 388 } 389 } 390 UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, "UTF-8"); 391 392 httpPost.setEntity(formEntiry); 393 394 HttpResponse response = httpClient.execute(httpPost); 395 String content = extractContent(response); 396 if (StringUtils.isBlank(content)) { 397 return ""; 398 } 399 return content; 400 } catch (Exception e) { 401 throw new RuntimeException(e.getMessage(), e); 402 } finally { 403 httpClient.getConnectionManager().shutdown(); 404 } 405 } 406 407 }
3.加密工具类GenMD5Util.java提供了将指定字符串加密成MD5的方法。代码实现如下:
package com.alibaba.tboss.util;
2
3 import java.text.SimpleDateFormat;
4 import java.util.Date;
5
6 public class GenArmoryKeyUtil {
7
8 private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
9
10 public static void main(String[] args) {
11 Date today = new Date();
12 String username = "idcm";
13 /* 开发环境和线上环境最好配置不一样的key */
14 String key = "dNdljpq05K0a62htckqXnQ==";
15 String sign = getKey(username, today, key);
16 System.out.println(sign);
17 }
18
19 public static String getKey(String username, Date today, String key) {
20 return getMD5(username + SIMPLE_DATE_FORMAT.format(today) + key);
21 }
22
23 public static String getMD5(String value) {
24 String result = "";
25 try {
26 result = getMD5(value.getBytes("UTF-8"));
27 } catch (Exception e) {
28 System.out.println(e.getMessage());
29 }
30 return result;
31 }
32
33 public static String getMD5(byte[] bytes) {
34 char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
35 char str[] = new char[16 * 2];
36 try {
37 java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
38 md.update(bytes);
39 byte tmp[] = md.digest();
40 int k = 0;
41 for (int i = 0; i < 16; i++) {
42 byte byte0 = tmp[i];
43 str[k++] = hexDigits[byte0 >>> 4 & 0xf];
44 str[k++] = hexDigits[byte0 & 0xf];
45 }
46 } catch (Exception e) {
47 System.out.println(e.getMessage());
48 }
49 return new String(str);
50 }
51
52 }5.当spring容器启动的时候,自动把实现了ApplicationContextAware的类找出来,然后为其注入ApplicationContext属性,使得SpringContextUtil可以自由自在的根据名字获取Bean实例。当需要手动获取Bean
实例时,就可以直接使用工具类来获取。
package com.alibaba.tboss.util;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
*
* ClassName: SpringContextUtil <br/>
* Function: 在applicationContext.xml中加入配置
* <bean id="SpringContextUtil" class="com.alibaba.tboss.util.SpringContextUtil"/>
* 用来得到spring配置的Bean <br/>
* date: 2015年12月31日 <br/>
*/
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext; //Spring应用上下文环境
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
* @param applicationContext
* @throws BeansException
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取对象
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
/**
*
* getBean: 获取类型为requiredType的对象 . <br/>
*
* @param requiredType 返回对象类型
* @return 返回requiredType类型对象
*/
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
}
/**
* 获取类型为requiredType的对象
* 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException)
* @param name bean注册名
* @param requiredType 返回对象类型
* @return Object 返回requiredType类型对象
* @throws BeansException
*/
public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return applicationContext.getBean(name, requiredType);
}
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
* @param name
* @return boolean
*/
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
* 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
* @param name
* @return boolean
* @throws NoSuchBeanDefinitionException
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return applicationContext.isSingleton(name);
}
/**
* @param name
* @return Class 注册对象的类型
* @throws NoSuchBeanDefinitionException
*/
@SuppressWarnings("rawtypes")
public static Class getType(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getType(name);
}
/**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
* @param name
* @return
* @throws NoSuchBeanDefinitionException
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getAliases(name);
}
}
SpringContextUtil.java
6.项目中常用的数据类型转换中,工具类JsonToBeanUtil.java提供了json和bean相互转换的方法,主要支持gson和fastjson。
package com.alibaba.tboss.util;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class JsonToBeanUtil {
/**
* 使用com.alibaba.fastjson.JSONArray.parseArray()方法,将json转List<Bean>
*/
public static List<?> JsonToJavaBean(String json, Class objectClass) {
List<?> list = new ArrayList();
if (json != null && !"".equals(json)) {
try {
list = JSONArray.parseArray(json, objectClass);
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
/**
* 使用 com.google.gson.Gson.fromJson将json转Bean
*/
public static <T> T jsonToBean(String jsonString, Class<T> beanCalss) {
Gson gson = new Gson();
T bean = gson.fromJson(jsonString, beanCalss);
return bean;
}
public static <T> T jsonToBean(String jsonString, Class<T> beanCalss, String dateFormat) {
Gson gson = new GsonBuilder().setDateFormat(dateFormat).create();
T bean = gson.fromJson(jsonString, beanCalss);
return bean;
}
/**
* 使用 com.google.gson.Gson.fromJson将list转JSON
*/
public static String listToJson(List<?> list) {
Gson gson = new Gson();
String s = gson.toJson(list);
return s;
}
public static String listToJsonWithoutHtmlEscaping(List<?> list) {
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String s = gson.toJson(list);
return s;
}
}
JsonToBeanUtil.java
7.流程工具类FlowUtil.java,实现了字符串的不同编解码,调用post请求解析response数据。代码如下:
package com.alibaba.tboss.biz.flow.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class FlowUtil {
public static String emptyString = StringUtils.EMPTY;
/**
* 实体类Bean转JSON
*/
@SuppressWarnings("static-access")
public static String ObjectToJSON(Object obj, String key) {
if (obj != null) {
JSONObject jsonObject = new JSONObject().fromObject(obj);
if (!"".equals(key) && key != null) {
return "{" + key + ":" + jsonObject.toString() + "}";
}
return jsonObject.toString();
}
return emptyString;
}
/**
* <p>
* javaEncodeString TODO(转码)
* </p>
*
* @param v 转换字符串
* @param charset 转换格式
* @return String 设定文件
*/
public static String javaEncodeString(String v, String charset) {
try {
return URLEncoder.encode(v, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return v;
}
/**
* <p>
* javaDecodeString TODO(解码)
* </p>
*
* @param v 转换字符串
* @param charset 转换格式
* @return String 设定文件
*/
public static String javaDecodeString(String v, String charset) {
try {
return URLDecoder.decode(v, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return v;
}
/**
* 获取HttpResponse 对象内容
*/
public static String extractContent(HttpResponse response) throws Exception {
String htmStr = "";
if (response != null) {
HttpEntity entity = response.getEntity();
InputStream ins = entity.getContent();
BufferedReader br = null;
StringBuffer sbf = new StringBuffer();
try {
br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sbf.append(line);
}
} finally {
if (br != null) {
br.close();
}
}
// 处理内容
htmStr = sbf.toString();
}
return htmStr;
}
/**
* <p>
* 获取请求的数据
* </p>
*
* @param url
* @param params
* @return
* @throws Exception 参数描述
*/
public static String httpPostRequest(String url, List<NameValuePair> params) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// 创建UrlEncodedFormEntity对象
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(params, "UTF-8");
httpPost.setEntity(formEntiry);
HttpResponse response = httpclient.execute(httpPost);
String html = extractContent(response);
return html;
}
/**
* <p>
* 获取请求的数据
* </p>
*
* @param url
* @param params
* @return
* @throws Exception 参数描述
*/
public static String httpPostRequest(String url, HashMap<String, String> params) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
parameters.add(new BasicNameValuePair(key, params.get(key)));
}
// 创建UrlEncodedFormEntity对象
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, "UTF-8");
httpPost.setEntity(formEntiry);
HttpResponse response = httpclient.execute(httpPost);
String html = extractContent(response);
return html;
}
}
FlowUtil.java
8.文件上传工具类FileUpLoadUtil.java提供了文件上传的常用方法。
package com.alibaba.tboss.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.alibaba.tboss.common.idcFree.util.RackUtil;
import com.alibaba.tboss.dal.mysql.location.LocationCorrect;
import com.alibaba.tboss.dal.mysql.rack.RackCorrect;
import com.alibaba.tboss.exception.ErrorCode;
import com.alibaba.tboss.exception.ServiceException;
import com.alibaba.tboss.util.ExcelUtils.CellMapping;
public class FileUpLoadUtil {
public static <T> List<T> importFile(FileItem fileInput, String sheetName, Class<T> type) {
List<T> list = null;
if (null == fileInput) {
throw new ServiceException(ErrorCode.Params_Lost, "机柜导入文件");
}
Workbook wb = null;
InputStream is = null;
Sheet sheet = null;
try {
is = fileInput.getInputStream();
wb = new XSSFWorkbook(is);
sheet = wb.getSheet(sheetName);
} catch (Exception e) {
throw new ServiceException(ErrorCode.Upload_File_Error, "上传excel版本文件解析失败");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
if (sheet != null) {
// 初始化Excel栏目
List<CellMapping> mappingList = RackUtil.getLocationCorrectColumns();
try {
list = ExcelUtils.excel2bean(sheet, type, mappingList);
} catch (Exception e) {
throw new ServiceException(ErrorCode.Upload_File_Error, "Excel解析失败");
}
} else {
throw new ServiceException(ErrorCode.Upload_File_Error, "未找到模板对应sheet");
}
return list;
}
public static <T> List<T> importFileRack(FileItem fileInput, String sheetName, Class<T> type) {
List<T> list = null;
if (null == fileInput) {
throw new ServiceException(ErrorCode.Params_Lost, "机柜导入文件");
}
Workbook wb = null;
InputStream is = null;
Sheet sheet = null;
try {
is = fileInput.getInputStream();
wb = new XSSFWorkbook(is);
sheet = wb.getSheet(sheetName);
} catch (Exception e) {
throw new ServiceException(ErrorCode.Upload_File_Error, "上传excel版本文件解析失败");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
if (sheet != null) {
// 初始化Excel栏目
List<CellMapping> mappingList = RackUtil.getRackCorrectColumns();
try {
list = ExcelUtils.excel2bean(sheet, type, mappingList);
} catch (Exception e) {
throw new ServiceException(ErrorCode.Upload_File_Error, "Excel解析失败");
}
} else {
throw new ServiceException(ErrorCode.Upload_File_Error, "未找到模板对应sheet");
}
return list;
}
/**
* 导出文件
*/
public static void exportTemplate(List<LocationCorrect> locationCorrect, List<CellMapping> mappingList,
String fileName, String sheetName, HttpServletResponse response) {
OutputStream out = null;
try {
response.setHeader("Pragma", "public");// 解决IE浏览器在https模式下文件无法下载
response.setHeader("Cache-Control", "max-age=0");// 解决IE浏览器在https模式下文件无法下载
// 解决safari中下载会自动添加html后缀的问题
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setDateHeader("Expires", 0);
// 添加*=utf-8'解决中文文件名在firefox和safari中乱码的问题.
response.setHeader("Content-Disposition",
"attachment; filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
out = response.getOutputStream();
exportFileAsExcel(locationCorrect, mappingList, sheetName, out);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("导出异常:" + e.getMessage(), e);
} finally {
if (out != null) try {
out.close();
} catch (IOException e) {
out = null;
throw new RuntimeException("导出异常:" + e.getMessage(), e);
}
}
// 成功后返回cookie标志位
response.setHeader("SET-COOKIE", "fileDownload=true;Path=/;");
}
/**
* 导出文件
*/
public static void exportRackTemplate(List<RackCorrect> locationCorrect, List<CellMapping> mappingList,
String fileName, String sheetName, HttpServletResponse response) {
OutputStream out = null;
try {
response.setHeader("Pragma", "public");// 解决IE浏览器在https模式下文件无法下载
response.setHeader("Cache-Control", "max-age=0");// 解决IE浏览器在https模式下文件无法下载
// 解决safari中下载会自动添加html后缀的问题
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setDateHeader("Expires", 0);
// 添加*=utf-8'解决中文文件名在firefox和safari中乱码的问题.
response.setHeader("Content-Disposition",
"attachment; filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
out = response.getOutputStream();
exportFileAsExcel(locationCorrect, mappingList, sheetName, out);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("导出异常:" + e.getMessage(), e);
} finally {
if (out != null) try {
out.close();
} catch (IOException e) {
out = null;
throw new RuntimeException("导出异常:" + e.getMessage(), e);
}
}
// 成功后返回cookie标志位
response.setHeader("SET-COOKIE", "fileDownload=true;Path=/;");
}
/**
* 导出机柜列表为Excel文件
*
* @param datas 导出的机柜列表
* @param mappingList 导出的字段
* @param out 导出文件输出流
* @param sheetName 导出Excel的sheet名称
*/
public static void exportFileAsExcel(List<?> datas, List<CellMapping> mappingList, String sheetName,
OutputStream out) {
try {
// XSSFWorkbook
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet(sheetName);
ExcelUtils.bean2excel(datas, sheet, mappingList);
workbook.write(out);
} catch (Exception e) {
throw new RuntimeException("导出Excel时发生错误:" + e.getStackTrace(), e);
}
}
}
FileUploadUtil.java
9.缓存工具类CookieUtil.java文件提供了操作缓存的常用方法
package com.alibaba.tboss.util;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
/**
* 类CookieUtil.java的实现描述:操作Cookie的工具类
*
* @author chivas.liuzh 12 Jun 2011 9:30:14 PM
*/
public class CookieUtil {
private static final String PATH = "/";
/**
* US locale - all HTTP dates are in english
*/
public final static Locale LOCALE_US = Locale.US;
/**
* Pattern used for old cookies
*/
public final static String OLD_COOKIE_PATTERN = "EEE, dd-MMM-yyyy HH:mm:ss z";
//
// from RFC 2068, token special case characters
//
private static final String tspecials = "()<>@,;:\"/[]?={} ";
private static boolean checkFlag[] = new boolean[127];
static {
for (int i = 0; i < tspecials.length(); i++) {
checkFlag[tspecials.charAt(i)] = true;
}
}
public static String getCookieValue(String key, HttpServletRequest request) {
Cookie cookie = getCookie(key, request);
if (cookie == null)
return null;
return cookie.getValue();
}
public static Cookie getCookie(String key, HttpServletRequest request) {
if (request == null)
return null;
Cookie[] cookies = request.getCookies();
if (cookies == null)
return null;
Cookie value = null;
for (Cookie c : cookies) {
if (key.equals(c.getName())) {
value = c;
break;
}
}
return value;
}
public static void addCookie(String key, String value,
HttpServletResponse response) {
setCookie(key, value, -1, null, null, response);
}
public static void addCookie(String key, String value,
final boolean httpOnly, HttpServletResponse response) {
setCookie(key, value, -1, null, null, httpOnly, response);
}
public static void addCookie(String key, String value,
final boolean httpOnly, final boolean secure,
HttpServletResponse response) {
setCookie(key, value, -1, null, null, httpOnly, secure, response);
}
public static void addCookie(String key, String value, int maxAge,
HttpServletResponse response) {
setCookie(key, value, maxAge, null, null, response);
}
public static void addCookie(String key, String value, int maxAge,
final boolean httpOnly, HttpServletResponse response) {
setCookie(key, value, maxAge, null, null, httpOnly, response);
}
public static void addCookie(String key, String value, int maxAge,
final boolean httpOnly, final boolean secure,
HttpServletResponse response) {
setCookie(key, value, maxAge, null, null, httpOnly, secure, response);
}
public static void addCookie(String key, String value, int maxAge,
String path, String domainName, HttpServletResponse response) {
setCookie(key, value, maxAge, path, domainName, response);
}
public static void addCookie(String key, String value, int maxAge,
String path, String domainName, final boolean httpOnly,
HttpServletResponse response) {
setCookie(key, value, maxAge, path, domainName, httpOnly, response);
}
public static void addCookie(String key, String value, int maxAge,
String path, String domainName, final boolean httpOnly,
final boolean secure, HttpServletResponse response) {
setCookie(key, value, maxAge, path, domainName, httpOnly, secure,
response);
}
public static void removeCookie(String key, HttpServletResponse response) {
removeCookie(key, null, null, response);
}
public static void removeCookie(String key, String path, String domainName,
HttpServletResponse response) {
setCookie(key, StringUtils.EMPTY, 0, path, domainName, false, response);
}
private static void setCookie(String key, String value, int maxAge,
String path, String domainName, HttpServletResponse response) {
setCookie(key, value, maxAge, path, domainName, false, false, response);
}
private static void setCookie(String key, String value, int maxAge,
String path, String domainName, final boolean httpOnly,
HttpServletResponse response) {
setCookie(key, value, maxAge, path, domainName, httpOnly, false,
response);
}
private static void setCookie(String key, String value, int maxAge,
String path, String domainName, final boolean httpOnly,
final boolean secure, HttpServletResponse response) {
if (response != null) {
Cookie cookie = new Cookie(key, value);
cookie.setMaxAge(maxAge);
if (StringUtils.isNotBlank(path))
cookie.setPath(path);
else
cookie.setPath(PATH);
if (StringUtils.isNotBlank(domainName))
cookie.setDomain(domainName);
cookie.setVersion(0);
cookie.setSecure(secure);
if (httpOnly) {
final StringBuffer buf = new StringBuffer();
getCookieHeaderValue(cookie, buf, httpOnly);
response.addHeader(getCookieHeaderName(cookie), buf.toString());
} else
response.addCookie(cookie);
}
}
private static String getCookieHeaderName(final Cookie cookie) {
final int version = cookie.getVersion();
if (version == 1) {
return "Set-Cookie2";
} else {
return "Set-Cookie";
}
}
private static void getCookieHeaderValue(final Cookie cookie,
final StringBuffer buf, final boolean httpOnly) {
final int version = cookie.getVersion();
// this part is the same for all cookies
String name = cookie.getName(); // Avoid NPE on malformed cookies
if (name == null) {
name = "";
}
String value = cookie.getValue();
if (value == null) {
value = "";
}
buf.append(name);
buf.append("=");
maybeQuote(version, buf, value);
// add version 1 specific information
if (version == 1) {
// Version=1 ... required
buf.append("; Version=1");
// Comment=comment
if (cookie.getComment() != null) {
buf.append("; Comment=");
maybeQuote(version, buf, cookie.getComment());
}
}
// add domain information, if present
if (cookie.getDomain() != null) {
buf.append("; Domain=");
maybeQuote(version, buf, cookie.getDomain());
}
// Max-Age=secs/Discard ... or use old "Expires" format
if (cookie.getMaxAge() >= 0) {
if (version == 0) {
buf.append("; Expires=");
SimpleDateFormat dateFormat = new SimpleDateFormat(
OLD_COOKIE_PATTERN, LOCALE_US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // 必须使用GMT模式
if (cookie.getMaxAge() == 0) {
dateFormat.format(new Date(10000), buf,
new FieldPosition(0));
} else {
dateFormat.format(new Date(System.currentTimeMillis()
+ cookie.getMaxAge() * 1000L), buf,
new FieldPosition(0));
}
} else {
buf.append("; Max-Age=");
buf.append(cookie.getMaxAge());
}
} else if (version == 1) {
buf.append("; Discard");
}
// Path=path
if (cookie.getPath() != null) {
buf.append("; Path=");
maybeQuote(version, buf, cookie.getPath());
}
// Secure
if (cookie.getSecure()) {
buf.append("; Secure");
}
// HttpOnly
if (httpOnly) {
buf.append("; HttpOnly");
}
}
private static void maybeQuote(final int version, final StringBuffer buf,
final String value) {
if (version == 0 || isToken(value)) {
buf.append(value);
} else {
buf.append('"');
buf.append(value);
buf.append('"');
}
}
/*
* Return true iff the string counts as an HTTP/1.1 "token".
*/
private static boolean isToken(final String value) {
final int len = value.length();
char c;
final char[] charArray = value.toCharArray();
for (int i = 0; i < len; i++) {
c = charArray[i];
if (c < 0x20 || c >= 0x7f) {
return false;
} else {
if (checkFlag[c]) {
return false;
}
}
}
return true;
}
}
CookieUtil.java
10.表格Excel的导入导出功能实现
package com.alibaba.tboss.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.alibaba.fastjson.JSONObject;
/**
* @author yucai.xiayc Excel 解析工具,依赖POI Beanutils 1.8
*/
public class ExcelUtils {
/**
* 内置类,用来配置Excel与Bean属性的映射关系
*/
public static class CellMapping {
private String header;
private String property;
private String type;
// 熟悉下拉框数据源
private String[] propertyData;
public CellMapping(){
}
public CellMapping(String header, String property){
this.header = header;
this.property = property;
}
public CellMapping(String header, String property, String[] propertyData){
this.header = header;
this.property = property;
this.propertyData = propertyData;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String[] getPropertyData() {
return propertyData;
}
public void setPropertyData(String[] propertyData) {
this.propertyData = propertyData;
}
}
public static <T> List<T> excel2bean(Sheet sheet, Class<T> clazz, String config) throws Exception {
return excel2bean(sheet, clazz, config, 0);
}
public static <T> List<T> excel2bean(Sheet sheet, Class<T> clazz, String config, int headerRowNum) throws Exception {
List<CellMapping> mappingList = JSONObject.parseArray(config, CellMapping.class);
return excel2bean(sheet, clazz, mappingList, headerRowNum);
}
public static <T> List<T> excel2bean(Sheet sheet, Class<T> clazz, List<CellMapping> mappingList) throws Exception {
return excel2bean(sheet, clazz, mappingList, 0);
}
public static <T> List<T> importExcel2bean(Sheet sheet, Class<T> clazz, List<CellMapping> mappingList,
int headerRowNum) throws Exception {
Map<String, Integer> configMap = new HashMap<String, Integer>();
Row row = sheet.getRow(headerRowNum);
for (int c = 0; c < row.getLastCellNum(); c++) {
String key = getCellString(row.getCell(c));
if (!configMap.containsKey(key)) {
configMap.put(key, c);
} else {
throw new RuntimeException("表头第" + (configMap.get(key) + 1) + "列和第" + (c + 1) + "列重复");
}
}
List<T> resultList = new ArrayList<T>();
for (int r = headerRowNum + 1; r <= sheet.getLastRowNum(); r++) {
row = sheet.getRow(r);
T t = clazz.newInstance();
for (CellMapping cf : mappingList) {
Integer index = configMap.get(cf.getHeader());
if (index == null) {
continue;
}
if ("string".equalsIgnoreCase(cf.getType())) {
PropertyUtils.setSimpleProperty(t, cf.getProperty(), getCellString(row.getCell(index)));
} else if ("date".equalsIgnoreCase(cf.getType())) {
PropertyUtils.setSimpleProperty(t, cf.getProperty(), getCellDate(row.getCell(index)));
} else if ("double".equalsIgnoreCase(cf.getType())) {
PropertyUtils.setSimpleProperty(t, cf.getProperty(), getCellDouble(row.getCell(index)));
} else if ("float".equalsIgnoreCase(cf.getType())) {
PropertyUtils.setSimpleProperty(t, cf.getProperty(), (float) getCellDouble(row.getCell(index)));
} else if ("int".equalsIgnoreCase(cf.getType()) || "integer".equalsIgnoreCase(cf.getType())) {
PropertyUtils.setSimpleProperty(t, cf.getProperty(), (int) getCellDouble(row.getCell(index)));
} else if ("long".equalsIgnoreCase(cf.getType())) {
PropertyUtils.setSimpleProperty(t, cf.getProperty(), (long) getCellDouble(row.getCell(index)));
} else {
throw new Exception("Unrecognize Config Type");
}
}
resultList.add(t);
}
return resultList;
}
public static <T> List<T> excel2bean(Sheet sheet, Class<T> clazz, List<CellMapping> mappingList, int headerRowNum)
throws Exception {
Map<String, Integer> configMap = new HashMap<String, Integer>();
Row row = sheet.getRow(headerRowNum);
for (int c = 0; c < row.getLastCellNum(); c++) {
String key = getCellString(row.getCell(c));
if (!configMap.containsKey(key)) {
configMap.put(key, c);
} else {
throw new RuntimeException("表头第" + (configMap.get(key) + 1) + "列和第" + (c + 1) + "列重复");
}
}
List<T> resultList = new ArrayList<T>();
for (int r = headerRowNum + 1; r <= sheet.getLastRowNum(); r++) {
row = sheet.getRow(r);
if (row == null) break;// 遇空行,表示结束
T t = clazz.newInstance();
Map<String, Object> properties = new HashMap<String, Object>();
boolean flag = true;// 判断整行属性全为空
for (CellMapping cm : mappingList) {
Integer index = configMap.get(cm.getHeader());
if (index == null) {
continue;
}
Object cellValue = getCellValue(row.getCell(index));
if (cellValue != null) {
properties.put(cm.getProperty(), cellValue);
if (flag) {
flag = false;// 有一列值不为空,则为false
}
}
}
if (flag) break;// 遇一行中所有值都为空,结束
BeanUtils.populate(t, properties);
resultList.add(t);
}
return resultList;
}
public static List<Map<String, Object>> excel2map(Sheet sheet, List<CellMapping> mappingList) throws Exception {
return excel2map(sheet, mappingList, 0);
}
public static List<Map<String, Object>> excel2map(Sheet sheet, List<CellMapping> mappingList, int headerRowNum)
throws Exception {
Map<String, Integer> configMap = new HashMap<String, Integer>();
Row row = sheet.getRow(headerRowNum);
for (int c = 0; c < row.getLastCellNum(); c++) {
String key = getCellString(row.getCell(c));
if (!configMap.containsKey(key)) {
configMap.put(key, c);
} else {
throw new RuntimeException("表头第" + (configMap.get(key) + 1) + "列和第" + (c + 1) + "列重复");
}
}
List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
for (int r = headerRowNum + 1; r <= sheet.getLastRowNum(); r++) {
row = sheet.getRow(r);
if (row == null) break;// 遇空行,表示结束
Map<String, Object> properties = new HashMap<String, Object>();
boolean flag = true;// 判断整行属性全为空
for (CellMapping cm : mappingList) {
Integer index = configMap.get(cm.getHeader());
if (index == null) {
continue;
}
Object cellValue = getCellValue(row.getCell(index));
if (cellValue != null) {
properties.put(cm.getProperty(), cellValue);
if (flag) {
flag = false;// 有一列值不为空,则为false
}
}
}
if (flag) break;// 遇一行中所有值都为空,结束
resultList.add(properties);
}
return resultList;
}
public static List<Map<String, Object>> excel2mapnohead(Sheet sheet, List<CellMapping> mappingList,
HashMap<String, Integer> configMap) throws Exception {
int headerRowNum = 0;
List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
for (int r = headerRowNum; r <= sheet.getLastRowNum(); r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
Map<String, Object> properties = new HashMap<String, Object>();
for (CellMapping cm : mappingList) {
Integer index = configMap.get(cm.getHeader());
if (index == null) {
continue;
}
Object cellValue = getCellValue(row.getCell(index));
if (cellValue != null) {
properties.put(cm.getProperty(), cellValue);
}
}
if (properties.isEmpty() == false) {
resultList.add(properties);
}
}
return resultList;
}
public static <T> void bean2excel(List<T> list, Sheet sheet, List<CellMapping> mappingList) throws Exception {
bean2excel(list, sheet, mappingList, 0);
}
/**
* Excel sheet 由参数传入,建议Excel样式由模板提供 程序只负责导数据,后续可以考虑增加 CellStyle 参数
*/
public static <T> void bean2excel(List<T> list, Sheet sheet, List<CellMapping> mappingList, int headerRowNum)
throws Exception {
int colPointer = 0;
Row row = accessRow(sheet, headerRowNum++);
CellStyle dateStyle = null;
for (CellMapping cm : mappingList) {
XSSFCellStyle cellStytle = (XSSFCellStyle) sheet.getWorkbook().createCellStyle();
if (cm.getHeader().contains("*")) {
// 红色强调
cellStytle.setFillForegroundColor(new XSSFColor(new java.awt.Color(240, 180, 180)));
} else {
// 黄色标题
cellStytle.setFillForegroundColor(new XSSFColor(new java.awt.Color(220, 220, 220)));
}
cellStytle.setWrapText(true);
cellStytle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cellStytle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
cellStytle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
Cell cell = accessCell(row, colPointer++);
cell.setCellValue(cm.getHeader());
cell.setCellStyle(cellStytle);
}
// for (CellMapping cm : mappingList) {
// accessCell(row, colPointer++).setCellValue(cm.getHeader());
// }
// 为空时,只给第一行添加下拉选择器
if (CollectionUtils.isEmpty(list)) {
for (int i = 0; i < 1; i++) {
row = accessRow(sheet, headerRowNum++);
colPointer = 0;
for (CellMapping cm : mappingList) {
Cell cell = accessCell(row, colPointer++);
// sprint8 wb-liuluokang
if (null != cm.getPropertyData() && cm.getPropertyData().length > 0) {
setValidation(sheet, cm.getPropertyData(), row.getRowNum(), row.getRowNum(),
cell.getColumnIndex(), cell.getColumnIndex());
}
}
}
}
for (T d : list) {
row = accessRow(sheet, headerRowNum++);
colPointer = 0;
for (CellMapping cm : mappingList) {
Object o = PropertyUtils.getSimpleProperty(d, cm.getProperty());
Cell cell = accessCell(row, colPointer++);
// sprint8 wb-liuluokang
if (null != cm.getPropertyData() && cm.getPropertyData().length > 0) {
setValidation(sheet, cm.getPropertyData(), row.getRowNum(), row.getRowNum(), cell.getColumnIndex(),
cell.getColumnIndex());
}
if (o == null) {
} else if (String.class.isAssignableFrom(o.getClass())) {
cell.setCellValue((String) o);
} else if (Date.class.isAssignableFrom(o.getClass())) {
cell.setCellValue((Date) o);// 日期存储为Number,显示需求依赖CellStyle
if (dateStyle == null) {
dateStyle = sheet.getWorkbook().createCellStyle();
dateStyle.setDataFormat(sheet.getWorkbook().getCreationHelper().createDataFormat().getFormat("yyyy/m/d"));
}
cell.setCellStyle(dateStyle);
} else if (Number.class.isAssignableFrom(o.getClass())) {
cell.setCellValue(((Number) o).doubleValue());
} else if (Boolean.class.isAssignableFrom(o.getClass())) {
cell.setCellValue(((Boolean) o).booleanValue());
} else {
cell.setCellValue(o.toString());
}
}
}
}
public static <T> Workbook exportToExcel(List<T> list, List<CellMapping> mappingList) throws Exception {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("export");
int colPointer = 0;
int rowPointer = 0;
Row row = sheet.createRow(rowPointer++);
CellStyle dateStyle = null;
for (CellMapping cm : mappingList) {
row.createCell(colPointer++).setCellValue(cm.getHeader());
}
for (T d : list) {
row = sheet.createRow(rowPointer++);
colPointer = 0;
for (CellMapping cm : mappingList) {
Object o = PropertyUtils.getSimpleProperty(d, cm.getProperty());
Cell cell = accessCell(row, colPointer++);
if (o == null) {
} else if (String.class.isAssignableFrom(o.getClass())) {
cell.setCellValue((String) o);
} else if (Date.class.isAssignableFrom(o.getClass())) {
cell.setCellValue((Date) o);// 日期存储为Number,显示需求依赖CellStyle
if (dateStyle == null) {
dateStyle = wb.createCellStyle();
dateStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("yyyy/m/d"));
}
cell.setCellStyle(dateStyle);
} else if (Number.class.isAssignableFrom(o.getClass())) {
cell.setCellValue(((Number) o).doubleValue());
} else if (Boolean.class.isAssignableFrom(o.getClass())) {
cell.setCellValue(((Boolean) o).booleanValue());
} else {
cell.setCellValue(o.toString());
}
}
}
return wb;
}
public static void map2excel(List<Map<String, Object>> list, Sheet sheet, List<CellMapping> mappingList)
throws Exception {
int colPointer = 0;
int headerRowNum = 0;
Row row = accessRow(sheet, headerRowNum++);
CellStyle strStyle = sheet.getWorkbook().createCellStyle();
strStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));
CellStyle dateStyle = sheet.getWorkbook().createCellStyle();
dateStyle.setDataFormat(sheet.getWorkbook().getCreationHelper().createDataFormat().getFormat("yyyy/m/d"));
for (CellMapping cm : mappingList) {
accessCell(row, colPointer++).setCellValue(cm.getHeader());
}
for (Map<String, Object> d : list) {
row = accessRow(sheet, headerRowNum++);
colPointer = 0;
for (CellMapping cm : mappingList) {
Object o = d.get(cm.getProperty());
Cell cell = accessCell(row, colPointer++);
if (o == null) {
} else if (String.class.isAssignableFrom(o.getClass())) {
cell.setCellValue((String) o);
// spring 9 wb-jiangchengqiao加入 ,设置excel 下载格式为文本
cell.setCellStyle(strStyle);
} else if (Date.class.isAssignableFrom(o.getClass())) {
cell.setCellValue((Date) o);// 日期存储为Number,显示需求依赖CellStyle
cell.setCellStyle(dateStyle);
} else if (Number.class.isAssignableFrom(o.getClass())) {
cell.setCellValue(((Number) o).doubleValue());
} else if (Boolean.class.isAssignableFrom(o.getClass())) {
cell.setCellValue(((Boolean) o).booleanValue());
cell.setCellType(Cell.CELL_TYPE_BOOLEAN);// wb-liuluokang sprint9 加入
} else {
cell.setCellValue(o.toString());
}
}
}
}
public static void map2excelnohead(List<Map<String, Object>> list, Sheet sheet, List<CellMapping> mappingList)
throws Exception {
int colPointer = 0;
int headerRowNum = 0;
CellStyle dateStyle = sheet.getWorkbook().createCellStyle();
dateStyle.setDataFormat(sheet.getWorkbook().getCreationHelper().createDataFormat().getFormat("yyyy/m/d"));
/*
* Row row = accessRow(sheet,headerRowNum++); for(CellMapping cm:mappingList){
* accessCell(row,colPointer++).setCellValue(cm.getHeader()); }
*/
for (Map<String, Object> d : list) {
Row row = accessRow(sheet, headerRowNum++);
colPointer = 0;
for (CellMapping cm : mappingList) {
Object o = d.get(cm.getProperty());
Cell cell = accessCell(row, colPointer++);
if (o == null) {
} else if (String.class.isAssignableFrom(o.getClass())) {
cell.setCellValue((String) o);
} else if (Date.class.isAssignableFrom(o.getClass())) {
cell.setCellValue((Date) o);// 日期存储为Number,显示需求依赖CellStyle
cell.setCellStyle(dateStyle);
} else if (Number.class.isAssignableFrom(o.getClass())) {
cell.setCellValue(((Number) o).doubleValue());
} else if (Boolean.class.isAssignableFrom(o.getClass())) {
cell.setCellValue(((Boolean) o).booleanValue());
} else {
cell.setCellValue(o.toString());
}
}
}
}
public static void copyRow(Workbook workbook, Sheet worksheet, int sourceRowNum, int destinationRowNum) {
// Get the source / new row
Row newRow = worksheet.getRow(destinationRowNum);
Row sourceRow = worksheet.getRow(sourceRowNum);
// If the row exist in destination, push down all rows by 1 else create a new row
if (newRow != null) {
worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1);
} else {
newRow = worksheet.createRow(destinationRowNum);
}
// Loop through source columns to add to new row
for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
// Grab a copy of the old/new cell
Cell oldCell = sourceRow.getCell(i);
Cell newCell = newRow.createCell(i);
// If the old cell is null jump to next cell
if (oldCell == null) {
newCell = null;
continue;
}
// Copy style from old cell and apply to new cell
CellStyle newCellStyle = workbook.createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
;
newCell.setCellStyle(newCellStyle);
// If there is a cell comment, copy
if (oldCell.getCellComment() != null) {
newCell.setCellComment(oldCell.getCellComment());
}
// If there is a cell hyperlink, copy
if (oldCell.getHyperlink() != null) {
newCell.setHyperlink(oldCell.getHyperlink());
}
// Set the cell data type
newCell.setCellType(oldCell.getCellType());
// Set the cell data value
switch (oldCell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
newCell.setCellValue(oldCell.getRichStringCellValue());
break;
}
}
// If there are are any merged regions in the source row, copy to new row
for (int i = 0; i < worksheet.getNumMergedRegions(); i++) {
CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);
if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {
CellRangeAddress newCellRangeAddress = new CellRangeAddress(
newRow.getRowNum(),
(newRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())),
cellRangeAddress.getFirstColumn(),
cellRangeAddress.getLastColumn());
worksheet.addMergedRegion(newCellRangeAddress);
}
}
}
private static Row accessRow(Sheet sheet, int rownum) {
Row row = sheet.getRow(rownum);
if (row == null) {
row = sheet.createRow(rownum);
}
return row;
}
private static Cell accessCell(Row row, int column) {
Cell cell = row.getCell(column);
if (cell == null) {
cell = row.createCell(column);
}
return cell;
}
public static String getCellString(Cell cell) {
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
return null;
}
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC
|| (cell.getCellType() == Cell.CELL_TYPE_FORMULA && cell.getCachedFormulaResultType() == Cell.CELL_TYPE_NUMERIC)) {
if (cell.getNumericCellValue() == (long) cell.getNumericCellValue()) {
return String.valueOf((long) cell.getNumericCellValue());
} else {
return String.valueOf(cell.getNumericCellValue());
}
} else {
return cell.toString();
}
}
public static Date getCellDate(Cell cell) {
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
return null;
}
if (DateUtil.isCellDateFormatted(cell)) {
return DateUtil.getJavaDate(cell.getNumericCellValue());
} else {
String result = getCellString(cell);
Date resultDate = null;
try {
resultDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(result);
} catch (ParseException e) {
try {
resultDate = new SimpleDateFormat("yyyy-MM-dd").parse(result);
} catch (ParseException e1) {
}
}
return resultDate;
}
}
public static double getCellDouble(Cell cell) {
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
return 0D;
}
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return cell.getNumericCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
if (cell.getCachedFormulaResultType() == Cell.CELL_TYPE_NUMERIC) {
return cell.getNumericCellValue();
}
}
double result = 0;
try {
result = Double.parseDouble(getCellString(cell));
} catch (Exception e) {
}
return result;
}
public static Object getCellValue(Cell cell) {
Object result = null;
if (cell != null) {
int cellType = cell.getCellType();
if (cellType == Cell.CELL_TYPE_FORMULA) {
cellType = cell.getCachedFormulaResultType();
}
switch (cellType) {
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
result = cell.getDateCellValue();
} else {
if (cell.getNumericCellValue() == (long) cell.getNumericCellValue()) {
return (long) cell.getNumericCellValue();
} else {
return cell.getNumericCellValue();
}
}
break;
case Cell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue();
break;
default:
}
}
return result;
}
/**
* 设置某些列的值只能输入预制的数据,显示下拉框.
*
* @param sheet 要设置的sheet.
* @param textlist 下拉框显示的内容
* @param firstRow 开始行
* @param endRow 结束行
* @param firstCol 开始列
* @param endCol 结束列
*/
public static Sheet setValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
// 加载下拉列表内容
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
DataValidation dataValidation = helper.createValidation(constraint, regions);
// 处理Excel兼容性问题
if (dataValidation instanceof XSSFDataValidation) {
dataValidation.setSuppressDropDownArrow(true);
dataValidation.setShowErrorBox(true);
} else {
dataValidation.setSuppressDropDownArrow(false);
}
// 设置输入信息提示信息
dataValidation.createPromptBox("下拉选择提示", "请使用下拉方式选择合适的值!");
// 设置输入错误提示信息
dataValidation.createErrorBox("选择错误提示", "你输入的值未在备选列表中,请下拉选择合适的值!");
sheet.addValidationData(dataValidation);
return sheet;
}
public static void excels(List<Map<String, Object>> list, Sheet sheet, List<CellMapping> mappingList)
throws Exception {
Sheet sheet1 = sheet;
int colPointer = 0;
int headerRowNum = 0;
Row rows = accessRow(sheet1, headerRowNum++);
CellStyle strStyles = sheet1.getWorkbook().createCellStyle();
strStyles.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));
CellStyle dateStyles = sheet1.getWorkbook().createCellStyle();
dateStyles.setDataFormat(sheet1.getWorkbook().getCreationHelper().createDataFormat().getFormat("yyyy/m/d"));
for (CellMapping cm : mappingList) {
accessCell(rows, colPointer++).setCellValue(cm.getHeader());
}
colPointer = 0;
headerRowNum = 1;
Row row = accessRow(sheet, headerRowNum++);
CellStyle strStyle = sheet.getWorkbook().createCellStyle();
strStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));
CellStyle dateStyle = sheet.getWorkbook().createCellStyle();
dateStyle.setDataFormat(sheet.getWorkbook().getCreationHelper().createDataFormat().getFormat("yyyy/m/d"));
for (CellMapping cm : mappingList) {
accessCell(row, colPointer++).setCellValue(cm.getHeader());
}
for (Map<String, Object> d : list) {
row = accessRow(sheet, headerRowNum++);
colPointer = 0;
for (CellMapping cm : mappingList) {
Object o = d.get(cm.getProperty());
Cell cell = accessCell(row, colPointer++);
if (o == null) {
} else if (String.class.isAssignableFrom(o.getClass())) {
cell.setCellValue((String) o);
// spring 9 wb-jiangchengqiao加入 ,设置excel 下载格式为文本
cell.setCellStyle(strStyle);
} else if (Date.class.isAssignableFrom(o.getClass())) {
cell.setCellValue((Date) o);// 日期存储为Number,显示需求依赖CellStyle
cell.setCellStyle(dateStyle);
} else if (Number.class.isAssignableFrom(o.getClass())) {
cell.setCellValue(((Number) o).doubleValue());
} else if (Boolean.class.isAssignableFrom(o.getClass())) {
cell.setCellValue(((Boolean) o).booleanValue());
cell.setCellType(Cell.CELL_TYPE_BOOLEAN);// wb-liuluokang sprint9 加入
} else {
cell.setCellValue(o.toString());
}
}
}
}
}
ExcelUtil.java
11.错误码枚举值,规范定义了自定义异常
/*
* Copyright 2014 Alibaba.com All right reserved. This software is the confidential and proprietary information of
* Alibaba.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only
* in accordance with the terms of the license agreement you entered into with Alibaba.com.
*/
package com.alibaba.tboss.exception;
import java.text.MessageFormat;
/**
* 类ErrorCode.java的实现描述:TODO 类实现描述
*
* @author vmdata 2014年12月22日 下午4:09:48
*/
public enum ErrorCode {
// ----------------- 公用错误代码(1000-1099)---------------------------
Success("1000", "成功"),
Params_Lost("1001", "缺少必要参数[{0}]"),
Params_Invalid("1002", "参数[{0}]无效"),
Params_Undefine("1003", "错误的请求参数"),
No_Data("1004", "数据不存在或已取消"),
Opt_Expire("1006", "操作过期"),
Opt_Processed("1007", "工单已被处理"),
Upload_File_Error("1008", "文件上传失败[{0}]"),
Undefine_Params("1005", "错误的请求参数"),
Operation_expire("1006", "操作过期"),
Operation_processed("1007", "工单已被处理"),
Unexceptable_Params("1009", "不符合要求的参数"),
No_Permission("2000", "无操作权限"),
No_AssetData("2001", "缺少设备列表信息"),
NO_OVERDUE("2002", "时间超过5天不能修改"),
StarAgent_Error("9990", "StarAgent接口调用失败"),
Armory_Rack_Error("9991", "机柜信息变更请求出错[{0}]"),
Armory_Update_Error("9992", "设备信息更新到Amory出错"),
Query_Failured("9993", "查询资产数据库失败,没有符合条件的数据!"),
Armory_Query_Error("9994", "Armory查询失败"),
Send_Email_Error("9995", "发送邮件出错"),
Send_AliIM_Error("9996", "发送旺旺消息出错"),
Query_Error("9997", "查询数据出错"),
Sys_Error("9998", "系统错误"),
DB_error("9999", "数据库操作失败"),
Title_Null("8001", "标题不能为空"),
Demander_Null("8002", "需求方不能为空"),
Approval_Null("8003", "审批意见不能为空"),
Idc_Not_Found("8004", "机房信息不存在"),
Armory_UnSupport_QueryType("8005", "不支持的查询类型"),
Armory_Query_Dif_Result("8006", "设备查询数{},实际有效{}"),
location_error("8007", "机位占用释放错误"),
UnIslocks_error("8008", "设备锁释放失败"),
Api_Creator_Not_Found("2003", "创建人信息[{0}]不存在"),
Api_lock_Params("2004", "SN[{0}]已锁定,请解锁后再操作,或联系PD"),
Api_Unlock_Params("2004", "SN[{0}]处于已解锁状态,不可操作或联系PD"),
Resource_error("2005", "操作失败"),
Api_Query_Failured("2006", "查询失败SN[{0}]没有符合条件的数据!"),
Api_Query_Errory("2007", "SN[{0}]是网络设备,不能提交"),
Api_SN_Errory("2008", "SN有相同的数据,请检查"),
up_down_errory("2009", "sn[{0}]目标机位信息格式错误(格式:XX-YY)"),
Resource_Query_Error("2010", "Resource查询失败"),
Resource_Update_Error("2011", "ResouceArmoryInfo更新失败"),
work_order_is_null("2012", "工单不存在"),
Not_Is_Logistics("2013", "搬迁单是跨机房搬迁,无法跳过物流"),
Query_Rack_is_null("2014", "查询失败机柜[{0}]没有符合条件的数据!"),
Rack_isNot_Wiring("2015", "机柜[{0}]已处于布线中或已完成无法发起布线申请"),
Rack_Start_Wiring("2016", "机柜[{0}]生命周期处于非待验收和验收交付环节,无法发起布线申请"),
Rack_isNot_endWiring("2017", "机柜[{0}]机柜未发起布线申请或布线已经完成,无法再操作"),
Rack_end_Wiring("2018", "机柜[{0}]生命周期处于非验收交付环节,无法发起完成布线申请"),
RACK_ISNOT_ACCEPTANCE("1303", "机柜[{0}]生命周期非待验收,无法发起验收"),
ERROR_MESSAGES("1304", "风险库无法删除: {0}"),
Armory_spareUpdate_Error("2020", "配件信息更新到Amory出错"),
up_down_errorys("1305", "sn[{0}]目标机位信息格式错误(格式:XX)"),
// ----------------- 物流申请工单错误代码(10000-11000)---------------------------
Differ_SourceSite("10000", "原机房信息不一致"),
Differ_TagRoom("10001", "目标房间信息不一致"),
// ----------------- 设备出入工单错误代码(11001-12000)---------------------------
Site_Null("11001", "IDC机房不能为空"),
Contactor_Null("11002", "联系人不能为空"),
InOut_Null("11003", "出/入类型不能为空"),
signDate_Null("11004", "签字日期不能为空"),
InoutDate_Null("11005", "出/入日期不能为空"),
InoutReason_Null("11006", "出/入原因不能为空"),
Differ_Site("11007", "IDC机房信息不一致"),
Reminder_Error("11008", "催单失败,未配置运营商邮箱"),
Reminder_Success("11009", "催单成功"),
Approval_Achieved("11010", "工单已审批,已结单"),
Leng_limted("11011", "输入内容超过最大长度[{0}]限制"),
Email_Null("11012", "机房[{0}]运营商邮箱地址不能为空"),
No_Email("11013", "审批通过,运营商邮箱地址为空,邮件发送失败"),
Submit_Success("11014", "提交成功"),
Finish_Success("11015", "操作成功"),
// ----------------- 网络布/撤线工单错误代码(12001-13000)---------------------------
Asset_SN_Lost("12001", "设备名称不能为空"),
Fiber_Model_Lost("12002", "单双模不能为空"),
Interface_Type_Lost("12003", "接口类型不能为空"),
Line_Lable_Lost("12004", "线缆标签不能为空"),
Port_Id_Lost("12005", "端口号不能为空"),
Wiring_Id_Is_Null("12006", "网络设备布/撤线工单ID不能为空!"),
Wiring_Is_Not_Exists("12007", "网络设备布/撤线工单不存在!"),
Wiring_Detail_List_Is_Empty("12008", "网络设备布/撤线工单明细列表不能为空!"),
NOT_PORT("12009", "暂无可用端口"),
NOT_ORDERID("12010", "工单编号不能为空"),
NOT_SATISFIEDRESON("12011", "满意原因不能为空"),
NOT_DISSATISFIEDREASON("12012", "不满意原因不能为空"),
Wiring_IDC_Is_Null("12013", "IDC不能为空!"),
Wiring_Priority_Is_Null("12014", "优先级不能为空!"),
Wiring_OperationTime_Is_Null("12015", "操作时间不能为空!"),
Wiring_Type_Is_Null("12016", "工单类型不能为空!"),
Wiring_Status_Is_Null("12017", "工单状态或子状态不能为空!"),
Wiring_Detail_Is_Null("12018", "{0}网络设备布/撤线工单明细不能为空!"),
Wiring_Detail_SiteA_Is_Null("12019", "{0}A端机房为空或不存在!"),
Wiring_Detail_RoomA_Is_Null("12020", "{0}A端房间为空或不存在!"),
Wiring_Detail_RackA_Is_Null("12021", "{0}A端机柜为空或不存在!"),
Wiring_Detail_Line_Mode_A_Is_Null("12040", "{0}A端线缆类型为空或不存在!"),
Wiring_Detail_Interface_Type_A_Is_Null("12041", "{0}A端接口类型为空或不存在!"),
Wiring_Detail_Not_ODF_Port("12022", "{0}找不到空闲的ODF端口!"),
Wiring_Detail_SiteB_Is_Null("12023", "{0}B端机房为空或不存在!"),
Wiring_Detail_RoomB_Is_Null("12024", "{0}B端房间为空或不存在!"),
Wiring_Detail_RackB_Is_Null("12025", "{0}B端机柜为空或不存在!"),
Wiring_Detail_Line_Mode_B_Is_Null("12042", "{0}B端线缆类型为空或不存在!"),
Wiring_Detail_Interface_Type_B_Is_Null("12043", "{0}B端接口类型为空或不存在!"),
Wiring_Detail_PortAB_Is_Same("12027", "{0}A端和B端的端口不能相同!"),
NOT_NULL("12028", "该SN下无端口信息"),
NOT_SUPPLYED_BEFORE_ACHIEVE("12029", "工单不能结单,请补充设备信息后再结单"),
NOT_SAVED_BEFORE_POST("12030", "提交前请先保存!"),
Wiring_Title_Is_Null("12031", "工单标题不能为空!"),
Wiring_OperationTime_Is_Old("12032", "操作时间不能小于当前日期!"),
Wiring_Asset_A_Or_B_Is_Null("12033", "{0}A端和B端的设备名称必须同时为空或同时不为空!"),
Wiring_SiteA_Is_Not_IDC("12034", "{0}A端的机房必须和IDC机房相同!"),
Wiring_Same_Order_Null_Or_NotNull("12035", "同一个工单中的设备名称必须全部为空或全部不为空!"),
Wiring_Supply_All_Asset_NotNull("12036", "补充信息时所有的设备名称和端口都不能为空!"),
Batch_Import_AB_Length_Not_Same("12037", "A端文本的行数和B端文本的行数必须相同!"),
Batch_Import_Field_Length_Not_Six("12038", "{0}的数据不符合规范!"),
Asset_Port_Info_Is_Exists("12039", "设备端口已存在!"),
Asset_not_null("12040", "设备名不能为空"),
// 设备上下架工单错误代码(13001-14000)
UpDown_Lost_OptType("13001", "操作类型不能为空"),
UpDown_Lost_AssetType("13002", "设备类型不能为空"),
UpDown_Empty_Asset("13003", "缺少设备信息"),
DeviceReplace_Empty_Asset("13003", "缺少设备信息"),
Is_Not_ConforMity_with_Sn_A("13004", "A端设备信息与所填机房信息不符合"),
Is_Not_ConforMity_with_Sn_B("13005", "B端设备信息与所填机房信息不符合"),
Is_Not_ConforMity_with_Sn("13006", "SN在Armory无信息"),
NOT_FOUND_ROOM("13007", "房间不能为空"),
NOT_FOUND_RACK("13007", "机柜不能为空"),
NOT_PORT_ID("13008", "没有可用的ODF资源"),
Down_Site_NotFound("13009", "下架机房数据为空,请联系产品负责人/开发处理。"),
Updown_Notsame_Site("13010", "{0}原机房信息不一致"),
Updown_Notsame_Room("13011", "{0}原房间信息不一致"),
Updown_Notsame_Rack("13012", "{0}原机柜信息不一致"),
Updown_Notsame_Pos("13013", "{0}原机位信息不一致"),
Updown_Notsame_TargetSite("13014", "{0}目标机房信息不一致"),
Updown_Notsame_TargetRoom("13015", "{0}目标房间信息不一致"),
Updown_Notsame_TargetRack("13016", "{0}目标机柜信息不一致"),
updown_Notsame_Model("13017", "{0}设备型号不一致"),
updown_Not_sn("13018", "SN不一致"),
Updown_Exl_Errory("13019", "解析exl数据出错"),
Updown_Exl_Size("13020", "导入数据与原数据大小不一样"),
Up_Down_error("13021", "设备列表下载失败"),
updown_targetpos_error("13022", "{0}目标机位不能小于0"),
Import_Exl_Error("13023", "{0}"),
NOT_FOUND_TargetRoom("130224", "目标房间不能为空"),
TargetRoom_Is_Not_Null("130225", "sn{0}目标房间不能为空"),
UpDown_Room_IsNot_CK("130226", "sn[{0}]上架单原房间必须为仓库"),
TargetRack_Is_Not_Null("130227", "sn[{0}] 上架机柜不能为空"),
localtionId_is_not_null("130228", "sn[{0}] 上架localtionId不能为空"),
room_in_ck("130229", "sn[{0}] 已在仓库,无法创建下架单"),
UpDown_targetRoom_IsNot_CK("130230", "sn[{0}]上架单目标房间不能为为仓库"),
UP_DOWN_NOT_FOUND_ROOM("130231", "SN[{0}]房间不能为空"),
TargetRack_IS_NOTNULL("13024", "SN[{0}]目标房间为仓库,目标机柜,机位,LocationId必须为空"),
Updown_Notsame_TargetPos("13025", "[{0}]目标机位信息不一致"),
Is_Null_TargetPos("13026", "[{0}]服务器设备目标机位不能为空"),
EXL_VERSION_MISMATCH("13027", "EXL版本不匹配,仅支持2013"),
Is_Null_OptResult("13028", "sn[{0}]未检测,或检测结果为失败无法结单"),
Asset_Updown_NotFound("13029", "上下架工单编号[{0}]未查询到信息"),
// ---------------------服务器重启工单错误代码(14001-15000)---------------------
Server_Reboot_Is_Not_Exists("14001", "服务器重启工单不存在!"),
Server_Reboot_Type_Is_Null("14002", "重启类型不能为空!"),
Server_Reboot_Emergency_Level_Is_Null("14003", "紧急程度不能为空!"),
Server_Reboot_Detail_List_Is_Empty("14004", "服务器重启工单明细列表不能为空!"),
Server_Is_Not_Achieve("14005", "sn[{0}]未检测,无法结单"),
Server_Is_Not_Type("14006", "sn[{0}]未检测,无法设置失败类型"),
// ---------------------复合工单从20001-30000----------------------------
PARANT_ID_NULL("20001", "复合工单Id为空"),
Srmp_Interface_Request_Fail("20002", "向SRMP发送请求失败!"),
Srmp_SN_NULL("20003", "设备号不能为空!"),
Asset_Move_Order_CallBack_Error("20004", "搬迁工单回调失败"),
Asset_Move_Order_NotFound("20005", "搬迁工单[orderId={0}]信息不存在"),
Asset_Move_Order_NoPermission("20006", "无此工单查询权限"),
Asset_Move_Order_Asset_NotFound("20007", "设备信息sn=[{0}]未找到"),
Asset_Order_NotFound("20008", "原子工单信息不存在"),
Asset_order_islock("20009", "sn[{0}]处于已锁定状态不可操作"),
Asset_Move_Order_Achieve_Error("20010", "搬迁工单无法结单,{0}"),
Asset_Move_NotSameDeviceType("20012", "sn[{0}]设备类型不唯一,请检查"),
up_down_NotSamesite("20013", "原机房不一致,请检查"),
device_replace_NotSamesite("20014", "设备替换机房不一致,请检查"),
RACK_NOTIS_STORAGE("20014", "SN[{0}]是存储设备,目标机柜必须是存储机柜"),
ASSETMOVE_ISNOT_ACHIEVE("20015", "搬迁单[{0}]上下架单处理中,无法取消"),
Updown_Operation_processed("20016", "搬迁单[{0}]在下架环节已被处理,无法取消搬迁单"),
AssetMove_Isprocessed("20017", "搬迁单[{0}]已结单或已取消,无法继续取消"),
NOT_ALLOW_MODIFIER("20017", "buc无该操作人信息,不允许操作"),
ASSETMOVE_ASSET_ISNULL("20018", "SN{0}信息不存在,无法取消"),
ASSETMOVE_ISNOT_LOGIS("20019", "搬迁单[{0}]物流单处于待签收或已签收环节,无法取消"),
ASSETMOVE_ISNOT_ACHIEVES("20015", "搬迁单[{0}]上下架单处理中或物流单处于待签收或已签收环节,无法取消"),
RMA_Error("20016", "{0}"),
// ---------------------网络设备重启工单从30001-40000----------------------------
board_errory("30001", "SN[{0}]板卡系信息错误(符合数据为0——1000)"),
modular_errory("30001", "SN[{0}]模块系信息错误(符合数据为0——1000)"),
// ----------------- 机房相关错误信息(1100-1099)------------------------
// ----------------- 房间相关错误信息(1200-1299)------------------------
ROOM_IS_NULL("1201", "[{0}]房间不存在"),
// ----------------- 机柜相关错误信息(1300-1399)------------------------
param_number("1300", "单号请输入数字"),
NOT_FOUND_IDCRACK("1301", "[{0}]机柜数据为空或没找到该机柜"),
RACK_IN_ASW("1302", "[{0}]机柜已在网络分组中"),
RACK_AND_ROOM_IS_NOTNULL("1302", "[{0}]房间机柜只能同时为空,或则同时不为空"),
RACK_AND_ROOM_ISERROR("1303", "[{0}]机柜编号或房间不能为空"),
RACK_ACCEEPTANCE_INFO_LOCK("1304", "[{0}] 机柜验收属性已锁住,不可以修改"),
RACK_NETWORK_INFO_LOCK("1305", "[{0}] 机柜网络属性已锁住,不可以修改"),
RACK_PHYSICS_INFO_LOCK("1036", "[{0}]物理属性已锁住,不可以修改"),
RACK_IS_NOT_MODIFIER("1037", "机柜[{0}]生命周期非待验收或验收交付,机柜属性不可以修改"),
RACK_IsNot_CK("1038", "机柜[{0}]房间为仓库不能新建机柜"), RACK_IsLogicPod("1039", "机柜[{0}]网络集群,逻辑POD,POD 要一起修改"),
// ----------------- 机位相关错误信息(1400-1499)------------------------
Process_Failed("9997", "创建流程失败"),
DB_Failed("9998", "数据库操作失败"),
System_Error("9999", "系统错误"),
// --------------------设备替换错误信息(50001-60000)-----------------
Site_Is_Not_SAME("50001", "sn[{0}]新旧设备不在同一机房"),
Device_Replace_NOT_FOUND_ROOM("50002", "SN[{0}]房间不能为空"),
Device_Replace_Room_IsNot_CK("50003", "SN[{0}]新设备房间不为仓库,请检查"),
Device_Replace_NoPermission("50004", "无此工单查询权限"),
Device_Replace_NotFound("50005", "设备替换工单[orderId={0}]信息不存在"),
Device_Replace_Asset_NotFound("50006", "Sn[{0}]信息未找到"),
Device_Replace_Room_Is_Null("50007", "sn[{0}]新设备房间为空"),
Device_Replace_room_in_ck("50008", "sn[{0}]旧设备不在架上,请检查"),
Device_Replace_Operation_processed("50009", "工单已被处理,不能取消"),
Device_Replace_Model_Is_Null("50010", "SN[{0}]厂商型号为空"),
Device_Replace_Model_Is_Not_Same("50011", "SN[{0}]厂商型号不一致,无法创建设备替换工单"),
Device_Replace_Params_Invalid("50012", "参数[{0}]无效,必须为20150819202020格式"),
Device_Replace_Differ_SourceSite("50013", "机房信息不一致"),
Device_Replace_No_Data("50014", "设备替换工单信息不存在"),
Device_Replace_No_location_Data("50015", "SN[{0}]旧设备缺少机位信息"),
Device_Replace_No_rack_Data("50015", "SN[{0}]旧设备缺少机柜信息"),
device_replace_NotSamesites("50016", "SN[{0}]设备所在机房不一致,请检查"),
Device_Replace_canOptTimeStart_isLargerThan_canOptTimeEnd("50017", "参数允许操作时间段-开始时间不能晚于结束时间,请检查"),
device_replace_Date_error("50018", "日期格式错误,请检查"),
Device_Replace_canOptTimeEnd("50019", "参数操作时间段-结束时间不能早于当前时间,请检查"),
ALLOWS_ENDTIME_NOTEARLIER_CURRENTTIME("50020", "允许操作结束时间不能早于当前时间"),
ALLOW_STARTTIME_NOTLATER_OPERATIONTIME("50021", "允许操作开始时间不能晚于允许操作结束时间"),
NOT_ALLOW_CREATE("50022", "buc无该操作人信息,不允许建单"),
Device_Replace_Asset_Data_NotFound("50023", "设备替换工单信息不存在"),
NOT_ALLOW_CANCLE("50024", "buc无该操作人信息,不允许取消"),
// -------------------------设备安全,质量安全(60001-70000)-------------------------------
RISKPOINT_LENGTH_ERROR("60001", "风险点长度小于200个字"),
VERIFYMODE_LENGTH_ERROR("60002", "验证方式长度小于200个中文字符"),
COMPONENT_ID_LENGTH_ERROR("60003", "一级组件长度小于10个中文字符"),
TAG_ID_LENGTH_ERROR("60004", "标签长度小于20个中文字符"),
PARAMS_IS_NULL("60003", "参数[{0}]为空"),
DATA_IS_ON_PROCESS("60004", "数据已在流程中,不能重新操作"),
DATA_IS_OPRATORED("60005", "该数据已被操作,请检查"),
All_SITE_ON_RANGE("60006", "影响范围格式错误(整体机房与其他房间不能同时选择)"),
FINISH_SITUATION("60007", "[{0}]完成情况为未完成,不能结单"),
FINISH_SITUATIONS("60008", "该数据已经发起结单,不能再操作"),
RISKSTATUS_IS_ERROR("60009", "风险登记册未关闭无法开启: {0}"),
RISKREGISTRA_IS_NOTNULL("60010", "风险登记册{0}无法重新开启,该机房下已存在新的风险登记册"),
RISKPOOL_IS_NULL("60011", "风险登记册[{0}]的风险库条目已删除,无法重新开启"),
RiskEntriesNumber_Data_Is_Not_exit("60012", "风险库编号所对应的数据不存在"),
RISKSTATUS_IS_SAME("60013", "风险登记册编号[{0}]的机房和风险库编号相同,无法同时开启"),
// ---------------------------通用原子工单(70001-80000)---------------------------------
Common_Atomic_No_Data("70001", "工单信息不存在"), Common_Atomic_Operation_processed("70002", "工单已被处理,不能取消"),
Common_Atomic_Asset_NotFound("70002", "Sn[{0}]信息未找到"),
Common_Atomic_NoPermission("70003", "无此工单查询权限"),
Common_Atomic_No_AssetData("70004", "缺少SN信息"),
Common_Atomic_Differ_SourceSite("70005", "sn[{0}]机房信息不一致"),
// ------------------------------基础设施信息(80001-9000)--------------------------------------------
Infrastr_No_Is_Same("80001", "设备编号[{0}]已存在,请检查"),
SITENAME_IS_NULL("80002", "机房为空,请先选择机房"),
Profession_IS_NULL("80003", "所属专业为空,请先选择所属专业"),
BuildPeriod_IS_NULL("80004", "建设期为空,请先选择建设期"),
DeviceType_Is_Column_Header("80005", "设备类型为列头柜,不能导入"),
Approve_Informati_Is_Null("80006", "审批信息不存在"),
// ------------------------------流程引擎(90001-10000)--------------------------------------------
FLOW_CANT_START("90001", "无法启动流程实例"), FLOW_NOT_FOUND_ACTION("90002", "提交动作[{0}]未定义"),
FLOW_NONE_START_ACTION("90003", "未指定开始动作"), FLOW_NONE_TASK("90004", "未指定动作的执行任务"),
// ----------------- 人员入室相关错误信息(40000-50000)------------------------
selectMyStaffERApproval_Error("40001", "一级审批查询错误"), selectMyStaffERApprovalSecond_Error("40002", "二级审批查询错误"),
selectMyApprovalStaf("40003", "我的人员入档审批查询错误"),
// -------------------rma工单 下架结单生成硬盘拔出-----------------
createHardDiskPullOutOrder("40004", "生成硬盘拔除工单失败");
String code; // 代码
String msg; // 消息
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
private ErrorCode(String code, String msg){
this.code = code;
this.msg = msg;
}
public String getFullMsg(String... arg) {
if (null == arg || arg.length == 0) return this.msg;
else return MessageFormat.format(this.msg, arg);
}
public static String getMsgName(String code) {
for (ErrorCode c : ErrorCode.values()) {
if (c.getCode().equals(code)) {
return c.msg;
}
}
return null;
}
public static String getTypeName(String msg) {
for (ErrorCode c : ErrorCode.values()) {
if (c.getMsg().equals(msg)) {
return c.code;
}
}
return null;
}
}
ErrorCode.java