package com.cainiao.uop.dvc.web.home.module.screen; import com.alibaba.buc.sso.client.util.SimpleUserUtil; import com.alibaba.buc.sso.client.vo.BucSSOUser; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.taobao.loc.common.domain.LocOrderDO; import com.taobao.logistics.constants.LogisticsOrderGoodsConstant; import com.taobao.logistics.domain.dataobject.OrderGoodsDO; import com.taobao.logistics.domain.extend.ExtendsFieldDO; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.Cell; 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 javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class BaseAjax { private static Logger log = LoggerFactory.getLogger(BaseAjax.class); @Resource protected HttpServletRequest request; @Resource protected HttpServletResponse response; @Resource protected Map<String, String> dataShareMap; /** 默认每页显示10条 */ public final Integer PAGE_SIZE = 10; /** * @param resultList * @param <T> * @return */ public <T> Map<String, Object> toPageResult(List<T> resultList, Long total, boolean success, String errorMsg) { response.setHeader("Access-Control-Allow-Headers", "*"); Map<String, Object> result = new HashMap<String, Object>(); Map<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put("resultList", resultList); result.put("totalCount", total); result.put("data", dataMap); result.put("success", success); result.put("msg", errorMsg); return result; } /** * @param resultList * @param <T> * @return */ public <T> Map<String, Object> toPageResult(List<T> resultList, Long total,Long pageIndex,Long pageSize, boolean success, String errorMsg) { response.setHeader("Access-Control-Allow-Headers", "*"); Map<String, Object> result = new HashMap<String, Object>(); Map<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put("resultList", resultList); result.put("totalCount", total); result.put("pageIndex", pageIndex); result.put("pageSize", pageSize); result.put("data", dataMap); result.put("success", success); result.put("msg", errorMsg); return result; } /** * * @param obj * @param success * @param msg * @return */ public Map<String, Object> toResult(Object obj, boolean success, String msg) { response.setHeader("Access-Control-Allow-Headers", "*"); Map<String, Object> result = new HashMap<String, Object>(); result.put("data", obj); result.put("success", success); result.put("msg", msg); return result; } /** * @param data * @param response */ public static void toSendData(JSONObject data, HttpServletResponse response) { try { final PrintWriter out = response.getWriter(); out.print(data); out.flush(); out.close(); } catch (IOException e) { } } /** * @param dateStr * @return * @throws Exception */ public static Date getDate(String dateStr) throws Exception{ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf.parse(dateStr); } /** * @param date * @return */ public static String getStringDate(Date date) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = formatter.format(date); return dateString; } protected void writerSuccessData(Object object) { JSONObject js = new JSONObject(); js.put("success", true); js.put("data", object); writeResult(js.toString()); } protected void writerPageData(Object object,Integer total) { JSONObject js = new JSONObject(); js.put("success", true); js.put("data", object); js.put("total", total); writeResult(js.toString()); } /** * 执行错误的ajax返回信息 * * @param errorMessage * @throws IOException * */ protected void writerErrorMsg(String errorMessage) throws IOException { writerMsg(false, errorMessage); } /** * 用于ajax返回信息 * * @param isSuccess * @param message * @throws IOException */ protected void writerMsg(boolean isSuccess, String message) throws IOException { JSONObject json = new JSONObject(); if (isSuccess) { json.put("success", true); json.put("isError", false); json.put("successMsg", message); } else { json.put("success", false); json.put("isError", true); json.put("errorMsg", message); } writeResult(json.toString()); } protected void writeResult(String str) { this.outPrint(str); } protected void outPrint(String result) { PrintWriter out = null; try { response.setHeader("Cache-Control", "no-cache"); // response.setContentType("text/plain"); response.setContentType("application/json;charset=UTF-8"); out = response.getWriter(); out.print(result); } catch (IOException e) { // 忽略 } finally { if (out != null) { out.close(); } } } protected void outPrintJSON(String result) { PrintWriter out = null; try { response.setHeader("Cache-Control", "no-cache"); response.setContentType("application/json"); out = response.getWriter(); out.print(result); } catch (IOException e) { // 忽略 } finally { if (out != null) { out.close(); } } } protected String getSuccessData(Object object) { JSONObject js = new JSONObject(); js.put("success", true); js.put("data", object); return js.toJSONString(); } /** * * 解析扩展字段时间 以下是key * outBound 仓出库时间 * storeAccept 仓接单时间 * consignHoldStart 挂起时间 * fulfilStart 下发仓时间 * @param locOrderDO * @param key * @return */ public static String convertWarehouseTime(LocOrderDO locOrderDO,String key){ List<ExtendsFieldDO> extendsFieldDOs = locOrderDO.getExtendsFieldDOs(); String returnTime=""; if(extendsFieldDOs.size()>0){ for(ExtendsFieldDO extendsFieldDO : extendsFieldDOs){ if("consignTimeStat".equals(extendsFieldDO.getFieldName())){ JSONObject timeJson = JSON.parseObject(extendsFieldDO.getValueStart()); if(timeJson != null){ if(timeJson.get(key)!=null){ returnTime = timeJson.get(key).toString(); } } break; } } } return returnTime; } public String getDateStart(String str){ return str+" 00:00:00"; } public String getDateEnd(String str){ return str+" 23:59:59"; } //以下为导出------------------------------------------------------- /** * 导出Excel * @param excelName 要导出的excel名称 * @param list 要导出的数据集合 * @param fieldMap 中英文字段对应Map,即要导出的excel表头 * @return */ public <T> void exportExcel(String excelName, List<T> list, LinkedHashMap<String, String> fieldMap) throws Exception{ // 设置默认文件名为当前时间:年月日时分秒 if (excelName==null || excelName=="") { excelName = new SimpleDateFormat("yyyyMMddhhmmss").format( new Date()).toString(); } // 设置response头信息 response.reset(); response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件 try { response.setHeader("Content-disposition", "attachment; filename=" +new String(excelName.getBytes("gb2312"), "ISO-8859-1") + ".xls"); } catch (UnsupportedEncodingException e1) { log.info(e1.getMessage()); } //创建一个WorkBook,对应一个Excel文件 HSSFWorkbook wb=new HSSFWorkbook(); //在Workbook中,创建一个sheet,对应Excel中的工作薄(sheet) HSSFSheet sheet=wb.createSheet(excelName); //创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style=wb.createCellStyle(); //创建一个居中格式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 填充工作表 fillSheet(sheet,list,fieldMap,style); //将文件输出 OutputStream ouputStream = response.getOutputStream(); wb.write(ouputStream); ouputStream.flush(); ouputStream.close(); } /** * 根据字段名获取字段对象 * * @param fieldName * 字段名 * @param clazz * 包含该字段的类 * @return 字段 */ public Field getFieldByName(String fieldName, Class<?> clazz) { log.info("根据字段名获取字段对象:getFieldByName()"); // 拿到本类的所有字段 Field[] selfFields = clazz.getDeclaredFields(); // 如果本类中存在该字段,则返回 for (Field field : selfFields) { //如果本类中存在该字段,则返回 if (field.getName().equals(fieldName)) { return field; } } // 否则,查看父类中是否存在此字段,如果有则返回 Class<?> superClazz = clazz.getSuperclass(); if (superClazz != null && superClazz != Object.class) { //递归 return getFieldByName(fieldName, superClazz); } // 如果本类和父类都没有,则返回空 return null; } /** * 根据字段名获取字段值 * * @param fieldName 字段名 * @param o 对象 * @return 字段值 * @throws Exception 异常 * */ public Object getFieldValueByName(String fieldName, Object o) throws Exception { log.info("根据字段名获取字段值:getFieldValueByName()"); Object value = null; //根据字段名得到字段对象 Field field = getFieldByName(fieldName, o.getClass()); //如果该字段存在,则取出该字段的值 if (field != null) { field.setAccessible(true);//类中的成员变量为private,在类外边使用属性值,故必须进行此操作 value = field.get(o);//获取当前对象中当前Field的value } else { throw new Exception(o.getClass().getSimpleName() + "类不存在字段名 " + fieldName); } return value; } /** * 根据带路径或不带路径的属性名获取属性值,即接受简单属性名, * 如userName等,又接受带路径的属性名,如student.department.name等 * * @param fieldNameSequence 带路径的属性名或简单属性名 * @param o 对象 * @return 属性值 * @throws Exception 异常 * */ public Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception { log.info("根据带路径或不带路径的属性名获取属性值,即接受简单属性名:getFieldValueByNameSequence()"); Object value = null; // 将fieldNameSequence进行拆分 String[] attributes = fieldNameSequence.split("\\."); if (attributes.length == 1) { value = getFieldValueByName(fieldNameSequence, o); } else { // 根据数组中第一个连接属性名获取连接属性对象,如student.department.name Object fieldObj = getFieldValueByName(attributes[0], o); //截取除第一个属性名之后的路径 String subFieldNameSequence = fieldNameSequence .substring(fieldNameSequence.indexOf(".") + 1); //递归得到最终的属性对象的值 value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj); } return value; } /** * 向工作表中填充数据 * * @param sheet * excel的工作表名称 * @param list * 数据源 * @param fieldMap * 中英文字段对应关系的Map * @param style * 表格中的格式 * @throws Exception * 异常 * */ public <T> void fillSheet(HSSFSheet sheet, List<T> list, LinkedHashMap<String, String> fieldMap,HSSFCellStyle style) throws Exception { log.info("向工作表中填充数据:fillSheet()"); // 定义存放英文字段名和中文字段名的数组 String[] enFields = new String[fieldMap.size()]; String[] cnFields = new String[fieldMap.size()]; // 填充数组 int count = 0; for (Map.Entry<String, String> entry : fieldMap.entrySet()) { enFields[count] = entry.getKey(); cnFields[count] = entry.getValue(); count++; } //在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short HSSFRow row=sheet.createRow((int)0); // 填充表头 for (int i = 0; i < cnFields.length; i++) { HSSFCell cell=row.createCell(i); cell.setCellValue(cnFields[i]); cell.setCellStyle(style); // sheet.autoSizeColumn(i); } // 填充内容 for (int index = 0; index < list.size(); index++) { row = sheet.createRow(index + 1); // 获取单个对象 T item = list.get(index); for (int i = 0; i < enFields.length; i++) { Object objValue = getFieldValueByNameSequence(enFields[i], item); String fieldValue = objValue == null ? "" : objValue.toString(); row.createCell(i).setCellValue(fieldValue); } } } public Long fetchOwnerId(LocOrderDO locOrderDO) { if (null == locOrderDO || null == locOrderDO.getOrderDO()) { return null; } List<OrderGoodsDO> orderGoods = locOrderDO.getOrderGoods(); Long ownerId = null; try { if (CollectionUtils.isNotEmpty(orderGoods)) { // 遍历Goods for (OrderGoodsDO orderGoodsDO : orderGoods) { if (orderGoodsDO != null) { ownerId = parseLong(orderGoodsDO.getFeature(LogisticsOrderGoodsConstant.FEATURE_NAME_PROVIDER_ID)); if(ownerId!=null){ return ownerId; } } } } if(ownerId == null) { ownerId = parseLong(locOrderDO.getOrderDO().getFeature(LogisticsOrderGoodsConstant.FEATURE_NAME_PROVIDER_ID)); } if(ownerId == null) { ownerId = locOrderDO.getOrderDO().getUserId(); } } catch (Exception e) { ownerId = locOrderDO.getOrderDO().getUserId(); } return ownerId; } private Long parseLong(String id){ if(StringUtils.isEmpty(id)){ return null; } return Long.valueOf(id); } public String getLoginEmpId() { BucSSOUser bucSSOUser = this.getSessionUser(); if(bucSSOUser!=null){ return bucSSOUser.getEmpId(); }else{ return "0"; } } public BucSSOUser getSessionUser() { BucSSOUser sessionUser = null; try { sessionUser = SimpleUserUtil.getBucSSOUser(this.request); if (sessionUser != null && sessionUser.getLoginName() != null) { String loginName = sessionUser.getLoginName(); int index = loginName.indexOf('@'); if (index != -1) { loginName = loginName.substring(0, index); sessionUser.setLoginName(loginName); } } } catch (IOException e) { log.error("WebBase.getSessionUser failed", e); } catch (ServletException e) { log.error("WebBase.getSessionUser failed", e); } return sessionUser; } protected List<String> getJsonArray2List(String jsonArr) { if (StringUtils.isNotBlank(jsonArr)) { JSONArray jsonArray = JSONObject.parseArray(jsonArr); if (jsonArray != null && jsonArray.size() > 0) { List<String> list = Lists.newArrayList(); for (Object object : jsonArray) { list.add(object.toString()); } return list; } } return null; } //验证字符串是否是时间格式yyyy-MM-dd protected boolean isValidDate(String str) { if(StringUtils.isBlank(str)){ return false; } boolean convertSuccess=true; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { format.setLenient(false); format.parse(str); } catch (ParseException e) { // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对 convertSuccess=false; } return convertSuccess; } //导入 /** * @Title: importDataFromExcel * @Description: 将sheet中的数据保存到list中, * 1、调用此方法时,vo的属性个数必须和excel文件每行数据的列数相同且一一对应,vo的所有属性都为String * 2、在action调用此方法时,需声明 * private File excelFile;上传的文件 * private String excelFileName;原始文件的文件名 * 3、页面的file控件name需对应File的文件名 * @param @param vo javaBean * @param @param is 输入流 * @param @param excelFileName * @param @return * @return List<Object> * @throws */ public List<Object> importDataFromExcel(Object vo, InputStream is, String excelFileName) throws Exception{ List<Object> list = new ArrayList<Object>(); //创建工作簿 Workbook workbook = this.createWorkbook(is, excelFileName); //创建工作表sheet Sheet sheet = this.getSheet(workbook, 0); //获取sheet中数据的行数 int rows = sheet.getPhysicalNumberOfRows(); //获取表头单元格个数 int cells = sheet.getRow(0).getPhysicalNumberOfCells(); //利用反射,给JavaBean的属性进行赋值 Field[] fields = vo.getClass().getDeclaredFields(); for (int i = 1; i < rows; i++) {//第一行为标题栏,从第二行开始取数据 Row row = sheet.getRow(i); int index = 0; while (index < cells) { Cell cell = row.getCell(index); if (null == cell) { cell = row.createCell(index); } cell.setCellType(Cell.CELL_TYPE_STRING); String value = null == cell.getStringCellValue()?"":cell.getStringCellValue(); Field field = fields[index]; String fieldName = field.getName(); String methodName = "set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1); Method setMethod = vo.getClass().getMethod(methodName, new Class[]{String.class}); setMethod.invoke(vo, new Object[]{value}); index++; } if (isHasValues(vo)) {//判断对象属性是否有值 list.add(vo); vo.getClass().getConstructor(new Class[]{}).newInstance(new Object[]{});//重新创建一个vo对象 } } is.close();//关闭流 return list; } /** * @Title: createWorkbook * @Description: 判断excel文件后缀名,生成不同的workbook * @param @param is * @param @param excelFileName * @param @return * @param @throws IOException * @return Workbook * @throws */ public Workbook createWorkbook(InputStream is,String excelFileName) throws IOException{ if (excelFileName.endsWith(".xls")) { return new HSSFWorkbook(is); }else if (excelFileName.endsWith(".xlsx")) { return new XSSFWorkbook(is); } return null; } /** * @Title: getSheet * @Description: 根据sheet索引号获取对应的sheet * @param @param workbook * @param @param sheetIndex * @param @return * @return Sheet * @throws */ public Sheet getSheet(Workbook workbook,int sheetIndex){ return workbook.getSheetAt(0); } /** 138 * @Title: isHasValues 139 * @Description: 判断一个对象所有属性是否有值,如果一个属性有值(分空),则返回true 140 * @param @param object 141 * @param @return 142 * @return boolean 143 * @throws 144 */ public boolean isHasValues(Object object) throws Exception{ Field[] fields = object.getClass().getDeclaredFields(); boolean flag = false; for (int i = 0; i < fields.length; i++) { String fieldName = fields[i].getName(); String methodName = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1); Method getMethod = object.getClass().getMethod(methodName); Object obj = getMethod.invoke(object); if (null != obj && "".equals(obj)) { flag = true; break; } } return flag; } }
这里来码一下 文件上传的一些东西
最新推荐文章于 2022-06-30 13:12:23 发布