Commit e9629e7a authored by Sun's avatar Sun
Browse files

no commit message

parent e4054436
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.utils;
import javax.servlet.http.HttpServletRequest;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.DeviceType;
import eu.bitwalker.useragentutils.UserAgent;
/**
* 用户代理字符串识别工具
* @author 黄炳桂 516821420@qq.com
* @version 2014-6-13
*/
public class UserAgentUtils {
/**
* 获取用户代理对象
* @param request
* @return
*/
public static UserAgent getUserAgent(HttpServletRequest request){
return UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
}
/**
* 获取设备类型
* @param request
* @return
*/
public static DeviceType getDeviceType(HttpServletRequest request){
return getUserAgent(request).getOperatingSystem().getDeviceType();
}
/**
* 是否是PC
* @param request
* @return
*/
public static boolean isComputer(HttpServletRequest request){
return DeviceType.COMPUTER.equals(getDeviceType(request));
}
/**
* 是否是手机
* @param request
* @return
*/
public static boolean isMobile(HttpServletRequest request){
return DeviceType.MOBILE.equals(getDeviceType(request));
}
/**
* 是否是平板
* @param request
* @return
*/
public static boolean isTablet(HttpServletRequest request){
return DeviceType.TABLET.equals(getDeviceType(request));
}
/**
* 是否是手机和平板
* @param request
* @return
*/
public static boolean isMobileOrTablet(HttpServletRequest request){
DeviceType deviceType = getDeviceType(request);
return DeviceType.MOBILE.equals(deviceType) || DeviceType.TABLET.equals(deviceType);
}
/**
* 获取浏览类型
* @param request
* @return
*/
public static Browser getBrowser(HttpServletRequest request){
return getUserAgent(request).getBrowser();
}
/**
* 是否IE版本是否小于等于IE8
* @param request
* @return
*/
public static boolean isLteIE8(HttpServletRequest request){
Browser browser = getBrowser(request);
return Browser.IE5.equals(browser) || Browser.IE6.equals(browser)
|| Browser.IE7.equals(browser) || Browser.IE8.equals(browser);
}
}
package com.jeespring.common.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class WorkDayUtils {
/*public static void main(String[] args) {
try {
String strDateStart = "2013-08-01";
String strDateEnd = "2014-08-31";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date_start = sdf.parse(strDateStart);
Date date_end = sdf.parse(strDateEnd);
WorkDayUtils app = new WorkDayUtils();
Calendar cal_start = Calendar.getInstance();
Calendar cal_end = Calendar.getInstance();
cal_start.setTime(date_start);
cal_end.setTime(date_end);
System.out.println("开始日:" + cal_start.get(Calendar.YEAR) + "-" + (cal_start.get(Calendar.MONTH) + 1)
+ "-" + cal_start.get(Calendar.DAY_OF_MONTH) + " " + app.getChineseWeek(cal_start));
System.out.println("结束日:" + cal_end.get(Calendar.YEAR) + "-" + (cal_end.get(Calendar.MONTH) + 1)
+ "-" + cal_end.get(Calendar.DAY_OF_MONTH) + " " + app.getChineseWeek(cal_end));
System.out.println("工作日:" + app.getWorkingDay(cal_start, cal_end));
System.out.println("休息日:" + app.getHolidays(cal_start, cal_end));
} catch (Exception e) {
e.printStackTrace();
}
}*/
/**
* 获取日期之间的天数
* @param d1
* @param d2
* @return
*/
public int getDaysBetween(Calendar d1, Calendar d2) {
if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
Calendar swap = d1;
d1 = d2;
d2 = swap;
}
int days = d2.get(Calendar.DAY_OF_YEAR)
- d1.get(Calendar.DAY_OF_YEAR);
int y2 = d2.get(Calendar.YEAR);
if (d1.get(Calendar.YEAR) != y2) {
d1 = (Calendar) d1.clone();
do {
days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);
d1.add(Calendar.YEAR, 1);
} while (d1.get(Calendar.YEAR) != y2);
}
return days;
}
/**
* 获取工作日
* @param d1
* @param d2
* @return
*/
public int getWorkingDay(Calendar d1, Calendar d2) {
int result = -1;
if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
Calendar swap = d1;
d1 = d2;
d2 = swap;
}
// int betweendays = getDaysBetween(d1, d2);
// int charge_date = 0;
int charge_start_date = 0;// 开始日期的日期偏移量
int charge_end_date = 0;// 结束日期的日期偏移量
// 日期不在同一个日期内
int stmp;
int etmp;
stmp = 7 - d1.get(Calendar.DAY_OF_WEEK);
etmp = 7 - d2.get(Calendar.DAY_OF_WEEK);
if (stmp != 0 && stmp != 6) {// 开始日期为星期六和星期日时偏移量为0
charge_start_date = stmp - 1;
}
if (etmp != 0 && etmp != 6) {// 结束日期为星期六和星期日时偏移量为0
charge_end_date = etmp - 1;
}
// }
result = (getDaysBetween(this.getNextMonday(d1), this.getNextMonday(d2)) / 7)
* 5 + charge_start_date - charge_end_date;
// System.out.println("charge_start_date>" + charge_start_date);
// System.out.println("charge_end_date>" + charge_end_date);
// System.out.println("between day is-->" + betweendays);
return result;
}
/**
* 获取中文日期
* @param date
* @return
*/
public String getChineseWeek(Calendar date) {
final String[] dayNames = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
// System.out.println(dayNames[dayOfWeek - 1]);
return dayNames[dayOfWeek - 1];
}
/**
* 获得日期的下一个星期一的日期
* @param date
* @return
*/
public Calendar getNextMonday(Calendar date) {
Calendar result = null;
result = date;
do {
result = (Calendar) result.clone();
result.add(Calendar.DATE, 1);
} while (result.get(Calendar.DAY_OF_WEEK) != 2);
return result;
}
/**
* 获取休息日
* @param d1
* @param d2
* @return
*/
public int getHolidays(Calendar d1, Calendar d2) {
return this.getDaysBetween(d1, d2) - this.getWorkingDay(d1, d2);
}
}
package com.jeespring.common.utils;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 条形码和二维码编码解码
*
* @author JeeSpring
* @version 2014-02-28
*/
public class ZxingHandler {
/**
* 条形码编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encode(String contents, int width, int height, String imgPath) {
int codeWidth = 3 + // start guard
(7 * 6) + // left bars
5 + // middle guard
(7 * 6) + // right bars
3; // end guard
codeWidth = Math.max(codeWidth, width);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.EAN_13, codeWidth, height, null);
MatrixToImageWriter
.writeToFile(bitMatrix, "png", new File(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 条形码解码
*
* @param imgPath
* @return String
*/
public static String decode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 二维码编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encode2(String contents, int width, int height, String imgPath) {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "GBK");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter
.writeToFile(bitMatrix, "png", new File(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 二维码解码
*
* @param imgPath
* @return String
*/
public static String decode2(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "GBK");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param args
*/
/*public static void main(String[] args) {
// 条形码
String imgPath = "target\\zxing_EAN13.png";
String contents = "6923450657713";
int width = 105, height = 50;
ZxingHandler.encode(contents, width, height, imgPath);
System.out.println("finished zxing EAN-13 encode.");
String decodeContent = ZxingHandler.decode(imgPath);
System.out.println("解码内容如下:" + decodeContent);
System.out.println("finished zxing EAN-13 decode.");
// 二维码
String imgPath2 = "target\\zxing.png";
String contents2 = "Hello Gem, welcome to Zxing!"
+ "\nBlog [ http://thinkgem.iteye.com ]"
+ "\nEMail [ thinkgem@163.com ]";
int width2 = 300, height2 = 300;
ZxingHandler.encode2(contents2, width2, height2, imgPath2);
System.out.println("finished zxing encode.");
String decodeContent2 = ZxingHandler.decode2(imgPath2);
System.out.println("解码内容如下:" + decodeContent2);
System.out.println("finished zxing decode.");
}*/
}
\ No newline at end of file
package com.jeespring.common.utils.bean;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Bean 工具类
*
* @author JeeSpring
*/
public class BeanUtils
{
/** Bean方法名中属性名开始的下标 */
private static final int BEAN_METHOD_PROP_INDEX = 3;
/** * 匹配getter方法的正则表达式 */
private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)");
/** * 匹配setter方法的正则表达式 */
private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)");
/**
* Bean属性复制工具方法。
*
* @param dest 目标对象
* @param src 源对象
*/
public static void copyBeanProp(Object dest, Object src)
{
List<Method> destSetters = getSetterMethods(dest);
List<Method> srcGetters = getGetterMethods(src);
try
{
for (Method setter : destSetters)
{
for (Method getter : srcGetters)
{
if (isMethodPropEquals(setter.getName(), getter.getName())
&& setter.getParameterTypes()[0].equals(getter.getReturnType()))
{
setter.invoke(dest, getter.invoke(src));
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 获取对象的setter方法。
*
* @param obj 对象
* @return 对象的setter方法列表
*/
public static List<Method> getSetterMethods(Object obj)
{
// setter方法列表
List<Method> setterMethods = new ArrayList<Method>();
// 获取所有方法
Method[] methods = obj.getClass().getMethods();
// 查找setter方法
for (Method method : methods)
{
Matcher m = SET_PATTERN.matcher(method.getName());
if (m.matches() && (method.getParameterTypes().length == 1))
{
setterMethods.add(method);
}
}
// 返回setter方法列表
return setterMethods;
}
/**
* 获取对象的getter方法。
*
* @param obj 对象
* @return 对象的getter方法列表
*/
public static List<Method> getGetterMethods(Object obj)
{
// getter方法列表
List<Method> getterMethods = new ArrayList<Method>();
// 获取所有方法
Method[] methods = obj.getClass().getMethods();
// 查找getter方法
for (Method method : methods)
{
Matcher m = GET_PATTERN.matcher(method.getName());
if (m.matches() && (method.getParameterTypes().length == 0))
{
getterMethods.add(method);
}
}
// 返回getter方法列表
return getterMethods;
}
/**
* 检查Bean方法名中的属性名是否相等。<br>
* 如getName()和setName()属性名一样,getName()和setAge()属性名不一样。
*
* @param m1 方法名1
* @param m2 方法名2
* @return 属性名一样返回true,否则返回false
*/
public static boolean isMethodPropEquals(String m1, String m2)
{
return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX));
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.utils.excel;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
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.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.jeespring.common.utils.Encodes;
import com.jeespring.common.utils.Reflections;
import com.jeespring.common.utils.excel.annotation.ExcelField;
import com.jeespring.modules.sys.utils.DictUtils;
/**
* 导出Excel文件(导出“XLSX”格式,支持大数据量导出 @see org.apache.poi.ss.SpreadsheetVersion)
* @author 黄炳桂 516821420@qq.com
* @version 2013-04-21
*/
public class ExportExcel {
private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
/**
* 工作薄对象
*/
private SXSSFWorkbook wb;
/**
* 工作表对象
*/
private Sheet sheet;
/**
* 样式列表
*/
private Map<String, CellStyle> styles;
/**
* 当前行号
*/
private int rownum;
/**
* 注解列表(Object[]{ ExcelField, Field/Method })
*/
List<Object[]> annotationList = Lists.newArrayList();
/**
* 构造函数
* @param title 表格标题,传“空值”,表示无标题
* @param cls 实体对象,通过annotation.ExportField获取标题
*/
public ExportExcel(String title, Class<?> cls){
this(title, cls, 1);
}
/**
* 构造函数
* @param title 表格标题,传“空值”,表示无标题
* @param cls 实体对象,通过annotation.ExportField获取标题
* @param type 导出类型(1:导出数据;2:导出模板)
* @param groups 导入分组
*/
public ExportExcel(String title, Class<?> cls, int type, int... groups){
// Get annotation field
Field[] fs = cls.getDeclaredFields();
for (Field f : fs){
ExcelField ef = f.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==type)){
if (groups!=null && groups.length>0){
boolean inGroup = false;
for (int g : groups){
if (inGroup){
break;
}
for (int efg : ef.groups()){
if (g == efg){
inGroup = true;
annotationList.add(new Object[]{ef, f});
break;
}
}
}
}else{
annotationList.add(new Object[]{ef, f});
}
}
}
// Get annotation method
Method[] ms = cls.getDeclaredMethods();
for (Method m : ms){
ExcelField ef = m.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==type)){
if (groups!=null && groups.length>0){
boolean inGroup = false;
for (int g : groups){
if (inGroup){
break;
}
for (int efg : ef.groups()){
if (g == efg){
inGroup = true;
annotationList.add(new Object[]{ef, m});
break;
}
}
}
}else{
annotationList.add(new Object[]{ef, m});
}
}
}
// Field sorting
Collections.sort(annotationList, new Comparator<Object[]>() {
@Override
public int compare(Object[] o1, Object[] o2) {
return new Integer(((ExcelField)o1[0]).sort()).compareTo(
new Integer(((ExcelField)o2[0]).sort()));
};
});
// Initialize
List<String> headerList = Lists.newArrayList();
for (Object[] os : annotationList){
String t = ((ExcelField)os[0]).title();
// 如果是导出,则去掉注释
if (type==1){
String[] ss = StringUtils.split(t, "**", 2);
if (ss.length==2){
t = ss[0];
}
}
headerList.add(t);
}
initialize(title, headerList);
}
/**
* 构造函数
* @param title 表格标题,传“空值”,表示无标题
* @param headers 表头数组
*/
public ExportExcel(String title, String[] headers) {
initialize(title, Lists.newArrayList(headers));
}
/**
* 构造函数
* @param title 表格标题,传“空值”,表示无标题
* @param headerList 表头列表
*/
public ExportExcel(String title, List<String> headerList) {
initialize(title, headerList);
}
/**
* 初始化函数
* @param title 表格标题,传“空值”,表示无标题
* @param headerList 表头列表
*/
private void initialize(String title, List<String> headerList) {
this.wb = new SXSSFWorkbook(500);
this.sheet = wb.createSheet("Export");
this.styles = createStyles(wb);
// Create title
if (StringUtils.isNotBlank(title)){
Row titleRow = sheet.createRow(rownum++);
titleRow.setHeightInPoints(30);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellStyle(styles.get("title"));
titleCell.setCellValue(title);
sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1));
}
// Create header
if (headerList == null){
throw new RuntimeException("headerList not null!");
}
Row headerRow = sheet.createRow(rownum++);
headerRow.setHeightInPoints(16);
for (int i = 0; i < headerList.size(); i++) {
Cell cell = headerRow.createCell(i);
cell.setCellStyle(styles.get("header"));
String[] ss = StringUtils.split(headerList.get(i), "**", 2);
if (ss.length==2){
cell.setCellValue(ss[0]);
Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
comment.setString(new XSSFRichTextString(ss[1]));
cell.setCellComment(comment);
}else{
cell.setCellValue(headerList.get(i));
}
sheet.autoSizeColumn(i);
}
for (int i = 0; i < headerList.size(); i++) {
int colWidth = sheet.getColumnWidth(i)*2;
sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
}
log.debug("Initialize success.");
}
/**
* 创建表格样式
* @param wb 工作薄对象
* @return 样式列表
*/
private Map<String, CellStyle> createStyles(Workbook wb) {
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
CellStyle style = wb.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
Font titleFont = wb.createFont();
titleFont.setFontName("Arial");
titleFont.setFontHeightInPoints((short) 16);
titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(titleFont);
styles.put("title", style);
style = wb.createCellStyle();
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
Font dataFont = wb.createFont();
dataFont.setFontName("Arial");
dataFont.setFontHeightInPoints((short) 10);
style.setFont(dataFont);
styles.put("data", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(CellStyle.ALIGN_LEFT);
styles.put("data1", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(CellStyle.ALIGN_CENTER);
styles.put("data2", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(CellStyle.ALIGN_RIGHT);
styles.put("data3", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
// style.setWrapText(true);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
Font headerFont = wb.createFont();
headerFont.setFontName("Arial");
headerFont.setFontHeightInPoints((short) 10);
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
headerFont.setColor(IndexedColors.WHITE.getIndex());
style.setFont(headerFont);
styles.put("header", style);
return styles;
}
/**
* 添加一行
* @return 行对象
*/
public Row addRow(){
return sheet.createRow(rownum++);
}
/**
* 添加一个单元格
* @param row 添加的行
* @param column 添加列号
* @param val 添加值
* @return 单元格对象
*/
public Cell addCell(Row row, int column, Object val){
return this.addCell(row, column, val, 0, Class.class);
}
/**
* 添加一个单元格
* @param row 添加的行
* @param column 添加列号
* @param val 添加值
* @param align 对齐方式(1:靠左;2:居中;3:靠右)
* @return 单元格对象
*/
public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType){
Cell cell = row.createCell(column);
String cellFormatString = "@";
try {
if(val == null){
cell.setCellValue("");
}else if(fieldType != Class.class){
cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val));
}else{
if(val instanceof String) {
cell.setCellValue((String) val);
}else if(val instanceof Integer) {
cell.setCellValue((Integer) val);
cellFormatString = "0";
}else if(val instanceof Long) {
cell.setCellValue((Long) val);
cellFormatString = "0";
}else if(val instanceof Double) {
cell.setCellValue((Double) val);
cellFormatString = "0.00";
}else if(val instanceof Float) {
cell.setCellValue((Float) val);
cellFormatString = "0.00";
}else if(val instanceof Date) {
cell.setCellValue((Date) val);
cellFormatString = "yyyy-MM-dd HH:mm";
}else {
cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
"fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val));
}
}
if (val != null){
CellStyle style = styles.get("data_column_"+column);
if (style == null){
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"+(align>=1&&align<=3?align:"")));
style.setDataFormat(wb.createDataFormat().getFormat(cellFormatString));
styles.put("data_column_" + column, style);
}
cell.setCellStyle(style);
}
} catch (Exception ex) {
log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString());
cell.setCellValue(val.toString());
}
return cell;
}
/**
* 添加数据(通过annotation.ExportField添加数据)
* @return list 数据列表
*/
public <E> ExportExcel setDataList(List<E> list){
for (E e : list){
int colunm = 0;
Row row = this.addRow();
StringBuilder sb = new StringBuilder();
for (Object[] os : annotationList){
ExcelField ef = (ExcelField)os[0];
Object val = null;
// Get entity value
try{
if (StringUtils.isNotBlank(ef.value())){
val = Reflections.invokeGetter(e, ef.value());
}else{
if (os[1] instanceof Field){
val = Reflections.invokeGetter(e, ((Field)os[1]).getName());
}else if (os[1] instanceof Method){
val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {});
}
}
// If is dict, get dict label
if (StringUtils.isNotBlank(ef.dictType())){
val = DictUtils.getDictLabel(val==null?"":val.toString(), ef.dictType(), "");
}
}catch(Exception ex) {
// Failure to ignore
log.info(ex.toString());
val = "";
}
this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
sb.append(val + ", ");
}
log.debug("Write success: ["+row.getRowNum()+"] "+sb.toString());
}
return this;
}
/**
* 输出数据流
* @param os 输出数据流
*/
public ExportExcel write(OutputStream os) throws IOException{
wb.write(os);
return this;
}
/**
* 输出到客户端
* @param fileName 输出文件名
*/
public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
response.reset();
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
write(response.getOutputStream());
return this;
}
/**
* 输出到文件
* @param fileName 输出文件名
*/
public ExportExcel writeFile(String name) throws FileNotFoundException, IOException{
FileOutputStream os = new FileOutputStream(name);
this.write(os);
return this;
}
/**
* 清理临时文件
*/
public ExportExcel dispose(){
wb.dispose();
return this;
}
// /**
// * 导出测试
// */
// public static void main(String[] args) throws Throwable {
//
// List<String> headerList = Lists.newArrayList();
// for (int i = 1; i <= 10; i++) {
// headerList.add("表头"+i);
// }
//
// List<String> dataRowList = Lists.newArrayList();
// for (int i = 1; i <= headerList.size(); i++) {
// dataRowList.add("数据"+i);
// }
//
// List<List<String>> dataList = Lists.newArrayList();
// for (int i = 1; i <=1000000; i++) {
// dataList.add(dataRowList);
// }
//
// ExportExcel ee = new ExportExcel("表格标题", headerList);
//
// for (int i = 0; i < dataList.size(); i++) {
// Row row = ee.addRow();
// for (int j = 0; j < dataList.get(i).size(); j++) {
// ee.addCell(row, j, dataList.get(i).get(j));
// }
// }
//
// ee.writeFile("target/export.xlsx");
//
// ee.dispose();
//
// log.debug("Export success.");
//
// }
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.utils.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import com.google.common.collect.Lists;
import com.jeespring.common.utils.Reflections;
import com.jeespring.common.utils.excel.annotation.ExcelField;
import com.jeespring.modules.sys.utils.DictUtils;
/**
* 导入Excel文件(支持“XLS”和“XLSX”格式)
* @author 黄炳桂 516821420@qq.com
* @version 2013-03-10
*/
public class ImportExcel {
private static Logger log = LoggerFactory.getLogger(ImportExcel.class);
/**
* 工作薄对象
*/
private Workbook wb;
/**
* 工作表对象
*/
private Sheet sheet;
/**
* 标题行号
*/
private int headerNum;
/**
* 构造函数
* @param path 导入文件,读取第一个工作表
* @param headerNum 标题行号,数据行号=标题行号+1
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(String fileName, int headerNum)
throws InvalidFormatException, IOException {
this(new File(fileName), headerNum);
}
/**
* 构造函数
* @param path 导入文件对象,读取第一个工作表
* @param headerNum 标题行号,数据行号=标题行号+1
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(File file, int headerNum)
throws InvalidFormatException, IOException {
this(file, headerNum, 0);
}
/**
* 构造函数
* @param path 导入文件
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(String fileName, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
this(new File(fileName), headerNum, sheetIndex);
}
/**
* 构造函数
* @param path 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(File file, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
}
/**
* 构造函数
* @param file 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
}
/**
* 构造函数
* @param path 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
if (StringUtils.isBlank(fileName)){
throw new RuntimeException("导入文档为空!");
}else if(fileName.toLowerCase().endsWith("xls")){
this.wb = new HSSFWorkbook(is);
}else if(fileName.toLowerCase().endsWith("xlsx")){
this.wb = new XSSFWorkbook(is);
}else{
throw new RuntimeException("文档格式不正确!");
}
if (this.wb.getNumberOfSheets()<sheetIndex){
throw new RuntimeException("文档中没有工作表!");
}
this.sheet = this.wb.getSheetAt(sheetIndex);
this.headerNum = headerNum;
log.debug("Initialize success.");
}
/**
* 获取行对象
* @param rownum
* @return
*/
public Row getRow(int rownum){
return this.sheet.getRow(rownum);
}
/**
* 获取数据行号
* @return
*/
public int getDataRowNum(){
return headerNum+1;
}
/**
* 获取最后一个数据行号
* @return
*/
public int getLastDataRowNum(){
return this.sheet.getLastRowNum()+headerNum;
}
/**
* 获取最后一个列号
* @return
*/
public int getLastCellNum(){
return this.getRow(headerNum).getLastCellNum();
}
/**
* 获取单元格值
* @param row 获取的行
* @param column 获取单元格列号
* @return 单元格值
*/
public Object getCellValue(Row row, int column){
Object val = "";
try{
Cell cell = row.getCell(column);
if (cell != null){
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
val = cell.getNumericCellValue();
}else if (cell.getCellType() == Cell.CELL_TYPE_STRING){
val = cell.getStringCellValue();
}else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA){
val = cell.getCellFormula();
}else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
val = cell.getBooleanCellValue();
}else if (cell.getCellType() == Cell.CELL_TYPE_ERROR){
val = cell.getErrorCellValue();
}
}
}catch (Exception e) {
return val;
}
return val;
}
/**
* 获取导入数据列表
* @param cls 导入对象类型
* @param groups 导入分组
*/
public <E> List<E> getDataList(Class<E> cls, int... groups) throws InstantiationException, IllegalAccessException{
List<Object[]> annotationList = Lists.newArrayList();
// Get annotation field
Field[] fs = cls.getDeclaredFields();
for (Field f : fs){
ExcelField ef = f.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==2)){
if (groups!=null && groups.length>0){
boolean inGroup = false;
for (int g : groups){
if (inGroup){
break;
}
for (int efg : ef.groups()){
if (g == efg){
inGroup = true;
annotationList.add(new Object[]{ef, f});
break;
}
}
}
}else{
annotationList.add(new Object[]{ef, f});
}
}
}
// Get annotation method
Method[] ms = cls.getDeclaredMethods();
for (Method m : ms){
ExcelField ef = m.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==2)){
if (groups!=null && groups.length>0){
boolean inGroup = false;
for (int g : groups){
if (inGroup){
break;
}
for (int efg : ef.groups()){
if (g == efg){
inGroup = true;
annotationList.add(new Object[]{ef, m});
break;
}
}
}
}else{
annotationList.add(new Object[]{ef, m});
}
}
}
// Field sorting
Collections.sort(annotationList, new Comparator<Object[]>() {
@Override
public int compare(Object[] o1, Object[] o2) {
return new Integer(((ExcelField)o1[0]).sort()).compareTo(
new Integer(((ExcelField)o2[0]).sort()));
};
});
//log.debug("Import column count:"+annotationList.size());
// Get excel data
List<E> dataList = Lists.newArrayList();
for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
E e = cls.newInstance();
int column = 0;
Row row = this.getRow(i);
StringBuilder sb = new StringBuilder();
for (Object[] os : annotationList){
Object val = this.getCellValue(row, column++);
if (val != null){
ExcelField ef = (ExcelField)os[0];
// If is dict type, get dict value
if (StringUtils.isNotBlank(ef.dictType())){
val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
//log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
}
// Get param type and type cast
Class<?> valType = Class.class;
if (os[1] instanceof Field){
valType = ((Field)os[1]).getType();
}else if (os[1] instanceof Method){
Method method = ((Method)os[1]);
if ("get".equals(method.getName().substring(0, 3))){
valType = method.getReturnType();
}else if("set".equals(method.getName().substring(0, 3))){
valType = ((Method)os[1]).getParameterTypes()[0];
}
}
//log.debug("Import value type: ["+i+","+column+"] " + valType);
try {
if (valType == String.class){
String s = String.valueOf(val.toString());
if(StringUtils.endsWith(s, ".0")){
val = StringUtils.substringBefore(s, ".0");
}else{
val = String.valueOf(val.toString());
}
}else if (valType == Integer.class){
val = Double.valueOf(val.toString()).intValue();
}else if (valType == Long.class){
val = Double.valueOf(val.toString()).longValue();
}else if (valType == Double.class){
val = Double.valueOf(val.toString());
}else if (valType == Float.class){
val = Float.valueOf(val.toString());
}else if (valType == Date.class){
val = DateUtil.getJavaDate((Double)val);
}else{
if (ef.fieldType() != Class.class){
val = ef.fieldType().getMethod("getValue", String.class).invoke(null, val.toString());
}else{
val = Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
"fieldtype."+valType.getSimpleName()+"Type")).getMethod("getValue", String.class).invoke(null, val.toString());
}
}
} catch (Exception ex) {
log.info("Get cell value ["+i+","+column+"] error: " + ex.toString());
val = null;
}
// set entity value
if (os[1] instanceof Field){
Reflections.invokeSetter(e, ((Field)os[1]).getName(), val);
}else if (os[1] instanceof Method){
String mthodName = ((Method)os[1]).getName();
if ("get".equals(mthodName.substring(0, 3))){
mthodName = "set"+StringUtils.substringAfter(mthodName, "get");
}
Reflections.invokeMethod(e, mthodName, new Class[] {valType}, new Object[] {val});
}
}
sb.append(val+", ");
}
dataList.add(e);
log.debug("Read success: ["+i+"] "+sb.toString());
}
return dataList;
}
// /**
// * 导入测试
// */
// public static void main(String[] args) throws Throwable {
//
// ImportExcel ei = new ImportExcel("target/export.xlsx", 1);
//
// for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) {
// Row row = ei.getRow(i);
// for (int j = 0; j < ei.getLastCellNum(); j++) {
// Object val = ei.getCellValue(row, j);
// System.out.print(val+", ");
// }
// System.out.print("\n");
// }
//
// }
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.utils.excel.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Excel注解定义
* @author 黄炳桂 516821420@qq.com
* @version 2013-03-10
*/
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField {
/**
* 导出字段名(默认调用当前字段的“get”方法,如指定导出字段为对象,请填写“对象名.对象属性”,例:“area.name”、“office.name”)
*/
String value() default "";
/**
* 导出字段标题(需要添加批注请用“**”分隔,标题**批注,仅对导出模板有效)
*/
String title();
/**
* 字段类型(0:导出导入;1:仅导出;2:仅导入)
*/
int type() default 0;
/**
* 导出字段对齐方式(0:自动;1:靠左;2:居中;3:靠右)
*/
int align() default 0;
/**
* 导出字段字段排序(升序)
*/
int sort() default 0;
/**
* 如果是字典类型,请设置字典的type值
*/
String dictType() default "";
/**
* 反射类型
*/
Class<?> fieldType() default Class.class;
/**
* 字段归属组(根据分组导出导入)
*/
int[] groups() default {};
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.utils.excel.fieldtype;
import com.jeespring.common.utils.StringUtils;
import com.jeespring.modules.sys.entity.Area;
import com.jeespring.modules.sys.utils.UserUtils;
/**
* 字段类型转换
* @author 黄炳桂 516821420@qq.com
* @version 2013-03-10
*/
public class AreaType {
/**
* 获取对象值(导入)
*/
public static Object getValue(String val) {
for (Area e : UserUtils.getAreaList()){
if (StringUtils.trimToEmpty(val).equals(e.getName())){
return e;
}
}
return null;
}
/**
* 获取对象值(导出)
*/
public static String setValue(Object val) {
if (val != null && ((Area)val).getName() != null){
return ((Area)val).getName();
}
return "";
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.utils.excel.fieldtype;
import com.jeespring.common.utils.StringUtils;
import com.jeespring.modules.sys.entity.Office;
import com.jeespring.modules.sys.utils.UserUtils;
/**
* 字段类型转换
* @author 黄炳桂 516821420@qq.com
* @version 2013-03-10
*/
public class OfficeType {
/**
* 获取对象值(导入)
*/
public static Object getValue(String val) {
for (Office e : UserUtils.getOfficeList()){
if (StringUtils.trimToEmpty(val).equals(e.getName())){
return e;
}
}
return null;
}
/**
* 设置对象值(导出)
*/
public static String setValue(Object val) {
if (val != null && ((Office)val).getName() != null){
return ((Office)val).getName();
}
return "";
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.utils.excel.fieldtype;
import java.util.List;
import com.google.common.collect.Lists;
import com.jeespring.common.utils.Collections3;
import com.jeespring.common.utils.SpringContextHolder;
import com.jeespring.common.utils.StringUtils;
import com.jeespring.modules.sys.entity.Role;
import com.jeespring.modules.sys.service.SystemService;
/**
* 字段类型转换
* @author 黄炳桂 516821420@qq.com
* @version 2013-5-29
*/
public class RoleListType {
private static SystemService systemService = SpringContextHolder.getBean(SystemService.class);
/**
* 获取对象值(导入)
*/
public static Object getValue(String val) {
List<Role> roleList = Lists.newArrayList();
List<Role> allRoleList = systemService.findAllRole();
for (String s : StringUtils.split(val, ",")){
for (Role e : allRoleList){
if (StringUtils.trimToEmpty(s).equals(e.getName())){
roleList.add(e);
}
}
}
return roleList.size()>0?roleList:null;
}
/**
* 设置对象值(导出)
*/
public static String setValue(Object val) {
if (val != null){
@SuppressWarnings("unchecked")
List<Role> roleList = (List<Role>)val;
return Collections3.extractToString(roleList, "name", ", ");
}
return "";
}
}
package com.jeespring.common.utils.http;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
/**
* 通用http发送方法
*
* @author JeeSpring
*/
public class HttpUtils
{
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
/**
* 向指定 URL 发送GET方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param)
{
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try
{
String urlNameString = url + "?" + param;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result.append(line);
}
log.info("recv - {}", result);
}
catch (ConnectException e)
{
log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e.getMessage());
}
catch (SocketTimeoutException e)
{
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
}
catch (IOException e)
{
log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e.getMessage());
}
catch (Exception e)
{
log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e.getMessage());
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (Exception ex)
{
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex.getMessage());
}
}
return result.toString();
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param)
{
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try
{
String urlNameString = url + "?" + param;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null)
{
result.append(line);
}
log.info("recv - {}", result);
}
catch (ConnectException e)
{
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e.getMessage());
}
catch (SocketTimeoutException e)
{
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
}
catch (IOException e)
{
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e.getMessage());
}
catch (Exception e)
{
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e.getMessage());
}
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex.getMessage());
}
}
return result.toString();
}
public static String sendSSLPost(String url, String param)
{
StringBuilder result = new StringBuilder();
String urlNameString = url + "?" + param;
try
{
log.info("sendSSLPost - {}", urlNameString);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
URL console = new URL(urlNameString);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
while ((ret = br.readLine()) != null)
{
if (ret != null && !"".equals(ret.trim()))
{
result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
}
}
log.info("recv - {}", result);
conn.disconnect();
br.close();
}
catch (ConnectException e)
{
log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e.getMessage());
}
catch (SocketTimeoutException e)
{
log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
}
catch (IOException e)
{
log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e.getMessage());
}
catch (Exception e)
{
log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e.getMessage());
}
return result.toString();
}
private static class TrustAnyTrustManager implements X509TrustManager
{
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
{
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
{
}
@Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
}
}
\ No newline at end of file
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package com.jeespring.common.validator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* JSR303 Validator(Hibernate Validator)工具类.
*
* ConstraintViolation中包含propertyPath, message 和invalidValue等信息.
* 提供了各种convert方法,适合不同的i18n需求:
* 1. List<String>, String内容为message
* 2. List<String>, String内容为propertyPath + separator + message
* 3. Map<propertyPath, message>
*
* 详情见wiki: https://github.com/springside/springside4/wiki/HibernateValidator
* @author calvin
* @version 2013-01-15
*/
public class BeanValidators {
/**
* 调用JSR303的validate方法, 验证失败时抛出ConstraintViolationException.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void validateWithException(Validator validator, Object object, Class<?>... groups)
throws ConstraintViolationException {
Set constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
throw new ConstraintViolationException(constraintViolations);
}
}
/**
* 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>中为List<message>.
*/
public static List<String> extractMessage(ConstraintViolationException e) {
return extractMessage(e.getConstraintViolations());
}
/**
* 辅助方法, 转换Set<ConstraintViolation>为List<message>
*/
@SuppressWarnings("rawtypes")
public static List<String> extractMessage(Set<? extends ConstraintViolation> constraintViolations) {
List<String> errorMessages = Lists.newArrayList();
for (ConstraintViolation violation : constraintViolations) {
errorMessages.add(violation.getMessage());
}
return errorMessages;
}
/**
* 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>为Map<property, message>.
*/
public static Map<String, String> extractPropertyAndMessage(ConstraintViolationException e) {
return extractPropertyAndMessage(e.getConstraintViolations());
}
/**
* 辅助方法, 转换Set<ConstraintViolation>为Map<property, message>.
*/
@SuppressWarnings("rawtypes")
public static Map<String, String> extractPropertyAndMessage(Set<? extends ConstraintViolation> constraintViolations) {
Map<String, String> errorMessages = Maps.newHashMap();
for (ConstraintViolation violation : constraintViolations) {
errorMessages.put(violation.getPropertyPath().toString(), violation.getMessage());
}
return errorMessages;
}
/**
* 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>为List<propertyPath message>.
*/
public static List<String> extractPropertyAndMessageAsList(ConstraintViolationException e) {
return extractPropertyAndMessageAsList(e.getConstraintViolations(), " ");
}
/**
* 辅助方法, 转换Set<ConstraintViolations>为List<propertyPath message>.
*/
@SuppressWarnings("rawtypes")
public static List<String> extractPropertyAndMessageAsList(Set<? extends ConstraintViolation> constraintViolations) {
return extractPropertyAndMessageAsList(constraintViolations, " ");
}
/**
* 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>为List<propertyPath +separator+ message>.
*/
public static List<String> extractPropertyAndMessageAsList(ConstraintViolationException e, String separator) {
return extractPropertyAndMessageAsList(e.getConstraintViolations(), separator);
}
/**
* 辅助方法, 转换Set<ConstraintViolation>为List<propertyPath +separator+ message>.
*/
@SuppressWarnings("rawtypes")
public static List<String> extractPropertyAndMessageAsList(Set<? extends ConstraintViolation> constraintViolations,
String separator) {
List<String> errorMessages = Lists.newArrayList();
for (ConstraintViolation violation : constraintViolations) {
errorMessages.add(violation.getPropertyPath() + separator + violation.getMessage());
}
return errorMessages;
}
}
\ No newline at end of file
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.web;
import com.jeespring.common.mapper.JsonMapper;
import com.jeespring.common.redis.RedisUtils;
import com.jeespring.common.utils.DateUtils;
import com.jeespring.common.validator.BeanValidators;
import com.jeespring.modules.oauth.service.OauthService;
import com.jeespring.modules.utils.service.EmailService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* 控制器支持类
*
* @author 黄炳桂 516821420@qq.com
* @version 2013-3-23
*/
public abstract class AbstractBaseController {
/**
* 日志对象
*/
protected Logger logger = LoggerFactory.getLogger(getClass());
/**
* 管理基础路径
*/
@Value("${adminPath}")
protected String adminPath;
/**
* 验证Bean实例对象
*/
@Autowired
protected Validator validator;
@Autowired
private EmailService mailService;
@Autowired
private OauthService oauthService;
/**
* 服务端参数有效性验证
*
* @param object 验证的实体对象
* @param groups 验证组
* @return 验证成功:返回true;严重失败:将错误信息添加到 message 中
*/
protected boolean beanValidator(Model model, Object object, Class<?>... groups) {
try {
BeanValidators.validateWithException(validator, object, groups);
} catch (ConstraintViolationException ex) {
List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
list.add(0, "数据验证失败:");
addMessage(model, list.toArray(new String[]{}));
return false;
}
return true;
}
/**
* 服务端参数有效性验证
*
* @param object 验证的实体对象
* @param groups 验证组
* @return 验证成功:返回true;严重失败:将错误信息添加到 flash message 中
*/
protected boolean beanValidator(RedirectAttributes redirectAttributes, Object object, Class<?>... groups) {
try {
BeanValidators.validateWithException(validator, object, groups);
} catch (ConstraintViolationException ex) {
List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
list.add(0, "数据验证失败:");
addMessage(redirectAttributes, list.toArray(new String[]{}));
return false;
}
return true;
}
/**
* 服务端参数有效性验证
*
* @param object 验证的实体对象
* @param groups 验证组,不传入此参数时,同@Valid注解验证
* @return 验证成功:继续执行;验证失败:抛出异常跳转400页面。
*/
protected void beanValidator(Object object, Class<?>... groups) {
BeanValidators.validateWithException(validator, object, groups);
}
/**
* 添加Model消息
*
* @param model
* @param messages
*/
protected void addMessage(Model model, String... messages) {
StringBuilder sb = new StringBuilder();
for (String message : messages) {
sb.append(message).append(messages.length > 1 ? "<br/>" : "");
}
model.addAttribute("message", sb.toString());
}
/**
* 添加Flash消息
*/
protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
StringBuilder sb = new StringBuilder();
for (String message : messages) {
sb.append(message).append(messages.length > 1 ? "<br/>" : "");
}
redirectAttributes.addFlashAttribute("message", sb.toString());
}
/**
* 客户端返回JSON字符串
*
* @param response
* @param object
* @return
*/
protected String renderString(HttpServletResponse response, Object object) {
return renderString(response, JsonMapper.toJsonString(object), "application/json");
}
/**
* 客户端返回字符串
*
* @param response
* @param string
* @return
*/
protected String renderString(HttpServletResponse response, String string, String type) {
try {
response.reset();
response.setContentType(type);
response.setCharacterEncoding("utf-8");
response.getWriter().print(string);
return null;
} catch (IOException e) {
return null;
}
}
/**
* 参数绑定异常
*/
@ExceptionHandler({Exception.class,BindException.class, ConstraintViolationException.class, ValidationException.class})
public String bindException(Exception ex,HttpServletRequest request) {
//if(ex instanceof IOException){
// return "error/400";
//}
try {
mailService.sendMailException("Java后台异常", "URL:" + request.getRequestURL() + "<br>QueryString:" + request.getQueryString() + "<br>Exception:" + ex.getMessage() + "<br>");
}catch (Exception exception){}
return "error/400";
}
/**
* 授权登录异常
*/
@ExceptionHandler({AuthenticationException.class})
public String authenticationException() {
return "error/403";
}
/**
* 拦截API调用次数控制
*/
@ModelAttribute
protected void APIHandler(HttpServletRequest request, HttpServletResponse response) {
try{
if(!RedisUtils.isShireRedis()){ return;}
if(!oauthService.isOauthOpen()){ return;}
//if(request.getRequestURI().indexOf("/rest/")<0) return;
if(request.getRequestURI().indexOf("/rest/oauth/apiTimeLimiFaild")>=0) {
return;
}
if(request.getRequestURI().indexOf("/admin?login")>=0) {
return;
}
if(request.getRequestURI().indexOf("/admin/login")>=0) {
return;
}
if("/admin".equals(request.getRequestURI())){
Result result=oauthService.userOnlineAmount();
if("-1".equals(result.getResultCode())) {
response.sendRedirect("/rest/oauth/userOnlineAmountFaild");
}
return;
}
oauthService.setApiTime();
Result result = oauthService.ApiTimeLimi(request.getRemoteAddr());
if(result.getResultCoe().toString()=="-1"){
//response.sendRedirect("../error/403");
if(request.getRequestURI().indexOf("/rest/")>0) {
response.sendRedirect("/rest/oauth/apiTimeLimiFaild?apiTimeLimi=" + result.getResultObject());
} else {
response.sendRedirect("/rest/oauth/apiTimeLimiFaild?apiTimeLimi=" + result.getResultObject());
}
//response.sendRedirect("/rest/oauth/apiTimeLimifaild");
}
}catch (Exception e){
}
}
/**
* Rest云接口安全拦截
*/
@ModelAttribute
protected void RestHandler(HttpServletRequest request, HttpServletResponse response) {
try{
if(!RedisUtils.isShireRedis()){ return;}
if(!oauthService.isOauthOpen()){ return;}
if(request.getRequestURI().indexOf("/rest/")<0) {
return;
}
if(request.getRequestURI().indexOf("/rest/oauth/token")>=0) {
return;
}
if(request.getRequestURI().indexOf("/rest/oauth/faild")>=0) {
return;
}
if(request.getRequestURI().indexOf("/rest/oauth/checkToken")>=0) {
return;
}
Result result = oauthService.checkToken(request.getParameter("token"),request.getRemoteAddr());
if(result.getResultCoe().toString()=="-1"){
//response.sendRedirect("../error/403");
response.sendRedirect("/rest/oauth/faild");
}
}catch (Exception e){
}
}
/**
* 初始化数据绑定
* 1. 将所有传递进来的String进行HTML编码,防止XSS攻击
* 2. 将字段中Date类型转换为String类型
*/
@InitBinder
protected void initBinder(WebDataBinder binder) {
// String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击
binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
//过滤,进行html转码
setValue(text == null ? null : StringEscapeUtils.unescapeHtml4(StringEscapeUtils.escapeHtml4(text.trim())));
//不过滤,不进行html转码
//setValue(text == null ? null : text.trim());
}
@Override
public String getAsText() {
Object value = getValue();
return value != null ? StringEscapeUtils.unescapeHtml4(value.toString()) : "";
//return value != null ? value.toString() : "";
}
});
// Date 类型转换
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(DateUtils.parseDate(text));
}
// @Override
// public String getAsText() {
// Object value = getValue();
// return value != null ? DateUtils.formatDateTime((Date)value) : "";
// }
});
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.web;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Scanner;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.ckfinder.connector.configuration.Configuration;
import com.ckfinder.connector.configuration.Events;
import com.ckfinder.connector.data.AccessControlLevel;
import com.ckfinder.connector.utils.AccessControlUtil;
import com.ckfinder.connector.utils.PathUtils;
import com.jeespring.common.config.Global;
import com.jeespring.common.utils.FileUtils;
import com.jeespring.modules.sys.security.SystemAuthorizingRealm;
import com.jeespring.modules.sys.utils.UserUtils;
/**
* CKFinder配置
*
* @author 黄炳桂 516821420@qq.com
* @version 2014-06-25
*/
public class CKFinderConfig extends Configuration {
public CKFinderConfig(ServletConfig servletConfig) {
super(servletConfig);
}
@Override
protected Configuration createConfigurationInstance() {
SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
if (principal == null) {
return new CKFinderConfig(this.servletConf);
}
boolean isView = true;
boolean isUpload = true;
boolean isEdit = true;
AccessControlLevel alc = this.getAccessConrolLevels().get(0);
alc.setFolderView(isView);
alc.setFolderCreate(isEdit);
alc.setFolderRename(isEdit);
alc.setFolderDelete(isEdit);
alc.setFileView(isView);
alc.setFileUpload(isUpload);
alc.setFileRename(isEdit);
alc.setFileDelete(isEdit);
AccessControlUtil.getInstance(this).loadACLConfig();
try {
this.baseURL = FileUtils.path(Servlets.getRequest().getContextPath() + Global.USERFILES_BASE_URL + principal + "/");
this.baseDir = FileUtils.path(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + principal + "/");
} catch (Exception e) {
throw new RuntimeException(e);
}
return new CKFinderConfig(this.servletConf);
}
@Override
public boolean checkAuthentication(final HttpServletRequest request) {
return UserUtils.getPrincipal() != null;
}
@Override
public void init() throws Exception {
DefaultResourceLoader loader = new DefaultResourceLoader();
Resource resource = loader.getResource(this.xmlFilePath);
Class<?> clazz = getClass().getSuperclass();
Field field = clazz.getDeclaredField("lastCfgModificationDate");
Method method = clazz.getDeclaredMethod("clearConfiguration");
method.setAccessible(true);
method.invoke(this);
field.setAccessible(true);
field.set(this, System.currentTimeMillis());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(resource.getInputStream());
doc.normalize();
Node node = doc.getFirstChild();
if (node != null) {
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); ++i) {
Node childNode = nodeList.item(i);
if ("enabled".equals(childNode.getNodeName())) {
this.enabled = Boolean.valueOf(childNode.getTextContent().trim()).booleanValue();
}
if ("baseDir".equals(childNode.getNodeName())) {
this.baseDir = childNode.getTextContent().trim();
this.baseDir = PathUtils.escape(this.baseDir);
this.baseDir = PathUtils.addSlashToEnd(this.baseDir);
}
if ("baseURL".equals(childNode.getNodeName())) {
this.baseURL = childNode.getTextContent().trim();
this.baseURL = PathUtils.escape(this.baseURL);
this.baseURL = PathUtils.addSlashToEnd(this.baseURL);
}
if ("licenseName".equals(childNode.getNodeName())) {
this.licenseName = childNode.getTextContent().trim();
}
if ("licenseKey".equals(childNode.getNodeName())) {
this.licenseKey = childNode.getTextContent().trim();
}
String value;
if ("imgWidth".equals(childNode.getNodeName())) {
value = childNode.getTextContent().trim();
value = value.replaceAll("//D", "");
try {
this.imgWidth = Integer.valueOf(value);
} catch (NumberFormatException var13) {
this.imgWidth = null;
}
}
if ("imgQuality".equals(childNode.getNodeName())) {
value = childNode.getTextContent().trim();
value = value.replaceAll("//D", "");
method = clazz.getDeclaredMethod("adjustQuality", new Class[]{String.class});
method.setAccessible(true);
this.imgQuality = Float.parseFloat(method.invoke(this, value).toString());
}
if ("imgHeight".equals(childNode.getNodeName())) {
value = childNode.getTextContent().trim();
value = value.replaceAll("//D", "");
try {
this.imgHeight = Integer.valueOf(value);
} catch (NumberFormatException var12) {
this.imgHeight = null;
}
}
if ("thumbs".equals(childNode.getNodeName())) {
method = clazz.getDeclaredMethod("setThumbs", new Class[]{NodeList.class});
method.setAccessible(true);
method.invoke(this, childNode.getChildNodes());
}
if ("accessControls".equals(childNode.getNodeName())) {
method = clazz.getDeclaredMethod("setACLs", new Class[]{NodeList.class});
method.setAccessible(true);
method.invoke(this, childNode.getChildNodes());
}
if ("hideFolders".equals(childNode.getNodeName())) {
method = clazz.getDeclaredMethod("setHiddenFolders", new Class[]{NodeList.class});
method.setAccessible(true);
method.invoke(this, childNode.getChildNodes());
}
if ("hideFiles".equals(childNode.getNodeName())) {
method = clazz.getDeclaredMethod("setHiddenFiles", new Class[]{NodeList.class});
method.setAccessible(true);
method.invoke(this, childNode.getChildNodes());
}
if ("checkDoubleExtension".equals(childNode.getNodeName())) {
this.doubleExtensions = Boolean.valueOf(childNode.getTextContent().trim()).booleanValue();
}
if ("disallowUnsafeCharacters".equals(childNode.getNodeName())) {
this.disallowUnsafeCharacters = Boolean.valueOf(childNode.getTextContent().trim()).booleanValue();
}
if ("forceASCII".equals(childNode.getNodeName())) {
this.forceASCII = Boolean.valueOf(childNode.getTextContent().trim()).booleanValue();
}
if ("checkSizeAfterScaling".equals(childNode.getNodeName())) {
this.checkSizeAfterScaling = Boolean.valueOf(childNode.getTextContent().trim()).booleanValue();
}
Scanner sc;
if ("htmlExtensions".equals(childNode.getNodeName())) {
value = childNode.getTextContent();
sc = (new Scanner(value)).useDelimiter(",");
while (sc.hasNext()) {
String val = sc.next();
if (val != null && !"".equals(val)) {
this.htmlExtensions.add(val.trim().toLowerCase());
}
}
}
if ("secureImageUploads".equals(childNode.getNodeName())) {
this.secureImageUploads = Boolean.valueOf(childNode.getTextContent().trim()).booleanValue();
}
if ("uriEncoding".equals(childNode.getNodeName())) {
this.uriEncoding = childNode.getTextContent().trim();
}
if ("userRoleSessionVar".equals(childNode.getNodeName())) {
this.userRoleSessionVar = childNode.getTextContent().trim();
}
if ("defaultResourceTypes".equals(childNode.getNodeName())) {
value = childNode.getTextContent().trim();
sc = (new Scanner(value)).useDelimiter(",");
while (sc.hasNext()) {
this.defaultResourceTypes.add(sc.next());
}
}
if ("plugins".equals(childNode.getNodeName())) {
method = clazz.getDeclaredMethod("setPlugins", new Class[]{Node.class});
method.setAccessible(true);
method.invoke(this, childNode);
}
if ("basePathBuilderImpl".equals(childNode.getNodeName())) {
method = clazz.getDeclaredMethod("setBasePathImpl", new Class[]{String.class});
method.setAccessible(true);
method.invoke(this, childNode.getTextContent().trim());
}
}
}
method = clazz.getDeclaredMethod("setTypes", new Class[]{Document.class});
method.setAccessible(true);
method.invoke(this, doc);
field = clazz.getDeclaredField("events");
field.setAccessible(true);
field.set(this, new Events());
this.registerEventHandlers();
}
}
package com.jeespring.common.web;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Result extends HashMap<String, Object> implements Map<String, Object>{
/**
*
*/
private static final long serialVersionUID = 1L;
private HashMap<String,Object> resultHashMap = new HashMap<String, Object>();
public void setResultObject(Object obejct) {
put("RESULT", obejct);
}
public void setResultExtend(String key,Object object){
JSONObject jsonObject= JSON.parseObject(JSON.toJSONString(get("RESULT")));
jsonObject.put(key,object);
put("RESULT", jsonObject);
}
public void setResultHashMap(String item,Object obejct) {
resultHashMap.put(item,obejct);
put("RESULT", resultHashMap);
}
public void setResultCode(Object resultCode) {
put("CODE", resultCode);
}
public Object getResultCoe(){
return get("CODE");
}
public Object getResultCode(){
return get("CODE");
}
public <T> List<T> getResutObjectList() {
return (List<T>) get("RESULT");
}
public <V, K> Map<K,V> getResutObjectMap() {
return (Map<K, V>) get("RESULT");
}
public <T extends Object> T getResultObject() {
return (T) get("RESULT");
}
}
package com.jeespring.common.web;
public class ResultFactory {
private ResultFactory() {
}
protected static final String SuccessCode = "0";
protected static final String ErrorCode = "-1";
public static Result getSuccessResult() {
return getResultBean(SuccessCode, "成功");
}
public static Result getSuccessResult(String resultMessage) {
return getResultBean(SuccessCode, resultMessage);
}
public static Result getErrorResult(String resultMessage) {
return getResultBean(ErrorCode, resultMessage);
}
private static Result getResultBean(String resultCode, String resultMessage) {
Result result = ResultBean.result.getResult();
result.put("CODE", resultCode);
result.put("MESSAGE", resultMessage);
return result;
}
public static Result getResultBean(String resultMessage, Object o) {
Result result = ResultBean.result.getResult();
result.put("CODE", SuccessCode);
result.put("MESSAGE", resultMessage);
result.put("Object", o);
return result;
}
private enum ResultBean {
result;
Result getResult() {
return new Result();
}
}
}
/**
* Copyright (c) 2005-2012 springside.org.cn
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jeespring.common.web;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.Validate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.google.common.net.HttpHeaders;
import com.jeespring.common.config.Global;
import com.jeespring.common.utils.Encodes;
import com.jeespring.common.utils.StringUtils;
import com.jeespring.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.jeespring.modules.sys.utils.UserUtils;
/**
* Http与Servlet工具类.
*
* @author calvin/HuangBingGui
* @version 2014-8-19
*/
public class Servlets {
// -- 常用数值定义 --//
public static final long ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
// 静态文件后缀
private static String[] staticFiles;
/**
* 设置客户端缓存过期时间 的Header.
*/
public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {
// Http 1.0 header, set a fix expires date.
response.setDateHeader(HttpHeaders.EXPIRES, System.currentTimeMillis() + expiresSeconds * 1000);
// Http 1.1 header, set a time after now.
response.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=" + expiresSeconds);
}
/**
* 设置禁止客户端缓存的Header.
*/
public static void setNoCacheHeader(HttpServletResponse response) {
// Http 1.0 header
response.setDateHeader(HttpHeaders.EXPIRES, 1L);
response.addHeader(HttpHeaders.PRAGMA, "no-cache");
// Http 1.1 header
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0");
}
/**
* 设置LastModified Header.
*/
public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {
response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModifiedDate);
}
/**
* 设置Etag Header.
*/
public static void setEtag(HttpServletResponse response, String etag) {
response.setHeader(HttpHeaders.ETAG, etag);
}
/**
* 根据浏览器If-Modified-Since Header, 计算文件是否已被修改.
* <p>
* 如果无修改, checkIfModify返回false ,设置304 not modify status.
*
* @param lastModified 内容的最后修改时间.
*/
public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,
long lastModified) {
long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return false;
}
return true;
}
/**
* 根据浏览器 If-None-Match Header, 计算Etag是否已无效.
* <p>
* 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.
*
* @param etag 内容的ETag.
*/
public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {
String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);
if (headerValue != null) {
boolean conditionSatisfied = false;
if (!"*".equals(headerValue)) {
StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(etag)) {
conditionSatisfied = true;
}
}
} else {
conditionSatisfied = true;
}
if (conditionSatisfied) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader(HttpHeaders.ETAG, etag);
return false;
}
}
return true;
}
/**
* 设置让浏览器弹出下载对话框的Header.
*
* @param fileName 下载后的文件名.
*/
public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {
try {
// 中文文件名支持
String encodedfileName = new String(fileName.getBytes(), "ISO8859-1");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
} catch (UnsupportedEncodingException e) {
e.getMessage();
}
}
/**
* 取得带相同前缀的Request Parameters, copy from spring WebUtils.
* <p>
* 返回的结果的Parameter名已去除前缀.
*/
@SuppressWarnings("rawtypes")
public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {
Validate.notNull(request, "Request must not be null");
Enumeration paramNames = request.getParameterNames();
Map<String, Object> params = new TreeMap<String, Object>();
String pre = prefix;
if (pre == null) {
pre = "";
}
while (paramNames != null && paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
if ("".equals(pre) || paramName.startsWith(pre)) {
String unprefixed = paramName.substring(pre.length());
String[] values = request.getParameterValues(paramName);
if (values == null || values.length == 0) {
values = new String[]{};
// Do nothing, no values found at all.
} else if (values.length > 1) {
params.put(unprefixed, values);
} else {
params.put(unprefixed, values[0]);
}
}
}
return params;
}
/**
* 组合Parameters生成Query String的Parameter部分,并在paramter name上加上prefix.
*/
public static String encodeParameterStringWithPrefix(Map<String, Object> params, String prefix) {
StringBuilder queryStringBuilder = new StringBuilder();
String pre = prefix;
if (pre == null) {
pre = "";
}
Iterator<Entry<String, Object>> it = params.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Object> entry = it.next();
queryStringBuilder.append(pre).append(entry.getKey()).append("=").append(entry.getValue());
if (it.hasNext()) {
queryStringBuilder.append("&");
}
}
return queryStringBuilder.toString();
}
/**
* 客户端对Http Basic验证的 Header进行编码.
*/
public static String encodeHttpBasic(String userName, String password) {
String encode = userName + ":" + password;
return "Basic " + Encodes.encodeBase64(encode.getBytes());
}
/**
* 是否是Ajax异步请求
*
* @param request
*/
public static boolean isAjaxRequest(HttpServletRequest request) {
String accept = request.getHeader("accept");
String xRequestedWith = request.getHeader("X-Requested-With");
Principal principal = UserUtils.getPrincipal();
// 如果是异步请求或是手机端,则直接返回信息
return ((accept != null && accept.indexOf("application/json") != -1
|| (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1)
|| (principal != null && principal.isMobileLogin())));
}
/**
* 获取当前请求对象
*
* @return
*/
public static HttpServletRequest getRequest() {
try {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
} catch (Exception e) {
return null;
}
}
/**
* 判断访问URI是否是静态文件请求
*
* @throws Exception
*/
public static boolean isStaticFile(String uri) {
if (staticFiles == null) {
staticFiles = StringUtils.split(Global.getConfig("web.staticFile"), ",");
}
return StringUtils.endsWithAny(uri, staticFiles) && !StringUtils.endsWithAny(uri, ".html")
&& !StringUtils.endsWithAny(uri, ".jsp") && !StringUtils.endsWithAny(uri, ".java");
}
}
package com.jeespring.common.websocket;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import org.java_websocket.WebSocketImpl;
import com.jeespring.common.websocket.onchat.ChatServer;
public class WebSockertFilter{
/**
* 初始化
*/
public void init(FilterConfig fc) throws ServletException {
this.startWebsocketChatServer();
// this.startWebsocketOnline();
}
/**
* 启动即时聊天服务
*/
public void startWebsocketChatServer(){
WebSocketImpl.DEBUG = false;
ChatServer s;
try {
s = new ChatServer(8668);
s.start();
System.out.println( "websocket服务器启动,端口" + s.getPort() );
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
//计时器
public void timer() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9); // 控制时
calendar.set(Calendar.MINUTE, 0); // 控制分
calendar.set(Calendar.SECOND, 0); // 控制秒
Date time = calendar.getTime(); // 得出执行任务的时间
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//PersonService personService = (PersonService)ApplicationContext.getBean("personService");
//System.out.println("-------设定要指定任务--------");
}
}, time, 1000*60*60*24);// 这里设定将延时每天固定执行
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// TODO Auto-generated method stub
}
}
package com.jeespring.common.websocket.onchat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import com.jeespring.common.json.AjaxJson;
import com.jeespring.common.utils.SpringContextHolder;
import com.jeespring.common.websocket.utils.Constant;
import com.jeespring.modules.iim.entity.ChatHistory;
import com.jeespring.modules.iim.service.ChatHistoryService;
import java.util.List;
public class ChatServer extends WebSocketServer{
public ChatServer(int port) throws UnknownHostException {
super(new InetSocketAddress(port));
}
public ChatServer(InetSocketAddress address) {
super(address);
}
/**
* 触发连接事件
*/
@Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
// Collection<String> onlineUsers = MsgServerPool.getOnlineUser();
// AjaxJson j = new AjaxJson();
// j.put("data", onlineUsers);
// MsgServerPool.sendMessageToUser(conn, "_online_all_status_"+j.getJsonStr());//首次登陆系统时,获取用户的在线状态
}
/**
* 触发关闭事件
*/
@Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
userLeave(conn);
Collection<String> onlineUsers = ChatServerPool.getOnlineUser();
AjaxJson j = new AjaxJson();
j.put("data", onlineUsers);
ChatServerPool.sendMessage("_online_all_status_"+j.getJsonStr());//通知所有用户更新在线信息
}
/**
* 客户端发送消息到服务器时触发事件
*/
@Override
public void onMessage(WebSocket conn, String message){
message = message.toString();
ChatHistoryService chatHistoryService = SpringContextHolder.getBean("chatHistoryService");
// TODO Auto-generated catch block
if(null != message && message.startsWith(Constant._online_user_)){//用户上线
String userId = message.replaceFirst(Constant._online_user_, "");
this.userjoin(userId,conn);
//通知所有用户更新在线信息
Collection<String> onlineUsers = ChatServerPool.getOnlineUser();
AjaxJson j = new AjaxJson();
j.put("data", onlineUsers);
ChatServerPool.sendMessage("_online_all_status_"+j.getJsonStr());//通知所有用户更新在线信息
//读取离线信息
ChatHistory chat = new ChatHistory();
chat.setUserid2(userId);
chat.setStatus("0");
List<ChatHistory> list =chatHistoryService.findList(chat);
for(ChatHistory c : list){
ChatServerPool.sendMessageToUser(conn, c.getUserid1()+Constant._msg_+c.getUserid2()+Constant._msg_+c.getMsg()+Constant._msg_+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getCreateDate()));//向所某用户发送消息
c.setStatus("1");//标记为已读
chatHistoryService.save(c);
}
}if(null != message && message.startsWith(Constant._leave_user_)){//用户离线
this.userLeave(conn);
Collection<String> onlineUsers = ChatServerPool.getOnlineUser();
AjaxJson j = new AjaxJson();
j.put("data", onlineUsers);
ChatServerPool.sendMessage("_online_all_status_"+j.getJsonStr());//通知所有用户更新在线信息
}if(null != message && message.contains(Constant._msg_)){//
String []arr = message.split(Constant._msg_);
String fromUser = arr[0];
String toUser = arr[1];
String msg = arr[2];
//保存聊天记录
ChatHistory chat = new ChatHistory();
chat.setUserid1(fromUser);
chat.setUserid2(toUser);
chat.setMsg(msg);
chat.setCreateDate(new Date());
WebSocket toUserConn = ChatServerPool.getWebSocketByUser(toUser);
if(toUserConn != null){
ChatServerPool.sendMessageToUser(ChatServerPool.getWebSocketByUser(toUser),message);//向所某用户发送消息
chat.setStatus("1");//设置为已读
}else{
ChatServerPool.sendMessageToUser(conn, "_sys_对方现在离线,他将在上线后收到你的消息!");//同时向本人发送消息
chat.setStatus("0");//设置为未读
}
chatHistoryService.save(chat);
}
}
@Override
public void onMessage(WebSocket conn, ByteBuffer buffer){
Charset charset = null;
CharsetDecoder decoder = null;
CharBuffer charBuffer = null;
try {
charset = Charset.forName("UTF-8");
decoder = charset.newDecoder();
// charBuffer = decoder.decode(buffer);//用这个的话,只能输出来一次结果,第二次显示为空
charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
//return charBuffer.toString();
System.out.println( charBuffer.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void onFragment( WebSocket conn, Framedata fragment ) {
}
/**
* 触发异常事件
*/
@Override
public void onError( WebSocket conn, Exception ex ) {
ex.printStackTrace();
if( conn != null ) {
//some errors like port binding failed may not be assignable to a specific websocket
}
}
/**
* 用户加入处理
* @param user
*/
public void userjoin(String user, WebSocket conn){
// AjaxJson j = new AjaxJson();
// j.put("type", "user_join");
// j.put("user", "<a onclick=\"toUserMsg('"+user+"');\">"+user+"</a>");
// MsgServerPool.sendMessage(j.getJsonStr()); //把当前用户加入到所有在线用户列表中
// String joinMsg = "{\"from\":\"[系统]\",\"content\":\""+user+"上线了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}";
// MsgServerPool.sendMessage(joinMsg); //向所有在线用户推送当前用户上线的消息
// j = new AjaxJson();
// j.put("type", "get_online_user");
ChatServerPool.addUser(user,conn); //向连接池添加当前的连接对象
// j.put("list", MsgServerPool.getOnlineUser());
// MsgServerPool.sendMessageToUser(conn, j.getJsonStr()); //向当前连接发送当前在线用户的列表
}
/**
* 用户下线处理
* @param user
*/
public void userLeave(WebSocket conn){
String user = ChatServerPool.getUserByKey(conn);
boolean b = ChatServerPool.removeUser(conn); //在连接池中移除连接
// if(b){
// AjaxJson j = new AjaxJson();
// j.put("type", "user_leave");
// j.put("user", "<a onclick=\"toUserMsg('"+user+"');\">"+user+"</a>");
// MsgServerPool.sendMessage(j.getJsonStr()); //把当前用户从所有在线用户列表中删除
// String joinMsg = "{\"from\":\"[系统]\",\"content\":\""+user+"下线了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}";
// MsgServerPool.sendMessage(joinMsg); //向在线用户发送当前用户退出的消息
// }
}
/*public static void main( String[] args ) throws InterruptedException , IOException {
WebSocketImpl.DEBUG = false;
int port = 8667; //端口
ChatServer s = new ChatServer(port);
s.start();
//System.out.println( "服务器的端口" + s.getPort() );
}*/
}
package com.jeespring.common.websocket.onchat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.java_websocket.WebSocket;
public class ChatServerPool {
private static final Map<WebSocket,String> userconnections = new HashMap<WebSocket,String>();
/**
* 获取用户名
* @param session
*/
public static String getUserByKey(WebSocket conn){
return userconnections.get(conn);
}
/**
* 获取WebSocket
* @param user
*/
public static WebSocket getWebSocketByUser(String user){
Set<WebSocket> keySet = userconnections.keySet();
synchronized (keySet) {
for (WebSocket conn : keySet) {
String cuser = userconnections.get(conn);
if(cuser.equals(user)){
return conn;
}
}
}
return null;
}
/**
* 向连接池中添加连接
* @param inbound
*/
public static void addUser(String user, WebSocket conn){
userconnections.put(conn,user); //添加连接
}
/**
* 获取所有的在线用户
* @return
*/
public static Collection<String> getOnlineUser(){
// List<String> setUsers = new ArrayList<String>();
Collection<String> setUsers = userconnections.values();
// for(String u:setUser){
// setUsers.add("<a onclick=\"toUserMsg('"+u+"');\">"+u+"</a>");
// }
return setUsers;
}
/**
* 移除连接池中的连接
* @param inbound
*/
public static boolean removeUser(WebSocket conn){
if(userconnections.containsKey(conn)){
userconnections.remove(conn); //移除连接
return true;
}else{
return false;
}
}
/**
* 向特定的用户发送数据
* @param user
* @param message
*/
public static void sendMessageToUser(WebSocket conn,String message){
if(null != conn && null != userconnections.get(conn)){
conn.send(message);
}
}
/**
* 向所有的用户发送消息
* @param message
*/
public static void sendMessage(String message){
Set<WebSocket> keySet = userconnections.keySet();
synchronized (keySet) {
for (WebSocket conn : keySet) {
String user = userconnections.get(conn);
if(user != null){
conn.send(message);
}
}
}
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment