J2EE项目开发中常用到的公共方法

  在项目IDCM中涉及到多种工单,包括有:服务器|网络设备上下架工单、服务器|网络设备重启工单、服务器光纤网线更换工单、网络设备撤线布线工单、服务器|网络设备替换工单、服务器|网络设备RMA工单、通用原子工单、硬盘消磁折弯工单、物流工单、资产初入门工单、机柜上下电工单、待盘点|待盘盈工单等等。工单管理系统中要涉及到工单的创建|API创建和维护。所以有必要将一些通用的方法提出来,类似于模块化的架构涉及。

目录:

  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三个类,附上代码:

 package com.alibaba.tboss.util;

 import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale; import org.apache.commons.lang3.StringUtils; import com.alibaba.common.lang.StringUtil;
import com.alibaba.nonda.json.ParseException; public class DateUtil { public static final String DATE_FORMAT = "yyyy-MM-dd";
public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DATETIME = "yyyyMMddHHmmss"; /**
* 计算两个日期之间相差的天数
*
* @param smdate 较小的时间
* @param bdate 较大的时间
* @return 相差天数
* @throws ParseException
* @throws Exception
*/
public static int daysBetween(Date smdate, Date bdate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
smdate = sdf.parse(sdf.format(smdate));
bdate = sdf.parse(sdf.format(bdate));
} catch (java.text.ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(bdate);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return new BigDecimal(String.valueOf(between_days)).abs().intValue();
} /**
* @description 将时间字符串转化为Date
* @author Anan
* @time 2013年7月26日 下午7:50:32
* @param time 时间字符串
* @param formatStr 时间格式 如"2013-7-26 19:52:47"、"2013-7-26"
* @return
*/
public static Date toDate(String time, String formatStr) {
Date date = null;
DateFormat dateFormat = new SimpleDateFormat(formatStr);
try {
date = dateFormat.parse(time);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
return date;
} public static Date toDatebyday(String time, String formatStr) {
Date date = null;
DateFormat dateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH);
try {
date = dateFormat.parse(time);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
return date;
} public static String toDatebydaytoString(String time, String formatStr) throws java.text.ParseException {
Date date = null;
String dateString = "";
DateFormat dateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH); date = dateFormat.parse(time);
dateString = formateDate(date); return dateString;
} public static Date toDatebytime(Date time, String formatStr) throws java.text.ParseException {
Date date = null;
String dateString = "";
DateFormat dateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH); dateString = formateDate(time);
date = toDate(dateString); return date;
} /**
* @description 将日期转化为字符串
* @author Anan
* @time 2013年7月30日 下午4:32:30
* @param date
* @param formatStr
* @return
*/
public static String toString(Date date, String formatStr) {
if (null == date || StringUtils.isBlank(formatStr)) return "";
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(date);
} /**
* @description 将年月日转化为日期
* @author Anan
* @time 2013年7月30日 下午5:00:33
* @param year
* @param month
* @param day
* @return
* @throws java.text.ParseException
*/
public static Date toDate(int year, int month, int day) throws java.text.ParseException {
Date date = null;
Calendar calender = Calendar.getInstance();
calender.set(Calendar.YEAR, year);
calender.set(Calendar.MONTH, month - 1);
calender.set(Calendar.DATE, day);
calender.set(Calendar.HOUR_OF_DAY, 0);
calender.set(Calendar.MINUTE, 0);
calender.set(Calendar.SECOND, 0);
date = calender.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
date = sdf.parse(sdf.format(date));
return date;
} /**
* @description 结束日期属于开始日期后的第几个月的日期
* @author Anan
* @time 2013年8月27日 下午10:00:33
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
public static int monthsFromStartDate(Date startDate, Date endDate) {
int result = 0;
Date temp = null;
startDate = toDate(toString(startDate, "yyyy-MM-dd"), "yyyy-MM-dd");
endDate = toDate(toString(endDate, "yyyy-MM-dd"), "yyyy-MM-dd");
// 开始日期 大于 结束日期 两个日期互换 例如: startDate 2013-05-21 endDate = 2013-04-20
if (startDate.after(endDate)) {
temp = startDate;
startDate = endDate;
endDate = temp;
}
Date tempEndDate1 = null;
Date tempEndDate2 = null;
int a = getDayOfMonth(startDate);
int b = getDayOfMonth(endDate);
int c = a - b;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(startDate);
c2.setTime(endDate);
c2.set(Calendar.DAY_OF_MONTH, a);
tempEndDate2 = c2.getTime();
int i = 0;
while (true) {
tempEndDate1 = addToMonth(startDate, i);
if (tempEndDate1.compareTo(tempEndDate2) == 0) {
result = i;
break;
}
i++;
if (i == 999999999) {// 防止死循环
break;
}
}
if (c < 0) {
result = result + 1;
}
return result;
} /**
* 获取开始时间与结束时间之间间隔的月数
*
* @author yansong
* @param startDate
* @param endDate
* @return
*/
public static int monthsBetween(Date startDate, Date endDate) {
int iMonth = 0;
try {
Calendar objCalendarDateStart = Calendar.getInstance();
objCalendarDateStart.setTime(startDate);
Calendar objCalendarDateEnd = Calendar.getInstance();
objCalendarDateEnd.setTime(endDate);
if (objCalendarDateEnd.equals(objCalendarDateStart) || objCalendarDateStart.after(objCalendarDateEnd)) {
return 0;
} else {
if (objCalendarDateEnd.get(Calendar.YEAR) > objCalendarDateStart.get(Calendar.YEAR)) {
iMonth = (objCalendarDateEnd.get(Calendar.YEAR) - objCalendarDateStart.get(Calendar.YEAR)) * 12
+ objCalendarDateEnd.get(Calendar.MONTH) - objCalendarDateStart.get(Calendar.MONTH);
} else {
iMonth = objCalendarDateEnd.get(Calendar.MONTH) - objCalendarDateStart.get(Calendar.MONTH);
}
} } catch (Exception e) {
e.printStackTrace();
}
return iMonth;
} /**
* 获取输入日期所在月份的第一天
*
* @author yansong
* @param date
* @return
*/
public static Date getFristDateForCurrentMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(GregorianCalendar.DAY_OF_MONTH, 1); return cal.getTime();
} /**
* 获取输入日期所在月份的最后一天
*
* @author yansong
* @param date
* @return
*/
public static Date getLastDateForCurrentMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date); cal.set(Calendar.DATE, 1);
cal.roll(Calendar.DATE, -1); return cal.getTime();
} /**
* @description 获取某年某月的第一天
* @author Anan
* @time 2013年7月30日 下午4:27:53
* @param year 某年
* @param month 某月
* @return
*/
public static Date getMonthBegin(int year, int month) {
Date _month_begin = null;
Calendar calender = Calendar.getInstance();
calender.set(Calendar.YEAR, year);
calender.set(Calendar.MONTH, month - 1);
calender.set(Calendar.DATE, 1);// 把日期设置为当月第一天
calender.set(Calendar.HOUR_OF_DAY, 0);
calender.set(Calendar.MINUTE, 0);
calender.set(Calendar.SECOND, 0);
_month_begin = calender.getTime();
return _month_begin;
} /**
* @description 获取某年某月的最后一天
* @author Anan
* @time 2013年7月30日 下午4:28:59
* @param year 某年
* @param month 某月
* @return
*/
public static Date getMonthEnd(int year, int month) {
Date month_end = null;
Calendar calender = Calendar.getInstance();
calender.set(Calendar.YEAR, year);
calender.set(Calendar.MONTH, month - 1);
calender.set(Calendar.DATE, 1);// 把日期设置为当月第一天
calender.roll(Calendar.DATE, -1);// 日期回滚一天,也就是最后一天
calender.set(Calendar.HOUR_OF_DAY, 0);
calender.set(Calendar.MINUTE, 0);
calender.set(Calendar.SECOND, 0);
month_end = calender.getTime();
return month_end;
} /**
* @description 得到指定月的天数
* @author Anan
* @time 2013年7月30日 下午4:48:00
* @param year 某年
* @param month 某月
* @return
*/
public static int getMonthLastDay(int year, int month) {
Calendar calender = Calendar.getInstance();
calender.set(Calendar.YEAR, year);
calender.set(Calendar.MONTH, month - 1);
calender.set(Calendar.DATE, 1);// 把日期设置为当月第一天
calender.roll(Calendar.DATE, -1);// 日期回滚一天,也就是最后一天
int maxDate = calender.get(Calendar.DATE);
return maxDate;
} /**
* @description 得到当前日期月的天数
* @author Anan
* @time 2013年9月1日 下午1:01:44
* @param date
* @return
*/
public static int getMonthLastDay(Date date) {
Calendar calender = Calendar.getInstance();
calender.setTime(date);
calender.set(Calendar.DATE, 1);// 把日期设置为当月第一天
calender.roll(Calendar.DATE, -1);// 日期回滚一天,也就是最后一天
int maxDate = calender.get(Calendar.DATE);
return maxDate;
} /**
* @description 得到日期中的月份
* @author William
* @time 2013年10月24日 下午1:01:44
* @param date
* @return
*/
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH);
} /**
* @description 当月的第几天
* @author Anan
* @time 2013年8月22日 下午9:24:30
* @param date
* @return
*/
public static int getDayOfMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.DAY_OF_MONTH);
} /**
* @description 获得当前日期 + N个月 之后的日期
* @author Anan
* @time 2013年8月23日 上午12:26:53
* @param oldDate
* @param n
* @return
*/
public static Date addToMonth(Date oldDate, int n) {
Date newDate = null;
Calendar calOld = Calendar.getInstance();
calOld.setTime(oldDate);
int month = calOld.get(Calendar.MONTH);
Calendar calNew = Calendar.getInstance();
calNew.setTime(oldDate);
calNew.set(Calendar.MONTH, n + month);
newDate = calNew.getTime();
return newDate;
} /**
* @description 获得当前日期 减去 N月 之后的日期
* @author Anan
* @time 2013年9月1日 上午12:26:53
* @param oldDate
* @param n
* @return
*/
public static Date removeMonths(Date oldDate, int n) {
Date newDate = null;
Calendar calOld = Calendar.getInstance();
calOld.setTime(oldDate);
int month = calOld.get(Calendar.MONTH);
Calendar calNew = Calendar.getInstance();
calNew.setTime(oldDate);
calNew.set(Calendar.MONTH, month - n);
newDate = calNew.getTime();
return newDate;
} /**
* @description 获得当前日期 减去 N天 之后的日期
* @author Anan
* @time 2013年8月23日 上午12:26:53
* @param oldDate
* @param n
* @return
*/
public static Date removeDays(Date oldDate, int n) {
Date newDate = null;
Calendar calOld = Calendar.getInstance();
calOld.setTime(oldDate);
int day = calOld.get(Calendar.DAY_OF_YEAR);
Calendar calNew = Calendar.getInstance();
calNew.setTime(oldDate);
calNew.set(Calendar.DAY_OF_YEAR, day - n);
newDate = calNew.getTime();
return newDate;
} /**
* @description 获得当前日期 加上 N天 之后的日期
* @author Anan
* @time 2013年8月23日 上午12:26:53
* @param oldDate
* @param n
* @return
*/
public static Date addDays(Date oldDate, int n) {
Date newDate = null;
Calendar calOld = Calendar.getInstance();
calOld.setTime(oldDate);
int day = calOld.get(Calendar.DAY_OF_YEAR);
Calendar calNew = Calendar.getInstance();
calNew.setTime(oldDate);
calNew.set(Calendar.DAY_OF_YEAR, day + n);
newDate = calNew.getTime();
return newDate;
} /**
* @description 获取两个年份之间的差值
* @author Anan
* @time 2013年8月23日 上午2:28:29
* @param startDate
* @param endDate
* @return
*/
public static int yearsBetween(Date startDate, Date endDate) {
int iYears = 0;
Calendar calS = Calendar.getInstance();
calS.setTime(startDate);
Calendar calE = Calendar.getInstance();
calE.setTime(endDate);
int i = startDate.compareTo(endDate);
if (i == 1) {
iYears = calS.get(Calendar.YEAR) - calE.get(Calendar.YEAR);
} else if (i == -1) {
iYears = calE.get(Calendar.YEAR) - calS.get(Calendar.YEAR);
}
return iYears;
} /**
* @param date 日期
* @param offset 偏移量,0为周日 单位为日
* @return WeekOfYear
*/
public static int getWeekOfYear(Date date, int offset) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date.getTime() - offset * 24 * 3600 * 1000L);
return calendar.get(Calendar.WEEK_OF_YEAR);
} // public static void main(String[] args) {
// Date now = toDate("2013-1-12", "yyyy-MM-dd");
// System.out.println(DateUtil.toString(DateUtil.addDays(now, 2),"yyyy-MM-dd"));
// } /**
* 标准格式化date
*
* @param date
* @return
*/
public static String formateDate(Date date) {
if (date == null) {
return StringUtil.EMPTY_STRING;
} return new SimpleDateFormat(DATE_FORMAT).format(date);
} /**
* 标准格式化datetime
*
* @param date
* @return
*/
public static String formateDatetime(Date date) {
if (date == null) {
return StringUtil.EMPTY_STRING;
} return new SimpleDateFormat(DATETIME_FORMAT).format(date);
} /**
* 按照"yyyy-MM-dd"的格式转换日期字符串为Date类型
*
* @param dateStr 日期字符串
* @return
*/
public static Date toDate(String dateStr) {
Date date = null;
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
try {
date = dateFormat.parse(dateStr);
} catch (java.text.ParseException e) {
return null;
}
return date;
} public static Date toDateTimes(String dateStr) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String result = null;
Date date = null;
try {
Date strToDate = sdf.parse(dateStr);
result = toString(strToDate, DATETIME_FORMAT);
date = toDate(result, DATETIME_FORMAT);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date; } public static String toDateTimeCompara(String dateStr) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String result = null; try {
Date strToDate = sdf.parse(dateStr);
result = toString(strToDate, DATETIME_FORMAT); } catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result; } /**
* 按照"yyyy-MM-dd HH:mm:ss"的格式转换日期时间字符串为Date类型
*
* @param dateTimeStr 日期时间字符串
* @return
*/
public static Date toDateTime(String dateTimeStr) {
Date date = null;
DateFormat dateFormat = new SimpleDateFormat(DATETIME_FORMAT);
try {
date = dateFormat.parse(dateTimeStr);
} catch (java.text.ParseException e) {
return null;
}
return date;
} public static String transferLongToDate(Long millSec) { SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_FORMAT); Date date = new Date(millSec); return sdf.format(date); } /**
* 校验日期格式是否满足yyyyMMddHHmmss这种格式
*
* @param time
* @return
*/
public static boolean checkValidDate(String time) {
boolean ret = true;
try {
int year = new Integer(time.substring(0, 4)).intValue();
int month = new Integer(time.substring(4, 6)).intValue();
int date = new Integer(time.substring(6, 8)).intValue();
int hourOfDay = new Integer(time.substring(8, 10)).intValue();
int minute = new Integer(time.substring(10, 12)).intValue();
int second = new Integer(time.substring(12, 14)).intValue();
Calendar cal = Calendar.getInstance();
cal.setLenient(false); // 允许严格检查日期格式
cal.set(year, month - 1, date);
cal.set(year, month - 1, date, hourOfDay, minute, second);
cal.getTime();// 该方法调用就会抛出异常
} catch (Exception e) {
e.printStackTrace();
ret = false;
}
return ret;
} public static void main(String[] args) {
String format = "20150819202020";
String datestr = "09090909090909";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
System.out.println("456" + checkValidDate(datestr));
System.out.println("789" + toDateTimes(datestr));
System.out.println("123" + toString(toDateTimes(datestr), DATETIME_FORMAT));
try {
Date strToDate = sdf.parse(format);
String result = toString(strToDate, DATETIME_FORMAT);
System.out.println("strToDate" + strToDate);
System.out.println("strToDate" + result); } catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } /**
* 获得指定日期的后一天
*
* @param specifiedDay
* @return
*/
public static Date getSpecifiedDayAfter(Date date) {
Calendar c = Calendar.getInstance(); c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day + 1); String dayAfter = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
Date newdate = toDate(dayAfter);
return newdate;
}
}

DateUtil.java

2.工具类HttpClientUtil.java提供了系统调用外部接口的公共方法,包括post、get方法,以及对于HTTPS协议的支持。在httpPostWithJson方法中流的关闭采用了传统的方法,如果项目的JDK版本在1.7之上,可以采用try...with...resources来关闭流。

 package com.alibaba.tboss.util;

 import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import org.apache.commons.lang.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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fasttext.sec.url.SSRFChecker; public class HttpClientUtil { private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); public static String httpPostWithJson(String ecUrl, String params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url = new URL(ecUrl);
connection = (HttpURLConnection) url.openConnection();
// 创建连接
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect(); // POST请求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(params);
out.flush();
out.close(); // 读取响应
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
return sb.toString();
} catch (MalformedURLException e) {
logger.error("httpPostWithJsonMalformedURLException error", e);
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
logger.error("httpPostWithJsonUnsupportedEncodingException error", e);
e.printStackTrace();
} catch (IOException e) {
logger.error("httpPostWithJsonIOException error", e);
e.printStackTrace();
} finally {
try {
if (null != reader) {
reader.close();
}
if (null != connection) {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
} public static String HttpPostWithJsonByHttpClient(String url, String json) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
try {
StringEntity s = new StringEntity(json);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s); HttpResponse response = client.execute(post);
// 读取内容
String result = extractContent(response);
return result;
} catch (Exception e) {
logger.error("HttpPostWithJsonByHttpClientException error", e);
return null;
}
} public static String httpPostRequest(String url, Map<String, String> params) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
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;
} public static String httpGetRequest(String url) throws Exception {
HttpClient httpclient = new DefaultHttpClient(); // 使用安全包进行检查是否安全
SSRFChecker ssrfChecker = SSRFChecker.instance;
if (!ssrfChecker.checkUrlWithoutConnection(url)) {
logger.error("HttpClientUtils SSRFCheck Errors ", url);
throw new RuntimeException("SSRFChecker fail, url=[" + url + "]");
} HttpPost httpGet = new HttpPost(url);
httpGet.setHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
// 创建UrlEncodedFormEntity对象
HttpResponse response = httpclient.execute(httpGet);
String html = extractContent(response);
return html;
} private static String extractContent(HttpResponse response) throws Exception {
String htmStr = null;
if (response.getStatusLine().getStatusCode() == 200) {
if (response != null) {
HttpEntity entity = response.getEntity();
InputStream ins = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
sbf.append(line);
}
// 处理内容
htmStr = sbf.toString();
}
}
return htmStr;
} /**
* 实现HTTPS的API访问
*
* @param sn
* @param nodegroup
* @param traceInfo
* @return
*/
public static boolean httpsPostRequest(String url, Map<String, Object> params) { DefaultHttpClient httpClient = new DefaultHttpClient();
try {
TrustManager easyTrustManager = new X509TrustManager() { @Override
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
} @Override
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
} @Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0]; // To change body of implemented methods use File
// | Settings | File Templates.
}
}; SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
Scheme sch = new Scheme("https", 443, sf);
httpClient.getConnectionManager().getSchemeRegistry().register(sch); HttpPost httpPost = new HttpPost(url);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
if (params.get(key) != null) {
parameters.add(new BasicNameValuePair(key, params.get(key).toString()));
}
}
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, "UTF-8"); httpPost.setEntity(formEntiry); HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
if (content != null) {
JSONObject jo = JSONObject.parseObject(content);
if (jo.getBooleanValue("content")) {
return true;
}
}
return false;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
httpClient.getConnectionManager().shutdown();
}
} public static JSONObject httpsPostRequestString(String url, Map<String, Object> params) { DefaultHttpClient httpClient = new DefaultHttpClient();
String content = "";
try {
TrustManager easyTrustManager = new X509TrustManager() { @Override
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
} @Override
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
} @Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0]; // To change body of implemented methods use File
// | Settings | File Templates.
}
}; SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
Scheme sch = new Scheme("https", 443, sf);
httpClient.getConnectionManager().getSchemeRegistry().register(sch); HttpPost httpPost = new HttpPost(url);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
if (params.get(key) != null) {
parameters.add(new BasicNameValuePair(key, params.get(key).toString()));
}
}
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, "UTF-8"); httpPost.setEntity(formEntiry); HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
content = EntityUtils.toString(entity);
if (content != null) {
JSONObject jo = JSONObject.parseObject(content);
return jo;
}
return null;
} catch (Exception e) {
logger.error("httpsPostRequestString [url={},params={},response={}] error:", url,
JSONObject.toJSONString(params), content, e);
throw new RuntimeException(e.getMessage(), e);
} finally {
httpClient.getConnectionManager().shutdown();
}
} public static String httpsGetByHttpclient(String url, String authorization) { DefaultHttpClient httpClient = new DefaultHttpClient();
try {
TrustManager easyTrustManager = new X509TrustManager() { @Override
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
} @Override
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
} @Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0]; // To change body of implemented methods use File
// | Settings | File Templates.
}
}; SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
Scheme sch = new Scheme("https", 443, sf);
httpClient.getConnectionManager().getSchemeRegistry().register(sch); // 使用安全包进行检查是否安全
SSRFChecker ssrfChecker = SSRFChecker.instance;
if (!ssrfChecker.checkUrlWithoutConnection(url)) {
logger.error("HttpClientUtils SSRFCheck Errors ", url);
throw new RuntimeException("SSRFChecker fail, url=[" + url + "]");
} HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization", authorization); HttpResponse response = httpClient.execute(httpGet);
String content = extractContent(response);
if (StringUtils.isBlank(content)) {
return "";
}
return content;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
httpClient.getConnectionManager().shutdown();
}
} /**
* https post 方式,包含Authorization认证
*
* @param url
* @param params
* @param authorization
* @return
*/
public static String httpsPostByHttpclient(String url, Map<String, Object> params, String authorization) {
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
TrustManager easyTrustManager = new X509TrustManager() { @Override
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
} @Override
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
} @Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0]; // To change body of implemented methods use File
// | Settings | File Templates.
}
}; SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
Scheme sch = new Scheme("https", 443, sf);
httpClient.getConnectionManager().getSchemeRegistry().register(sch); HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Authorization", authorization);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
if (params.get(key) != null) {
parameters.add(new BasicNameValuePair(key, params.get(key).toString()));
}
}
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, "UTF-8"); httpPost.setEntity(formEntiry); HttpResponse response = httpClient.execute(httpPost);
String content = extractContent(response);
if (StringUtils.isBlank(content)) {
return "";
}
return content;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
httpClient.getConnectionManager().shutdown();
}
} }

HttpClientUtil.java

3.加密工具类GenMD5Util.java提供了将指定字符串加密成MD5的方法。代码实现如下:

 package com.alibaba.tboss.util;

 import java.text.SimpleDateFormat;
import java.util.Date; public class GenArmoryKeyUtil { private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd"); public static void main(String[] args) {
Date today = new Date();
String username = "idcm";
/* 开发环境和线上环境最好配置不一样的key */
String key = "dNdljpq05K0a62htckqXnQ==";
String sign = getKey(username, today, key);
System.out.println(sign);
} public static String getKey(String username, Date today, String key) {
return getMD5(username + SIMPLE_DATE_FORMAT.format(today) + key);
} public static String getMD5(String value) {
String result = "";
try {
result = getMD5(value.getBytes("UTF-8"));
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
} public static String getMD5(byte[] bytes) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
char str[] = new char[16 * 2];
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
md.update(bytes);
byte tmp[] = md.digest();
int k = 0;
for (int i = 0; i < 16; i++) {
byte byte0 = tmp[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new String(str);
} }

GenMD5Util.java

4.在工单表中有公共属性:`creator`、'gmt_create'、`modifier`、`gmt_modified`、`is_deleted`,公共方法抽象工具类CommonUtil.java提供了对基础工单表的公共操作方法,在工单操作中将新建工单,修改工单,设置通用值的方法提取出来,利用java反射来实现设值。代码如下:

 package com.alibaba.tboss.common.auth.common;

 import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import com.alibaba.tboss.common.auth.costants.AppRoleType;
import com.alibaba.tboss.common.auth.exception.AppAuthCommonException;
import com.alibaba.tboss.common.auth.privilege.PrivilegeInfo; public class CommonUtil { private static String MODIFIER = "modifier"; private static String GMT_MODIFIED = "gmtModified"; private static String IS_DELETED = "is_deleted"; private static String FULL_ORG_PATH = "fullOrgPath"; private static String OWNER = "owner"; public static void setCommonValueForCreate(Object pojo, PrivilegeInfo privilegeInfo) {
try {
Method setCreator = pojo.getClass().getMethod("setCreator", String.class);
setCreator.invoke(pojo, getOperator(privilegeInfo)); Method setModifier = pojo.getClass().getMethod("setModifier", String.class);
setModifier.invoke(pojo, getOperator(privilegeInfo)); Method setGmtCreate = pojo.getClass().getMethod("setGmtCreate", Date.class);
setGmtCreate.invoke(pojo, new Date()); Method setGmtModified = pojo.getClass().getMethod("setGmtModified", Date.class);
setGmtModified.invoke(pojo, new Date()); Method setIsDeleted = pojo.getClass().getMethod("setIsDeleted", String.class);
setIsDeleted.invoke(pojo, "n"); } catch (Exception e) {
throw new AppAuthCommonException("invoke method error ", e);
} } public static void setCommonValueForDeletes(Object pojo, PrivilegeInfo privilegeInfo) {
try {
Method setModifier = pojo.getClass().getMethod("setModifier", String.class);
setModifier.invoke(pojo, getOperator(privilegeInfo)); Method setGmtModified = pojo.getClass().getMethod("setGmtModified", Date.class);
setGmtModified.invoke(pojo, new Date()); Method setIsDeleted = pojo.getClass().getMethod("setIsDeleted", String.class);
setIsDeleted.invoke(pojo, "y");
} catch (Exception e) {
throw new AppAuthCommonException("invoke method error ", e);
}
} public static void setCommonValueForDelete(Map<String, Object> param, PrivilegeInfo privilegeInfo) {
if (param.get(MODIFIER) == null || StringUtils.isEmpty((String) param.get(MODIFIER))) {
param.put(MODIFIER, getOperator(privilegeInfo));
}
param.put(GMT_MODIFIED, new Date());
param.put(IS_DELETED, "n"); } public static void setCommonValueForUpdate(Object pojo, PrivilegeInfo privilegeInfo) {
try {
Method setGmtModified = pojo.getClass().getMethod("setGmtModified", Date.class);
setGmtModified.invoke(pojo, new Date());
Method setModifier = pojo.getClass().getMethod("setModifier", String.class);
setModifier.invoke(pojo, getOperator(privilegeInfo)); } catch (Exception e) {
throw new AppAuthCommonException("invoke method error ", e);
} } public static void setCommonValueForUpdate(Map<String, Object> param, PrivilegeInfo privilegeInfo) {
if (param.get(MODIFIER) == null || StringUtils.isEmpty((String) param.get(MODIFIER))) {
param.put(MODIFIER, getOperator(privilegeInfo));
}
param.put(GMT_MODIFIED, new Date());
} public static void setOrgPathForSelectMap(Map<String, Object> param, PrivilegeInfo privilegeInfo) {
if (privilegeInfo.getCurrentRoleType().equals(AppRoleType.MASTER.toString())) {
if (param.get(FULL_ORG_PATH) == null || StringUtils.isEmpty((String) param.get(FULL_ORG_PATH))) {
param.put(FULL_ORG_PATH, getCurrentDataAuthAccessPath(privilegeInfo));
}
} else {
if (param.get(OWNER) == null || StringUtils.isEmpty((String) param.get(OWNER))) {
param.put(OWNER, privilegeInfo.getAppUserId());
}
} } private static String getCurrentDataAuthAccessPath(PrivilegeInfo pvgInfo) {
if (pvgInfo == null || StringUtils.isEmpty(pvgInfo.getCurrentDataAuthAccessPath())) {
return "1/2";
} else {
return pvgInfo.getCurrentDataAuthAccessPath();
}
} public static String getOperator(PrivilegeInfo pvgInfo) {
if (pvgInfo == null || StringUtils.isEmpty(pvgInfo.getWorkNo())) {
return "SYSTEM";
} else {
return pvgInfo.getWorkNo();
}
} public static boolean numStart(String workNo) {
Pattern pattern = Pattern.compile("^(\\d+)(.*)");
Matcher matcher = pattern.matcher(workNo);
return matcher.matches();
} public static String preprWorkNo(String workNo) {
if (StringUtils.isEmpty(workNo)) {
return workNo;
}
if (numStart(workNo) && workNo.length() < 6) {
while (workNo.length() < 6) {
workNo = "0" + workNo;
}
}
return workNo;
} }

CommonUtil.java

5.当spring容器启动的时候,自动把实现了ApplicationContextAware的类找出来,然后为其注入ApplicationContext属性,使得SpringContextUtil可以*自在的根据名字获取Bean实例。当需要手动获取Bean实例时,就可以直接使用工具类来获取。

package com.alibaba.tboss.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; /**
*
* ClassName: SpringContextUtil <br/>
* Function: 在applicationContext.xml中加入配置
* <bean id="SpringContextUtil" class="com.alibaba.tboss.util.SpringContextUtil"/>
* 用来得到spring配置的Bean <br/>
* date: 2015年12月31日 <br/>
*/
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext; //Spring应用上下文环境 /**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
* @param applicationContext
* @throws BeansException
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
} /**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
} /**
* 获取对象
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
} /**
*
* getBean: 获取类型为requiredType的对象 . <br/>
*
* @param requiredType 返回对象类型
* @return 返回requiredType类型对象
*/
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
} /**
* 获取类型为requiredType的对象
* 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException)
* @param name bean注册名
* @param requiredType 返回对象类型
* @return Object 返回requiredType类型对象
* @throws BeansException
*/
public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return applicationContext.getBean(name, requiredType);
} /**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
* @param name
* @return boolean
*/
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
} /**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
* 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
* @param name
* @return boolean
* @throws NoSuchBeanDefinitionException
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return applicationContext.isSingleton(name);
} /**
* @param name
* @return Class 注册对象的类型
* @throws NoSuchBeanDefinitionException
*/
@SuppressWarnings("rawtypes")
public static Class getType(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getType(name);
} /**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
* @param name
* @return
* @throws NoSuchBeanDefinitionException
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getAliases(name);
}
}

SpringContextUtil.java

6.项目中常用的数据类型转换中,工具类JsonToBeanUtil.java提供了json和bean相互转换的方法,主要支持gson和fastjson。

package com.alibaba.tboss.util;

import java.util.ArrayList;
import java.util.List; import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder; @SuppressWarnings({ "unchecked", "rawtypes" })
public class JsonToBeanUtil { /**
* 使用com.alibaba.fastjson.JSONArray.parseArray()方法,将json转List<Bean>
*/
public static List<?> JsonToJavaBean(String json, Class objectClass) {
List<?> list = new ArrayList();
if (json != null && !"".equals(json)) {
try {
list = JSONArray.parseArray(json, objectClass);
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
} /**
* 使用 com.google.gson.Gson.fromJson将json转Bean
*/
public static <T> T jsonToBean(String jsonString, Class<T> beanCalss) {
Gson gson = new Gson();
T bean = gson.fromJson(jsonString, beanCalss);
return bean;
} public static <T> T jsonToBean(String jsonString, Class<T> beanCalss, String dateFormat) {
Gson gson = new GsonBuilder().setDateFormat(dateFormat).create();
T bean = gson.fromJson(jsonString, beanCalss);
return bean;
} /**
* 使用 com.google.gson.Gson.fromJson将list转JSON
*/
public static String listToJson(List<?> list) {
Gson gson = new Gson();
String s = gson.toJson(list);
return s;
} public static String listToJsonWithoutHtmlEscaping(List<?> list) {
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String s = gson.toJson(list);
return s;
}
}

JsonToBeanUtil.java

7.流程工具类FlowUtil.java,实现了字符串的不同编解码,调用post请求解析response数据。代码如下:

package com.alibaba.tboss.biz.flow.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import net.sf.json.JSONObject; import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; public class FlowUtil { public static String emptyString = StringUtils.EMPTY; /**
* 实体类Bean转JSON
*/
@SuppressWarnings("static-access")
public static String ObjectToJSON(Object obj, String key) {
if (obj != null) {
JSONObject jsonObject = new JSONObject().fromObject(obj);
if (!"".equals(key) && key != null) {
return "{" + key + ":" + jsonObject.toString() + "}";
}
return jsonObject.toString();
}
return emptyString;
} /**
* <p>
* javaEncodeString TODO(转码)
* </p>
*
* @param v 转换字符串
* @param charset 转换格式
* @return String 设定文件
*/
public static String javaEncodeString(String v, String charset) {
try {
return URLEncoder.encode(v, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return v;
} /**
* <p>
* javaDecodeString TODO(解码)
* </p>
*
* @param v 转换字符串
* @param charset 转换格式
* @return String 设定文件
*/
public static String javaDecodeString(String v, String charset) {
try {
return URLDecoder.decode(v, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return v;
} /**
* 获取HttpResponse 对象内容
*/
public static String extractContent(HttpResponse response) throws Exception {
String htmStr = "";
if (response != null) {
HttpEntity entity = response.getEntity();
InputStream ins = entity.getContent();
BufferedReader br = null;
StringBuffer sbf = new StringBuffer();
try {
br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sbf.append(line);
}
} finally {
if (br != null) {
br.close();
}
}
// 处理内容
htmStr = sbf.toString();
} return htmStr;
} /**
* <p>
* 获取请求的数据
* </p>
*
* @param url
* @param params
* @return
* @throws Exception 参数描述
*/
public static String httpPostRequest(String url, List<NameValuePair> params) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// 创建UrlEncodedFormEntity对象
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(params, "UTF-8");
httpPost.setEntity(formEntiry); HttpResponse response = httpclient.execute(httpPost);
String html = extractContent(response);
return html;
} /**
* <p>
* 获取请求的数据
* </p>
*
* @param url
* @param params
* @return
* @throws Exception 参数描述
*/
public static String httpPostRequest(String url, HashMap<String, String> params) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
parameters.add(new BasicNameValuePair(key, params.get(key)));
}
// 创建UrlEncodedFormEntity对象
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, "UTF-8");
httpPost.setEntity(formEntiry); HttpResponse response = httpclient.execute(httpPost);
String html = extractContent(response);
return html;
}
}

FlowUtil.java

8.文件上传工具类FileUpLoadUtil.java提供了文件上传的常用方法。

package com.alibaba.tboss.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.alibaba.tboss.common.idcFree.util.RackUtil;
import com.alibaba.tboss.dal.mysql.location.LocationCorrect;
import com.alibaba.tboss.dal.mysql.rack.RackCorrect;
import com.alibaba.tboss.exception.ErrorCode;
import com.alibaba.tboss.exception.ServiceException;
import com.alibaba.tboss.util.ExcelUtils.CellMapping; public class FileUpLoadUtil { public static <T> List<T> importFile(FileItem fileInput, String sheetName, Class<T> type) {
List<T> list = null;
if (null == fileInput) {
throw new ServiceException(ErrorCode.Params_Lost, "机柜导入文件");
}
Workbook wb = null;
InputStream is = null;
Sheet sheet = null;
try {
is = fileInput.getInputStream();
wb = new XSSFWorkbook(is);
sheet = wb.getSheet(sheetName);
} catch (Exception e) {
throw new ServiceException(ErrorCode.Upload_File_Error, "上传excel版本文件解析失败");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
} if (sheet != null) {
// 初始化Excel栏目
List<CellMapping> mappingList = RackUtil.getLocationCorrectColumns();
try {
list = ExcelUtils.excel2bean(sheet, type, mappingList);
} catch (Exception e) {
throw new ServiceException(ErrorCode.Upload_File_Error, "Excel解析失败");
}
} else {
throw new ServiceException(ErrorCode.Upload_File_Error, "未找到模板对应sheet");
} return list;
} public static <T> List<T> importFileRack(FileItem fileInput, String sheetName, Class<T> type) {
List<T> list = null;
if (null == fileInput) {
throw new ServiceException(ErrorCode.Params_Lost, "机柜导入文件");
}
Workbook wb = null;
InputStream is = null;
Sheet sheet = null;
try {
is = fileInput.getInputStream();
wb = new XSSFWorkbook(is);
sheet = wb.getSheet(sheetName);
} catch (Exception e) {
throw new ServiceException(ErrorCode.Upload_File_Error, "上传excel版本文件解析失败");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
} if (sheet != null) {
// 初始化Excel栏目
List<CellMapping> mappingList = RackUtil.getRackCorrectColumns();
try {
list = ExcelUtils.excel2bean(sheet, type, mappingList);
} catch (Exception e) {
throw new ServiceException(ErrorCode.Upload_File_Error, "Excel解析失败");
}
} else {
throw new ServiceException(ErrorCode.Upload_File_Error, "未找到模板对应sheet");
} return list;
} /**
* 导出文件
*/
public static void exportTemplate(List<LocationCorrect> locationCorrect, List<CellMapping> mappingList,
String fileName, String sheetName, HttpServletResponse response) {
OutputStream out = null;
try {
response.setHeader("Pragma", "public");// 解决IE浏览器在https模式下文件无法下载
response.setHeader("Cache-Control", "max-age=0");// 解决IE浏览器在https模式下文件无法下载
// 解决safari中下载会自动添加html后缀的问题
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setDateHeader("Expires", 0);
// 添加*=utf-8'解决中文文件名在firefox和safari中乱码的问题.
response.setHeader("Content-Disposition",
"attachment; filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
out = response.getOutputStream();
exportFileAsExcel(locationCorrect, mappingList, sheetName, out);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("导出异常:" + e.getMessage(), e);
} finally {
if (out != null) try {
out.close();
} catch (IOException e) {
out = null;
throw new RuntimeException("导出异常:" + e.getMessage(), e);
}
}
// 成功后返回cookie标志位
response.setHeader("SET-COOKIE", "fileDownload=true;Path=/;");
} /**
* 导出文件
*/
public static void exportRackTemplate(List<RackCorrect> locationCorrect, List<CellMapping> mappingList,
String fileName, String sheetName, HttpServletResponse response) {
OutputStream out = null;
try {
response.setHeader("Pragma", "public");// 解决IE浏览器在https模式下文件无法下载
response.setHeader("Cache-Control", "max-age=0");// 解决IE浏览器在https模式下文件无法下载
// 解决safari中下载会自动添加html后缀的问题
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setDateHeader("Expires", 0);
// 添加*=utf-8'解决中文文件名在firefox和safari中乱码的问题.
response.setHeader("Content-Disposition",
"attachment; filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
out = response.getOutputStream();
exportFileAsExcel(locationCorrect, mappingList, sheetName, out);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("导出异常:" + e.getMessage(), e);
} finally {
if (out != null) try {
out.close();
} catch (IOException e) {
out = null;
throw new RuntimeException("导出异常:" + e.getMessage(), e);
}
}
// 成功后返回cookie标志位
response.setHeader("SET-COOKIE", "fileDownload=true;Path=/;");
} /**
* 导出机柜列表为Excel文件
*
* @param datas 导出的机柜列表
* @param mappingList 导出的字段
* @param out 导出文件输出流
* @param sheetName 导出Excel的sheet名称
*/
public static void exportFileAsExcel(List<?> datas, List<CellMapping> mappingList, String sheetName,
OutputStream out) {
try {
// XSSFWorkbook
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet(sheetName);
ExcelUtils.bean2excel(datas, sheet, mappingList);
workbook.write(out);
} catch (Exception e) {
throw new RuntimeException("导出Excel时发生错误:" + e.getStackTrace(), e);
}
}
}

FileUploadUtil.java

9.缓存工具类CookieUtil.java文件提供了操作缓存的常用方法

package com.alibaba.tboss.util;

import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; /**
* 类CookieUtil.java的实现描述:操作Cookie的工具类
*
* @author chivas.liuzh 12 Jun 2011 9:30:14 PM
*/
public class CookieUtil {
private static final String PATH = "/"; /**
* US locale - all HTTP dates are in english
*/
public final static Locale LOCALE_US = Locale.US; /**
* Pattern used for old cookies
*/
public final static String OLD_COOKIE_PATTERN = "EEE, dd-MMM-yyyy HH:mm:ss z"; //
// from RFC 2068, token special case characters
//
private static final String tspecials = "()<>@,;:\\\"/[]?={} \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表中的主键,当操作人与登录人相一致时,可以通过附件上传文件。

J2EE项目开发中常用到的公共方法

  解决方案:抽象出了详情页面中的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分支调整顺序提交一次,复制到冲突分之中,复制提交一次,然后合并代码发布就可以了。

上一篇:Two ways to see predicates added by VPD or FGAC


下一篇:web开发过程中经常用到的一些公共方法及操作