package com.yc.action;
|
|
import com.yc.action.grid.GridUtils;
|
import com.yc.action.grid.PoiExcelWriter;
|
import com.yc.currentThreadInfo.CurrentLocal;
|
import com.yc.entity.attachment.AttachmentWhereEntity;
|
import com.yc.exception.ApplicationException;
|
import com.yc.factory.FactoryBean;
|
import com.yc.sdk.shopping.util.SettingKey;
|
import com.yc.service.excel.ExcelIfc;
|
import com.yc.service.grid.TableMetaData;
|
import com.yc.service.upload.AttachmentIfc;
|
import com.yc.utils.*;
|
import org.apache.commons.lang3.StringUtils;
|
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.data.redis.core.RedisTemplate;
|
import org.springframework.jdbc.support.rowset.SqlRowSetMetaData;
|
import org.springframework.ui.ModelMap;
|
import org.springframework.validation.BindingResult;
|
import org.springframework.validation.FieldError;
|
import org.springframework.web.bind.annotation.SessionAttributes;
|
|
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpSession;
|
import java.io.*;
|
import java.lang.reflect.Type;
|
import java.sql.Types;
|
import java.text.DateFormat;
|
import java.text.ParseException;
|
import java.text.SimpleDateFormat;
|
import java.util.*;
|
import java.util.concurrent.TimeUnit;
|
import java.util.regex.Matcher;
|
import java.util.regex.Pattern;
|
|
/**
|
* 基类,封装gt-grid返回json的处理
|
*
|
* @author 邓文峰 2010-2-25
|
* **/
|
@SessionAttributes("success")
|
// 定义保存跨页面提示信息
|
public class BaseAction {
|
private final static Object lock=new Object();//锁对象
|
protected Map<String, String> env=new HashMap<String,String>();
|
/**
|
* 处理分页信息
|
* **/
|
protected Logger log = LoggerFactory.getLogger(this.getClass()); //Logger.getLogger(this.getClass());
|
|
public static void clearDuplicateSubmitUNID(){//删除指定的key
|
RedisTemplate redisTemplate= (RedisTemplate) FactoryBean.getBean("redisTemplate");
|
if(CurrentLocal.getunidLocal()!=null) {
|
redisTemplate.delete(CurrentLocal.getunidLocal());
|
}
|
}
|
|
protected com.yc.utils.Page setPageInfo(HttpServletRequest request) {
|
return com.yc.utils.JOSNUtils.init(request);
|
}
|
|
protected com.yc.utils.Page setPageInfoTree(HttpServletRequest request) {
|
return com.yc.utils.JOSNUtils.initTree(request);
|
}
|
|
/**
|
* 输出验证结果
|
*
|
* **/
|
protected boolean getErrors(ModelMap model, BindingResult result) {
|
|
StringBuilder sb = new StringBuilder();
|
if (result.hasErrors()) {// 未通过验证
|
sb.append("验证出错,请填写完整\\n");
|
for (FieldError f : result.getFieldErrors()) {
|
sb.append(f.getDefaultMessage()).append("\\n");
|
}
|
model.addAttribute("success", sb.toString());
|
return true;
|
}
|
return false;
|
}
|
|
/**
|
* 输出操作结果提示
|
*
|
* **/
|
protected void printInfo(HttpServletResponse resp, boolean bl, String str) {
|
try {
|
PrintWriter out = resp.getWriter();
|
StringBuffer outData = new StringBuffer();
|
outData.append("{");
|
outData.append("gt_success: ").append(bl);
|
outData.append("}");
|
out.print(outData.toString());
|
out.flush();
|
out.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
/**
|
* 输出操作结果提示
|
*
|
* **/
|
protected void print(HttpServletResponse resp, String str, String contentType) {
|
try {
|
resp.setContentType(contentType + ";charset=utf-8");
|
PrintWriter out = resp.getWriter();
|
out.print(str);
|
out.flush();
|
out.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
/**
|
* 输出操作结果提示
|
*
|
* **/
|
protected void print(HttpServletResponse resp, String str) {
|
try {
|
resp.setContentType("text/html;charset=utf-8");
|
PrintWriter out = resp.getWriter();
|
out.print(str);
|
out.flush();
|
out.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
/**
|
* 向页面输出json
|
*
|
* **/
|
protected void printJson(HttpServletResponse resp, String s) {
|
try {
|
resp.setCharacterEncoding("utf-8");
|
resp.setContentType("application/json;charset=utf-8");
|
PrintWriter out = resp.getWriter();
|
out.print(s);
|
out.flush();
|
out.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
/**
|
* 向页面输出json
|
*
|
* **/
|
protected void printJsonInfo(HttpServletResponse resp, com.yc.utils.Page page, Type dataType) {
|
try {
|
PrintWriter out = resp.getWriter();
|
out.print(JOSNUtils.toJosn(page, dataType));
|
out.flush();
|
out.close();
|
page = null;
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
protected List<?> getDelEntity(HttpServletRequest request) {
|
return com.yc.utils.JOSNUtils.del(request);
|
}
|
|
/**
|
* InputStream转换为InputStreambyte[]
|
* @param inStream
|
* @return 字符串
|
* @throws IOException
|
*/
|
protected static final String input2bytet(InputStream inStream) throws IOException {
|
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
|
byte[] buff = new byte[100];
|
int rc = 0;
|
while ((rc = inStream.read(buff, 0, 100)) > 0) {
|
swapStream.write(buff, 0, rc);
|
}
|
byte[] in2b = swapStream.toByteArray();
|
// return in2b;
|
StringBuffer sb = new StringBuffer();
|
String stmp = "";
|
for (int n = 0; n < in2b.length; n++) {
|
stmp = Integer.toHexString(in2b[n] & 0XFF);
|
if (stmp.length() == 1) {
|
sb.append("0" + stmp);
|
} else {
|
sb.append(stmp);
|
}
|
}
|
return sb.toString();
|
}
|
|
/**
|
*
|
* 获得异常信息
|
* */
|
protected String getErrorMsg(Exception e){
|
String msg="";
|
if(e.getCause()!=null){
|
msg=e.getCause().getMessage();
|
}else{
|
msg=e.getMessage();
|
}
|
return msg;
|
}
|
protected Map printErrorMsgToJson(Exception e,Map otherMsg){
|
String msg=this.getErrorMsg(e);
|
Map root=new HashMap(5);
|
Map map=new HashMap(5);
|
map.put("error",msg);
|
if(otherMsg!=null) {
|
map.putAll(otherMsg);
|
}
|
root.put("state",-1);
|
root.put("info",map);
|
return root;
|
}
|
|
protected int getTypeByMetaData(Map<String,TableMetaData> tableMetaDatas, String id) {
|
|
String dataType=tableMetaDatas.get(id.toLowerCase())==null?"":tableMetaDatas.get(id.toLowerCase()).getDataType();
|
switch (dataType) {
|
case "tinyint":
|
case "int":
|
case "decimal":
|
case "double":
|
case "float":
|
case "numeric":
|
case "bigint":
|
case "real":
|
case "smallint":
|
case "money":
|
case "smallmoney":
|
return 1;
|
case "binary":
|
case "blob":
|
case "clob":
|
case "nclob":
|
return 2;
|
case "date":
|
case "time":
|
case "timestamp":
|
case "datetime":
|
case "smalldatetime":
|
return 4;// 日期
|
case "bit":
|
return 5;
|
case "longnvarchar":// varchar(MAX)
|
case "longvarchar":
|
return 3;
|
default:
|
return 3;
|
}
|
}
|
/**
|
* 根据列名查找列的数据类型是否需要去掉双引号, 因为客户端传过来的json经过转换都加上双引号,但到写入数据库时需要区分数据类型 <br>
|
* 1 --表示数值型<br>
|
* 2---表示text,ntext,image之类<br>
|
* 3---字符
|
* 4---日期
|
* */
|
protected int getType(SqlRowSetMetaData md, String id) {
|
int s = 3;
|
for (int i = 1; i <= md.getColumnCount(); i++) {
|
if (id.equalsIgnoreCase(md.getColumnName(i))) {
|
s = md.getColumnType(i);
|
break;
|
}
|
}
|
switch (s) {
|
case Types.TINYINT:
|
case Types.INTEGER:
|
case Types.DECIMAL:
|
case Types.DOUBLE:
|
case Types.FLOAT:
|
case Types.NUMERIC:
|
case Types.BIGINT:
|
case Types.REAL:
|
case Types.SMALLINT:
|
case 0:
|
return 1;
|
case Types.BINARY:
|
case Types.BLOB:
|
case Types.CLOB:
|
case Types.NCLOB:
|
return 2;
|
case Types.DATE:
|
case Types.TIME:
|
case Types.TIMESTAMP:
|
return 4;// 日期
|
case Types.BIT:
|
return 5;
|
case Types.LONGNVARCHAR:// varchar(MAX)
|
case Types.LONGVARCHAR:
|
return 3;
|
default:
|
return 3;
|
}
|
}
|
|
/*
|
* 得到服务器地址xiangluan2010-04-15
|
*/
|
protected String getURI(HttpServletRequest req) {
|
return req.getProtocol().substring(0, 4).toLowerCase() + "://" + req.getRemoteHost() + ":" + req.getLocalPort() + req.getContextPath();
|
}
|
|
/**
|
* 初始化系统一些全局变量值
|
*
|
* @formid 当前功能号
|
*@user 登录用户代码
|
*@usercode 登录用户代码
|
*@username 登录用户名
|
*@today 今天日期 YYYY-MM-DD
|
*@day 今天日期 YYYY-MM-DD
|
*@space 空格
|
*@date 今天日期 YYYY-MM-DD
|
*@treename 树节点名称 ,例:matgroupname
|
*@companyid 当前登录的公司代码
|
*@host 登录主机名(C/S) #表示有值传值,没值传空
|
* @param flag TODO
|
* **/
|
protected Map<String, String> initEnv(HttpServletRequest request, int formid, String doccode, boolean flag) {
|
if(request==null) return env;
|
return GridUtils.getSessionAttributes(request.getSession(), formid, doccode, flag);
|
}
|
|
/**
|
* 重新根据css设置把page类的sql组合
|
*
|
* @param String expr 形式:a|b;c|d...
|
* @return String 形式:新的sql
|
* */
|
protected String cssexprTOSql(String expr, String sql,String name) {
|
if (expr == null || expr.isEmpty()) return sql;
|
String[] temp = expr.replaceAll("<", "<").replaceAll(">", ">").split(";");
|
for (String str : temp) {
|
String[] qt = str.split("\\|");
|
if (getColumnNum(qt[0], sql)) {
|
//dist|! case when dist>0 then 'color:red' else '' end
|
qt[1]=qt[1].replaceAll("~", ";");//把转义的;还
|
if(qt[1].startsWith("!")){//动态css样式
|
if (qt.length>1&&qt[1].indexOf("@") > -1) {
|
Pattern p = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词
|
java.util.regex.Matcher propsMatcher = p.matcher(qt[1]);
|
while (propsMatcher.find()) {
|
qt[1]=qt[1].replaceAll(propsMatcher.group(), env.get(propsMatcher.group().toLowerCase()));
|
}
|
}
|
//case when '@cccode' in ('D','G') then 1 else 0 end //_cssexpr
|
String s = "["+qt[0].toLowerCase() + "], (" + qt[1].replaceFirst("!", "") +" ) as [" + qt[0].toLowerCase() + name+"]";
|
sql = sql.replaceAll("\\[" + qt[0].toLowerCase() + "\\]", s);
|
}else{
|
String s = "["+ qt[0].toLowerCase() + "], '"+qt[1]+"' as [" + qt[0].toLowerCase() + name+"]";
|
sql = sql.replaceAll("\\[" + qt[0].toLowerCase() + "\\]", s);
|
}
|
}else{//静态css样式
|
String s = "["+ qt[0].toLowerCase() + "], '"+qt[1]+"' as [" + qt[0].toLowerCase() + name+"]";
|
sql = sql.replaceAll("\\[" + qt[0].toLowerCase() + "\\]", s);
|
}
|
}
|
return sql;
|
}
|
|
/**
|
* 替换前台传过来的权限表达式
|
*
|
* @param String expr 形式:a|b;c|d...
|
* @return String 形式:新的sql
|
* */
|
protected String getExprTOSql(String expr) {
|
StringBuffer sb=new StringBuffer();
|
if (expr == null || expr.isEmpty()) return expr;
|
sb.append(" select ");
|
String[] temp = expr.replaceAll("<", "<").replaceAll(">", ">").replaceAll("&", "&").split(";");
|
int inx=0;
|
for (String str : temp) {
|
if(inx!=0) sb.append(",");
|
String[] qt = str.split("\\|");
|
//case when 'YC'=companyid then 1 else 0 end
|
// case when '@cccode' = 'CW' then salary then '--HideColumn--' end as salary
|
if (qt.length>1&&qt[1].indexOf("@") > -1) {
|
Pattern p = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词
|
java.util.regex.Matcher propsMatcher = p.matcher(qt[1]);
|
while (propsMatcher.find()) {
|
qt[1]=qt[1].replaceAll(propsMatcher.group(), env.get(propsMatcher.group().toLowerCase()));
|
}
|
}
|
//去掉没权限时返回null的条件,"case when (" + qt[1] + ") = 0 then null else " + qt[0].toLowerCase() + " end as
|
sb.append("case when (" + qt[1] + ") =1 then 1 when (" + qt[1] + ") =2 then 2 else 0 end as [" + qt[0].toLowerCase()+"]");
|
inx++;
|
}
|
return sb.toString();
|
}
|
|
/**
|
* 重新根据权限设置把page类的sql组合
|
*
|
* @return String 形式:新的sql
|
* */
|
protected String exprTOSql(Page page, String sql) {
|
String expr=page.getExpr();
|
if (expr == null || expr.isEmpty()) return sql;
|
Map<String,String> strs=new HashMap<String,String>();//保存权限表达式,给统计列使用
|
String[] temp = expr.replaceAll("<", "<").replaceAll(">", ">").replaceAll("&", "&").split(";");
|
for (String str : temp) {
|
String[] qt = str.split("\\|");
|
if (getColumnNum(qt[0], sql)) {
|
//case when 'YC'=companyid then 1 else 0 end
|
// case when '@cccode' = 'CW' then salary then '--HideColumn--' end as salary
|
if (qt.length>1&&qt[1].indexOf("@") > -1) {
|
Pattern p = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词
|
java.util.regex.Matcher propsMatcher = p.matcher(qt[1]);
|
while (propsMatcher.find()) {
|
qt[1]=qt[1].replaceAll(propsMatcher.group(), env.get(propsMatcher.group().toLowerCase()));
|
}
|
}
|
//去掉没权限时返回null的条件,"case when (" + qt[1] + ") = 0 then null else " + qt[0].toLowerCase() + " end as
|
String s = "[" + qt[0].toLowerCase() + "],case when (" + qt[1] + ") =1 then 1 when (" + qt[1] + ") =2 then 2 else 0 end as [" + qt[0].toLowerCase() + "_expr]";
|
strs.put(qt[0].toLowerCase(), " case when (" + qt[1] + ") = 0 then 0 else " + qt[0].toLowerCase() + " end ");
|
if(page.getType()!=null&&page.getWinType().equals("38")){
|
if(sql.toLowerCase().contains(" as "+qt[0].toLowerCase())){
|
sql = sql.replaceAll(" as "+qt[0].toLowerCase(), " as "+s);
|
}else {
|
sql = sql.replaceAll(qt[0].toLowerCase(), s);
|
}
|
}else {
|
sql = sql.replaceAll("\\[" + qt[0].toLowerCase() + "\\]", s);
|
}
|
}
|
}
|
page.setTbExpr(strs);
|
return sql;
|
}
|
|
protected String exprTOSql( String expr,String sql,HttpSession session) {//42类型控件使用
|
if (expr == null || expr.isEmpty()) return sql;
|
String[] temp = expr.replaceAll("#", "'").replaceAll("<", "<").replaceAll(">", ">").replaceAll("&", "&").split(";");
|
sql+=",";//增加,号是为了处理替换方便
|
for (String str : temp) {
|
if("".equalsIgnoreCase(str)) continue;
|
String[] qt = str.split("\\|");
|
if (getColumnNum(qt[0], sql)) {
|
if (qt.length>1){
|
qt[1]=qt[1].replaceAll("\\*","#");
|
Pattern p = Pattern.compile("\\/##.*?##\\/");// 去除 /**...**/的注释
|
java.util.regex.Matcher propsMatcher = p.matcher(qt[1]);
|
while (propsMatcher.find()) {
|
qt[1]=qt[1].replace(propsMatcher.group(),"");
|
}
|
qt[1]=qt[1].replaceAll("#","*");
|
if(qt[1].indexOf("@") > -1) {
|
p = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词
|
propsMatcher = p.matcher(qt[1]);
|
while (propsMatcher.find()) {
|
qt[1]=qt[1].replaceAll(propsMatcher.group(), session.getAttribute(propsMatcher.group().toLowerCase())+"");
|
}
|
}
|
}
|
//去掉没权限时返回null的条件,"case when (" + qt[1] + ") = 0 then null else " + qt[0].toLowerCase() + " end as
|
String s = "[" + qt[0].toLowerCase() + "],case when (" + qt[1] + ") =1 then 1 when (" + qt[1] + ") =2 then 2 else 0 end as [" + qt[0].toLowerCase() + "_expr]";
|
sql = sql.replaceAll(","+qt[0].toLowerCase()+",", ","+s+",");
|
}
|
}
|
return sql.lastIndexOf(",")>0?sql.substring(0, sql.length()-1):sql;
|
}
|
|
/**
|
* 查找字符串中是否存在指定的内容
|
*
|
* */
|
protected boolean getColumnNum(String colName, String gridcaption) {
|
// int num=0;
|
Pattern p = Pattern.compile("\\b" + colName.toLowerCase() + "\\b");
|
java.util.regex.Matcher propsMatcher = p.matcher(gridcaption.toLowerCase());
|
while (propsMatcher.find()) {
|
return true;
|
}
|
return false;
|
}
|
|
/**
|
* 判断字符串是否为空或null
|
* **/
|
protected boolean isNullOrEmptry(String s) {
|
return s != null && s != "" && "".equalsIgnoreCase("") && s.length() != 0 ? false : true;
|
}
|
|
// 去除字符串中的换行符等
|
public String replaceBlank(String str) {
|
if (str == null || str == "") { return ""; }
|
Matcher m = null;
|
try {
|
Pattern p = Pattern.compile("\t|\r|\n");
|
m = p.matcher(str);
|
} catch (Exception e) {
|
e.printStackTrace();
|
throw new ApplicationException(str + "-解析出错,存在有特殊字符");
|
}
|
return m.replaceAll(" ").replaceAll("\\$", "\\\\\\$");
|
}
|
|
/***
|
*
|
* 检测9802设置中的格式会存在连续输入多一个分隔符的情况:yyyy--mm-dd
|
* 出错返回false;
|
* */
|
public boolean checkFormat(String str){
|
if(str==null||str.length()==0) return true;
|
char temp='0';
|
boolean flg=true;
|
boolean ft=false;
|
for(char c:str.toCharArray()){
|
if(temp==c&&ft){
|
flg=false;
|
break;
|
}else{
|
if(c=='-'||c=='.'||c=='/'||c==':'){
|
temp=c;
|
ft=true;
|
}else{
|
ft=false;
|
}
|
}
|
}
|
return flg;
|
}
|
protected static boolean isBase64(String str) {
|
String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
|
return Pattern.matches(base64Pattern, str);
|
}
|
@SuppressWarnings("unchecked")
|
protected void print2Excel(HttpServletRequest request,HttpServletResponse resp, Page page, Object object,int formid,String type) {
|
try {
|
//读取当前功能号哪些字段是需要导出的
|
String s=FileUtil.readFile(request.getServletContext().getRealPath("/")+request.getSession().getAttribute(SessionKey.PAGE_PATH)+File.separator+formid+File.separator+type+File.separator+"data");//
|
if(request.getSession().getAttribute(SessionKey.USERCODE)==null){
|
this.printJson(resp, "error;会话过期,请重新登录!");
|
return;
|
}
|
if("".equalsIgnoreCase(s)||s==null){
|
this.printJson(resp, "error;未在9802设置有需要导出的内容或找不到相关的文件");
|
return;
|
}
|
Map<String,Object> map=null;
|
String[] panel_name=null;
|
String[] panel_tfiled=null;
|
String local="";
|
// StringBuffer fileName=new StringBuffer();//生成下载的文件名
|
if(object!=null){
|
map=(Map<String,Object>)object;
|
String[] panel_names=((String)map.get("desc")).split("-")[0].split(";");//内容
|
local=((String)map.get("desc")).split("-")[3];
|
Map<String,String> pmap=getTitle(page,0);//0表示取面板
|
int lens=panel_names.length;
|
panel_name=new String[lens];//字段标题
|
panel_tfiled=new String[lens];//字段名
|
setDyTtile(pmap, panel_names, panel_name, panel_tfiled);
|
|
// if(((String)map.get("desc")).split("-").length==5){
|
// String[] title_names=((String)map.get("desc")).split("-")[4].split(";");//文件名称
|
// Map<String,String> tmap=((List<Map<String, String>>) map.get("plist")).get(0);
|
// for(String st:title_names) {
|
// try {
|
// String temp=this.replaceBlank(st);
|
// fileName.append(tmap.get(temp.trim())).append("-");
|
// }catch(Exception e) {
|
// }
|
// }
|
// }
|
}
|
Map<String, String> gmap = getTitle(page,1);//1表示取格线
|
String[] str=s.split("-");
|
String[] temp=str[1].split(";");
|
int len=temp.length;
|
String[] name=new String[len];//字段说明
|
String[] filed=new String[len];//字段名
|
setDyTtile(gmap, temp, name, filed);
|
//然后写入excel文件
|
page.setExcelTitle(str.length==4?str[3]:"");
|
//处理生成文件名
|
// fileName.append(str[0]);
|
String dbid =request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"";
|
String hostUrl = SettingKey.getHostUrl(request);
|
PoiExcelWriter poi=new PoiExcelWriter();
|
Map m=poi.writeExcel( dbid,str[0], page, name, filed,panel_name, panel_tfiled,
|
map!=null?(List<?>)map.get("plist"):null,str[0],local,
|
map!=null?(((String)map.get("desc")).split("-").length==5?this.replaceBlank(((String)map.get("desc")).split("-")[4]):""):"",hostUrl);
|
SXSSFWorkbook wb=(SXSSFWorkbook)m.get("wb");
|
String fileName=m.get("title")+"";
|
if(wb!=null){
|
File file1=new File(request.getServletContext().getRealPath("/")+"excel"+File.separator+dbid+File.separator+formid+File.separator+type);
|
if(!file1.exists()){
|
file1.mkdirs();
|
}
|
String path=request.getServletContext().getRealPath("/")+"excel"+File.separator+dbid+File.separator+formid+File.separator+type+File.separator+fileName.replace("/","_").replace("*","")+".xlsx";
|
File file=new File(path);
|
resp.setContentType("application/msexcel");
|
resp.setHeader("Content-Disposition", "attachment;Filename=" +new String(fileName.getBytes("utf-8"), "ISO8859-1")+ ".xlsx");
|
|
//写到磁盘生成文件,为了给审计用 by danaus 2020/11/10 16:12
|
FileOutputStream fileOut = new FileOutputStream(file);
|
wb.write(fileOut);
|
fileOut.flush();
|
fileOut.close();
|
//通过流输出到页面
|
OutputStream os = resp.getOutputStream();
|
try (FileInputStream fis = new FileInputStream(file)) {
|
int lens;
|
byte[] buffer = new byte[4096];
|
while ((lens = fis.read(buffer)) > 0) {
|
os.write(buffer, 0, lens);
|
}
|
os.flush();
|
|
} catch (IOException e) {
|
e.printStackTrace();
|
this.printJson(resp, "error;"+e.getMessage());
|
}finally {
|
os.close();
|
}
|
excelRecords(formid,type,map,file,request,page);//导出数据审计记录执行方法
|
wb.dispose();
|
}
|
page = null;
|
}catch (ParseException e) {
|
// TODO Auto-generated catch block
|
e.printStackTrace();
|
this.printJson(resp, "error;"+e.getMessage());
|
} catch (Exception e) {
|
e.printStackTrace();
|
this.printJson(resp, "error;"+e.getMessage());
|
}
|
}
|
|
/**
|
* 导出数据审计记录执行方法
|
* @param formid
|
* @param type
|
* @param map
|
* @param reque
|
* @return
|
*/
|
public int excelRecords(int formid,String type,Map<String, Object> map,File file,HttpServletRequest request,Page page){
|
Date now = new Date();
|
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置显示格式
|
// int types=Integer.parseInt(type.split("\\|")[0]);
|
//int formid=Integer.parseInt(reque.getParameter("formidd").toString());
|
// String doccode=reque.getParameter("doccode");
|
// int type=Integer.parseInt(reque.getParameter("formidtyped").toString().split("\\|")[0]);
|
String doccode=page.getWhere();//((Map)((List)map.get("plist")).get(0)).get("DocCode").toString();
|
if(doccode.toLowerCase().indexOf("doccode")!=-1){
|
try{
|
doccode=doccode.split("doccode='")[1].split("'")[0];
|
}catch (Exception e) {
|
doccode="";
|
}
|
}else{
|
doccode="";
|
}
|
int cont =0;
|
String unid=UUID.randomUUID().toString().toUpperCase();//生成uuid
|
try {
|
InputStream inStream = new FileInputStream(file);
|
AttachmentIfc attachmentIfc=(AttachmentIfc)FactoryBean.getBean("AttachmentImpl");
|
AttachmentWhereEntity attachmentWhereEntity=attachmentIfc.saveAttachment(unid, formid,input2byte(inStream),file.getName(),"xls","1");//保存导出的数据到指定数据库里面
|
if(attachmentWhereEntity!=null && attachmentWhereEntity.getSeq() != null && !attachmentWhereEntity.getSeq().equals(0)){
|
ExcelIfc excelIfc=(ExcelIfc)FactoryBean.getBean("com.yc.service.excel.ExcelImpl");
|
String ActionStatus="Success";
|
String ActionMemo="";
|
cont= excelIfc.excelRecord(formid, doccode, request.getSession().getAttribute(SessionKey.USERCODE).toString(), request.getSession().getAttribute(SessionKey.USERNAME).toString(), "Out", df.format(now), unid+";"+attachmentWhereEntity.getSeq(), "", type,ActionStatus,ActionMemo);
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
}finally {
|
if(file!=null&&file.exists()&&file.isFile()) {
|
log.info("del>>userCode:"+request.getSession().getAttribute(SessionKey.USERCODE)+"|dbid:"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"|"+file.getAbsolutePath());
|
file.delete();
|
}
|
}
|
return cont;
|
}
|
|
public void setDyTtile(Map<String, String> gmap, String[] temp, String[] name, String[] filed) {//替换以!开头的动态内容
|
int i=0;
|
for(String st:temp){
|
if(st.length()>1){
|
String[] ss=st.split("#");
|
if(ss.length>1){
|
if(StringUtils.isNotBlank(ss[1])) {
|
//标题存在复合标题的情况,需要处理
|
String[] value = ss[1].split("\\|");
|
if (value.length > 1) {
|
StringJoiner newTitle = new StringJoiner("|");
|
for (String s : value) {
|
if (s.trim().startsWith("!"))//如果是动态标题则替换
|
newTitle.add(gmap.get(ss[0].toLowerCase()));
|
else
|
newTitle.add(s);
|
}
|
name[i] = newTitle.toString();
|
} else {
|
name[i] = value[0];
|
}
|
}
|
}else{
|
name[i]="";
|
}
|
if(ss.length>2)
|
filed[i]=ss[0]+";"+ss[2];
|
else
|
filed[i]=ss[0];
|
i++;
|
}
|
}
|
}
|
|
public static Map<String, String> getTitle(Page page,int index) {//取得页面传过来的动态标题内容,以便替换excel对应的标题
|
String[] tit=null;
|
Map<String,String> gmap=new HashMap<String,String>();
|
try {
|
tit = EncodeUtil.base64Decode(page.getExcelTitle()).split("~");
|
if(tit.length>0){
|
String[] temp=tit[index].split("'");//动态标题内容
|
if(temp.length>1){
|
for(String st:temp){
|
String[] tt=st.split("(");
|
gmap.put(tt[0], tt[1]);
|
}
|
}
|
}
|
} catch (UnsupportedEncodingException e) {
|
// TODO Auto-generated catch block
|
e.printStackTrace();
|
}
|
return gmap;
|
}
|
|
public static final byte[] input2byte(InputStream inStream) {
|
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
|
try{
|
byte[] buff = new byte[1024];
|
int rc = 0;
|
while ((rc = inStream.read(buff, 0, buff.length)) > 0) {
|
swapStream.write(buff, 0, rc);
|
}
|
byte[] in2b = swapStream.toByteArray();
|
inStream.close();
|
swapStream.close();
|
return in2b;
|
}catch(Exception e){
|
return null;
|
}finally{
|
try {
|
swapStream.close();
|
inStream.close();
|
} catch (IOException e) {
|
// TODO Auto-generated catch block
|
e.printStackTrace();
|
}
|
}
|
}
|
|
public void checkDuplicateSubmit(String unid){
|
|
RedisTemplate redisTemplate= (RedisTemplate) FactoryBean.getBean("redisTemplate");
|
if(unid.equals("excel")){return;}//导入的跳出
|
if(unid!=null&&!"".equalsIgnoreCase(unid)) {
|
synchronized(lock) {
|
Object object = redisTemplate.opsForValue().get(unid);
|
if (object == null) {
|
//不存在,加到redis里,过期时间设置为2分钟
|
final int OVERTIME = 2;
|
redisTemplate.opsForValue().set(unid, 1, OVERTIME, TimeUnit.MINUTES);
|
CurrentLocal.setUnidLocal(unid);
|
|
} else {
|
throw new ApplicationException("正在处理中...请不要重复提交");
|
}
|
}
|
}else{
|
throw new ApplicationException("参数unid不能为空,请确认前端是否有传递过来");
|
}
|
}
|
}
|