J2EE項目開發中經常使用到的公共方法

  在項目IDCM中涉及到多種工單,包括有:服務器|網絡設備上下架工單、服務器|網絡設備重啓工單、服務器光纖網線更換工單、網絡設備撤線佈線工單、服務器|網絡設備替換工單、服務器|網絡設備RMA工單、通用原子工單、硬盤消磁折彎工單、物流工單、資產初入門工單、機櫃上下電工單、待盤點|待盤盈工單等等。工單管理系統中要涉及到工單的建立|API建立和維護。因此有必要將一些通用的方法提出來,相似於模塊化的架構涉及。html

目錄:前端

  1. 日期工具類DateUtil.java提供日期計算的相關靜態方法
  2. 接口調用工具類HttpClientUtil.java提供調用外部接口的公共方法
  3. 加密工具類GenMD5Util.java提供了將制定字符串加密成MD5的方法
  4. 公共方法抽象工具類CommonUtil.java提供了對工單表增刪改查的公共方法
  5. 獲取Bean實例工具類SpringContextUtil.java提供了根據bean id獲取Bean實例的方法
  6. 實體Bean和JSON轉換工具類JsonToBeanUtil.java提供了json和bean相互轉換的方法
  7. 流程工具類FlowUtil.java提供了字符串轉換和解析response的經常使用方法
  8. 文件上傳工具類FileUpLoadUtil.java封裝了上傳的公共方法
  9. 工具類CookieUtil.java提供了經常使用的操縱緩存的方法
  10. 表格Excel轉換實體Bean工具類ExcelUtil.java提供了文件導入導出的方法
  11. 複用$control.setTemplate("web:orderOptList.vm")實現日誌記錄
  12. JDK反射提供抽象參數類實現動態加載
  13. api auth受權機制保證外部調用接口的安全性

1.日期工具類DateUtil.java提供了經常使用的日期計算方法,涉及SimpleDateFormat、Calendar、Date三個類,附上代碼:java

  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 }
DateUtil.java

2.工具類HttpClientUtil.java提供了系統調用外部接口的公共方法,包括post、get方法,以及對於HTTPS協議的支持。在httpPostWithJson方法中流的關閉採用了傳統的方法,若是項目的JDK版本在1.7之上,能夠採用try...with...resources來關閉流。node

  1 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 }
HttpClientUtil.java

3.加密工具類GenMD5Util.java提供了將指定字符串加密成MD5的方法。代碼實現以下:mysql

 1 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 }
GenMD5Util.java

4.在工單表中有公共屬性:`creator`、'gmt_create'、`modifier`、`gmt_modified`、`is_deleted`,公共方法抽象工具類CommonUtil.java提供了對基礎工單表的公共操做方法,在工單操做中將新建工單,修改工單,設置通用值的方法提取出來,利用java反射來實現設值。代碼以下:c++

  1 package com.alibaba.tboss.common.auth.common;
  2 
  3 import java.lang.reflect.Method;
  4 import java.util.Date;
  5 import java.util.Map;
  6 import java.util.regex.Matcher;
  7 import java.util.regex.Pattern;
  8 
  9 import org.apache.commons.lang.StringUtils;
 10 
 11 import com.alibaba.tboss.common.auth.costants.AppRoleType;
 12 import com.alibaba.tboss.common.auth.exception.AppAuthCommonException;
 13 import com.alibaba.tboss.common.auth.privilege.PrivilegeInfo;
 14 
 15 public class CommonUtil {
 16 
 17     private static String MODIFIER      = "modifier";
 18 
 19     private static String GMT_MODIFIED  = "gmtModified";
 20 
 21     private static String IS_DELETED    = "is_deleted";
 22 
 23     private static String FULL_ORG_PATH = "fullOrgPath";
 24 
 25     private static String OWNER         = "owner";
 26 
 27     public static void setCommonValueForCreate(Object pojo, PrivilegeInfo privilegeInfo) {
 28         try {
 29             Method setCreator = pojo.getClass().getMethod("setCreator", String.class);
 30             setCreator.invoke(pojo, getOperator(privilegeInfo));
 31 
 32             Method setModifier = pojo.getClass().getMethod("setModifier", String.class);
 33             setModifier.invoke(pojo, getOperator(privilegeInfo));
 34 
 35             Method setGmtCreate = pojo.getClass().getMethod("setGmtCreate", Date.class);
 36             setGmtCreate.invoke(pojo, new Date());
 37 
 38             Method setGmtModified = pojo.getClass().getMethod("setGmtModified", Date.class);
 39             setGmtModified.invoke(pojo, new Date());
 40 
 41             Method setIsDeleted = pojo.getClass().getMethod("setIsDeleted", String.class);
 42             setIsDeleted.invoke(pojo, "n");
 43 
 44         } catch (Exception e) {
 45             throw new AppAuthCommonException("invoke method error ", e);
 46         }
 47 
 48     }
 49 
 50     public static void setCommonValueForDeletes(Object pojo, PrivilegeInfo privilegeInfo) {
 51         try {
 52             Method setModifier = pojo.getClass().getMethod("setModifier", String.class);
 53             setModifier.invoke(pojo, getOperator(privilegeInfo));
 54 
 55             Method setGmtModified = pojo.getClass().getMethod("setGmtModified", Date.class);
 56             setGmtModified.invoke(pojo, new Date());
 57 
 58             Method setIsDeleted = pojo.getClass().getMethod("setIsDeleted", String.class);
 59             setIsDeleted.invoke(pojo, "y");
 60         } catch (Exception e) {
 61             throw new AppAuthCommonException("invoke method error ", e);
 62         }
 63     }
 64 
 65     public static void setCommonValueForDelete(Map<String, Object> param, PrivilegeInfo privilegeInfo) {
 66         if (param.get(MODIFIER) == null || StringUtils.isEmpty((String) param.get(MODIFIER))) {
 67             param.put(MODIFIER, getOperator(privilegeInfo));
 68         }
 69         param.put(GMT_MODIFIED, new Date());
 70         param.put(IS_DELETED, "n");
 71 
 72     }
 73 
 74     public static void setCommonValueForUpdate(Object pojo, PrivilegeInfo privilegeInfo) {
 75         try {
 76             Method setGmtModified = pojo.getClass().getMethod("setGmtModified", Date.class);
 77             setGmtModified.invoke(pojo, new Date());
 78             Method setModifier = pojo.getClass().getMethod("setModifier", String.class);
 79             setModifier.invoke(pojo, getOperator(privilegeInfo));
 80 
 81         } catch (Exception e) {
 82             throw new AppAuthCommonException("invoke method error ", e);
 83         }
 84 
 85     }
 86 
 87     public static void setCommonValueForUpdate(Map<String, Object> param, PrivilegeInfo privilegeInfo) {
 88         if (param.get(MODIFIER) == null || StringUtils.isEmpty((String) param.get(MODIFIER))) {
 89             param.put(MODIFIER, getOperator(privilegeInfo));
 90         }
 91         param.put(GMT_MODIFIED, new Date());
 92     }
 93 
 94     public static void setOrgPathForSelectMap(Map<String, Object> param, PrivilegeInfo privilegeInfo) {
 95         if (privilegeInfo.getCurrentRoleType().equals(AppRoleType.MASTER.toString())) {
 96             if (param.get(FULL_ORG_PATH) == null || StringUtils.isEmpty((String) param.get(FULL_ORG_PATH))) {
 97                 param.put(FULL_ORG_PATH, getCurrentDataAuthAccessPath(privilegeInfo));
 98             }
 99         } else {
100             if (param.get(OWNER) == null || StringUtils.isEmpty((String) param.get(OWNER))) {
101                 param.put(OWNER, privilegeInfo.getAppUserId());
102             }
103         }
104 
105     }
106 
107     private static String getCurrentDataAuthAccessPath(PrivilegeInfo pvgInfo) {
108         if (pvgInfo == null || StringUtils.isEmpty(pvgInfo.getCurrentDataAuthAccessPath())) {
109             return "1/2";
110         } else {
111             return pvgInfo.getCurrentDataAuthAccessPath();
112         }
113     }
114 
115     public static String getOperator(PrivilegeInfo pvgInfo) {
116         if (pvgInfo == null || StringUtils.isEmpty(pvgInfo.getWorkNo())) {
117             return "SYSTEM";
118         } else {
119             return pvgInfo.getWorkNo();
120         }
121     }
122 
123     public static boolean numStart(String workNo) {
124         Pattern pattern = Pattern.compile("^(\\d+)(.*)");
125         Matcher matcher = pattern.matcher(workNo);
126         return matcher.matches();
127     }
128 
129     public static String preprWorkNo(String workNo) {
130         if (StringUtils.isEmpty(workNo)) {
131             return workNo;
132         }
133         if (numStart(workNo) && workNo.length() < 6) {
134             while (workNo.length() < 6) {
135                 workNo = "0" + workNo;
136             }
137         }
138         return workNo;
139     }
140 
141 }
CommonUtil.java

5.當spring容器啓動的時候,自動把實現了ApplicationContextAware的類找出來,而後爲其注入ApplicationContext屬性,使得SpringContextUtil能夠自由自在的根據名字獲取Bean實例。當須要手動獲取Bean實例時,就能夠直接使用工具類來獲取。git

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。web

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數據。代碼以下:spring

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提供了文件上傳的經常使用方法。sql

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 = "()<>@,;:\\\"/[]?={} \t";
    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", "風險庫沒法刪除:\n{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", "風險登記冊未關閉沒法開啓:\n{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

12.業務邏輯描述:在工單系統的詳情頁中,須要展現對工單的操做記錄,因此作了通用的模塊設計,這樣當要對工單詳情中的日誌部分做出修改的時候,能在最短的時間,最小的改動的狀況下,完美的解決問題。日誌表中新增附件字段,關聯app_attachment表中的主鍵,當操做人與登陸人相一致時,能夠經過附件上傳文件。

  解決方案:抽象出了詳情頁面中的orderOptList.vm模塊,在工單詳情頁中經過$control.setTemplate("web:orderOptList.vm")引入到工單詳情頁中,同時在後端須要提供公共的context.put("operations", operations)和context.put("appUserInfo", pvgInfo)來配合前端數據的展示。

2.業務邏輯描述:須要在工單的詳情頁中添加是否超時字段,用於在結單時判斷工單是否超時,若是逐個在工單中添加,侵入式過重,不利於後期維護,所以利用了java的反射機制,動態的更新是否超時字段。

  解決方案:方法中的參數設置爲超級父類Object,傳入的類,經過.getClass().getDeclaredMethod("方法名",方法入參逗號分隔)獲取到Method類,而後再知足業務邏輯的狀況下,經過method.invoke(Object obj, Object.. args)方法,調用方法刷新數據。

反射代碼

對類的方法實現動態賦值,使用方法method.invoke(obj,args...)方法,方法中的obj就是一個實例化對象,args是方法的參數。

public Object invoke(Object obj, Object... args)
    obj:從中調用底層方法的對象,必須是實例化對象
    args:用於方法調用,是一個object的數組,由於參數有可能有多個

3.業務邏輯描述:在內網系統中須要提供外網訪問的API接口的時候,須要

  解決方案:

4.業務邏輯描述:對部門敏感數據採用md5進行加密。

附:

1.解決SVN衝突心得:Eclipse分支調整順序提交一次,複製到衝突分之中,複製提交一次,而後合併代碼發佈就能夠了。

相關文章
相關標籤/搜索