记忆中唯独就wwW13www221ddcomm缺失了,调整入口的131dd那一段

社区快捷入口:
日星期一注册用户位,目前在线363910人
关注我们的微信公众号,发现信息价值。微信中搜索「凯迪」或扫一扫下方二维码:
学习著作权法,保护合法权益,打击侵权盗版。全省投诉举报电话:12318。&&&&&&&&&&&&&&&&&&
posts - 228,comments - 220,trackbacks - 0
  在项目IDCM中涉及到多种工单,包括有:服务器|网络设备上下架工单、服务器|网络设备重启工单、服务器光纤网线更换工单、网络设备撤线布线工单、服务器|网络设备替换工单、服务器|网络设备RMA工单、通用原子工单、硬盘消磁折弯工单、物流工单、资产初入门工单、机柜上下电工单、待盘点|待盘盈工单等等。工单管理系统中要涉及到工单的创建|API创建和维护。所以有必要将一些通用的方法提出来,类似于模块化的架构涉及。
日期工具类DateUtil.java提供日期计算的相关静态方法
接口调用工具类HttpClientUtil.java提供调用外部接口的公共方法
加密工具类GenMD5Util.java提供了将制定字符串加密成MD5的方法
公共方法抽象工具类CommonUtil.java提供了对工单表增删改查的公共方法
获取Bean实例工具类SpringContextUtil.java提供了根据bean id获取Bean实例的方法
实体Bean和JSON转换工具类JsonToBeanUtil.java提供了json和bean相互转换的方法
流程工具类FlowUtil.java提供了字符串转换和解析response的常用方法
文件上传工具类FileUpLoadUtil.java封装了上传的公共方法
工具类CookieUtil.java提供了常用的操纵缓存的方法
表格Excel转换实体Bean工具类ExcelUtil.java提供了文件导入导出的方法
复用$control.setTemplate("web:orderOptList.vm")实现日志记录
JDK反射提供抽象参数类实现动态加载
api auth授权机制保证外部调用接口的安全性
1.日期工具类DateUtil.java提供了常用的日期计算方法,涉及SimpleDateFormat、Calendar、Date三个类,附上代码:
1 package com.alibaba.tboss.
3 import java.math.BigD
4 import java.text.DateF
5 import java.text.SimpleDateF
6 import java.util.C
7 import java.util.D
8 import java.util.GregorianC
9 import java.util.L
11 import org.apache.commons.lang3.StringU
13 import com.alibaba.common.lang.StringU
14 import com.alibaba.nonda.json.ParseE
16 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");
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 日 下午7:50:32
* @param time 时间字符串
* @param formatStr 时间格式 如" 19:52:47"、""
public static Date toDate(String time, String formatStr) {
Date date = null;
DateFormat dateFormat = new SimpleDateFormat(formatStr);
date = dateFormat.parse(time);
} catch (java.text.ParseException e) {
e.printStackTrace();
public static Date toDatebyday(String time, String formatStr) {
Date date = null;
DateFormat dateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH);
date = dateFormat.parse(time);
} catch (java.text.ParseException e) {
e.printStackTrace();
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 dateS
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);
* @description 将日期转化为字符串
* @author Anan
* @time 日 下午4:32:30
* @param date
* @param formatStr
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 日 下午5:00:33
* @param year
* @param month
* @param day
* @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));
* @description 结束日期属于开始日期后的第几个月的日期
* @author Anan
* @time 日 下午10:00:33
* @param startDate 开始日期
* @param endDate 结束日期
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
if (startDate.after(endDate)) {
temp = startD
startDate = endD
Date tempEndDate1 = null;
Date tempEndDate2 = null;
int a = getDayOfMonth(startDate);
int b = getDayOfMonth(endDate);
int c = a -
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) {
if (i == ) {// 防止死循环
if (c & 0) {
result = result + 1;
* 获取开始时间与结束时间之间间隔的月数
* @author yansong
* @param startDate
* @param endDate
public static int monthsBetween(Date startDate, Date endDate) {
int iMonth = 0;
Calendar objCalendarDateStart = Calendar.getInstance();
objCalendarDateStart.setTime(startDate);
Calendar objCalendarDateEnd = Calendar.getInstance();
objCalendarDateEnd.setTime(endDate);
if (objCalendarDateEnd.equals(objCalendarDateStart) || objCalendarDateStart.after(objCalendarDateEnd)) {
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);
iMonth = objCalendarDateEnd.get(Calendar.MONTH) - objCalendarDateStart.get(Calendar.MONTH);
} catch (Exception e) {
e.printStackTrace();
* 获取输入日期所在月份的第一天
* @author yansong
* @param date
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
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 日 下午4:27:53
* @param year 某年
* @param month 某月
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_
* @description 获取某年某月的最后一天
* @author Anan
* @time 日 下午4:28:59
* @param year 某年
* @param month 某月
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_
* @description 得到指定月的天数
* @author Anan
* @time 日 下午4:48:00
* @param year 某年
* @param month 某月
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 maxD
* @description 得到当前日期月的天数
* @author Anan
* @time 日 下午1:01:44
* @param date
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 maxD
* @description 得到日期中的月份
* @author William
* @time 日 下午1:01:44
* @param date
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH);
* @description 当月的第几天
* @author Anan
* @time 日 下午9:24:30
* @param date
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 日 上午12:26:53
* @param oldDate
* @param n
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 newD
* @description 获得当前日期 减去 N月 之后的日期
* @author Anan
* @time 日 上午12:26:53
* @param oldDate
* @param n
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 newD
* @description 获得当前日期 减去 N天 之后的日期
* @author Anan
* @time 日 上午12:26:53
* @param oldDate
* @param n
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 newD
* @description 获得当前日期 加上 N天 之后的日期
* @author Anan
* @time 日 上午12:26:53
* @param oldDate
* @param n
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 newD
* @description 获取两个年份之间的差值
* @author Anan
* @time 日 上午2:28:29
* @param startDate
* @param endDate
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);
* @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("", "yyyy-MM-dd");
// System.out.println(DateUtil.toString(DateUtil.addDays(now, 2),"yyyy-MM-dd"));
* 标准格式化date
* @param date
public static String formateDate(Date date) {
if (date == null) {
return StringUtil.EMPTY_STRING;
return new SimpleDateFormat(DATE_FORMAT).format(date);
* 标准格式化datetime
* @param date
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 日期字符串
public static Date toDate(String dateStr) {
Date date = null;
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
date = dateFormat.parse(dateStr);
} catch (java.text.ParseException e) {
return null;
public static Date toDateTimes(String dateStr) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String result = null;
Date date = null;
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();
public static String toDateTimeCompara(String dateStr) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String result = null;
Date strToDate = sdf.parse(dateStr);
result = toString(strToDate, DATETIME_FORMAT);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
* 按照"yyyy-MM-dd HH:mm:ss"的格式转换日期时间字符串为Date类型
* @param dateTimeStr 日期时间字符串
public static Date toDateTime(String dateTimeStr) {
Date date = null;
DateFormat dateFormat = new SimpleDateFormat(DATETIME_FORMAT);
date = dateFormat.parse(dateTimeStr);
} catch (java.text.ParseException e) {
return null;
public static String transferLongToDate(Long millSec) {
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_FORMAT);
Date date = new Date(millSec);
return sdf.format(date);
* 校验日期格式是否满足yyyyMMddHHmmss这种格式
* @param time
public static boolean checkValidDate(String time) {
boolean ret = true;
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;
public static void main(String[] args) {
String format = "20";
String datestr = "09";
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));
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
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);
DateUtil.java
2.工具类HttpClientUtil.java提供了系统调用外部接口的公共方法,包括post、get方法,以及对于HTTPS协议的支持。在httpPostWithJson方法中流的关闭采用了传统的方法,如果项目的JDK版本在1.7之上,可以采用try...with...resources来关闭流。
1 package com.alibaba.tboss.
3 import java.io.BufferedR
4 import java.io.DataOutputS
5 import java.io.IOE
6 import java.io.InputS
7 import java.io.InputStreamR
8 import java.io.UnsupportedEncodingE
9 import java.net.HttpURLC
10 import java.net.MalformedURLE
11 import java.net.URL;
12 import java.util.ArrayL
13 import java.util.L
14 import java.util.M
16 import javax.net.ssl.SSLC
17 import javax.net.ssl.TrustM
18 import javax.net.ssl.X509TrustM
20 import org.apache.commons.lang.StringU
21 import org.apache.http.HttpE
22 import org.apache.http.HttpR
23 import org.apache.http.NameValueP
24 import org.apache.http.client.HttpC
25 import org.apache.http.client.entity.UrlEncodedFormE
26 import org.apache.http.client.methods.HttpG
27 import org.apache.http.client.methods.HttpP
28 import org.apache.http.conn.scheme.S
29 import org.apache.http.conn.ssl.SSLSocketF
30 import org.apache.http.entity.StringE
31 import org.apache.http.impl.client.DefaultHttpC
32 import org.apache.http.message.BasicNameValueP
33 import org.apache.http.util.EntityU
34 import org.slf4j.L
35 import org.slf4j.LoggerF
37 import com.alibaba.fastjson.JSONO
38 import com.alibaba.fasttext.sec.url.SSRFC
40 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;
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()));
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 {
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);
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);
} 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-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);
public static String httpGetRequest(String url) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
// 使用安全包进行检查是否安全
SSRFChecker ssrfChecker = SSRFChecker.
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-charset=UTF-8");
// 创建UrlEncodedFormEntity对象
HttpResponse response = httpclient.execute(httpGet);
String html = extractContent(response);
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 htmS
* 实现HTTPS的API访问
* @param sn
* @param nodegroup
* @param traceInfo
public static boolean httpsPostRequest(String url, Map&String, Object& params) {
DefaultHttpClient httpClient = new DefaultHttpClient();
TrustManager easyTrustManager = new X509TrustManager() {
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
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 = "";
TrustManager easyTrustManager = new X509TrustManager() {
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
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 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();
TrustManager easyTrustManager = new X509TrustManager() {
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
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.
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 "";
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
httpClient.getConnectionManager().shutdown();
* https post 方式,包含Authorization认证
* @param url
* @param params
* @param authorization
public static String httpsPostByHttpclient(String url, Map&String, Object& params, String authorization) {
DefaultHttpClient httpClient = new DefaultHttpClient();
TrustManager easyTrustManager = new X509TrustManager() {
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
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 "";
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
httpClient.getConnectionManager().shutdown();
HttpClientUtil.java
3.加密工具类GenMD5Util.java提供了将指定字符串加密成MD5的方法。代码实现如下:
1 package com.alibaba.tboss.
3 import java.text.SimpleDateF
4 import java.util.D
6 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 = "";
result = getMD5(value.getBytes("UTF-8"));
} catch (Exception e) {
System.out.println(e.getMessage());
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];
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反射来实现设值。代码如下:
1 package com.alibaba.tboss.common.auth.
3 import java.lang.reflect.M
4 import java.util.D
5 import java.util.M
6 import java.util.regex.M
7 import java.util.regex.P
9 import org.apache.commons.lang.StringU
11 import com.alibaba.tboss.common.auth.costants.AppRoleT
12 import com.alibaba.tboss.common.auth.exception.AppAuthCommonE
13 import com.alibaba.tboss.common.auth.privilege.PrivilegeI
15 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) {
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) {
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) {
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));
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";
return pvgInfo.getCurrentDataAuthAccessPath();
public static String getOperator(PrivilegeInfo pvgInfo) {
if (pvgInfo == null || StringUtils.isEmpty(pvgInfo.getWorkNo())) {
return "SYSTEM";
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.
import org.springframework.beans.BeansE
import org.springframework.beans.factory.NoSuchBeanDefinitionE
import org.springframework.context.ApplicationC
import org.springframework.context.ApplicationContextA
* ClassName: SpringContextUtil &br/&
* Function: 在applicationContext.xml中加入配置
&bean id="SpringContextUtil" class="com.alibaba.tboss.util.SpringContextUtil"/&
用来得到spring配置的Bean &br/&
* date: 日 &br/&
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationC
//Spring应用上下文环境
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
* @param applicationContext
* @throws BeansException
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationC
* @return ApplicationContext
public static ApplicationContext getApplicationContext() {
return applicationC
* 获取对象
* @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
* @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.
import java.util.ArrayL
import java.util.L
import com.alibaba.fastjson.JSONA
import com.google.gson.G
import com.google.gson.GsonB
@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)) {
list = JSONArray.parseArray(json, objectClass);
} catch (Exception e) {
e.printStackTrace();
* 使用 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);
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);
* 使用 com.google.gson.Gson.fromJson将list转JSON
public static String listToJson(List&?& list) {
Gson gson = new Gson();
String s = gson.toJson(list);
public static String listToJsonWithoutHtmlEscaping(List&?& list) {
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String s = gson.toJson(list);
JsonToBeanUtil.java
7.流程工具类FlowUtil.java,实现了字符串的不同编解码,调用post请求解析response数据。代码如下:
package com.alibaba.tboss.biz.flow.
import java.io.BufferedR
import java.io.InputS
import java.io.InputStreamR
import java.io.UnsupportedEncodingE
import java.net.URLD
import java.net.URLE
import java.util.ArrayL
import java.util.HashM
import java.util.L
import net.sf.json.JSONO
import org.apache.commons.lang3.StringU
import org.apache.http.HttpE
import org.apache.http.HttpR
import org.apache.http.NameValueP
import org.apache.http.client.HttpC
import org.apache.http.client.entity.UrlEncodedFormE
import org.apache.http.client.methods.HttpP
import org.apache.http.impl.client.DefaultHttpC
import org.apache.http.message.BasicNameValueP
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 emptyS
* javaEncodeString TODO(转码)
* @param v 转换字符串
* @param charset 转换格式
* @return String 设定文件
public static String javaEncodeString(String v, String charset) {
return URLEncoder.encode(v, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
* javaDecodeString TODO(解码)
* @param v 转换字符串
* @param charset 转换格式
* @return String 设定文件
public static String javaDecodeString(String v, String charset) {
return URLDecoder.decode(v, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
* 获取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();
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 htmS
* 获取请求的数据
* @param url
* @param params
* @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);
* 获取请求的数据
* @param url
* @param params
* @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);
FlowUtil.java
8.文件上传工具类FileUpLoadUtil.java提供了文件上传的常用方法。
package com.alibaba.tboss.
import java.io.IOE
import java.io.InputS
import java.io.OutputS
import java.net.URLE
import java.util.L
import javax.servlet.http.HttpServletR
import org.apache.commons.fileupload.FileI
import org.apache.poi.ss.usermodel.S
import org.apache.poi.ss.usermodel.W
import org.apache.poi.xssf.usermodel.XSSFW
import com.alibaba.tboss.common.idcFree.util.RackU
import com.alibaba.tboss.dal.mysql.location.LocationC
import com.alibaba.tboss.dal.mysql.rack.RackC
import com.alibaba.tboss.exception.ErrorC
import com.alibaba.tboss.exception.ServiceE
import com.alibaba.tboss.util.ExcelUtils.CellM
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;
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) {
is.close();
} catch (IOException e) {
if (sheet != null) {
// 初始化Excel栏目
List&CellMapping& mappingList = RackUtil.getLocationCorrectColumns();
list = ExcelUtils.excel2bean(sheet, type, mappingList);
} catch (Exception e) {
throw new ServiceException(ErrorCode.Upload_File_Error, "Excel解析失败");
throw new ServiceException(ErrorCode.Upload_File_Error, "未找到模板对应sheet");
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;
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) {
is.close();
} catch (IOException e) {
if (sheet != null) {
// 初始化Excel栏目
List&CellMapping& mappingList = RackUtil.getRackCorrectColumns();
list = ExcelUtils.excel2bean(sheet, type, mappingList);
} catch (Exception e) {
throw new ServiceException(ErrorCode.Upload_File_Error, "Excel解析失败");
throw new ServiceException(ErrorCode.Upload_File_Error, "未找到模板对应sheet");
* 导出文件
public static void exportTemplate(List&LocationCorrect& locationCorrect, List&CellMapping& mappingList,
String fileName, String sheetName, HttpServletResponse response) {
OutputStream out = null;
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",
" 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=Path=/;");
* 导出文件
public static void exportRackTemplate(List&RackCorrect& locationCorrect, List&CellMapping& mappingList,
String fileName, String sheetName, HttpServletResponse response) {
OutputStream out = null;
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",
" 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=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) {
// 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.
import java.text.FieldP
import java.text.SimpleDateF
import java.util.D
import java.util.L
import java.util.TimeZ
import javax.servlet.http.C
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import org.apache.commons.lang.StringU
* 类CookieUtil.java的实现描述:操作Cookie的工具类
* @author chivas.liuzh 12 Jun :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];
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())) {
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);
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());
response.addCookie(cookie);
private static String getCookieHeaderName(final Cookie cookie) {
final int version = cookie.getVersion();
if (version == 1) {
return "Set-Cookie2";
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));
dateFormat.format(new Date(System.currentTimeMillis()
+ cookie.getMaxAge() * 1000L), buf,
new FieldPosition(0));
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());
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);
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();
final char[] charArray = value.toCharArray();
for (int i = 0; i & i++) {
c = charArray[i];
if (c & 0x20 || c &= 0x7f) {
return false;
if (checkFlag[c]) {
return false;
return true;
CookieUtil.java
10.表格Excel的导入导出功能实现
package com.alibaba.tboss.
import java.text.ParseE
import java.text.SimpleDateF
import java.util.ArrayL
import java.util.D
import java.util.HashM
import java.util.L
import java.util.M
import org.apache.commons.beanutils.BeanU
import org.apache.commons.beanutils.PropertyU
import org.apache.commons.collections.CollectionU
import org.apache.poi.hssf.usermodel.HSSFDataF
import org.apache.poi.ss.usermodel.C
import org.apache.poi.ss.usermodel.CellS
import org.apache.poi.ss.usermodel.DataV
import org.apache.poi.ss.usermodel.DataValidationC
import org.apache.poi.ss.usermodel.DataValidationH
import org.apache.poi.ss.usermodel.DateU
import org.apache.poi.ss.usermodel.R
import org.apache.poi.ss.usermodel.S
import org.apache.poi.ss.usermodel.W
import org.apache.poi.ss.util.CellRangeA
import org.apache.poi.ss.util.CellRangeAddressL
import org.apache.poi.xssf.usermodel.XSSFCellS
import org.apache.poi.xssf.usermodel.XSSFC
import org.apache.poi.xssf.usermodel.XSSFDataV
import org.apache.poi.xssf.usermodel.XSSFW
import com.alibaba.fastjson.JSONO
* @author yucai.xiayc Excel 解析工具,依赖POI Beanutils 1.8
public class ExcelUtils {
* 内置类,用来配置Excel与Bean属性的映射关系
public static class CellMapping {
// 熟悉下拉框数据源
private String[] propertyD
public CellMapping(){
public CellMapping(String header, String property){
this.header =
this.property =
public CellMapping(String header, String property, String[] propertyData){
this.header =
this.property =
this.propertyData = propertyD
public String getHeader() {
public void setHeader(String header) {
this.header =
public String getProperty() {
public void setProperty(String property) {
this.property =
public String getType() {
public void setType(String type) {
this.type =
public String[] getPropertyData() {
return propertyD
public void setPropertyData(String[] propertyData) {
this.propertyData = propertyD
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);
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) {
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)));
throw new Exception("Unrecognize Config Type");
resultList.add(t);
return resultL
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);
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) {
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 resultL
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);
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) {
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 resultL
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 = headerRowN r &= sheet.getLastRowNum(); r++) {
Row row = sheet.getRow(r);
if (row == null) {
Map&String, Object& properties = new HashMap&String, Object&();
for (CellMapping cm : mappingList) {
Integer index = configMap.get(cm.getHeader());
if (index == null) {
Object cellValue = getCellValue(row.getCell(index));
if (cellValue != null) {
properties.put(cm.getProperty(), cellValue);
if (properties.isEmpty() == false) {
resultList.add(properties);
return resultL
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)));
// 黄色标题
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());
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());
cell.setCellValue(o.toString());
pu}

我要回帖

更多关于 wwwdd11ddcom 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信