From 6028b2256d800083ed6d86c2af27e900603d5021 Mon Sep 17 00:00:00 2001 From: rengp Date: Tue, 17 Oct 2023 14:42:15 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=80=E6=94=B9=E7=AD=BE=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cusvideo/util/YealinkVideoUtil.java | 392 + com/api/tjyh/AcceptXcDataActionApi.java | 16 + .../custom/sl/entity/EsbRequestHeader.java | 2 +- com/engine/msgcenter/util/MsgECToEM.java | 851 ++ .../tjbankSocket/impl/CWGLSocketExecute.java | 11 +- com/engine/tjyh/xc/cmd/Test.java | 759 ++ com/engine/tjyh/xc/cmd/XcCmd.java | 975 ++ com/engine/tjyh/xc/cmd/XcCmd2.java | 894 ++ com/engine/tjyh/xc/service/XcService.java | 17 + .../tjyh/xc/service/impl/XcServiceImpl.java | 28 + .../tjyh/xc/util/HttpClientWrapper.java | 57 + com/engine/tjyh/xc/util/HttpRequestUtil.java | 284 + .../tjyh/xc/util/WorkflowCreateHandler.java | 534 ++ .../tjyh/xc/web/AcceptXcDataAction.java | 123 + com/engine/web/meeting/NewMeet.java | 108 +- com/engine/web/tjbk/TjbkServerSocket.java | 4 +- com/engine/web/tjbk/Tjbk_SL_ServerSocket.java | 166 - com/engine/web/zhsl/Tjbk_SL_ServerSocket.java | 167 - rebel.xml | 16 + weaver/file/FileDownload.java | 8400 +++++++++-------- .../action/javacode/Action20231013103613.java | 127 + .../action/javacode/Action20231015024217.java | 339 + weaver/ofs/manager/OfsTodoDataManagerNew.java | 3 + 23 files changed, 9708 insertions(+), 4565 deletions(-) create mode 100644 com/api/meeting/cusvideo/util/YealinkVideoUtil.java create mode 100644 com/api/tjyh/AcceptXcDataActionApi.java create mode 100644 com/engine/msgcenter/util/MsgECToEM.java create mode 100644 com/engine/tjyh/xc/cmd/Test.java create mode 100644 com/engine/tjyh/xc/cmd/XcCmd.java create mode 100644 com/engine/tjyh/xc/cmd/XcCmd2.java create mode 100644 com/engine/tjyh/xc/service/XcService.java create mode 100644 com/engine/tjyh/xc/service/impl/XcServiceImpl.java create mode 100644 com/engine/tjyh/xc/util/HttpClientWrapper.java create mode 100644 com/engine/tjyh/xc/util/HttpRequestUtil.java create mode 100644 com/engine/tjyh/xc/util/WorkflowCreateHandler.java create mode 100644 com/engine/tjyh/xc/web/AcceptXcDataAction.java delete mode 100644 com/engine/web/tjbk/Tjbk_SL_ServerSocket.java delete mode 100644 com/engine/web/zhsl/Tjbk_SL_ServerSocket.java create mode 100644 rebel.xml create mode 100644 weaver/interfaces/workflow/action/javacode/Action20231013103613.java create mode 100644 weaver/interfaces/workflow/action/javacode/Action20231015024217.java diff --git a/com/api/meeting/cusvideo/util/YealinkVideoUtil.java b/com/api/meeting/cusvideo/util/YealinkVideoUtil.java new file mode 100644 index 0000000..6ed3386 --- /dev/null +++ b/com/api/meeting/cusvideo/util/YealinkVideoUtil.java @@ -0,0 +1,392 @@ +package com.api.meeting.cusvideo.util; + +import cn.hutool.core.codec.Base64; +import cn.hutool.core.lang.UUID; +import cn.hutool.http.ContentType; +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.BaseBean; +import weaver.general.StaticObj; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; + +import java.nio.charset.StandardCharsets; +import java.util.*; + +/** + * @Description: + * @Author: lj + * @CreateTime: 2023-06-05 15:51 + * @Version: 1.0 + */ +public class YealinkVideoUtil { + private static BaseBean logger = new BaseBean(); + private static final String YEA_LINK_TOKEN_KEY = "YEA_LINK_TOKEN_KEY"; + private static StaticObj cache = StaticObj.getInstance(); + + /** + * 执行post请求 + * + * @param url + * @param header + * @param body + * @return + */ + public static JSONObject doPost(String url, String token, Map header, JSONObject body) { + try { + logger.writeLog("^^^ YealinkVideoUtil.doPost : url = " + url); + if (header == null) header = new HashMap<>(); + if (!header.containsKey("Authorization")) header.put("Authorization", "Bearer " + token); + if (!header.containsKey("timestamp")) header.put("timestamp", System.currentTimeMillis() + ""); + if (!header.containsKey("nonce")) header.put("nonce", UUID.randomUUID().toString(true)); + if (body == null) body = new JSONObject(); + logger.writeLog("^^^ YealinkVideoUtil.doPost : url = " + url + + " , header = " + JSONObject.toJSONString(header) + + " , body = " + body.toJSONString() + ); + HttpResponse response = HttpRequest.post(url) + .charset(StandardCharsets.UTF_8) + .addHeaders(header) + .body(body.toJSONString()) + .execute() + .charset(StandardCharsets.UTF_8); + String result = response.body(); + logger.writeLog("^^^ YealinkVideoUtil.doPost : url = " + url + " , result = " + result); + JSONObject resultJson = JSONObject.parseObject(result); + if (response.getStatus() != 200) { + throw new RuntimeException("[" + resultJson.getString("code") + "]" + resultJson.getString("message")); + } + return resultJson; + } catch (Exception e) { + logger.writeLog("^^^ YealinkVideoUtil.doPost : 接口[" + url + "]请求失败!!!", e); + throw new RuntimeException(e.getMessage()); + } + } + + /** + * 执行get请求 + * + * @param url + * @param token + */ + public static JSONObject doGet(String url, String token, Map header, JSONObject body) { + try { + logger.writeLog("^^^ YealinkVideoUtil.doGet : url = " + url); + if (header == null) header = new HashMap<>(); + if (!header.containsKey("Authorization")) header.put("Authorization", "Bearer " + token); + if (!header.containsKey("timestamp")) header.put("timestamp", System.currentTimeMillis() + ""); + if (!header.containsKey("nonce")) header.put("nonce", UUID.randomUUID().toString(true)); + if (body == null) body = new JSONObject(); + logger.writeLog("^^^ YealinkVideoUtil.doGet : url = " + url + + " , header = " + JSONObject.toJSONString(header) + + " , body = " + body.toJSONString() + ); + HttpResponse response = HttpRequest.get(url) + .charset(StandardCharsets.UTF_8) + .addHeaders(header) + .contentType(ContentType.JSON.getValue()) + .form(body) + .execute() + .charset(StandardCharsets.UTF_8); + String result = response.body(); + logger.writeLog("^^^ YealinkVideoUtil.doGet : url = " + url + " , result = " + result); + JSONObject resultJson = JSONObject.parseObject(result); + if (response.getStatus() != 200) { + throw new RuntimeException("[" + resultJson.getString("code") + "]" + resultJson.getString("message")); + } + return resultJson; + } catch (Exception e) { + logger.writeLog("^^^ YealinkVideoUtil.doGet : 接口[" + url + "]请求失败!!!", e); + throw new RuntimeException(e.getMessage()); + } + } + + /** + * 执行put请求 + * + * @param url + * @param token + * @param header + * @param body + * @return + */ + public static JSONObject doPut(String url, String token, Map header, JSONObject body) { + try { + logger.writeLog("^^^ YealinkVideoUtil.doPut : url = " + url); + if (header == null) header = new HashMap<>(); + if (!header.containsKey("Authorization")) header.put("Authorization", "Bearer " + token); + if (!header.containsKey("timestamp")) header.put("timestamp", System.currentTimeMillis() + ""); + if (!header.containsKey("nonce")) header.put("nonce", UUID.randomUUID().toString(true)); + if (body == null) body = new JSONObject(); + logger.writeLog("^^^ YealinkVideoUtil.doPut : url = " + url + + " , header = " + JSONObject.toJSONString(header) + + " , body = " + body.toJSONString() + ); + HttpResponse response = HttpRequest.put(url) + .charset(StandardCharsets.UTF_8) + .addHeaders(header) + .body(body.toJSONString()) + .execute() + .charset(StandardCharsets.UTF_8); + String result = response.body(); + logger.writeLog("^^^ YealinkVideoUtil.doPut : url = " + url + " , result = " + result); + JSONObject resultJson = JSONObject.parseObject(result); + if (response.getStatus() != 200) { + throw new RuntimeException("[" + resultJson.getString("code") + "]" + resultJson.getString("message")); + } + return resultJson; + } catch (Exception e) { + logger.writeLog("^^^ YealinkVideoUtil.doPut : 接口[" + url + "]请求失败!!!", e); + throw new RuntimeException(e.getMessage()); + } + } + + /** + * 执行delete方法 + * + * @param url + * @param token + * @param header + * @param body + * @return + */ + public static JSONObject doDelete(String url, String token, Map header, JSONObject body) { + try { + logger.writeLog("^^^ YealinkVideoUtil.doDelete : url = " + url); + if (header == null) header = new HashMap<>(); + if (!header.containsKey("Authorization")) header.put("Authorization", "Bearer " + token); + if (!header.containsKey("timestamp")) header.put("timestamp", System.currentTimeMillis() + ""); + if (!header.containsKey("nonce")) header.put("nonce", UUID.randomUUID().toString(true)); + if (body == null) body = new JSONObject(); + logger.writeLog("^^^ YealinkVideoUtil.doDelete : url = " + url + + " , header = " + JSONObject.toJSONString(header) + + " , body = " + body.toJSONString() + ); + List queryList = new ArrayList<>(); + for (Object key : body.keySet()) { + if (key != null) { + queryList.add(key + "=" + body.getString((String) key)); + } + } + if (queryList.size() > 0) { + if (url.contains("?")) { + url += "&"; + } else { + url += "?"; + } + url += StringUtils.join(queryList, "&"); + } + HttpResponse response = HttpRequest.delete(url) + .charset(StandardCharsets.UTF_8) + .addHeaders(header) + .contentType(ContentType.JSON.getValue()) + .execute() + .charset(StandardCharsets.UTF_8); + String result = response.body(); + logger.writeLog("^^^ YealinkVideoUtil.doDelete : url = " + url + " , result = " + result); + JSONObject resultJson = JSONObject.parseObject(result); + if (response.getStatus() != 200) { + throw new RuntimeException("[" + resultJson.getString("code") + "]" + resultJson.getString("message")); + } + return resultJson; + } catch (Exception e) { + logger.writeLog("^^^ YealinkVideoUtil.doDelete : 接口[" + url + "]请求失败!!!", e); + throw new RuntimeException(e.getMessage()); + } + } + + /** + * 获取token + * + * @param appKey + * @param appSecret + * @return + */ + public static String getToken(String host, String appKey, String appSecret) { + String token = ""; + try { + //1、从缓存中获取 + Object object = cache.getObject(YEA_LINK_TOKEN_KEY); + if (object != null) { + JSONObject tokenObj = JSONObject.parseObject((String) object); + if (tokenObj != null) { + long expires_in = tokenObj.getLongValue("expires_in"); + if (expires_in > System.currentTimeMillis()) { + token = tokenObj.getString("access_token"); + } else { + cache.removeObject(YEA_LINK_TOKEN_KEY); + } + } + } + if (StringUtils.isBlank(token)) {//去获取token + //请求头 + Map header = new HashMap<>(); + header.put("Authorization", "Basic " + Base64.encode(appKey + ":" + appSecret)); + header.put("timestamp", System.currentTimeMillis() + ""); + header.put("nonce", UUID.randomUUID().toString(true)); + //请求体 + JSONObject body = new JSONObject(); + body.put("grant_type", "client_credentials"); + //构建请求url + String url = host + "/token"; + //执行请求 + logger.writeLog("^^^ YealinkVideoUtil.getToken : url = " + url); + logger.writeLog("^^^ YealinkVideoUtil.getToken : header = " + JSONObject.toJSONString(header)); + logger.writeLog("^^^ YealinkVideoUtil.getToken : body = " + body.toJSONString()); + HttpResponse response = HttpRequest.post(url) + .charset(StandardCharsets.UTF_8) + .addHeaders(header) + .body(body.toJSONString()) + .execute() + .charset(StandardCharsets.UTF_8); + String result = response.body(); + logger.writeLog("^^^ YealinkVideoUtil.getToken : url = " + url + " , result = " + result); + JSONObject resultJson = JSONObject.parseObject(result); + if (response.getStatus() != 200) { + throw new RuntimeException("[" + resultJson.getString("code") + "]" + resultJson.getString("message")); + } + //设置过期时间 + int expires_in = resultJson.getIntValue("expires_in"); + resultJson.put("expires_in", System.currentTimeMillis() + expires_in * 1000L); + //缓存token + cache.putObject(YEA_LINK_TOKEN_KEY, resultJson.toJSONString()); + token = resultJson.getString("access_token"); + } + return token; + } catch (Exception e) { + logger.writeLog("^^^ YealinkVideoUtil.getToken : error !!!", e); + throw new RuntimeException("Token获取失败:" + e.getMessage()); + } + } + + /** + * 获取yealink的用户id + * + * @param host + * @param token + * @param userId + * @return + */ + public static String getYeaLinkUserId(String host, String token, String userId) { + String value = ""; + String hrmYeaLinkCusFieldName = Util.null2String(Prop.getPropValue("qc2281950", "hrmYeaLinkCusFieldName")); + String hrmYeaLinkIdCusFieldScope = Util.null2s(Prop.getPropValue("qc2281950", "hrmYeaLinkIdCusFieldScope"), "-1"); + RecordSet rs = new RecordSet(); + new BaseBean().writeLog("^^^ YealinkVideoUtil.getYeaLinkUserId : userId = " + userId + + " , hrmYeaLinkCusFieldName = " + hrmYeaLinkCusFieldName + + " , hrmYeaLinkIdCusFieldScope = " + hrmYeaLinkIdCusFieldScope); + rs.executeQuery("select " + hrmYeaLinkCusFieldName + " from cus_fielddata " + + "where scope='HrmCustomFieldByInfoType' and scopeid=? and id=?", hrmYeaLinkIdCusFieldScope, userId); + if (rs.next()) { + value = Util.null2String(rs.getString(1)); + } + if (StringUtils.isBlank(value)) { + //如果为空,则这里需要去添加用户,以获得返回后的亿联用户ID + value = addYeaLinkUser(userId, host, token); + } + return value; + } + + /** + * 添加yealink用户 + * + * @param userId + * @param host + * @param token + * @return + */ + public static String addYeaLinkUser(String userId, String host, String token) { + try { + ResourceComInfo comInfo = new ResourceComInfo(); + JSONObject body = new JSONObject(); + body.put("name", comInfo.getLastname(userId)); + body.put("extension", comInfo.getWorkcode(userId)); + String mobile = comInfo.getMobile(userId); + body.put("mobile", mobile); + //判断手机号是否存在 + if (StringUtils.isBlank(mobile)) { + throw new RuntimeException("手机号[mobile]不能为空"); + } + //先查询亿联是否存在用户 + String yeaLinkUserId = queryYeaLinkUserId(host, token, mobile); + if (StringUtils.isBlank(yeaLinkUserId)) { + String url = host + "/users"; + JSONObject resultObj = doPost(url, token, null, body); + //取出ID + yeaLinkUserId = resultObj.getString("id"); + } + //更新到人力资源自定义表中 + updateHrmYeaLinkUserId(userId, yeaLinkUserId); + return yeaLinkUserId; + } catch (Exception e) { + logger.writeLog("^^^ YealinkVideoUtil.addYeaLinkUser : error !!!", e); + throw new RuntimeException("添加亿联用户失败:" + e.getMessage()); + } + } + + /** + * 根据手机号查询用户 + * + * @param mobile + * @return + */ + private static String queryYeaLinkUserId(String host, String token, String mobile) { + JSONObject body = new JSONObject(); + body.put("mobile", mobile); + body.put("limit", 1); + String url = host + "/users"; + JSONObject resultObj = doGet(url, token, null, body); + //取出数据 + JSONArray dataArr = resultObj.getJSONArray("data"); + if (dataArr != null && dataArr.size() > 0) { + JSONObject dataObj = dataArr.getJSONObject(0); + String phone = Util.null2String(dataObj.getString("mobile")); + if (mobile.equals(phone)) { + return Util.null2String(dataObj.getString("id")); + } + } + return null; + } + + /** + * 更新自定义字段值 + * + * @param yeaLinkUserId + */ + private static void updateHrmYeaLinkUserId(String userId, String yeaLinkUserId) { + String hrmYeaLinkCusFieldName = Util.null2String(Prop.getPropValue("qc2281950", "hrmYeaLinkCusFieldName")); + String hrmYeaLinkIdCusFieldScope = Util.null2s(Prop.getPropValue("qc2281950", "hrmYeaLinkIdCusFieldScope"), "-1"); + RecordSet rs = new RecordSet(); + new BaseBean().writeLog("^^^ YealinkVideoUtil.updateHrmYeaLinkUserId : userId = " + userId + + " , hrmYeaLinkCusFieldName = " + hrmYeaLinkCusFieldName + + " , hrmYeaLinkIdCusFieldScope = " + hrmYeaLinkIdCusFieldScope); + String sql = "select * from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid=? and id=?"; + rs.executeQuery(sql, hrmYeaLinkIdCusFieldScope, userId); + if (rs.next()) {//存在记录做更新 + sql = "update cus_fielddata set " + hrmYeaLinkCusFieldName + + "=? where scope='HrmCustomFieldByInfoType' and scopeid=? and id=?"; + List params = Arrays.asList(yeaLinkUserId, hrmYeaLinkIdCusFieldScope, userId); + boolean flag = rs.executeUpdate(sql, params.toArray()); + if (!flag) { + logger.writeLog("^^^ YealinkVideoUtil.updateHrmYeaLinkUserId : execute update sql error , sql = " + sql + + " , params = " + JSONObject.toJSONString(params)); + } + } else {//不存在记录做新增 + sql = "insert into cus_fielddata (scope,scopeid,id," + hrmYeaLinkCusFieldName + ") " + + "values ('HrmCustomFieldByInfoType',?,?,?)"; + List params = Arrays.asList(hrmYeaLinkIdCusFieldScope, userId, yeaLinkUserId); + boolean flag = rs.executeUpdate(sql, params.toArray()); + if (!flag) { + logger.writeLog("^^^ YealinkVideoUtil.updateHrmYeaLinkUserId : execute insert sql error , sql = " + sql + + " , params = " + JSONObject.toJSONString(params)); + } + } + + } + +} diff --git a/com/api/tjyh/AcceptXcDataActionApi.java b/com/api/tjyh/AcceptXcDataActionApi.java new file mode 100644 index 0000000..1b77204 --- /dev/null +++ b/com/api/tjyh/AcceptXcDataActionApi.java @@ -0,0 +1,16 @@ +package com.api.tjyh; + +import com.engine.tjyh.xc.web.AcceptXcDataAction; + +import javax.ws.rs.Path; + +/** + * TODO + * + * @Description + * @Author matrix + * @Date 2023/6/15 10:19 + **/ +@Path("/tjyh/secondev/xc") +public class AcceptXcDataActionApi extends AcceptXcDataAction { +} diff --git a/com/engine/custom/sl/entity/EsbRequestHeader.java b/com/engine/custom/sl/entity/EsbRequestHeader.java index 71c0803..d0a8436 100644 --- a/com/engine/custom/sl/entity/EsbRequestHeader.java +++ b/com/engine/custom/sl/entity/EsbRequestHeader.java @@ -24,7 +24,7 @@ public class EsbRequestHeader { } - +//此方法为推送补贴报销单到ESB的消息头,其他类型需自己set属性 public EsbRequestHeader(int id) { BaseBean baseBean = new BaseBean(); String idStr = String.format("%06d", id); diff --git a/com/engine/msgcenter/util/MsgECToEM.java b/com/engine/msgcenter/util/MsgECToEM.java new file mode 100644 index 0000000..ce9cfaa --- /dev/null +++ b/com/engine/msgcenter/util/MsgECToEM.java @@ -0,0 +1,851 @@ +package com.engine.msgcenter.util; + +import com.alibaba.fastjson.JSONObject; +import com.cloudstore.dev.api.bean.MessageBean; +import com.cloudstore.dev.api.message.constant.ConstantMapping; +import com.cloudstore.dev.api.util.APPManager; +import com.cloudstore.dev.api.util.EMManager; +import com.cloudstore.eccom.common.WeaIndexManager; +import com.engine.msgcenter.constant.MsgToEMConstant; +import com.engine.msgcenter.entity.MsgDataItem; +import com.engine.systeminfo.util.AppSyncUtil; +import com.weaver.file.Prop; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import weaver.conn.RecordSet; +import weaver.file.FileNamingManager; +import weaver.file.ImageFileManager; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.io.InputStream; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class MsgECToEM { + private static final Log log = LogFactory.getLog(MsgECToEM.class); + + /** + * 设置在EM创建消息型应用的参数 + * + * @param img_url 应用在EM显示的图标的地址 + * @param agent_type 2:消息型应用 + * @param name 应用名称 + * @param description 描述 + * @param dialog_url 描述 + * @param sendmobile 是否发送到emobile + * @return + */ + public static MsgDataItem createMsgDataItem(String img_url, int agent_type, String name, String description, String dialog_url, String dialog_url_pc, String sendmobile) { + MsgDataItem item = new MsgDataItem(); + item.setImg_url(img_url); + item.setAgent_type(agent_type); + item.setDescription(description); + item.setDialog_url(dialog_url); + item.setDialog_url_pc(dialog_url_pc);//EM根据这个是否为空来决定显示原生的还是H5页面,传和dialog_url一样的值 + sendmobile = MsgToEMConstant.SEND_MOBILE.equals(sendmobile) ? "1" : "0"; + item.setSend_to_em(sendmobile); + String zh_name = name; + if (name.contains("~")) + zh_name = Util.formatMultiLang(name, 7 + ""); + item.setName(zh_name); + Set set = new HashSet<>(); + for (int i = 7; i <= 9; i++) { + Map map = new HashMap<>(); + if (i == 7) + map.put("lang_tag", "zh"); + if (i == 8) + map.put("lang_tag", "en"); + if (i == 9) + map.put("lang_tag", "zh_TW"); + map.put("set_value", Util.formatMultiLang(name, i + "")); + set.add(map); + } + + item.setLang_data(set); + return item; + } + + + /** + * @param agentid EM消息型应用唯一id + * @param img_url 应用在EM显示的图标的地址 + * @param agent_type 2:消息型应用 + * @param name 应用名称 + * @param description 描述 + * @param dialog_url 是否发送到emobile + * @return + */ + public static MsgDataItem updateMsgDataItem(String agentid, String img_url, int agent_type, String name, String description, String dialog_url, String dialog_url_pc, String sendmobile) { + MsgDataItem item = new MsgDataItem(); + item.setAgentid(agentid); + item.setImg_url(img_url); + item.setAgent_type(agent_type); + item.setDescription(description); + item.setDialog_url(dialog_url); + item.setDialog_url_pc(dialog_url_pc); + sendmobile = MsgToEMConstant.SEND_MOBILE.equals(sendmobile) ? "1" : "0"; + item.setSend_to_em(sendmobile); + String zh_name = name; + if (name.contains("~")) + zh_name = Util.formatMultiLang(name, 7 + ""); + item.setName(zh_name); + Set set = new HashSet<>(); + for (int i = 7; i <= 9; i++) { + Map map = new HashMap<>(); + if (i == 7) + map.put("lang_tag", "zh"); + if (i == 8) + map.put("lang_tag", "en"); + if (i == 9) + map.put("lang_tag", "zh_TW"); + map.put("set_value", Util.formatMultiLang(name, i + "")); + set.add(map); + } + item.setLang_data(set); + return item; + } + + /** + * 设置在EM创建消息型应用的参数 + * + * @param msgtype "share" + * @param agentid 移动端agentid + * @param send_type 1 + * @param opentype 1 + * @param opentype_pc 2 + * @param canforward 0:不允许转发 1:可以转发 + * @param callbackurl 消息转发回调地址 + * @return + */ + public static MsgDataItem sendMsgDataItem(String senderid, String userids, String msgtype, String agentid, String send_type, String content, String desc, + String linkurl, String linkurl_pc, String opentype, String opentype_pc, + String canforward, String callbackurl, String sharetype, String shareid, String sharetypename, Map sendParams) { + MsgDataItem item = new MsgDataItem(); + item.setSenderid(senderid); + item.setUserids(userids); + item.setMsgtype(msgtype); + item.setAgentid(agentid); + item.setSend_type(send_type); + item.setContent(content); + item.setDesc(desc); + item.setLinkurl(linkurl); + item.setLinkurl_pc(linkurl_pc); + item.setOpentype(opentype); + item.setOpentype_pc(opentype_pc); + item.setCanforward(canforward); + item.setCallbackurl(callbackurl); + item.setSharetypename(sharetypename); + item.setSharetype(sharetype); + item.setShareid(shareid); + item.setSendParams(sendParams); + new BaseBean().writeLog("qwe====>"+JSONObject.toJSONString(item)); + + return item; + } + + + /** + * 设置在EM创建消息型应用的参数,封装成一个Map + */ + public static Map createAppParams(MsgDataItem item) { + Map params = new HashMap<>(); + if (StringUtils.isNotBlank(item.getAgentid())) + params.put("agentid", item.getAgentid()); + if (StringUtils.isNotBlank(item.getName())) + params.put("name", item.getName()); + if (!item.getLang_data().isEmpty()) + params.put("lang_data", item.getLang_data()); + if (StringUtils.isNotBlank(item.getEnglish_name())) + params.put("english_name", item.getEnglish_name()); + if (StringUtils.isNotBlank(item.getDescription())) + params.put("description", item.getDescription()); + if (StringUtils.isNotBlank(String.valueOf(item.getAgent_type()))) + params.put("agent_type", String.valueOf(item.getAgent_type())); + if (StringUtils.isNotBlank(item.getLogo())) + params.put("logo", item.getLogo()); + if (StringUtils.isNotBlank(item.getLogo_pc())) + params.put("logo_pc", item.getLogo_pc()); + if (StringUtils.isNotBlank(item.getClienttypes())) + params.put("clienttypes", item.getClienttypes()); + if (StringUtils.isNotBlank(item.getDialog_url())) + params.put("dialog_url", item.getDialog_url()); + if (StringUtils.isNotBlank(item.getDialog_url_pc())) + params.put("dialog_url_pc", item.getDialog_url_pc()); + if (StringUtils.isNotBlank(item.getStatus_url())) + params.put("status_url", item.getStatus_url()); + if (StringUtils.isNotBlank(item.getAttention_url())) + params.put("attention_url", item.getAttention_url()); + if (StringUtils.isNotBlank(item.getMsg_url())) + params.put("msg_url", item.getMsg_url()); + if (StringUtils.isNotBlank(item.getShare_url())) + params.put("share_url", item.getShare_url()); + if (StringUtils.isNotBlank(item.getEnable_auth())) + params.put("enable_auth", item.getEnable_auth()); + if (StringUtils.isNotBlank(item.getSend_to_em())) + params.put("send_to_em", item.getSend_to_em()); + + return params; + } + + + /** + * 设置消息发给EM的参数,封装成一个Map + */ + public static Map sendMsgParams(MsgDataItem item) { + Map params = new HashMap<>(item.getSendParams()); + if (StringUtils.isNotBlank(item.getSenderid())) + params.put("senderid", item.getSenderid()); + if (StringUtils.isNotBlank(item.getUserids())) + params.put("userids", item.getUserids()); + if (StringUtils.isNotBlank(item.getMsgtype())) + params.put("msgtype", item.getMsgtype()); + if (StringUtils.isNotBlank(item.getAgentid())) + params.put("agentid", item.getAgentid()); + if (StringUtils.isNotBlank(item.getSend_type())) + params.put("send_type", item.getSend_type()); + Map shareParams = new HashMap<>(); + if (params.get("share") != null) { + shareParams = (Map) JSONObject.toJSON(params.get("share")); + } + if (StringUtils.isNotBlank(item.getContent())) + shareParams.put("content", item.getContent()); + Map extraParams = new HashMap<>(); + if (shareParams.get("extra") != null) { + extraParams = (Map) JSONObject.toJSON(shareParams.get("extra")); + } + if (StringUtils.isNotBlank(item.getDesc())) + extraParams.put("desc", item.getDesc()); + if (StringUtils.isNotBlank(item.getLinkurl())) + extraParams.put("linkurl", item.getLinkurl()); + if (StringUtils.isNotBlank(item.getLinkurl_pc())) + extraParams.put("linkurl_pc", item.getLinkurl_pc()); + if (StringUtils.isNotBlank(item.getOpentype())) + extraParams.put("opentype", item.getOpentype()); + if (StringUtils.isNotBlank(item.getOpentype_pc())) + extraParams.put("opentype_pc", item.getOpentype_pc()); + if (StringUtils.isNotBlank(item.getCanforward())) + extraParams.put("canforward", item.getCanforward()); + if (StringUtils.isNotBlank(item.getSharetypename())) + extraParams.put("sharetypename", item.getSharetypename()); + if (StringUtils.isNotBlank(item.getSharetype())) + extraParams.put("sharetype", item.getSharetype()); + if (StringUtils.isNotBlank(item.getShareid())) + extraParams.put("shareid", item.getShareid()); + shareParams.put("extra", extraParams); + params.put("share", shareParams); + + return params; + } + + public static String delHTMLTag(String htmlStr) { + if (htmlStr != null) { + htmlStr = htmlStr.replaceAll("\\

|
|
|
", "\n"); + + htmlStr = htmlStr.replaceAll(" ", " "); + + String regEx_html = "(]*)(>)"; + Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); + Matcher m_html = p_html.matcher(htmlStr); + + htmlStr = m_html.replaceAll("[" + SystemEnv.getHtmlLabelName(74, 7) + "]"); //过滤html标签 + regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式 + p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); + m_html = p_html.matcher(htmlStr); + htmlStr = m_html.replaceAll(""); //过滤html标签 + return htmlStr.trim(); + } + return null; + + } + + /** + * 创建EC在EM的消息型应用 + */ + public static String CreateMsgTypeApp(String img_url, String name, String description, String dialog_url, String sendmobile) { + MsgDataItem item = createMsgDataItem(img_url, 2, name, description, checkDialogUrl_New(dialog_url), checkDialogUrl_Old(dialog_url), sendmobile); + return getAgentId(item); + } + + /** + * 创建EC在EM的消息型应用 + */ + public static String CreateMsgTypeApp(String img_url, String name, String description, String app_Dialog_url, String pc_Dialogurl, String sendmobile) { + MsgDataItem item = createMsgDataItem(img_url, 2, name, description, checkDialogUrl_New(app_Dialog_url), checkDialogUrl_Old(pc_Dialogurl), sendmobile); + return getAgentId(item); + } + + public static String getDialog_Url(String belongId, String isTab) { + String dialog_url = MsgToEMConstant.DIALOG_URL + belongId; + //新到达流程 + if (MsgToEMConstant.IS_TAB.equals(isTab)) + dialog_url += MsgToEMConstant.DIALOG_URL_Flag; + return dialog_url; + } + + + /** + * 用于创建消息型应用的时候,获取默认的EM PC端地址 + * + * @param id ecology_biz_mobile_config 表中的id + * @return + */ + public static String getEM_PC_DialogUrl(String id) { + String dialog_url = MsgToEMConstant.DIALOG_URL + id; + return dialog_url; + } + + + /** + * 用于创建消息型应用的时候,获取默认的EM 移动端地址 + * + * @param id ecology_biz_mobile_config 表中的id + * @return + */ + public static String getEM_APP_DialogUrl(String id) { + String dialog_url = MsgToEMConstant.DIALOG_URL_NEW + id; + return dialog_url; + } + + + //上传图片,setlogo + public static MsgDataItem mediaUpload(MsgDataItem item) { + if (StringUtils.isNotBlank(item.getImg_url())) { + FileNamingManager manager = FileNamingManager.getInstance(); + String fileUrl = manager.unTransform(item.getImg_url()); + String fileid = fileUrl.replaceAll("/weaver/weaver.file.FileDownload\\?fileid=", ""); + ImageFileManager imageFileManager = new ImageFileManager(); + InputStream input; + String responseData = null; + try { + if (StringUtils.isNumeric(fileid)) { + imageFileManager.getImageFileInfoById(Util.getIntValue(fileid)); + responseData = APPManager.mediaUpload("image", imageFileManager.getImageFileType(), imageFileManager.getInputStream(), "media", imageFileManager.getImageFileName()); + + } else if ((input = AppSyncUtil.getFileInputSteam(null, item.getImg_url())) != null) { + responseData = APPManager.mediaUpload("image", AppSyncUtil.getFileType(item.getImg_url()), input, "media", AppSyncUtil.getFileName(item.getImg_url())); + } else { + return null; + } + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + JSONObject objectData = JSONObject.parseObject(responseData); + if (objectData != null && objectData.getIntValue("errcode") != 0) { + log.error(objectData.getString("errmsg")); + return null; + } + if (objectData != null) + item.setLogo(objectData.getString("media_id")); + else + log.info("==========" + item.getName() + " 图片为空 ========"); + return item; + } + return null; + } + + public static String getAgentId(MsgDataItem item) { + if (StringUtils.isBlank(item.getAgentid()) && StringUtils.isNotBlank(item.getImg_url())) { + String responseData = null; + item = mediaUpload(item); + if (item != null) { + Map params = createAppParams(item);//将参数基类转化为map + try { + responseData = APPManager.createApp(params);//创建应用 + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + JSONObject objectData = JSONObject.parseObject(responseData); + if (objectData != null && objectData.getIntValue("errcode") != 0) { + log.error(objectData.getString("errmsg")); + return null; + } + return objectData.getString("agentid"); + } + return null; + } + return null; + } + + + public static boolean getApp(String agentid) { + if (StringUtils.isNotBlank(agentid)) { + Map param = new HashMap(); + String responseData = null; + param.put("agentid", agentid); + try { + responseData = APPManager.getApp(param);//获取单个应用 + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + JSONObject objectData = JSONObject.parseObject(responseData); + if (objectData != null && objectData.getIntValue("errcode") != 0) { + log.error(objectData.getString("errmsg")); + return false; + } + return true; + } + return false; + } + + + public static String send(MsgDataItem item) { + String responseData = null; + try { + responseData = APPManager.send(sendMsgParams(item)); + } catch (KeyManagementException e) { + log.error("消息推送到EM平台失败:" + e); + } catch (NoSuchAlgorithmException e) { + log.error("消息推送到EM平台失败:" + e); + } + + JSONObject objectData = JSONObject.parseObject(responseData); + if (objectData != null && objectData.getIntValue("errcode") != 0) + log.error("消息推送到EM错误信息:" + objectData.getString("errmsg")); + return responseData; + } + + + /** + * 设置在EM创建消息型应用的参数 + * + * @param message 发送的消息体 + */ + + public static void sendMsg(MessageBean message) { + for (MessageBean messageBean : getLangMsgList(message)) { + send(sendMsgDataItem(messageBean)); + } + } + + + /** + * 设置消息发给EM的参数 + * + * @return + */ + public static MsgDataItem sendMsgDataItem(MessageBean messageBean) { + + StringBuilder str = new StringBuilder(); + String senderid = messageBean.getEmParams().get("senderid") == null ? Util.null2String(messageBean.getCreater()) : Util.null2String(messageBean.getEmParams().get("senderid")); +// String userids = messageBean.getEmParams().get("userids") == null ? null : Util.null2String(messageBean.getEmParams().get("userids")); + String userids; + String msgtype = messageBean.getEmParams().get("msgtype") == null ? "share" : Util.null2String(messageBean.getEmParams().get("msgtype")); + String agentid = messageBean.getEmParams().get("agentid") == null ? messageBean.getAgentId() : Util.null2String(messageBean.getEmParams().get("agentid")); + String send_type = messageBean.getEmParams().get("send_type") == null ? "1" : Util.null2String(messageBean.getEmParams().get("send_type")); + Map shareMap = messageBean.getEmParams().get("share") == null ? new HashMap() : (Map) JSONObject.toJSON(messageBean.getEmParams().get("share")); + String title; + if (StringUtils.isNotBlank(messageBean.getDetailTitle()) && !messageBean.getMessageGroupTypeName().equals(messageBean.getDetailTitle())) + title = shareMap.get("content") == null ? messageBean.getDetailTitle() + ": " + delHTMLTag(messageBean.getTitle()) : Util.null2String(shareMap.get("content")); + else + title = shareMap.get("content") == null ? delHTMLTag(messageBean.getTitle()) : Util.null2String(shareMap.get("content")); + + + Map extraMap = shareMap.get("extra") == null ? new HashMap() : (Map) JSONObject.toJSON(shareMap.get("extra")); + String content = extraMap.get("desc") == null ? delHTMLTag(messageBean.getContext()) : Util.null2String(extraMap.get("desc")); + String linkurl = extraMap.get("linkurl") == null ? messageBean.getLinkMobileUrl() : Util.null2String(extraMap.get("linkurl")); + String linkurl_pc = extraMap.get("linkurl_pc") == null ? messageBean.getLinkUrl() : Util.null2String(extraMap.get("linkurl_pc")); +// String linkurl = extraMap.get("linkurl") == null ? "/message.jsp?linkurl=" + codeBase64(messageBean.getLinkUrl()) + "&linkmobileurl="+codeBase64(messageBean.getLinkMobileUrl()) : Util.null2String(extraMap.get("linkurl")); +// String linkurl_pc = extraMap.get("linkurl_pc") == null ? "/message.jsp?linkurl="+ codeBase64(messageBean.getLinkUrl()) + "&linkmobileurl="+codeBase64(messageBean.getLinkMobileUrl()) : Util.null2String(extraMap.get("linkurl_pc")); + String opentype = extraMap.get("opentype") == null ? "1" : Util.null2String(extraMap.get("opentype")); + String opentype_pc = extraMap.get("opentype_pc") == null ? "2" : Util.null2String(extraMap.get("opentype_pc")); + String canforward = extraMap.get("canforward") == null ? "0" : Util.null2String(extraMap.get("canforward")); + String callbackurl = extraMap.get("callbackurl") == null ? "" : Util.null2String(extraMap.get("callbackurl")); + String sharetypename = extraMap.get("sharetypename") == null ? messageBean.getDetailTitle() : Util.null2String(extraMap.get("sharetypename")); + String sharetype = extraMap.get("sharetype") == null ? null : Util.null2String(extraMap.get("sharetype")); + String shareid = extraMap.get("shareid") == null ? null : Util.null2String(extraMap.get("shareid")); + + if (messageBean.getUserList().size() == 0) { + userids = Util.null2String(messageBean.getUserId()); + } else { + for (String userid : messageBean.getUserList()) + str.append(userid).append("|"); + userids = str.toString().substring(0, str.length() - 1);//去掉最后一个“|” + } + + if (StringUtils.isNotBlank(Util.null2String(messageBean.getEmParams().get("userids")))) + userids = userids + "|" + Util.null2String(messageBean.getEmParams().get("userids")); + + if (StringUtils.isBlank(sharetype) && StringUtils.isNotBlank(messageBean.getTargetId())) { + sharetype = "workflow"; + shareid = messageBean.getTargetId(); + } + + + if ("share".equals(msgtype) && StringUtils.isBlank(linkurl)) { + msgtype = "text"; + Map textMap = new HashMap<>(); + if (StringUtils.isNotBlank(messageBean.getDetailTitle()) && !messageBean.getMessageGroupTypeName().equals(messageBean.getDetailTitle())) + textMap.put("content", messageBean.getDetailTitle() + ": " + delHTMLTag(messageBean.getTitle()) + "\n" + delHTMLTag(messageBean.getContext())); + else + textMap.put("content", delHTMLTag(messageBean.getTitle()) + "\n" + delHTMLTag(messageBean.getContext())); + Map map = new HashMap<>(); + map.put("text", textMap); + map.put("safe", 0); + messageBean.getEmParams().putAll(map); + } + //如果是此消息id是需要修改的消息则替换为空 + String msgTypeId = (Util.null2String(Prop.getPropValue("QC2586804", "msgtype"))); + if (msgTypeId.contains(messageBean.getMessageGroupType())){ + title=title.replace(":","\u0020"); + // if (title.indexOf("-")>0){ + // title = title.split("-")[1]; + // } + // agentid = "87"; + } + return sendMsgDataItem(senderid, userids, msgtype, agentid, send_type, title, content, linkurl, + linkurl_pc, opentype, opentype_pc, canforward, callbackurl, sharetype, shareid, sharetypename, messageBean.getEmParams()); + } + + + public static List getLangMsgList(MessageBean message) { + List messageBeanList = new ArrayList<>(); + Map lang_map = new HashMap<>(); + int userLang; + if (message.getUserList().isEmpty()) + message.getUserList().add(Util.null2String(message.getUserId())); + for (String userid : message.getUserList()) { + userLang = User.getUserLang(Util.getIntValue(userid, 0)); + if (!lang_map.containsKey(userLang)) { + Set userSet = new HashSet<>(); + userSet.add(userid); + lang_map.put(userLang, userSet); + } else { + lang_map.get(userLang).add(userid); + } + } + for (Map.Entry entry : lang_map.entrySet()) { + MessageBean messageBean = message.shallowClone(); + messageBean.setUserList(entry.getValue()); + messageBean.setMessageGroupTypeName(Util.formatMultiLang(messageBean.getMessageGroupTypeName(), entry.getKey() + "")); + messageBean.setDetailTitle(MsgTypeUtil.spilt(messageBean.getDetailTitle(), entry.getKey())); + messageBean.setTitle(Util.formatMultiLang(messageBean.getTitle(), entry.getKey() + "")); + messageBean.setContext(Util.formatMultiLang(messageBean.getContext(), entry.getKey() + "")); + messageBeanList.add(messageBean); + } + return messageBeanList; + + } + + + public static boolean updateMsgTypeApp(String agentid, String img_url, String name, String description, String sendmobile) { + String responseData = null; + + MsgDataItem item = updateMsgDataItem(agentid, img_url, 2, name, description, null, null, sendmobile); + item = mediaUpload(item); + + try { + responseData = APPManager.updateApp(createAppParams(item)); + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + JSONObject objectData = JSONObject.parseObject(responseData); + if (objectData != null && objectData.getIntValue("errcode") != 0) { + log.error(objectData.getString("errmsg")); + return false; + } + return true; + + } + + public static boolean updateMsgTypeApp(String agentid, String img_url, String name, String description, String dialogurl, String sendmobile) { + String responseData = null; + + MsgDataItem item = updateMsgDataItem(agentid, img_url, 2, name, description, checkDialogUrl_New(dialogurl), checkDialogUrl_Old(dialogurl), sendmobile); + item = mediaUpload(item); + if (StringUtils.isBlank(item.getLogo())) + return false; + + try { + responseData = APPManager.updateApp(createAppParams(item)); + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + JSONObject objectData = JSONObject.parseObject(responseData); + if (objectData != null && objectData.getIntValue("errcode") != 0) { + log.error(objectData.getString("errmsg")); + return false; + } + return true; + + } + + + public static boolean updateMsgTypeApp(String agentid, String img_url, String name, String description, String dialogurl, String dialogurl_pc, String sendmobile) { + String responseData = null; + + MsgDataItem item = updateMsgDataItem(agentid, img_url, 2, name, description, checkDialogUrl_New(dialogurl), checkDialogUrl_Old(dialogurl_pc), sendmobile); + item = mediaUpload(item); + if (StringUtils.isBlank(item.getLogo())) + return false; + + try { + responseData = APPManager.updateApp(createAppParams(item)); + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + JSONObject objectData = JSONObject.parseObject(responseData); + if (objectData != null && objectData.getIntValue("errcode") != 0) { + log.error(objectData.getString("errmsg")); + return false; + } + return true; + + } + + public static boolean updateMsgBizType(String id, String imgurl, String group, String enable, String enablepc, String enableem, String sendmobile) { + RecordSet rs = new RecordSet(); + boolean flag; + rs.executeUpdate("update ecology_biz_mobile_config set groupid = ? , enable = ? ,enablepc = ?,enableem = ? ,imgurl=?, sendmobile = ? where belongid = ? and biztypeid is not null ", group, enable, enablepc, enableem, imgurl, sendmobile, id); + rs.executeQuery("select * from ecology_biz_mobile_config where belongid = ? and biztypeid is not null ", id); + while (rs.next()) { + if (StringUtils.isNotBlank(rs.getString("agentid"))) { + flag = updateMsgTypeApp(rs.getString("agentid"), rs.getString("imgurl"), rs.getString("name"), rs.getString("description"), rs.getString("em_app_url"), rs.getString("dialogurl"), rs.getString("sendmobile")); + } + } + return true; + } + + public static void deleteMsgTypeApp(String agentids) { + try { + String[] agentid = agentids.split(","); + for (String id : agentid) { + String data = APPManager.delete(id); + log.info(data); + } + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + } + + public static void deleteMsgBizType(String ids) { + String[] idStr = Util.splitString(ids, ","); + RecordSet rs = new RecordSet(); + for (String id : idStr) { + rs.executeQuery("select * from ecology_biz_mobile_config where belongid = ? and biztypeid is not null ", id); + while (rs.next() && StringUtils.isNotBlank(rs.getString("agentid"))) { + deleteMsgTypeApp(rs.getString("agentid")); + } + rs.executeUpdate("delete from ecology_biz_mobile_config where belongid = ? and biztypeid is not null ", id); + } + } + + /** + * 初始化更新保存在EC的EM消息型应用地址 dialogurl + * + * @return + */ + public static void initDialogUrlOld() { + //EM移动端地址在EC数据库中初始化 + RecordSet rs = new RecordSet(); + rs.executeQuery("select id,dialogurl,is_em_app_url from ECOLOGY_BIZ_MOBILE_CONFIG where is_em_app_url = ?", "n"); + List params = new ArrayList<>(); + while (rs.next()) { + if (("n").equals(rs.getString("is_em_app_url"))) { + if (rs.getString("dialogurl")!= null && rs.getString("dialogurl").startsWith(MsgToEMConstant.DIALOG_URL)){ + List list = new ArrayList<>(); + list.add(checkDialogUrl_New(rs.getString("dialogurl"))); + list.add("y"); + list.add(rs.getString("id")); + params.add(list); + } + } + } + + rs.executeBatchSql("update ECOLOGY_BIZ_MOBILE_CONFIG set em_app_url = ? ,is_em_app_url = ? where id = ? ", params); + + // EM移动端地址在EM初始化 + if (EMManager.getJoinStatus(true)) { + RecordSet recordSet = new RecordSet(); + int random = (int) (Math.random() * 1000); + rs.executeQuery("select id,agentid,imgurl,name,dialogurl,em_app_url,sendmobile,belongid,is_dialogurl,is_em_app_url from ECOLOGY_BIZ_MOBILE_CONFIG where agentid is not null"); + while (rs.next()) { + if (StringUtils.isNotBlank(rs.getString("agentid"))) { + // 修复客户交流提醒数据 + if("28".equals(rs.getString("id")) && "y".equals(rs.getString("is_em_app_url"))){ + try { + boolean flag = MsgECToEM.updateMsgTypeApp(rs.getString("agentid"), rs.getString("imgurl"), rs.getString("name"), "", randomDialogUrl(checkDialogUrl_New("/spa/crm/static4mobile/index.html#/remind"), random), randomDialogUrl(checkDialogUrl_Old(rs.getString("dialogurl")), random), rs.getString("sendmobile")); + if (flag) + recordSet.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set is_em_app_url =? where id = ? ", "n", rs.getString("id")); + } catch (Exception e) { + e.printStackTrace(); + } + } + + if (("n").equals(rs.getString("is_dialogurl"))) { + try { + boolean flag = MsgECToEM.updateMsgTypeApp(rs.getString("agentid"), rs.getString("imgurl"), rs.getString("name"), "", randomDialogUrl(checkDialogUrl_New(rs.getString("em_app_url")), random), randomDialogUrl(checkDialogUrl_Old(rs.getString("dialogurl")), random), rs.getString("sendmobile")); + if (flag) + recordSet.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set dialogurl = ?,is_dialogurl=? where id = ? ", checkDialogUrl_Old(rs.getString("dialogurl")), "y", rs.getString("id")); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + } + + } + + /** + * 检测保存在EC的EM消息型应用地址,并添加一个随机数用于EM手机端刷新地址缓存 + * + * @param dialogurl EM消息型应用地址 + * @param random 随机数 + * @return + */ + public static String randomDialogUrl(String dialogurl, int random) { + if (dialogurl.startsWith(MsgToEMConstant.DIALOG_URL) || dialogurl.startsWith(MsgToEMConstant.DIALOG_URL_NEW)) { + // dialogurl = checkDialogUrl(dialogurl); //检测dialogUrl + String[] dialogurls = dialogurl.split("\\?"); + if (dialogurls.length > 1) + dialogurl = dialogurl.replaceAll("#", "?" + dialogurls[1] + "&v=test" + random + "#"); + else + return null; + } + return dialogurl; + } + + /** + * 检测保存在EC的EM消息型应用地址 + * + * @param dialogurl EM消息型应用地址 + * @return 新的dialogurl + */ + public static String checkDialogUrl_New(String dialogurl) { + if (StringUtils.isNotBlank(dialogurl) && dialogurl.startsWith(MsgToEMConstant.DIALOG_URL)) + dialogurl = dialogurl.replace(MsgToEMConstant.DIALOG_URL, MsgToEMConstant.DIALOG_URL_NEW); + return dialogurl; + } + + + /** + * 检测保存在EC的EM消息型应用地址 + * + * @param dialogurl_Old EM消息型应用地址 + * @return 旧的dialogurl + */ + public static String checkDialogUrl_Old(String dialogurl_Old) { + if (StringUtils.isNotBlank(dialogurl_Old) && dialogurl_Old.startsWith(MsgToEMConstant.DIALOG_URL_NEW)) + dialogurl_Old = dialogurl_Old.replace(MsgToEMConstant.DIALOG_URL_NEW, MsgToEMConstant.DIALOG_URL); + return dialogurl_Old; + } + + + /** + * 确保消息类型对应的agentid参数更新为真正需要推向EM的agentid + */ + public static void insureMessageType(MessageBean bean) { + if (bean != null) { + String agentName = bean.getMessageGroupTypeName(); +// String dialogUrl = MsgToEMConstant.DIALOG_URL + bean.getMessageGroupType(); + String app_Dialogurl = getEM_APP_DialogUrl(bean.getMessageGroupType()); + String pc_Dialogurl = getEM_PC_DialogUrl(bean.getMessageGroupType()); + + String biztypeid = bean.getMessageGroupType() + "," + bean.getBizType(); + boolean isAssistant = false; + + RecordSet rs = new RecordSet(); + String agentid = null; + rs.executeQuery("select * from ECOLOGY_BIZ_MOBILE_CONFIG where id = ? ", bean.getMessageGroupType()); + if (rs.next()) { + agentid = rs.getString("agentid"); + app_Dialogurl = rs.getString("em_app_url"); + pc_Dialogurl = rs.getString("dialogurl"); + } + //1、对业务类型的处理 + if (StringUtils.isNotBlank(bean.getBizType()) && ConstantMapping.booleanOfString(bean.getIsDefault())) { + agentName = bean.getBizTitle(); + app_Dialogurl = MsgToEMConstant.DIALOG_URL_NEW + bean.getMessageGroupType() + "," + bean.getBizType(); + pc_Dialogurl = MsgToEMConstant.DIALOG_URL + bean.getMessageGroupType() + "," + bean.getBizType(); + isAssistant = true; + } + + + if (!isAssistant) { + //3、如果不是业务类型,当agentid为空时调用EM接口创建应用并更新 + if (StringUtils.isBlank(agentid)) { + //消息类型 + String agentId = CreateMsgTypeApp(bean.getImgUrl(), agentName, agentName, app_Dialogurl, pc_Dialogurl, bean.getSendMobile()); + rs.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set agentid=? where id=?", agentId, bean.getMessageGroupType()); + bean.setAgentId(agentId); + } else + bean.setAgentId(agentid); + } else { + //4、如果是业务类型,查询业务类型对应的agentid + rs.executeQuery("select * from ECOLOGY_BIZ_MOBILE_CONFIG where biztypeid = ? ", "2,-1," + bean.getBizType());//查询老的业务类型 + if (rs.next()) { + String eid = rs.getString("id"); + String img_url = rs.getString("imgurl"); + rs.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set NAME = ? , DIALOGURL = ? , em_app_url = ?,BIZTYPEID = ? where id = ?", bean.getBizTitle(), pc_Dialogurl, app_Dialogurl, biztypeid, eid); + updateMsgTypeApp(rs.getString("agentid"), img_url, bean.getBizTitle(), "", app_Dialogurl, pc_Dialogurl, bean.getSendMobile()); + } + + + rs.executeQuery("select name,agentid,em_app_url,dialogurl from ecology_biz_mobile_config where biztypeid=?", biztypeid); + if (rs.next()) { + //5、当前业务类型已经创建EM应用时则更新消息实体中agentid参数即可 + if (StringUtils.isNotBlank(rs.getString("agentid"))) { + bean.setAgentId(rs.getString("agentid")); + app_Dialogurl = rs.getString("em_app_url"); + pc_Dialogurl = rs.getString("dialogurl"); + if (!rs.getString("name").equals(bean.getBizTitle())) { + log.info("================update biztitle to EM ===================="); + updateMsgTypeApp(bean.getAgentId(), bean.getImgUrl(), bean.getBizTitle(), "", app_Dialogurl, pc_Dialogurl, bean.getSendMobile()); + rs.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set name=? where biztypeid=?", bean.getBizTitle(), biztypeid); + rs.executeUpdate("update ECOLOGY_MESSAGE_BIZ_TYPE set biztitle = ? where messagegrouptype = ? and biztype = ?", bean.getBizTitle(), bean.getMessageGroupType(), bean.getBizType()); + } + } else { + //6、当前业务类型没有创建EM应用时则调用EM接口创建应用并更新 + String agentId = CreateMsgTypeApp(bean.getImgUrl(), agentName, agentName, app_Dialogurl, pc_Dialogurl, bean.getSendMobile()); + rs.executeUpdate("update ECOLOGY_BIZ_MOBILE_CONFIG set agentid=? ,dialogurl = ?,em_app_url = ? where biztypeid=?", agentId, pc_Dialogurl, app_Dialogurl, biztypeid); + bean.setAgentId(agentId); + } + } else { + //7、如果当前业务类型是第一次接收,调用EM接口创建并更新即可 + String agentId = CreateMsgTypeApp(bean.getImgUrl(), agentName, agentName, app_Dialogurl, pc_Dialogurl, bean.getSendMobile()); + rs.executeUpdate("insert into ECOLOGY_BIZ_MOBILE_CONFIG (id,name,messagetypeid,belongid,biztypeid,moduleid,groupid,agentid,dialogurl,em_app_url,imgurl,enable,enablepc,enableem,sendmobile,isshow,isdefault) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + WeaIndexManager.getGuid(8), + bean.getBizTitle(), + bean.getMessageGroupType(), + bean.getBelongId(), + biztypeid, + bean.getModuleId(), + null, + agentId, + pc_Dialogurl, + app_Dialogurl, + bean.getImgUrl(), + bean.getEnable(), + bean.getEnablePC(), + bean.getEnableEM(), + bean.getSendMobile(), + ConstantMapping.CONST_N, + ConstantMapping.CONST_N); + bean.setAgentId(agentId); + } + } + } + } + +} diff --git a/com/engine/tjbankSocket/impl/CWGLSocketExecute.java b/com/engine/tjbankSocket/impl/CWGLSocketExecute.java index 6b128ac..182e213 100644 --- a/com/engine/tjbankSocket/impl/CWGLSocketExecute.java +++ b/com/engine/tjbankSocket/impl/CWGLSocketExecute.java @@ -29,7 +29,7 @@ public class CWGLSocketExecute extends BaseBean implements SocketExecute { Map resultMap = null; int userid = 0; try { - resultMap = getBeanByOAnum(oaTrvlBnsExpnsAcctNo, "formtable_main_281"); + resultMap = getBeanByOAnum(oaTrvlBnsExpnsAcctNo, "formtable_main_295"); } catch (Exception e) { e.printStackTrace(); return XMLUtils.CW2XML(paramMap, "1", e.getMessage()); @@ -79,7 +79,7 @@ public class CWGLSocketExecute extends BaseBean implements SocketExecute { private void updateStatus(int requestid, String flowStatus) throws Exception { try { RecordSet recordSet = new RecordSet(); - recordSet.executeUpdate("update formtable_main_281 set cwxtzt = ? where requestId = ?", flowStatus, requestid); + recordSet.executeUpdate("update formtable_main_295 set cwxtzt = ? where requestId = ?", flowStatus, requestid); } catch (Exception e) { throw new Exception("更新状态失败"); } @@ -112,8 +112,9 @@ public class CWGLSocketExecute extends BaseBean implements SocketExecute { } public static void main(String[] args) { - String rootPath = "D:\\WEAVER2\\ecology\\"; - GCONST.setRootPath(rootPath); - GCONST.setServerName("ecology"); + HashMap paramMap = new HashMap<>(); + String sgntrOpn = paramMap.get("sgntrOpn"); + sgntrOpn = "(" + 1111 + "):" + sgntrOpn; + System.out.println(sgntrOpn); } } diff --git a/com/engine/tjyh/xc/cmd/Test.java b/com/engine/tjyh/xc/cmd/Test.java new file mode 100644 index 0000000..0a9ff58 --- /dev/null +++ b/com/engine/tjyh/xc/cmd/Test.java @@ -0,0 +1,759 @@ +package com.engine.tjyh.xc.cmd; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import weaver.general.TimeUtil; +import weaver.general.Util; + +/** + * TODO + * + * @Description + * @Author matrix + * @Date 2023/8/12 18:15 + **/ +public class Test { + + public static void main(String[] args) { + String in = "{\n" + + " \"ItineraryList\": [\n" + + " {\n" + + " \"JourneyNO\": null,\n" + + " \"FlightOrderInfoList\": [\n" + + " {\n" + + " \"BasicInfo\": {\n" + + " \"OrderID\": \"26307778053\",\n" + + " \"TripID\": \"0\",\n" + + " \"OrderStatus\": \"全部退票\",\n" + + " \"OrderStatusCode\": \"R\",\n" + + " \"UID\": \"2188872790\",\n" + + " \"PreEmployName\": \"朱琴\",\n" + + " \"EmployeeID\": \"10110551\",\n" + + " \"AccountID\": 989019,\n" + + " \"SubAccountID\": 1098980,\n" + + " \"CorpPayType\": \"因公\",\n" + + " \"CreateTime\": \"2023-08-11 12:47:55\",\n" + + " \"FinishDate\": \"2023-08-11 12:50:41\",\n" + + " \"PrintTicketTime\": \"2023-08-11 12:50:41\",\n" + + " \"FlightClass\": \"N\",\n" + + " \"FlightWay\": \"单程\",\n" + + " \"Remarks\": \"\",\n" + + " \"PreBookDays\": 36,\n" + + " \"ServiceDetailInfo\": {\n" + + " \"BaseServiceFee\": 0,\n" + + " \"BindServiceFee\": 0,\n" + + " \"SpecialServiceFee\": 0,\n" + + " \"UnWorkTimeServiceFee\": 0,\n" + + " \"VIPServiceFee\": 0,\n" + + " \"ItineraryFeeForRMB\": 0,\n" + + " \"ItineraryFeeForForeign\": 0,\n" + + " \"TechnicalServiceFee\": 0,\n" + + " \"PresentInsuranceServiceFee\": 0\n" + + " },\n" + + " \"NBillingType\": \"D\",\n" + + " \"TicketStatus\": \"A\",\n" + + " \"RebookOrderID\": \"\",\n" + + " \"ServerFrom\": \"App\",\n" + + " \"IsOfficialCard\": \"\",\n" + + " \"BookingChannel\": \"App\",\n" + + " \"PlatformOrderID\": \"\",\n" + + " \"PayExchangeRate\": 1,\n" + + " \"OperationCode\": 3,\n" + + " \"Amount\": 2300,\n" + + " \"TravelMoney\": 0,\n" + + " \"ChangeAmount\": 0,\n" + + " \"RefundAmount\": 0,\n" + + " \"CCardPayFee\": 0,\n" + + " \"SendTicketFee\": 0,\n" + + " \"InsuranceFee\": 0,\n" + + " \"PrepayType\": \"MAPAY\",\n" + + " \"TotalServiceFee\": 0,\n" + + " \"Currency\": \"CNY\",\n" + + " \"ForeignAmount\": 2300,\n" + + " \"Refundable\": false,\n" + + " \"Rebookable\": false,\n" + + " \"JourneyID\": \"334388-1\",\n" + + " \"CostCenter\": \"信息技术部\",\n" + + " \"CostCenter2\": \"朱琴\",\n" + + " \"CostCenter3\": \"信息技术部\",\n" + + " \"CostCenter4\": \"\",\n" + + " \"CostCenter5\": \"\",\n" + + " \"CostCenter6\": \"\",\n" + + " \"DefineFlag\": \"2023-09-06 12:00\",\n" + + " \"DefineFlag2\": \"2023-09-07 12:00\",\n" + + " \"JourneyReason\": \"测试飞机退改签。\",\n" + + " \"Project\": \"CLSQDHZ-202308110025\",\n" + + " \"AuditStatus\": \"授权通过\",\n" + + " \"ConfirmPerson\": \"AUTOPASS_APPROVER\",\n" + + " \"ConfirmPerson2\": \"\",\n" + + " \"ConfirmPersonCC\": null,\n" + + " \"ConfirmPersonCC2\": null,\n" + + " \"ConfirmType\": \"A1;C0\",\n" + + " \"ConfirmType2\": \"\",\n" + + " \"PayMixed\": false,\n" + + " \"PaymentItemList\": [\n" + + " {\n" + + " \"PayType\": \"PERSONAL\",\n" + + " \"PayAmount\": 2300,\n" + + " \"ItemDetailList\": [\n" + + " {\n" + + " \"Sequence\": 1,\n" + + " \"PassengerId\": 194517689288163360,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"FeeCode\": \"FlightPackage-Refund\",\n" + + " \"FeeAmount\": 10\n" + + " },\n" + + " {\n" + + " \"Sequence\": 1,\n" + + " \"PassengerId\": 194517689288163360,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"FeeCode\": \"FlightPackage-AirportTransfer\",\n" + + " \"FeeAmount\": 10\n" + + " },\n" + + " {\n" + + " \"Sequence\": 1,\n" + + " \"PassengerId\": 194517689288163360,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"FeeCode\": \"TicketFee\",\n" + + " \"FeeAmount\": 2150\n" + + " },\n" + + " {\n" + + " \"Sequence\": 1,\n" + + " \"PassengerId\": 194517689288163360,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"FeeCode\": \"FlightPackage-Delay\",\n" + + " \"FeeAmount\": 20\n" + + " },\n" + + " {\n" + + " \"Sequence\": 1,\n" + + " \"PassengerId\": 194517689288163360,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"FeeCode\": \"FlightTax\",\n" + + " \"FeeAmount\": 50\n" + + " },\n" + + " {\n" + + " \"Sequence\": 1,\n" + + " \"PassengerId\": 194517689288163360,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"FeeCode\": \"FlightOilFee\",\n" + + " \"FeeAmount\": 60\n" + + " }\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"IsOnline\": \"T\",\n" + + " \"CorporationId\": \"TIANJINBANK\",\n" + + " \"DockingVendorPlatform\": 0,\n" + + " \"DockingVendorPlatformAccount\": null,\n" + + " \"CorpDockingInfoList\": null,\n" + + " \"airlineCountryIdEqualAccount\": null,\n" + + " \"PreEmployNamePinYin\": \"ZhuQin\",\n" + + " \"CancelAble\": false,\n" + + " \"NewTotalServiceFee\": 0\n" + + " },\n" + + " \"DeliveryInfo\": {\n" + + " \"DeliveryInfo\": \"无需报销凭证\",\n" + + " \"ContactPhone\": \"17612200533\",\n" + + " \"ContactMobile\": \"17612200533\",\n" + + " \"ContactName\": \"商旅客户\",\n" + + " \"DeliveryAddress\": \"\",\n" + + " \"ContactEmail\": \"\"\n" + + " },\n" + + " \"FlightInfo\": [\n" + + " {\n" + + " \"Sequence\": \"1\",\n" + + " \"Flight\": \"CA1507\",\n" + + " \"AirLineCode\": \"CA\",\n" + + " \"AirLineName\": \"中国国航\",\n" + + " \"Remark\": \"\",\n" + + " \"TakeoffTime\": \"2023-09-16 07:30:00\",\n" + + " \"ArrivalTime\": \"2023-09-16 10:00:00\",\n" + + " \"DCityName\": \"北京\",\n" + + " \"DCityName_EN\": \"Beijing\",\n" + + " \"DCityCode\": \"BJS\",\n" + + " \"DPortName\": \"首都国际机场\",\n" + + " \"DPortCode\": \"PEK\",\n" + + " \"Agreement\": \"非协议\",\n" + + " \"Amount\": 2260,\n" + + " \"Price\": 2150,\n" + + " \"PrintPrice\": 2150,\n" + + " \"PriceRate\": 1,\n" + + " \"StandardPrice\": 2150,\n" + + " \"HasMeal\": true,\n" + + " \"OilFee\": 60,\n" + + " \"Tax\": 50,\n" + + " \"Bindtype\": \"U\",\n" + + " \"BindNum\": 1,\n" + + " \"BindAmount\": 40,\n" + + " \"ServerFee\": 0,\n" + + " \"Subsidy\": 0,\n" + + " \"AgeType\": \"ADU\",\n" + + " \"Class\": \"Y\",\n" + + " \"ClassName\": \"经济舱\",\n" + + " \"ClassNameNew\": \"经济舱\",\n" + + " \"SubClass\": \"Y\",\n" + + " \"OfficeNo\": \"PEK841\",\n" + + " \"NonRer\": \"有条件改期\",\n" + + " \"RerNotes\": \"航班起飞前336小时(含)以外同等舱位免费更改,起飞前336小时(不含)内至航班起飞前48小时(含)收取票价5%的更改费,起飞前48小时(不含)内至起飞前4小时(含)收取票面价5%的更改费,起飞前4小时(不含)内及起飞后需收取票面价10%的更改费。改期费与升舱费同时发生时,需同时收取。(婴儿免收变更费)\",\n" + + " \"NonRef\": \"有条件退票\",\n" + + " \"RefNotes\": \"航班起飞前336小时(含)外免收退票费,起飞前336小时(不含)内至航班起飞前48小时(含)需收取票面价5%的退票费,起飞前48小时(不含)内至起飞前4小时(含)收取票面价10%的退票费,起飞前4小时(不含)内及起飞后需收取票面价15%的退票费。(婴儿免收退票费)\",\n" + + " \"NonEnd\": \"有条件签转\",\n" + + " \"EndNotes\": \"允许签转,如变更后承运人适用票价高于国航票价,需补齐票价差额后进行变更,同时收取变更手续费;如变更后承运人适用票价低于国航票价,可按自愿退票办理.如按照自愿变更办理,差额不退,同时收取变更手续费.\",\n" + + " \"Adtk\": \"\",\n" + + " \"FuelMileage\": 1178,\n" + + " \"EClassStandardPrice\": 2150,\n" + + " \"SpeicalClassTypeName\": \"\",\n" + + " \"SpeicalClassTypeDescription\": \"\",\n" + + " \"CraftType\": \"747\",\n" + + " \"DAirport\": {\n" + + " \"Name\": \"首都国际机场3号航站楼\",\n" + + " \"Name_en\": \"首都国际机场3号航站楼\",\n" + + " \"Shortname\": \"T3航站楼\",\n" + + " \"Shortname_en\": \"T3航站楼\"\n" + + " },\n" + + " \"ACityName\": \"上海\",\n" + + " \"ACityName_EN\": \"Shanghai\",\n" + + " \"ACityCode\": \"SHA\",\n" + + " \"APortName\": \"虹桥国际机场\",\n" + + " \"APortCode\": \"SHA\",\n" + + " \"AAirport\": {\n" + + " \"Name\": \"虹桥国际机场2号航站楼\",\n" + + " \"Name_en\": \"虹桥国际机场2号航站楼\",\n" + + " \"Shortname\": \"T2航站楼\",\n" + + " \"Shortname_en\": \"T2航站楼\"\n" + + " },\n" + + " \"IsOpenTran\": \"F\",\n" + + " \"IsSurface\": \"F\",\n" + + " \"Reason\": \"\",\n" + + " \"ReasonDesc\": \"您已选择预订时可订到的最低折扣航班\",\n" + + " \"PreBookReason\": \"\",\n" + + " \"PreBookReasonDesc\": \"\",\n" + + " \"LowFlight\": \"\",\n" + + " \"LowClass\": \"\",\n" + + " \"LowestPrice\": 0,\n" + + " \"LowRate\": 0,\n" + + " \"LowDTime\": \"\",\n" + + " \"Tpm\": 1087,\n" + + " \"ClassReason\": \"\",\n" + + " \"ClassReasonDesc\": \"\",\n" + + " \"AgreementReason\": \"\",\n" + + " \"AgreementReasonDesc\": \"\",\n" + + " \"DistanceReason\": \"\",\n" + + " \"DistanceReasonDesc\": \"\",\n" + + " \"FlightTime\": 150,\n" + + " \"AirlineRecordNo\": \"NDYHST\",\n" + + " \"FlightStopInfoList\": null,\n" + + " \"SaleType\": \"NORMAL\",\n" + + " \"PNR\": \"JP8PSH\",\n" + + " \"SegmentNo\": 1,\n" + + " \"ItineraryFee\": 0,\n" + + " \"ItineraryPassengers\": null,\n" + + " \"AgreementCode\": \"NA\",\n" + + " \"DepartureCountryCode\": \"CN\",\n" + + " \"ArrivalCountryCode\": \"CN\",\n" + + " \"TakeOffTimeUTC\": \"2023-09-15T23:30:00Z\",\n" + + " \"ArrivalTimeUTC\": \"2023-09-16T02:00:00Z\",\n" + + " \"Alliance\": \"星空联盟\",\n" + + " \"SectorType\": null,\n" + + " \"DepartureDistrictCode\": \"110000\",\n" + + " \"ArrivalDistrictCode\": \"310000\",\n" + + " \"SettlementAccntAmount\": 0,\n" + + " \"SettlementAccntPrice\": 0,\n" + + " \"SettlementAccntOilFee\": 0,\n" + + " \"SettlementAccntTax\": 0,\n" + + " \"SettlementIndividualAmount\": 2260,\n" + + " \"SettlementIndividualPrice\": 2150,\n" + + " \"SettlementIndividualOilFee\": 60,\n" + + " \"SettlementIndividualTax\": 50,\n" + + " \"ShareFlightNo\": null,\n" + + " \"ReasonCodeInfoList\": null\n" + + " }\n" + + " ],\n" + + " \"PassengerInfo\": [\n" + + " {\n" + + " \"PassengerBasic\": {\n" + + " \"CorpEid\": \"10110551\",\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"PassengerNamePY\": \"ZhuQin\",\n" + + " \"NationalityCode\": \"CN\",\n" + + " \"NationalityName\": \"中国\",\n" + + " \"CardTypeName\": \"身份证\",\n" + + " \"CardTypeNumber\": \"513701199709053029\",\n" + + " \"Gender\": \"F\",\n" + + " \"Birthday\": \"1997-09-05 00:00:00\",\n" + + " \"CostCenter\": \"信息技术部\",\n" + + " \"CostCenter2\": \"朱琴\",\n" + + " \"CostCenter3\": \"信息技术部\",\n" + + " \"CostCenter4\": \"\",\n" + + " \"CostCenter5\": \"\",\n" + + " \"CostCenter6\": \"\",\n" + + " \"Dept1\": \"信息技术部\",\n" + + " \"Dept2\": \"\",\n" + + " \"Dept3\": \"\",\n" + + " \"Dept4\": \"\",\n" + + " \"Dept5\": \"\",\n" + + " \"Dept6\": \"\",\n" + + " \"Dept7\": \"\",\n" + + " \"Dept8\": \"\",\n" + + " \"Dept9\": \"\",\n" + + " \"Dept10\": \"\",\n" + + " \"CardValid\": \"\"\n" + + " },\n" + + " \"SequenceInfo\": [\n" + + " {\n" + + " \"Sequence\": 1,\n" + + " \"TicketInfo\": [\n" + + " {\n" + + " \"AirLineCode\": \"999\",\n" + + " \"TicketNo\": \"2327199524\",\n" + + " \"TicketNoSignCode\": \"999-2327199524\",\n" + + " \"Status\": \"6\",\n" + + " \"StatusDesc\": \"已退票\"\n" + + " },\n" + + " {\n" + + " \"AirLineCode\": \"999\",\n" + + " \"TicketNo\": \"2327200094\",\n" + + " \"TicketNoSignCode\": \"999-2327200094\",\n" + + " \"Status\": \"6\",\n" + + " \"StatusDesc\": \"已退票\"\n" + + " }\n" + + " ],\n" + + " \"InsuranceInfo\": null,\n" + + " \"ChangeInfo\": [\n" + + " {\n" + + " \"Sequence\": 1,\n" + + " \"RebookId\": 66966439,\n" + + " \"CPrepayType\": \"MAPAY\",\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"CStatus\": \"改签成功\",\n" + + " \"CFee\": 0,\n" + + " \"RebookServiceFee\": 0,\n" + + " \"RebookingTime\": \"2023-08-11 12:55:30\",\n" + + " \"RebookedTime\": \"2023-08-11 12:57:00\",\n" + + " \"OriTicketNO\": \"2327199524\",\n" + + " \"PreTicketNO\": \"2327199524\",\n" + + " \"CTicketNO\": \"2327200094\",\n" + + " \"CTicketNoSignCode\": \"999-2327200094\",\n" + + " \"CAirline\": \"CA\",\n" + + " \"CAirlineName\": \"中国国航\",\n" + + " \"CAirType\": \"747\",\n" + + " \"CFlight\": \"CA1507\",\n" + + " \"CPrintPrice\": 2150,\n" + + " \"OilFee\": 60,\n" + + " \"Tax\": 50,\n" + + " \"Subsidy\": 0,\n" + + " \"SubClass\": \"Y\",\n" + + " \"CClass\": \"Y\",\n" + + " \"CClassName\": \"经济舱\",\n" + + " \"CTakeOffTime\": \"2023-09-15 07:30:00\",\n" + + " \"CArrivalTime\": \"2023-09-15 10:00:00\",\n" + + " \"CDCityName\": \"北京\",\n" + + " \"CDPortName\": \"首都国际机场\",\n" + + " \"CDTerminal\": \"T3\",\n" + + " \"CACityName\": \"上海\",\n" + + " \"CAPortName\": \"虹桥国际机场\",\n" + + " \"CATerminal\": \"T2\",\n" + + " \"RebookStatus\": \"S\",\n" + + " \"PriceDifferential\": 0,\n" + + " \"DateChangeFee\": 0,\n" + + " \"SendTicketFee\": 0,\n" + + " \"OriAirLineCode\": \"999\",\n" + + " \"CAirLineCode\": \"999\",\n" + + " \"RebookResonDesc\": \"测试飞机改签。\",\n" + + " \"FlightTime\": \"150\",\n" + + " \"FlightStopInfoList\": null,\n" + + " \"OilFeeDifferential\": 0,\n" + + " \"SpecialClassName\": \"\",\n" + + " \"SpecialClassDesc\": \"\",\n" + + " \"JounaryNo\": \"\",\n" + + " \"AuthorizeStatus\": \"A\",\n" + + " \"CDPortCode\": \"PEK\",\n" + + " \"CAPortCode\": \"SHA\",\n" + + " \"RebookReasonDesc\": \"测试飞机改签。\",\n" + + " \"RebookType\": \"0\",\n" + + " \"CACityCode\": \"SHA\",\n" + + " \"CDCityCode\": \"BJS\",\n" + + " \"TaxDifferential\": 0,\n" + + " \"TakeOffTimeUTC\": \"2023-09-14T23:30:00Z\",\n" + + " \"ArrivalTimeUTC\": \"2023-09-15T02:00:00Z\",\n" + + " \"PriceRate\": 1,\n" + + " \"DepartureCountryCode\": \"CN\",\n" + + " \"ArrivalCountryCode\": \"CN\",\n" + + " \"FlightWay\": \"\",\n" + + " \"DepartureDistrictCode\": \"110000\",\n" + + " \"ArrivalDistrictCode\": \"310000\",\n" + + " \"CheckTicketPrice\": 0,\n" + + " \"ShareFlightNo\": \"\",\n" + + " \"OriginalTicketNoSignCode\": \"999-2327199524\",\n" + + " \"PreTicketNoSignCode\": \"999-2327199524\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"RefundInfo\": [\n" + + " {\n" + + " \"TokenNO\": \"\",\n" + + " \"Audited\": \"F\",\n" + + " \"PayCustomerAmount\": 2260,\n" + + " \"PayCustomerTravelMoney\": 0,\n" + + " \"RefundAplyTime\": \"2023-08-11 13:02:30\",\n" + + " \"RefundAuditedTime\": \"\",\n" + + " \"RefundTime\": \"2023-08-11 13:04:08\",\n" + + " \"RefundDesc\": \"行程单未打印;航段1 自愿 朱琴,退/改金额0.00,费率0.00。 航段1 自愿 朱琴,退/改金额0.00,费率0.00。\",\n" + + " \"RefundOrderID\": 183992901,\n" + + " \"RefundStatus\": \"S\",\n" + + " \"RefundStatusDesc\": \"已退款\",\n" + + " \"RefundResonDesc\": \"测试退票。\",\n" + + " \"PrepareApprovalNo\": null,\n" + + " \"RefundEmergency\": false,\n" + + " \"RefundDetail\": [\n" + + " {\n" + + " \"Sequence\": 1,\n" + + " \"AirLineCode\": \"999\",\n" + + " \"TicketNo\": \"2327200094\",\n" + + " \"TicketNoSignCode\": \"999-2327200094\",\n" + + " \"Flight\": \"CA1507\",\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"RefundFee\": 0,\n" + + " \"RefundRate\": 0,\n" + + " \"RefundServiceFee\": 0,\n" + + " \"Subsidy\": 0,\n" + + " \"RebookingListID\": 66966439,\n" + + " \"RebookingID\": 66966439,\n" + + " \"UsedAmount\": 0,\n" + + " \"UsedTax\": 0,\n" + + " \"UnusedRefundServiceFeeType\": 0,\n" + + " \"UnusedRefundServiceFee\": 0,\n" + + " \"RefundItineraryFee\": 0,\n" + + " \"RefundInsuranceDetail\": null,\n" + + " \"TotalEmdAmount\": 0,\n" + + " \"ShareFlightNo\": \"\"\n" + + " },\n" + + " {\n" + + " \"Sequence\": 1,\n" + + " \"AirLineCode\": \"999\",\n" + + " \"TicketNo\": \"2327199524\",\n" + + " \"TicketNoSignCode\": \"999-2327199524\",\n" + + " \"Flight\": \"CA1507\",\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"RefundFee\": 0,\n" + + " \"RefundRate\": 0,\n" + + " \"RefundServiceFee\": 0,\n" + + " \"Subsidy\": 0,\n" + + " \"RebookingListID\": 0,\n" + + " \"RebookingID\": 0,\n" + + " \"UsedAmount\": 0,\n" + + " \"UsedTax\": 0,\n" + + " \"UnusedRefundServiceFeeType\": 0,\n" + + " \"UnusedRefundServiceFee\": 0,\n" + + " \"RefundItineraryFee\": 0,\n" + + " \"RefundInsuranceDetail\": null,\n" + + " \"TotalEmdAmount\": 0,\n" + + " \"ShareFlightNo\": null\n" + + " }\n" + + " ],\n" + + " \"RefundProcessList\": [\n" + + " {\n" + + " \"ProcessName\": \"A\",\n" + + " \"ProcessStatus\": 2\n" + + " },\n" + + " {\n" + + " \"ProcessName\": \"O\",\n" + + " \"ProcessStatus\": 2\n" + + " },\n" + + " {\n" + + " \"ProcessName\": \"F\",\n" + + " \"ProcessStatus\": 2\n" + + " },\n" + + " {\n" + + " \"ProcessName\": \"V\",\n" + + " \"ProcessStatus\": 2\n" + + " },\n" + + " {\n" + + " \"ProcessName\": \"C\",\n" + + " \"ProcessStatus\": 2\n" + + " },\n" + + " {\n" + + " \"ProcessName\": \"R\",\n" + + " \"ProcessStatus\": 2\n" + + " },\n" + + " {\n" + + " \"ProcessName\": \"Q\",\n" + + " \"ProcessStatus\": -1\n" + + " }\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"FlightChangeInfo\": null,\n" + + " \"RelatedOrderList\": null,\n" + + " \"FlightTicketPrintInfo\": {\n" + + " \"SegmentPrintInfoList\": null,\n" + + " \"RegularExpressInfoList\": null\n" + + " },\n" + + " \"PackageList\": [\n" + + " {\n" + + " \"PackageID\": 26309456058,\n" + + " \"PackageName\": \"商旅超能增值包\",\n" + + " \"PackageDescription\": \"1.机票发生退票后,航班延误服务不再适用于退票后重新预定的航班。
2.本产品不支持婴儿购买。\",\n" + + " \"RefundBookNotice\": \"航班起飞前,服务包中服务均未使用、未过期,服务包可与机票一起退订(不支持服务包子产品单退),航班起飞后服务包不可退订。\",\n" + + " \"PaymentAmount\": 40,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"ProductList\": [\n" + + " {\n" + + " \"ProductName\": \"24小时退票立减\",\n" + + " \"ProductDescription\": \"出票后24小时内,所下单机票起飞前发生退票,乘机人可获得1次退票费立减服务,可享抵扣退票费的40%。<br>使用说明:1. 退票费抵用券,所下单机票出票后24小时内可使用,仅限原航班起飞前使用。2. 机票发生退票后,航班延误补偿服务不再适用于退票后重新预定的航班。3. 成人可购买,不支持儿童婴儿购买。4. 本服务一经发放,不可退改。\",\n" + + " \"EffectTime\": \"\",\n" + + " \"ExpireTime\": \"2023-09-16 07:30:00\"\n" + + " },\n" + + " {\n" + + " \"ProductName\": \"延误补偿\",\n" + + " \"ProductDescription\": \"乘机人乘坐本航班,且抵达目的地时间延误2小时以上即可享受接送机券补偿。航班取消,备降,返航,以及改签后的航班不可享受该服务。抵达目的地时间延误超过2小时且 不超过4小时(含),补偿5张20元接送机券;抵达目的地时间延误超过4小时以上,补偿10张20元接送机券;接送机券自发放之日起30天内使用有效,且限对应乘机人使用。<br>使用说明:1. 仅适用于携程商旅Online和APP国内接送机服务,因公因私都可用。2. 购买携程商旅指定增值服务包赠送,每张价值20元。每张国内接送机订单只能使用一张优惠券,限预订账户使用。3. 订单支付成功后获得优惠券,获券之日起30天内有效。4. 本券一经发放不可退改。\",\n" + + " \"EffectTime\": \"\",\n" + + " \"ExpireTime\": \"2023-10-16 07:30:00\"\n" + + " },\n" + + " {\n" + + " \"ProductName\": \"商旅40元接送机券\",\n" + + " \"ProductDescription\": \"接送机券服务介绍:40元接送机券服务,仅限携程商旅国内接送机使用,抵扣40元,每张国内接送机订单只能使用一张优惠券,,30天内可使用。优惠券使用方法:1、仅适用于携程商旅Online和APP国内接送机服务,因公因私都可用。 2、购买携程商旅指定增值服务包赠送,每张价值40元。每张国内接送机订单只能使用一张优惠券,限预订账户使用。 3、订单支付成功后获得优惠券,获券之日起30天内有效。退定须知:航班起飞前,服务包中服务均未使用,未过期,服务包可与机票一起退定(不支持服务包子产品单退),航班起飞后服务包不可退订,\",\n" + + " \"EffectTime\": \"\",\n" + + " \"ExpireTime\": \"\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"XProductDetailList\": null,\n" + + " \"FlightOrderFeeDetailList\": [\n" + + " {\n" + + " \"TransactionType\": \"D\",\n" + + " \"PayType\": \"PERSONAL\",\n" + + " \"TransactionAmount\": 2260,\n" + + " \"PayCurrency\": \"CNY\",\n" + + " \"TransactionId\": 1326002175015649300,\n" + + " \"PassengerId\": 96759836,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"Sequence\": 1,\n" + + " \"EmployeeID\": \"10110551\",\n" + + " \"TransactionTime\": \"2023-08-11 12:49:37\"\n" + + " },\n" + + " {\n" + + " \"TransactionType\": \"R\",\n" + + " \"PayType\": \"PERSONAL\",\n" + + " \"TransactionAmount\": -2260,\n" + + " \"PayCurrency\": \"CNY\",\n" + + " \"TransactionId\": 1326009575083933700,\n" + + " \"PassengerId\": 96759836,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"Sequence\": 1,\n" + + " \"EmployeeID\": \"10110551\",\n" + + " \"TransactionTime\": \"2023-08-11 13:04:21\"\n" + + " },\n" + + " {\n" + + " \"TransactionType\": \"D\",\n" + + " \"PayType\": \"PERSONAL\",\n" + + " \"TransactionAmount\": 10,\n" + + " \"PayCurrency\": \"CNY\",\n" + + " \"TransactionId\": 1326002156393005000,\n" + + " \"PassengerId\": 96759836,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"Sequence\": 1,\n" + + " \"EmployeeID\": \"10110551\",\n" + + " \"TransactionTime\": \"2023-08-11 12:49:37\"\n" + + " },\n" + + " {\n" + + " \"TransactionType\": \"D\",\n" + + " \"PayType\": \"PERSONAL\",\n" + + " \"TransactionAmount\": 20,\n" + + " \"PayCurrency\": \"CNY\",\n" + + " \"TransactionId\": 1326002156393005000,\n" + + " \"PassengerId\": 96759836,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"Sequence\": 1,\n" + + " \"EmployeeID\": \"10110551\",\n" + + " \"TransactionTime\": \"2023-08-11 12:49:37\"\n" + + " },\n" + + " {\n" + + " \"TransactionType\": \"D\",\n" + + " \"PayType\": \"PERSONAL\",\n" + + " \"TransactionAmount\": 10,\n" + + " \"PayCurrency\": \"CNY\",\n" + + " \"TransactionId\": 1326002156393005000,\n" + + " \"PassengerId\": 96759836,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"Sequence\": 1,\n" + + " \"EmployeeID\": \"10110551\",\n" + + " \"TransactionTime\": \"2023-08-11 12:49:37\"\n" + + " },\n" + + " {\n" + + " \"TransactionType\": \"R\",\n" + + " \"PayType\": \"PERSONAL\",\n" + + " \"TransactionAmount\": -10,\n" + + " \"PayCurrency\": \"CNY\",\n" + + " \"TransactionId\": 1326008687367815200,\n" + + " \"PassengerId\": 96759836,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"Sequence\": 1,\n" + + " \"EmployeeID\": \"10110551\",\n" + + " \"TransactionTime\": \"2023-08-11 13:02:35\"\n" + + " },\n" + + " {\n" + + " \"TransactionType\": \"R\",\n" + + " \"PayType\": \"PERSONAL\",\n" + + " \"TransactionAmount\": -10,\n" + + " \"PayCurrency\": \"CNY\",\n" + + " \"TransactionId\": 1326008576513540000,\n" + + " \"PassengerId\": 96759836,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"Sequence\": 1,\n" + + " \"EmployeeID\": \"10110551\",\n" + + " \"TransactionTime\": \"2023-08-11 13:02:34\"\n" + + " },\n" + + " {\n" + + " \"TransactionType\": \"R\",\n" + + " \"PayType\": \"PERSONAL\",\n" + + " \"TransactionAmount\": -20,\n" + + " \"PayCurrency\": \"CNY\",\n" + + " \"TransactionId\": 1326008633413402600,\n" + + " \"PassengerId\": 96759836,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"Sequence\": 1,\n" + + " \"EmployeeID\": \"10110551\",\n" + + " \"TransactionTime\": \"2023-08-11 13:02:34\"\n" + + " }\n" + + " ],\n" + + " \"TripRecordInfoList\": [\n" + + " {\n" + + " \"TripId\": 49790311,\n" + + " \"Sequence\": 1,\n" + + " \"PassengerName\": \"朱琴\",\n" + + " \"RecordStatus\": \"R\",\n" + + " \"ValidFlag\": true,\n" + + " \"FlightClass\": \"N\",\n" + + " \"Flight\": \"CA1507\",\n" + + " \"ClassGrade\": \"Y\",\n" + + " \"SubClass\": \"Y\",\n" + + " \"TakeOffTime\": \"2023-09-15 07:30:00.000\",\n" + + " \"ArrivalTime\": \"2023-09-15 10:00:00.000\",\n" + + " \"DCity\": 1,\n" + + " \"DPort\": \"PEK\",\n" + + " \"DPortBuilding\": \"T3\",\n" + + " \"DPortBuildingId\": 3,\n" + + " \"ACity\": 2,\n" + + " \"APort\": \"SHA\",\n" + + " \"APortBuilding\": \"T2\",\n" + + " \"APortBuildingId\": 35,\n" + + " \"OpenTranFlag\": false,\n" + + " \"PrintPrice\": 2150,\n" + + " \"Oil\": 60,\n" + + " \"Tax\": 50,\n" + + " \"RecordNo\": \"JP8PSH\",\n" + + " \"AirlineRecordNo\": \"MFTPDS\",\n" + + " \"SharedFlag\": false,\n" + + " \"SharedFlight\": \"\",\n" + + " \"SurfaceFlag\": false,\n" + + " \"AirLineCode\": \"999\",\n" + + " \"TicketNo\": \"2327200094\",\n" + + " \"TicketNoStatus\": 1,\n" + + " \"DepartureCityName\": \"北京\",\n" + + " \"DepartureAirPortName\": \"首都国际机场\",\n" + + " \"ArrivalCityName\": \"上海\",\n" + + " \"ArrivalAirportName\": \"虹桥国际机场\",\n" + + " \"DepartureDistrictCode\": \"110000\",\n" + + " \"ArrivalDistrictCode\": \"310000\",\n" + + " \"ClassTypeName\": \"经济舱\",\n" + + " \"AirLineName\": \"中国国际航空股份有限公司\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"HotelOrderInfoList\": null,\n" + + " \"TrainOrderInfoList\": null,\n" + + " \"HotelSupplementOrderInfoList\": null,\n" + + " \"TrainSupplementOrderInfoList\": null,\n" + + " \"CarOrderInfoList\": null,\n" + + " \"CarQuickOrderInfoList\": null,\n" + + " \"DomPickUpOrderInfoList\": null,\n" + + " \"DomCharterCarOrderInfoList\": null,\n" + + " \"IntlTrainOrderInfoList\": null\n" + + " }\n" + + " ],\n" + + " \"Status\": {\n" + + " \"Success\": true,\n" + + " \"Message\": \"调用成功。\",\n" + + " \"ErrorCode\": 0\n" + + " }\n" + + "}"; + System.out.println(in); + JSONObject orderObj = JSONObject.parseObject(in); + JSONArray array = orderObj.getJSONArray("ItineraryList"); + JSONArray flightOrderInfoList = null; + for (int i = 0; i < array.size(); i++) { + JSONObject detailObj = array.getJSONObject(i); + flightOrderInfoList = detailObj.getJSONArray("FlightOrderInfoList"); + } + JSONObject obj = flightOrderInfoList.getJSONObject(0); +// JSONObject baseInfo = obj.getJSONObject("BasicInfo"); +// String employeeID = baseInfo.getString("EmployeeID"); + + // } + + + + JSONArray PassengerInfoList = obj.getJSONArray("PassengerInfo"); + JSONArray ticketInfoList = obj.getJSONArray("TicketInfoList"); + + + + JSONObject passengerInfoObj = PassengerInfoList.getJSONObject(0); + String employeeID = passengerInfoObj.getJSONObject("PassengerBasic").getString("CorpEid"); //FlightOrderInfoEntity—PassengerInfoEntity—PassengerBasic + + + JSONObject basicInfo = obj.getJSONObject("BasicInfo"); + String jouneryID = basicInfo.getString("JourneyID"); //—FlightOrderInfoEntity—BasicInfo + + JSONObject FlightInfo= obj.getJSONArray("FlightInfo").getJSONObject(0); + System.out.println(FlightInfo.getString("Flight"));//航班号 + System.out.println(FlightInfo.getString("TakeoffTime"));//开始时间 + System.out.println(FlightInfo.getString("ArrivalTime"));//到达时间 + System.out.println(FlightInfo.getString("DCityName")); + System.out.println(FlightInfo.getString("DCityCode")); + System.out.println(FlightInfo.getString("Amount")); + + JSONArray RefundInfoEntityList = obj.getJSONArray("RefundInfo"); + String tgqyy = ""; + JSONObject RefundInfoEntity = null; + if(RefundInfoEntityList!=null) { + RefundInfoEntity = RefundInfoEntityList.getJSONObject(0); +// 退票:ItineraryEntity—FlightOrderInfoEntity—RefundInfoEntity; +// 改签: +// ItineraryEntity—FlightOrderInfoEntity—PassengerInfoEntity—SequenceInfoEntity—ChangeInfoEntity + tgqyy = RefundInfoEntity.getString("RefundResonDesc");//TrainOrderInfoEntity—PassengerInfo—OrderTicketInfo + } + + JSONArray SequenceInfoEntityList = passengerInfoObj.getJSONArray("SequenceInfo"); + JSONObject SequenceInfoEntity = SequenceInfoEntityList.getJSONObject(0); + JSONArray ChangeInfoEntityList = SequenceInfoEntity.getJSONArray("ChangeInfo"); + JSONObject ChangeInfoEntity = ChangeInfoEntityList.getJSONObject(0); + + + JSONArray TripRecordInfoList = obj.getJSONArray("TripRecordInfoList"); + JSONObject TripRecordInfoEntity = TripRecordInfoList.getJSONObject(0); + + + tgqyy = RefundInfoEntity.getString("RefundResonDesc"); + System.out.println( tgqyy); +// System.out.println(ChangeInfoEntity.getString("CTicketNO"));//航班号 +// System.out.println(ChangeInfoEntity.getString("CTakeOffTime"));//开始时间 +// System.out.println(ChangeInfoEntity.getString("CArrivalTime"));//结束时间 +// System.out.println(ChangeInfoEntity.getString("CDCityName"));//cfd +// System.out.println(ChangeInfoEntity.getString("CACityName"));//到达地 +// System.out.println(ChangeInfoEntity.getString("CPrintPrice"));//改签后机票金额 + + + + + } +} + + diff --git a/com/engine/tjyh/xc/cmd/XcCmd.java b/com/engine/tjyh/xc/cmd/XcCmd.java new file mode 100644 index 0000000..25682c4 --- /dev/null +++ b/com/engine/tjyh/xc/cmd/XcCmd.java @@ -0,0 +1,975 @@ +package com.engine.tjyh.xc.cmd; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.tjyh.xc.util.HttpRequestUtil; +import com.engine.tjyh.xc.util.WorkflowCreateHandler; +import okhttp3.*; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.*; + +/** + * @Description + * @Author matrix + * @Date 2023/6/15 10:09 + **/ +public class XcCmd extends AbstractCommonCommand> { + + public XcCmd(JSONObject params) { + this.params = params; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + HttpRequestUtil httpRequestUtil = HttpRequestUtil.getInstance(); + RecordSet rs = new RecordSet(); + BaseBean bb = new BaseBean(); + Map apimap = new HashMap(); + writeLog("XcCmd--------:"+params); + String appKey = bb.getPropValue("tjyhxcjc","appKey"); + String appSecurity = bb.getPropValue("tjyhxcjc","appSecurity"); + String url = bb.getPropValue("tjyhxcjc","url"); + String orderurl = bb.getPropValue("tjyhxcjc","orderurl"); + String workflowId = bb.getPropValue("tjyhxcjc","workflowId"); + Map map= new HashMap<>(); + + + map.put("appKey",appKey); + map.put("appSecurity",appSecurity); + String input = JSON.toJSONString(map); + writeLog("input="+input); + String back = httpRequestUtil.doPostJson(url, input); + writeLog("back="+back); + JSONObject backObj = JSONObject.parseObject(back); + String ticket = backObj.getString("Ticket"); + bb.writeLog("ticket="+ticket); + + JSONObject obj = (JSONObject) params; + String approveScenario = obj.getString("approveScenario"); + String corpId = obj.getString("corpId"); + String orderId = obj.getString("orderId"); + String orderStatus = obj.getString("orderStatus"); + String productType = obj.getString("productType"); + String sign = obj.getString("sign"); + + String tgq="0"; //1 改签 2:退 + if("FlightInternational".equals(productType)||"FlightDomestic".equals(productType)){ + //机票 ,改签成功 + if("rebookSuccess".equals(orderStatus)){ + tgq="1"; + } + //退票成功(退款成功) + if("refunded".equals(orderStatus)||"RefundSuccess".equals(orderStatus)){ + tgq="2"; + } + } + if("HotelContract".equals(productType)||"HotelMember".equals(productType)){ + // 取消 + if("Cancelled".equals(orderStatus)){ + tgq="2"; + } + } + if("Train".equals(productType)){ + //已改签 + if("Rebooked".equals(orderStatus)){ + tgq="1"; + } + //SubmitRefund 退票成功 + if("SubmitRefund".equals(orderStatus)){ + tgq="2"; + } + } + + if("0".equals(tgq)){ + apimap.put("errno","-1"); + apimap.put("errmsg","不触发流程"); + return apimap; + } + + + Map orderMap = new HashMap(); + Map authMap = new HashMap(); + authMap.put("AppKey",appKey); + authMap.put("Ticket",ticket); + orderMap.put("Auth",authMap); + orderMap.put("JourneyNo",""); + orderMap.put("OrderID",orderId); + orderMap.put("SearchType",1); + + String orderInput = JSON.toJSONString(orderMap); + bb.writeLog("orderInput="+orderInput); + String orderBack = httpRequestUtil.doPostJson(orderurl, orderInput); +// String orderBack = postData(orderInput,orderurl); + bb.writeLog("orderBack="+orderBack); + if(isJsonValid(orderBack)) { + JSONObject orderObj = JSONObject.parseObject(orderBack); + JSONArray array = orderObj.getJSONArray("ItineraryList"); + for (int i = 0; i < array.size(); i++) { + JSONObject detailObj = array.getJSONObject(i); + JSONArray flightOrderInfoList = detailObj.getJSONArray("FlightOrderInfoList"); + JSONArray hotelOrderInfoList = detailObj.getJSONArray("HotelOrderInfoList"); + JSONArray trainOrderInfoList = detailObj.getJSONArray("TrainOrderInfoList"); + + if(flightOrderInfoList!=null){ + doFlightOrder(flightOrderInfoList,workflowId,tgq); + } + + if(hotelOrderInfoList!=null){ + doHotailOrder(hotelOrderInfoList,workflowId,tgq); + } + + if(trainOrderInfoList!=null){ + doTrainOrder(trainOrderInfoList,workflowId,tgq); + } + + } + }else{ + apimap.put("errno","-1"); + apimap.put("errmsg","订单数据格式不对"); + } + + + if("".equals(params.toString())){ + apimap.put("errno","-1"); + apimap.put("errmsg","空数据"); + }else { + apimap.put("errno", "0"); + apimap.put("errmsg", ""); + } + return apimap; + } + + + + public static String GetSign(String corpId,String productType,String orderStatus,String orderId,String statusIDs ,String refundType,String secret,String approveScenario) + { + //构造字典 + HashMap hashMap=new HashMap(); + hashMap.put("secret",secret); + hashMap.put("corpId",corpId); + hashMap.put("productType",productType); + hashMap.put("orderId",orderId); + hashMap.put("orderStatus",orderStatus); + //排序 + Collection collection=hashMap.keySet(); + ArrayList list=new ArrayList(collection); + Collections.sort(list); + //拼接 + String str=""; + for( int i=0;i(); + map.put("appKey",appKey); + map.put("appSecurity",appSecurity); + String input = JSON.toJSONString(map); +// String back =" postData(input,url)"; +// JSONObject backObj = JSONObject.parseObject(back); +// String ticket = backObj.getString("Ticket"); +// bb.writeLog("ticket="+ticket); +// +// JSONObject obj = (JSONObject) params; +// String approveScenario = obj.getString("approveScenario"); +// String corpId = obj.getString("corpId"); +// String orderId = obj.getString("orderId"); +// String orderStatus = obj.getString("orderStatus"); +// String productType = obj.getString("productType"); +// String sign = obj.getString("sign"); + + String tgq="2"; //1 改签 2:退 +// if("FlightInternational".equals(productType)||"FlightDomestic".equals(productType)){ +// //机票 ,改签成功 +// if("rebookSuccess".equals(orderStatus)){ +// tgq="1"; +// } +// //退票成功(退款成功) +// if("refunded".equals(orderStatus)){ +// tgq="2"; +// } +// } +// if("HotelContract".equals(productType)||"HotelMember".equals(productType)){ +// // 取消 +// if("Cancelled".equals(orderStatus)){ +// tgq="2"; +// } +// } +// if("Train".equals(productType)){ +// //已改签 +// if("Rebooked".equals(orderStatus)){ +// tgq="1"; +// } +// //SubmitRefund 退票成功 +// if("SubmitRefund".equals(orderStatus)){ +// tgq="2"; +// } +// } +// +// if("0".equals(tgq)){ +// apimap.put("errno","-1"); +// apimap.put("errmsg","不触发流程"); +// return apimap; +// } +// +// +// Map orderMap = new HashMap(); +// Map authMap = new HashMap(); +// authMap.put("AppKey",appKey); +// authMap.put("Ticket",ticket); +// orderMap.put("Auth",authMap); +// orderMap.put("JourneyNo",""); +// orderMap.put("OrderID",orderId); +// orderMap.put("SearchType",1); +// +// String orderInput = JSON.toJSONString(orderMap); + + String orderBack = JSON.toJSONString(params); + bb.writeLog("orderBack="+orderBack); + if(isJsonValid(orderBack)) { + JSONObject orderObj = JSONObject.parseObject(orderBack); + JSONArray array = orderObj.getJSONArray("ItineraryList"); + for (int i = 0; i < array.size(); i++) { + JSONObject detailObj = array.getJSONObject(i); + JSONArray flightOrderInfoList = detailObj.getJSONArray("FlightOrderInfoList"); + JSONArray hotelOrderInfoList = detailObj.getJSONArray("HotelOrderInfoList"); + JSONArray trainOrderInfoList = detailObj.getJSONArray("TrainOrderInfoList"); + + if(flightOrderInfoList!=null){ + doFlightOrder(flightOrderInfoList,workflowId,tgq); + } + + if(hotelOrderInfoList!=null){ + doHotailOrder(hotelOrderInfoList,workflowId,tgq); + } + + if(trainOrderInfoList!=null){ + doTrainOrder(trainOrderInfoList,workflowId,tgq); + } + + } + }else{ + apimap.put("errno","-1"); + apimap.put("errmsg","订单数据格式不对"); + } + + + if("".equals(params.toString())){ + apimap.put("errno","-1"); + apimap.put("errmsg","空数据"); + }else { + apimap.put("errno", "0"); + apimap.put("errmsg", ""); + } + return apimap; + } + + + + public static String GetSign(String corpId,String productType,String orderStatus,String orderId,String statusIDs ,String refundType,String secret,String approveScenario) + { + //构造字典 + HashMap hashMap=new HashMap(); + hashMap.put("secret",secret); + hashMap.put("corpId",corpId); + hashMap.put("productType",productType); + hashMap.put("orderId",orderId); + hashMap.put("orderStatus",orderStatus); + //排序 + Collection collection=hashMap.keySet(); + ArrayList list=new ArrayList(collection); + Collections.sort(list); + //拼接 + String str=""; + for( int i=0;i sendData(JSONObject input); + + Map sendData2(JSONObject input); +} diff --git a/com/engine/tjyh/xc/service/impl/XcServiceImpl.java b/com/engine/tjyh/xc/service/impl/XcServiceImpl.java new file mode 100644 index 0000000..cd81f44 --- /dev/null +++ b/com/engine/tjyh/xc/service/impl/XcServiceImpl.java @@ -0,0 +1,28 @@ +package com.engine.tjyh.xc.service.impl; + +import com.alibaba.fastjson.JSONObject; +import com.engine.core.impl.Service; +import com.engine.tjyh.xc.cmd.XcCmd; +import com.engine.tjyh.xc.cmd.XcCmd2; +import com.engine.tjyh.xc.service.XcService; + +import java.util.Map; + +/** + * TODO + * + * @Description + * @Author matrix + * @Date 2023/6/15 10:08 + **/ +public class XcServiceImpl extends Service implements XcService { + public Map sendData(JSONObject input) { + return commandExecutor.execute(new XcCmd(input)); + } + + + public Map sendData2(JSONObject input) { + return commandExecutor.execute(new XcCmd2(input)); + } + +} diff --git a/com/engine/tjyh/xc/util/HttpClientWrapper.java b/com/engine/tjyh/xc/util/HttpClientWrapper.java new file mode 100644 index 0000000..37119a1 --- /dev/null +++ b/com/engine/tjyh/xc/util/HttpClientWrapper.java @@ -0,0 +1,57 @@ +package com.engine.tjyh.xc.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import weaver.general.BaseBean; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +/** + * Created by fmj on 2018/9/18. + */ +public class HttpClientWrapper { + private static Log log = LogFactory.getLog(HttpClientWrapper.class.getClass()); + + public static DefaultHttpClient wrapClient(DefaultHttpClient base) { + try { + SSLContext ctx = SSLContext.getInstance("TLS"); + X509TrustManager tm = new WeaverTrustManager(); + ctx.init(null, new TrustManager[]{tm}, null); + SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("https", 443, ssf)); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry); + return new DefaultHttpClient(mgr, base.getParams()); + } catch (Exception ex) { + log.error("HttpClientWrapper.wrapClient catch a exception : " + ex); + } + + return base; + } + + static class WeaverTrustManager implements X509TrustManager { + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + } +} diff --git a/com/engine/tjyh/xc/util/HttpRequestUtil.java b/com/engine/tjyh/xc/util/HttpRequestUtil.java new file mode 100644 index 0000000..b3a5b12 --- /dev/null +++ b/com/engine/tjyh/xc/util/HttpRequestUtil.java @@ -0,0 +1,284 @@ +package com.engine.tjyh.xc.util; + +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.params.HttpMethodParams; +import org.apache.http.*; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.params.ConnRouteParams; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class HttpRequestUtil extends BaseBean { + private static HttpRequestUtil httpRequestUtil; + private String charset = "utf-8"; + + /** + * constructor + */ + private HttpRequestUtil() { + } + + /** + * 获取实例 + * + * @return + */ + public static HttpRequestUtil getInstance() { + return new HttpRequestUtil(); + } + + /** + * 获取HttpClient + * + * @return + */ + public DefaultHttpClient getClient() { + DefaultHttpClient client = new DefaultHttpClient(); + client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); + client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset); + //超时设置 + int timeOut = Util.getIntValue(60000); + client.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, timeOut); + + client = HttpClientWrapper.wrapClient(client); //先绕过证书,不验证证书 + + proxyConfig(client); + + return client; + } + + /** + * 代理的设置 + * + * @param client + */ + private void proxyConfig(DefaultHttpClient client) { + writeLog("================proxyConfig=================="); + boolean isAgent = true; + if (isAgent) { //开启了代理 + String host = "10.200.1.69"; + int port = 9063; + String userName = "root"; + String password = "Qasd!234"; + + client.getCredentialsProvider().setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(userName, password)); + + HttpHost httpHost = new HttpHost(host, port); + client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost); + } + } + + /** + * post请求方式,json数据格式 + * + * @param url + * @param params + * @return + */ + public String doPostJson(String url, Map params) { + String json = JSONObject.toJSONString(params); + return doPostJson(url, json); + } + + + public String doPostJson(String url, String json) { + String response = ""; + HttpClient client = getClient(); + HttpPost post = null; + + String exceptionmsg = ""; + + String timeformat = "yyyy-MM-dd HH:mm:ss.SSS"; + String currentTime = TimeUtil.getFormartString(Calendar.getInstance(), timeformat); +// if (!"".equals(url)) { +// url = ctripConfig.correctUrl(url); +// } + try { + post = new HttpPost(url); + post.setHeader(HTTP.CONTENT_TYPE, "application/json"); //请求数据的格式为json + post.setHeader(HTTP.CONN_DIRECTIVE, "Keep-Alive"); //长连接 + post.setHeader(HTTP.CONTENT_ENCODING, charset); + post.setHeader("accept", "*/*"); + post.setHeader(HTTP.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(8000) + .setSocketTimeout(8000).setConnectTimeout(8000).build(); + post.setConfig(requestConfig); + + StringEntity entity = new StringEntity(json, charset); + post.setEntity(entity); + HttpResponse httpResponse = client.execute(post); + + int httpCode = httpResponse.getStatusLine().getStatusCode(); + if (httpCode == HttpStatus.SC_OK) { + response = EntityUtils.toString(httpResponse.getEntity(), charset); + } else { + writeLog("WebUtil.doPostJson httpCode:" + httpCode); + } + } catch (UnsupportedEncodingException e) { + writeLog("WebUtil.doPostJson catch a UnsupportedEncodingException exception:" + e.getMessage()); + writeLog(e); + exceptionmsg = "WebUtil.doPostJson catch a UnsupportedEncodingException exception:" + e.getMessage(); + } catch (ClientProtocolException e) { + writeLog("WebUtil.doPostJson catch a ClientProtocolException exception:" + e.getMessage()); + writeLog(e); + exceptionmsg = "WebUtil.doPostJson catch a ClientProtocolException exception:" + e.getMessage(); + } catch (IOException e) { + writeLog("WebUtil.doPostJson catch a IOException exception:" + e.getMessage()); + writeLog(e); + exceptionmsg = "WebUtil.doPostJson catch a IOException exception:" + e.getMessage(); + } finally { + if (post != null) { + post.releaseConnection(); + } + } + +// String sql = "insert into ctrip_allrequest_logs (requesturl,requestjson,responsejson,exceptionmsg,logtime) values (?, ?, ?, ?,?)"; + +// ConnStatement connStatement = null; +// +// try { +// connStatement = new ConnStatement(); +// connStatement.setStatementSql(sql); +// connStatement.setString(1, url); +// connStatement.setString(2, json); +// connStatement.setString(3, response); +// connStatement.setString(4, exceptionmsg); +// connStatement.setString(5, currentTime); +// connStatement.executeUpdate(); +// connStatement.close(); +// } catch (SQLException e) { +// writeLog("WebUtil.doPostJson catch a SQLException:" + e.getMessage()); +// writeLog(e); +// } catch (Exception e) { +// writeLog("WebUtil.doPostJson catch a Exception:" + e.getMessage()); +// writeLog(e); +// } finally { +// if (connStatement != null) { +// connStatement.close(); +// } +// } + + return response; + } + + /** + * post请求,form数据格式 + * + * @param url + * @param params + * @return + */ + public String doPostForm(String url, Map params) { + String response = ""; + HttpClient client = getClient(); + HttpPost post = null; + + post = new HttpPost(url); + post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); + post.setHeader(HTTP.CONN_DIRECTIVE, "Keep-Alive"); //长连接 + post.setHeader(HTTP.CONTENT_ENCODING, charset); + + String json = JSONObject.toJSONString(params); + + try { + List pairList = new ArrayList(); + for (Iterator> iterator = params.entrySet().iterator(); iterator.hasNext(); ) { + Map.Entry entry = iterator.next(); + String key = entry.getKey(); + String value = entry.getValue(); + NameValuePair nameValuePair = new BasicNameValuePair(key, value); + pairList.add(nameValuePair); + } + + UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairList, charset); + post.setEntity(formEntity); + HttpResponse httpResponse = client.execute(post); + + int httpCode = httpResponse.getStatusLine().getStatusCode(); + if (httpCode == HttpStatus.SC_OK) { + response = EntityUtils.toString(httpResponse.getEntity(), charset); + } else { + writeLog("WebUtil.doPostForm httpCode:" + httpCode); + } + } catch (UnsupportedEncodingException e) { + writeLog("WebUtil.doPostForm catch a UnsupportedEncodingException exception:" + e.getMessage()); + writeLog(e); + } catch (ClientProtocolException e) { + writeLog("WebUtil.doPostForm catch a ClientProtocolException exception:" + e.getMessage()); + writeLog(e); + } catch (IOException e) { + writeLog("WebUtil.doPostForm catch a IOException exception:" + e.getMessage()); + writeLog(e); + } finally { + if (post != null) { + post.releaseConnection(); + } + } + return response; + } + + + /** + * 将unicode编码的中文解码 + * + * @param unicodeStr + * @return + */ + public String decode(String unicodeStr) { + /** + * unicode编码的正则表达式 + */ + Pattern reUnicode = Pattern.compile("\\\\u([0-9a-zA-Z]{4})"); + + Matcher m = reUnicode.matcher(unicodeStr); + StringBuffer sb = new StringBuffer(unicodeStr.length()); + while (m.find()) { + m.appendReplacement(sb, + Character.toString((char) Integer.parseInt(m.group(1), 16))); + } + m.appendTail(sb); + return sb.toString(); + } + + /** + * 将请求中的中文unicode编码 + * + * @param s + * @return + */ + public String encode(String s) { + StringBuilder sb = new StringBuilder(s.length() * 3); + for (char c : s.toCharArray()) { + if (c < 256) { + sb.append(c); + } else { + sb.append("\\u"); + sb.append(Character.forDigit((c >>> 12) & 0xf, 16)); + sb.append(Character.forDigit((c >>> 8) & 0xf, 16)); + sb.append(Character.forDigit((c >>> 4) & 0xf, 16)); + sb.append(Character.forDigit((c) & 0xf, 16)); + } + } + return sb.toString(); + } +} diff --git a/com/engine/tjyh/xc/util/WorkflowCreateHandler.java b/com/engine/tjyh/xc/util/WorkflowCreateHandler.java new file mode 100644 index 0000000..051f368 --- /dev/null +++ b/com/engine/tjyh/xc/util/WorkflowCreateHandler.java @@ -0,0 +1,534 @@ +package com.engine.tjyh.xc.util; + +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.soa.workflow.request.*; +import weaver.workflow.request.RequestComInfo; +import weaver.workflow.workflow.WorkflowComInfo; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * + * @ClassName: WorkflowCreateHandler + * @Description: TODO + * } + * @author shil + * @date 2020-03-25 下午5:03:03 + * + */ +public class WorkflowCreateHandler extends BaseBean { + + public WorkflowCreateHandler() { + super(); + } + + /*** + * + * @param workflowid + * @return + */ + public String findWorkflowForm(String workflowid) + { + String tablename = ""; + String cDandT = TimeUtil.getCurrentDateString()+" "+ TimeUtil.getCurrentTimeString(); + RecordSet ws = new RecordSet(); + ws.execute("select t2.tablename from workflow_base t1,workflow_bill t2 where t2.id=t1.formid and t1.id ='"+workflowid+"'"); + if(ws.next()){ + tablename = Util.null2String(ws.getString("tablename")); + }else{ + tablename = "-1"; + writeLog("shauter 当前时间:"+cDandT+"-workflowid="+workflowid+"-没有设置表单"); + } + return tablename; + + } + + /** + * + * @Title: bulidWorkflowTitle + * @Description: TODO(构建流程标题) + * @param @param workflowid + * @param @param creatorid + * @param @return 设定文件 + * @return String 返回类型 + * @throws + */ + public String bulidWorkflowTitle(String workflowid,String creatorid) + { + StringBuffer workflowtitle=new StringBuffer(""); + ResourceComInfo ResourceComInfo = null; + try { + ResourceComInfo = new ResourceComInfo(); + } catch (Exception e) { + e.printStackTrace(); + } + String latsname = ResourceComInfo.getLastname(creatorid); + workflowtitle.append(findWorkflowName(""+workflowid)+"--"+latsname); + return workflowtitle.toString(); + } + + /** + * + * @Title: findWorkflowName + * @Description: TODO(获取流程名称) + * @param @param workflowid + * @param @return 设定文件 + * @return String 返回类型 + * @throws + */ + public String findWorkflowName(String workflowid){ + String workflowname=""; + WorkflowComInfo WorkflowComInfo = null; + try { + WorkflowComInfo = new WorkflowComInfo(); + workflowname = WorkflowComInfo.getWorkflowname(""+workflowid); + } catch (Exception e) { + e.printStackTrace(); + workflowname ="-1"; + } + return workflowname; + } + + /** + * + * @Title: findDataIDByReqID + * @Description: TODO(获取表单数据id) + * @param @param workflowid + * @param @param requestid + * @param @return 设定文件 + * @return String 返回类型 + * @throws + */ + public String findDataIDByReqID(String workflowid,String requestid){ + String dataid=""; + RecordSet rs = new RecordSet(); + rs.execute("select id from "+findWorkflowForm(workflowid)+" where requestid='"+requestid+"' "); + rs.next(); + dataid = Util.null2String(rs.getString(1)); + return dataid; + } + /** + * + * @Title: expoundRequest + * @Description: TODO(这里用一句话描述这个方法的作用) + * @param @param requestid + * @param @return 设定文件 + * @return String 返回类型 + * @throws + */ + + public String expoundRequest(String requestid) + { + writeLog("--------------requestid:"+requestid); + String dec = ""; + int ireqid = Util.getIntValue(requestid, 0); + if(ireqid>0){ + + }else if(ireqid==-1){ + dec = "创建流程失败"; + }else if(ireqid==-2){ + dec = "用户没有流程创建权限"; + }else if(ireqid==-3){ + dec = "创建流程基本信息失败"; + }else if(ireqid==-4){ + dec = "保存表单主表信息失败"; + }else if(ireqid==-5){ + dec = "更新紧急程度失败"; + }else if(ireqid==-6){ + dec = "流程操作者失败"; + }else if(ireqid==-7){ + dec = "流转至下一节点失败"; + }else if(ireqid==-8){ + dec = "节点附加操作失败"; + } + return dec; + } + + /** + * + * @Title: WorkflowCreateByMainTableMap + * @param @param creatorId 创建人Id + * @param @param workflowId 流程Id + * @param @param requestName 请求标题 + * @param @param IsNextFlow 是否提交到下一节点 + * @param @param requestMap Map格式的主表数据=<字段名称,字段值> + * @param @return 设定文件 + * @return String 返回类型 + * @throws + */ + public String WorkflowCreateByRequestMap(String creatorId ,String workflowId ,String requestName ,String IsNextFlow,Map requestMainMap) + { + writeLog("creatorId:"+creatorId); + writeLog("workflowId:"+workflowId); + writeLog("requestName:"+requestName); + writeLog("IsNextFlow:"+IsNextFlow); + + String requestid = ""; + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setCreatorid(creatorId);//创建人Id + requestInfo.setWorkflowid(workflowId);//工作流Id + requestInfo.setDescription(requestName);//请求标题 + requestInfo.setRequestlevel("0"); + if(!"".equals(IsNextFlow)) + { + requestInfo.setIsNextFlow(IsNextFlow); + } + + //主表字段 + MainTableInfo mainTableInfo = new MainTableInfo(); + Property[] propertyArray = new Property[requestMainMap.size()]; + int p = 0; + for (Entry entry : requestMainMap.entrySet()) + { + propertyArray[p] = new Property(); + propertyArray[p].setName(Util.null2String(entry.getKey())); + propertyArray[p].setValue(Util.null2String(entry.getValue())); + writeLog("\r\n---p="+p+"---Key="+entry.getKey()+"---Value="+entry.getValue()); + p++; + } + writeLog("-----创建流程传递的参数个数p="+p); + mainTableInfo.setProperty(propertyArray); + requestInfo.setMainTableInfo(mainTableInfo); + RequestService service = new RequestService(); + + try { + //流程 + try { + requestid = service.createRequest(requestInfo);//创建请求id + } catch (Exception e) { + writeLog("======="+e.getMessage()); + } + //记录日志 + StringBuffer sbf = new StringBuffer("\r\n---创建工作流记录日志开始"); + WorkflowComInfo wfcif =new WorkflowComInfo(); + RequestComInfo rcif = new RequestComInfo(); + ResourceComInfo rscif = new ResourceComInfo(); + sbf.append("\r\n-----姓名:"+rscif.getLastname(rcif.getRequestCreater(requestid))); + sbf.append("\r\n-----时间:"+rcif.getRequestCreateTime(requestid)); + sbf.append("\r\n-----创建流程:"+wfcif.getWorkflowname(workflowId)); + sbf.append("\r\n-----请求:"+rcif.getRequestname(requestid)); + sbf.append("\r\n-----请求:"+requestid); + sbf.append("\r\n-----创建工作流记录日志结束"); + writeLog(sbf.toString()); + System.out.println(""+sbf.toString()); + } catch (Exception e) { + writeLog("错误:" + e); + System.out.println("错误:" + e); + } + return requestid; + } + + + + /*** + * + * @param ireqid + * @param detailList + * @param tablename + * @param dataid + * @return + */ + public String insertTableDt1(int ireqid, List> detailList, String tablename, String dataid, Set fileSet) + { + String message = "0" ; + if(!"".equals(dataid) && dataid !=null) + { + RecordSet rs = new RecordSet(); + //插入明细表 + String tablename_dt1 = tablename+"_dt1"; //明细表名 + for(Map detailMap : detailList) + { + String dttablename = "" ; + String dttablenvalue = "" ; + for (Entry entry : detailMap.entrySet()) + { + String fieldname = Util.null2String(entry.getKey()); + String fieldvalue = Util.null2String(entry.getValue()); + + dttablename += dttablename==""? fieldname :","+fieldname ; + if(fileSet.contains(fieldname)) + { + dttablenvalue += dttablenvalue == "" ? fieldvalue : ","+fieldvalue ; + }else{ + dttablenvalue += dttablenvalue == "" ? "'"+fieldvalue.replace("'", "''").trim()+"'" : ",'"+fieldvalue.replace("'", "''").trim()+"'" ; + } + } + writeLog("dttablename:"+dttablename); + writeLog("dttablenvalue:"+dttablenvalue); + if(dttablename !="" && dttablenvalue !="") + { + String sql = "insert into "+tablename_dt1+" (mainid,"+dttablename+") values ("+dataid+","+dttablenvalue+")"; + writeLog(sql); + boolean boo = rs.execute(sql); + if(!boo) + { + message = "-1" ; + } + }else{ + message = "-2" ; + } + } + }else{ + message = "-3" ; + } + return message; + } + + /** + * + * @param detailList + * @param tablename + * @param dataid + * @return + */ + public String insertTableDtMX(List> detailList, String tablename, String dataid,Set fileSet) + { + String message = "0" ; + if(!"".equals(dataid) && dataid !=null) + { + RecordSet rs = new RecordSet(); + //插入明细表 + String tablename_dt = tablename; + writeLog("tablename_dt="+tablename_dt); + for(Map detailMap : detailList) + { + String dttablename = "" ; + String dttablenvalue = "" ; + try { + + for (Entry entry : detailMap.entrySet()) { + String fieldname = Util.null2String(entry.getKey()); + String fieldvalue = "'" + Util.null2String(entry.getValue()) + "'"; + + dttablename += dttablename == "" ? fieldname : "," + fieldname; + if (fileSet.contains(fieldname)) { + dttablenvalue += dttablenvalue == "" ? fieldvalue : "," + fieldvalue; + } else { + dttablenvalue += dttablenvalue == "" ? "'" + fieldvalue.replace("'", "''").trim() + "'" : ",'" + fieldvalue.replace("'", "''").trim() + "'"; + } + } + }catch (Exception e){ + System.out.println(e.toString()); + e.printStackTrace(); + } + writeLog("dttablename:"+dttablename); + writeLog("dttablenvalue:"+dttablenvalue); + if(dttablename !="" && dttablenvalue !="") + { + String sql = "insert into "+tablename_dt+" (mainid,"+dttablename+") values ("+dataid+","+dttablenvalue+")"; + writeLog(sql); + boolean boo = rs.execute(sql); + if(!boo) + { + message = "-1" ; + } + }else{ + message = "-2" ; + } + } + }else{ + message = "-3" ; + } + return message; + } + + /*** + * + * @param requestid + * @param formtable + * @param requestMap + * @return + */ + public String updateWorkflowBySap(String requestid, String formtable, Map requestMap) + { + RecordSet rs = new RecordSet(); + BaseBean bb = new BaseBean(); + String msg = "" ; + try{ + String tableset = "" ; + for (Entry entry : requestMap.entrySet()) + { + String fieldname = Util.null2String(entry.getKey()).trim(); + String fieldvalue = Util.null2String(entry.getValue()).replace("'", "''").trim(); + tableset += tableset =="" ? fieldname+"='"+fieldvalue.replace("'", "''").trim()+"'" :","+fieldname+"='"+fieldvalue.replace("'", "''").trim()+"'" ; + } + if(!"".equals(tableset)) + { + String sql = " update "+formtable+" set "+tableset+" where requestid="+requestid; + bb.writeLog("sql:"+sql); + boolean flag = rs.executeUpdate(sql); + if(flag){ + msg = "1"; + }else{ + msg = "0"; + } + }else{ + msg = "-1"; + } + }catch (Exception e){ + msg = "-1"; + } + bb.writeLog("msg:"+msg); + return msg; + } + + /*** + * + * @param detailList + * @param detailid + * @return + */ + public DetailTableInfo queryDetailTableInfo(List> detailList,String detailid){ + DetailTableInfo dti = new DetailTableInfo(); + if("".equals(detailid)){ + return dti; + } + + List detailtables = new ArrayList(); + DetailTable dt = new DetailTable(); + dt.setId(detailid); + List rows = new ArrayList(); + + for(int i=0;i detailMap = detailList.get(i); + Row r = new Row(); + List cells = new ArrayList(); + for (Entry entry : detailMap.entrySet()) + { + String fieldname = Util.null2String(entry.getKey()).trim(); + String fieldvalue = Util.null2String(entry.getValue()).replace("'", "''").trim(); + Cell c = new Cell(); + c.setName(fieldname); + c.setValue(fieldvalue); + cells.add(c); + } + + Cell[] ca = new Cell[cells.size()]; + cells.toArray(ca); + r.setCell(ca); + rows.add(r); + } + + Row[] ra = new Row[rows.size()]; + rows.toArray(ra); + dt.setRow(ra); + detailtables.add(dt); + + DetailTable[] dta = new DetailTable[detailtables.size()]; + detailtables.toArray(dta); + dti.setDetailTable(dta); + + return dti; + } + + /*** + * + * @param creatorId + * @param workflowId + * @param requestName + * @param IsNextFlow + * @param requestMainMap + * @param detailList + * @return + */ + public String WorkflowCreateByRequestMap2(String creatorId ,String workflowId ,String requestName ,String IsNextFlow,Map requestMainMap,List> detailList) + { + writeLog("-----创建流程传递的参数个数--------"); + writeLog("creatorId:"+creatorId); + writeLog("workflowId:"+workflowId); + writeLog("requestName:"+requestName); + writeLog("IsNextFlow:"+IsNextFlow); + + String requestid = ""; + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setCreatorid(creatorId);//创建人Id + requestInfo.setWorkflowid(workflowId);//工作流Id + requestInfo.setDescription(requestName);//请求标题 + if(!"".equals(IsNextFlow)) + { + requestInfo.setIsNextFlow(IsNextFlow); + } + + //主表字段 + MainTableInfo mainTableInfo = new MainTableInfo(); + Property[] propertyArray = new Property[requestMainMap.size()]; + int p = 0; + for (Entry entry : requestMainMap.entrySet()) + { + propertyArray[p] = new Property(); + propertyArray[p].setName(Util.null2String(entry.getKey())); + propertyArray[p].setValue(Util.null2String(entry.getValue())); + writeLog("\r\n---p="+p+"---Key="+entry.getKey()+"---Value="+entry.getValue()); + p++; + } + writeLog("-----创建流程传递的参数个数p="+p); + mainTableInfo.setProperty(propertyArray); + requestInfo.setMainTableInfo(mainTableInfo); + + if(detailList.size() >0){ + DetailTableInfo detailTableInfo = queryDetailTableInfo(detailList,"1"); + requestInfo.setDetailTableInfo(detailTableInfo); + } + + RequestService service = new RequestService(); + try { + //流程 + try { + requestid = service.createRequest(requestInfo);//创建请求id + + } catch (Exception e) { + writeLog("======="+e.getMessage()); + } + //String userId = requestInfo.getLastoperator();//请求最后的操作者 + //记录日志 + StringBuffer sbf = new StringBuffer("\r\n-----xwd创建工作流记录日志开始"); + WorkflowComInfo wfcif =new WorkflowComInfo(); + RequestComInfo rcif = new RequestComInfo(); + ResourceComInfo rscif = new ResourceComInfo(); + sbf.append("\r\n-----姓名:"+rscif.getLastname(rcif.getRequestCreater(requestid))); + sbf.append("\r\n-----时间:"+rcif.getRequestCreateTime(requestid)); + sbf.append("\r\n-----创建流程:"+wfcif.getWorkflowname(workflowId)); + sbf.append("\r\n-----请求:"+rcif.getRequestname(requestid)); + sbf.append("\r\n-----请求:"+requestid); + sbf.append("\r\n-----创建工作流记录日志结束"); + writeLog(sbf.toString()); + System.out.println(""+sbf.toString()); + } catch (Exception e) { + writeLog("错误:" + e); + System.out.println("错误:" + e); + } + return requestid; + } + + /*** + * + * @param requestid + * @param userid + * @return + */ + public boolean WorkflowNextNodeBySubmit(int requestid,int userid) + { + writeLog("-----创建流程传递的参数个数--------"); + writeLog("requestid:"+requestid); + boolean istrue = false; + + RequestService service = new RequestService(); + RequestInfo requestInfo = service.getRequest(requestid); + try { + istrue = service.nextNodeBySubmit(requestInfo,requestid,userid, "");//创建请求id + } catch (Exception e) { + writeLog("======="+e.getMessage()); + istrue = false; + } + return istrue; + } +} diff --git a/com/engine/tjyh/xc/web/AcceptXcDataAction.java b/com/engine/tjyh/xc/web/AcceptXcDataAction.java new file mode 100644 index 0000000..b4840f4 --- /dev/null +++ b/com/engine/tjyh/xc/web/AcceptXcDataAction.java @@ -0,0 +1,123 @@ +package com.engine.tjyh.xc.web; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.engine.common.util.ServiceUtil; +import com.engine.tjyh.xc.service.XcService; +import com.engine.tjyh.xc.service.impl.XcServiceImpl; +import lombok.extern.slf4j.Slf4j; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.HashMap; +import java.util.Map; + +/** + * 接受携程数据 + * @Description + * @Author matrix + * @Date 2023/6/15 10:05 + **/ +@Slf4j +public class AcceptXcDataAction { + + public XcService getService(){ + return (XcService) ServiceUtil.getService(XcServiceImpl.class); + + } + + @POST + @Path("/sendData") + @Produces(MediaType.TEXT_PLAIN) + public String sendData(@Context HttpServletRequest request, @Context HttpServletResponse response){ + log.info("测试-------------------------"); + Map apidatas = new HashMap(); + try { + BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8")); + String line = null; + StringBuilder sb = new StringBuilder(); + while((line = br.readLine())!=null){ + sb.append(line); + } + String input = null2String(sb.toString()); + if(!"".equals(input)) { + if(isJsonValid(input)) { + JSONObject jo1 = JSON.parseObject(input); + apidatas.putAll(this.getService().sendData(jo1)); + }else{ + apidatas.put("errno", -1); + apidatas.put("errmsg", "输入参数不是json格式"); + } + }else { + apidatas.put("errno", -1); + apidatas.put("errmsg", "输入参数为空!"); + } + } catch (Exception e) { + apidatas.put("errno", -1); + apidatas.put("errmsg", "catch exception : " + e.getMessage()); + } + log.info("测试-------------------------"+JSON.toJSONString(apidatas)); + return JSONObject.toJSONString(apidatas); + } + + + @POST + @Path("/sendData2") + @Produces(MediaType.TEXT_PLAIN) + public String sendData2(@Context HttpServletRequest request, @Context HttpServletResponse response){ + Map apidatas = new HashMap(); + try { + BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8")); + String line = null; + StringBuilder sb = new StringBuilder(); + while((line = br.readLine())!=null){ + sb.append(line); + } + String input = null2String(sb.toString()); + if(!"".equals(input)) { + if(isJsonValid(input)) { + JSONObject jo1 = JSON.parseObject(input); + apidatas.putAll(this.getService().sendData2(jo1)); + }else{ + apidatas.put("errno", -1); + apidatas.put("errmsg", "输入参数不是json格式"); + } + }else { + apidatas.put("errno", -1); + apidatas.put("errmsg", "输入参数为空!"); + } + } catch (Exception e) { + apidatas.put("errno", -1); + apidatas.put("errmsg", "catch exception : " + e.getMessage()); + } + return JSONObject.toJSONString(apidatas); + } + + + + public static String null2String(String s) { + return s == null ? "" : s; + } + + /** + * 判断JSON字符串是否合法 + * + * @param jsonStr JSON字符串 + * @return true:合法;false:不合法 + */ + public static boolean isJsonValid(String jsonStr) { + try { + JSON.parse(jsonStr); + return true; + } catch (JSONException e) { + return false; + } + } + +} diff --git a/com/engine/web/meeting/NewMeet.java b/com/engine/web/meeting/NewMeet.java index 62f4aa0..22c0c09 100644 --- a/com/engine/web/meeting/NewMeet.java +++ b/com/engine/web/meeting/NewMeet.java @@ -1,48 +1,102 @@ package com.engine.web.meeting; import com.alibaba.fastjson.JSONObject; +import com.api.meeting.cusvideo.util.YealinkVideoUtil; import com.engine.common.util.ParamUtil; import weaver.general.BaseBean; +import weaver.meeting.video.consumer.MeetingVideoFactory; +import weaver.meeting.video.consumer.VideoMeetingClient; + +import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.POST; import javax.ws.rs.Path; +import javax.ws.rs.Produces; import javax.ws.rs.core.Context; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Enumeration; +import java.util.HashMap; import java.util.Map; public class NewMeet { @Path("/newMeet") @POST - public String newMeet(@Context HttpServletRequest request, @Context HttpServletResponse response) { + @Produces("application/json") + public String newMeet(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException { + // try { + // Map map = getRequestParams(request); + // Map map = ParamUtil.request2Map(request); + JSONObject requestBody = getJson(request); + JSONObject meetingInfo = requestBody.getJSONObject("data").getJSONObject("meetingInfo"); + HashMap param = new HashMap<>(); + param.put("meetingNum",meetingInfo.getString("meetingNum")); + param.put("meetingID",meetingInfo.getString("meetingID")); + param.put("subject",meetingInfo.getString("subject")); + param.put("startTime",meetingInfo.getString("startTime")); + param.put("createType",meetingInfo.getString("createType")); + param.put("subjectID",meetingInfo.getJSONObject("organizer").getString("subjectID")); + param.put("displayName",meetingInfo.getJSONObject("organizer").getString("displayName")); + VideoMeetingClient videoMeetingClient = MeetingVideoFactory.getInstance("yealink"); + // videoMeetingClient.addMeeting() + + + + + return JSONObject.toJSONString(param); + + + } + + + public static JSONObject getJson(HttpServletRequest request) throws IOException { + //从前端获取输入字节流 + ServletInputStream requestInputStream = request.getInputStream(); + //将字节流转换为字符流,并设置字符编码为utf-8 + InputStreamReader ir = new InputStreamReader(requestInputStream,"utf-8"); + //使用字符缓冲流进行读取 + BufferedReader br = new BufferedReader(ir); + StringBuilder sb = new StringBuilder(); + try { + //开始拼装json字符串 + String line = null; + + while((line = br.readLine())!=null) { + sb.append(line); + } + }catch (Exception e){ + e.printStackTrace(); + }finally { + requestInputStream.close(); + ir.close(); + br.close(); + } + JSONObject json = JSONObject.parseObject(sb.toString()); + return json; + // StringBuilder stringBuilder = new StringBuilder(); + // BufferedReader reader = request.getReader(); // try { - Map map = ParamUtil.request2Map(request); - new BaseBean().writeLog("oameeting/newMeet--->" + map); - new BaseBean().writeLog("oameeting/newMeet--->" + JSONObject.toJSONString(map)); - -// String dataTable = (String) map.get("dataTable"); -// RecordSet recordSet = new RecordSet(); -// recordSet.executeQuery("select * from uf_View_resume_perm where sfqy = 0"); -// StringBuilder s = new StringBuilder(); -// while (recordSet.next()){ -// String xld = Utils.null2String(recordSet.getString("xld")); -// s.append(xld).append(","); -// } -// HashMap result = new HashMap<>(); -// if (s.length()>0){ -// result.put("data",s.toString().substring(0, s.length()-1)); -// }else { -// result.put("data",""); -// } -// result.put("code","200"); -// return JSONObject.toJSONString(result); -// }catch (Exception e){ - // e.printStackTrace(); - // HashMap result = new HashMap<>(); - // result.put("data",e.getMessage()); - // result.put("code","500"); - return JSONObject.toJSONString(null); + // String line; + // while ((line = reader.readLine()) != null) { + // stringBuilder.append(line).append('\n'); + // } + // } finally { + // reader.close(); + // } + // return JSONObject.parseObject(stringBuilder.toString()) ; + } + + private String getYealinkUrl(String host, String token, String mtnum, String userId, String meetingPassword) { + String url = host + "/meeting-join-links/" + mtnum; + JSONObject body = new JSONObject(); + body.put("language", "zh"); + body.put("password", meetingPassword); + JSONObject resultJson = YealinkVideoUtil.doGet(url, token, null, body); + return resultJson.getString("joinLink"); } } \ No newline at end of file diff --git a/com/engine/web/tjbk/TjbkServerSocket.java b/com/engine/web/tjbk/TjbkServerSocket.java index e6935fc..68a2095 100644 --- a/com/engine/web/tjbk/TjbkServerSocket.java +++ b/com/engine/web/tjbk/TjbkServerSocket.java @@ -18,7 +18,7 @@ import java.nio.charset.StandardCharsets; import java.util.Map; public class TjbkServerSocket implements ServletContextListener { - private SocketThread_sl socketThread; + private SocketThread socketThread; @Override public void contextDestroyed(ServletContextEvent arg0) { @@ -35,7 +35,7 @@ public class TjbkServerSocket implements ServletContextListener { new BaseBean().writeLog("contextInitialized启动"); ServletContext servletContext = arg0.getServletContext(); if (socketThread == null) { - socketThread = new SocketThread_sl(null, servletContext); + socketThread = new SocketThread(null, servletContext); socketThread.start(); // servlet上下文初始化时启动socket服务端线程 } } diff --git a/com/engine/web/tjbk/Tjbk_SL_ServerSocket.java b/com/engine/web/tjbk/Tjbk_SL_ServerSocket.java deleted file mode 100644 index 3d52dd5..0000000 --- a/com/engine/web/tjbk/Tjbk_SL_ServerSocket.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.engine.web.tjbk; - -import com.engine.tjbankSocket.SocketExecute; -import com.engine.tjbankSocket.impl.CWGLSocketExecute; -import com.engine.tjbankSocket.impl.GetToCountSocketExecute; -import com.engine.util.XMLUtils; -import org.apache.commons.lang.StringEscapeUtils; -import weaver.general.BaseBean; -import weaver.general.StringUtil; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import java.io.*; -import java.net.ServerSocket; -import java.net.Socket; -import java.nio.charset.StandardCharsets; -import java.util.Map; - -public class Tjbk_SL_ServerSocket implements ServletContextListener { - private SocketThread_sl socketThread; - - @Override - public void contextDestroyed(ServletContextEvent arg0) { - // TODO Auto-generated method stub - if (socketThread != null && socketThread.isInterrupted()) { - socketThread.closeServerSocket(); - socketThread.interrupt(); - } - } - - @Override - public void contextInitialized(ServletContextEvent arg0) { - // TODO Auto-generated method stub - new BaseBean().writeLog("contextInitialized启动"); - ServletContext servletContext = arg0.getServletContext(); - if (socketThread == null) { - socketThread = new SocketThread_sl(null, servletContext); - socketThread.start(); // servlet上下文初始化时启动socket服务端线程 - } - } - -} - - -class SocketThread_sl extends Thread { - - private ServletContext servletContext; - private ServerSocket serverSocket; - - public SocketThread_sl(ServerSocket serverSocket, ServletContext servletContext) { - this.servletContext = servletContext; - // 从web.xml中context-param节点获取socket端口 - String port = this.servletContext.getInitParameter("socketPortSL"); - if (serverSocket == null) { - try { - this.serverSocket = new ServerSocket(Integer.parseInt(port)); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @Override - public void run() { - - while (!this.isInterrupted()) { // 线程未中断执行循环 - try { - new BaseBean().writeLog("SocketThread线程启动"); - Socket socket = serverSocket.accept(); - if (socket != null) { - new ProcessSocketData_sl(socket, this.servletContext).start(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public void closeServerSocket() { - try { - if (serverSocket != null && !serverSocket.isClosed()) { - serverSocket.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } -} - -class ProcessSocketData_sl extends Thread { - - private Socket socket; - private ServletContext servletContext; - - public ProcessSocketData_sl() { - super(); - } - - public ProcessSocketData_sl(Socket socket, ServletContext servletContext) { - this.socket = socket; - this.servletContext = servletContext; - } - - @Override - public void run() { - try { -// BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); - new BaseBean().writeLog("ServerSocket线程启动"); - OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8); - - PrintWriter pw = new PrintWriter(outputStreamWriter); - InputStream inputStream = socket.getInputStream(); - BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); - char[] datalen=new char[8];//报文前八位为报文体总长度 - - in.read(datalen,0,8); - String lendata=new String (datalen); - int length=Integer.parseInt(lendata); - new BaseBean().writeLog("报文长度"+length); - // byte[] data=new byte[length]; - char[] data=new char[length]; - int datalength = in.read(data,0,length); - String requestData = new String(data); - new BaseBean().writeLog("requestData",requestData); - String s = ""; - if (!StringUtil.isEmpty(requestData.toString())) { - new BaseBean().writeLog("requestData",requestData); - s = execute(requestData.toString()); - } - // 执行自定义的请求解析方法,生成响应response - pw.println(s); - pw.flush(); // 刷新缓冲区 - pw.close(); - socket.close(); -// System.out.println(sb); - } catch (IOException e) { - e.printStackTrace(); - System.out.println(e); - } - } - private String execute(String XMLparam){ - new BaseBean().writeLog(this.getClass().getName()+":XMLparam=="+XMLparam); - - Map paramMap = XMLUtils.parseXMLToMap(XMLparam); - new BaseBean().writeLog(this.getClass().getName()+":paramMap=="+paramMap); - StringEscapeUtils.unescapeXml(XMLparam); - //目标系统代码 - String system_id = paramMap.get("system_id"); - // 请求方系统代码 - String requester_id = paramMap.get("requester_id"); - // 请求方机构代号 - String branch_id = paramMap.get("branch_id"); - new BaseBean().writeLog(this.getClass().getName()+":requester_id=="+requester_id); - SocketExecute socketExecute = null; - if ("0157".equals(requester_id)){ - socketExecute = new GetToCountSocketExecute(); - new BaseBean().writeLog(this.getClass().getName()+":GetToCountSocketExecute"); - }else if("0170".equals(requester_id)){ - socketExecute = new CWGLSocketExecute(); - new BaseBean().writeLog(this.getClass().getName()+":CWGLSocketExecute"); - } - String execute = socketExecute.execute(XMLparam); - return execute; - } -} diff --git a/com/engine/web/zhsl/Tjbk_SL_ServerSocket.java b/com/engine/web/zhsl/Tjbk_SL_ServerSocket.java deleted file mode 100644 index b51c968..0000000 --- a/com/engine/web/zhsl/Tjbk_SL_ServerSocket.java +++ /dev/null @@ -1,167 +0,0 @@ -package com.engine.web.zhsl; - -import com.engine.tjbankSocket.SocketExecute; -import com.engine.tjbankSocket.impl.CWGLSocketExecute; -import com.engine.tjbankSocket.impl.GetToCountSocketExecute; -import com.engine.util.XMLUtils; -import org.apache.commons.lang.StringEscapeUtils; -import weaver.general.BaseBean; -import weaver.general.StringUtil; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import java.io.*; -import java.net.ServerSocket; -import java.net.Socket; -import java.nio.charset.StandardCharsets; -import java.util.Map; - -public class Tjbk_SL_ServerSocket implements ServletContextListener { - private SocketThread_sl socketThread; - - @Override - public void contextDestroyed(ServletContextEvent arg0) { - // TODO Auto-generated method stub - if (socketThread != null && socketThread.isInterrupted()) { - socketThread.closeServerSocket(); - socketThread.interrupt(); - } - } - - @Override - public void contextInitialized(ServletContextEvent arg0) { - // TODO Auto-generated method stub - new BaseBean().writeLog("Tjbk_SL_ServerSocket——contextInitialized启动"); - ServletContext servletContext = arg0.getServletContext(); - if (socketThread == null) { - socketThread = new SocketThread_sl(null, servletContext); - socketThread.start(); // servlet上下文初始化时启动socket服务端线程 - } - } - -} - - -class SocketThread_sl extends Thread { - - private ServletContext servletContext; - private ServerSocket serverSocket; - - public SocketThread_sl(ServerSocket serverSocket, ServletContext servletContext) { - this.servletContext = servletContext; - // 从web.xml中context-param节点获取socket端口 - String port = this.servletContext.getInitParameter("socketPortSL"); - new BaseBean().writeLog("socketPortSL端口"+port); - if (serverSocket == null) { - try { - this.serverSocket = new ServerSocket(Integer.parseInt(port)); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @Override - public void run() { - - while (!this.isInterrupted()) { // 线程未中断执行循环 - try { - new BaseBean().writeLog("SocketThread线程启动"); - Socket socket = serverSocket.accept(); - if (socket != null) { - new ProcessSocketData_sl(socket, this.servletContext).start(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public void closeServerSocket() { - try { - if (serverSocket != null && !serverSocket.isClosed()) { - serverSocket.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } -} - -class ProcessSocketData_sl extends Thread { - - private Socket socket; - private ServletContext servletContext; - - public ProcessSocketData_sl() { - super(); - } - - public ProcessSocketData_sl(Socket socket, ServletContext servletContext) { - this.socket = socket; - this.servletContext = servletContext; - } - - @Override - public void run() { - try { -// BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); - new BaseBean().writeLog("ServerSocket线程启动"); - OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8); - - PrintWriter pw = new PrintWriter(outputStreamWriter); - InputStream inputStream = socket.getInputStream(); - BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); - char[] datalen=new char[8];//报文前八位为报文体总长度 - - in.read(datalen,0,8); - String lendata=new String (datalen); - int length=Integer.parseInt(lendata); - new BaseBean().writeLog("报文长度"+length); - // byte[] data=new byte[length]; - char[] data=new char[length]; - int datalength = in.read(data,0,length); - String requestData = new String(data); - new BaseBean().writeLog("requestData",requestData); - String s = ""; - if (!StringUtil.isEmpty(requestData.toString())) { - new BaseBean().writeLog("requestData",requestData); - s = execute(requestData.toString()); - } - // 执行自定义的请求解析方法,生成响应response - pw.println(s); - pw.flush(); // 刷新缓冲区 - pw.close(); - socket.close(); -// System.out.println(sb); - } catch (IOException e) { - e.printStackTrace(); - System.out.println(e); - } - } - private String execute(String XMLparam){ - new BaseBean().writeLog(this.getClass().getName()+":XMLparam=="+XMLparam); - - Map paramMap = XMLUtils.parseXMLToMap(XMLparam); - new BaseBean().writeLog(this.getClass().getName()+":paramMap=="+paramMap); - StringEscapeUtils.unescapeXml(XMLparam); - //目标系统代码 - String system_id = paramMap.get("system_id"); - // 请求方系统代码 - String requester_id = paramMap.get("requester_id"); - // 请求方机构代号 - String branch_id = paramMap.get("branch_id"); - new BaseBean().writeLog(this.getClass().getName()+":requester_id=="+requester_id); - SocketExecute socketExecute = null; - if ("0157".equals(requester_id)){ - socketExecute = new GetToCountSocketExecute(); - new BaseBean().writeLog(this.getClass().getName()+":GetToCountSocketExecute"); - }else if("0170".equals(requester_id)){ - socketExecute = new CWGLSocketExecute(); - new BaseBean().writeLog(this.getClass().getName()+":CWGLSocketExecute"); - } - String execute = socketExecute.execute(XMLparam); - return execute; - } -} diff --git a/rebel.xml b/rebel.xml new file mode 100644 index 0000000..1e23c7d --- /dev/null +++ b/rebel.xml @@ -0,0 +1,16 @@ + + + + + + TJBK_project + + + + + + + diff --git a/weaver/file/FileDownload.java b/weaver/file/FileDownload.java index 3f9ee9e..0dde94e 100644 --- a/weaver/file/FileDownload.java +++ b/weaver/file/FileDownload.java @@ -1,4198 +1,4204 @@ -// package weaver.file; -// -// /** -// * Title: -// * Description: ,2004-6-25:增加了是否记录下载次数到数据库 -// * Copyright: Copyright (c) 2002 -// * Company: -// * @author ,Charoes Huang -// * @version 1.0,2004-6-25 -// */ -// -// import java.io.BufferedInputStream; -// import java.io.BufferedOutputStream; -// import java.io.ByteArrayInputStream; -// import java.io.ByteArrayOutputStream; -// import java.io.File; -// import java.io.FileInputStream; -// import java.io.FileNotFoundException; -// import java.io.FileOutputStream; -// import java.io.IOException; -// import java.io.InputStream; -// import java.io.OutputStream; -// import java.io.RandomAccessFile; -// import java.net.HttpURLConnection; -// import java.net.URL; -// import java.net.URLEncoder; -// import java.text.SimpleDateFormat; -// import java.util.ArrayList; -// import java.util.Arrays; -// import java.util.Date; -// import java.util.Enumeration; -// import java.util.HashMap; -// import java.util.List; -// import java.util.Map; -// import java.util.UUID; -// import java.util.zip.ZipInputStream; -// -// import javax.servlet.ServletException; -// import javax.servlet.ServletOutputStream; -// import javax.servlet.http.HttpServlet; -// import javax.servlet.http.HttpServletRequest; -// import javax.servlet.http.HttpServletResponse; -// import javax.servlet.http.HttpSession; -// -// import com.api.doc.detail.service.DocViewPermission; -// import com.api.doc.detail.service.impl.DocWaterServiceImpl; -// import com.api.doc.detail.util.PdfConvertUtil; -// import com.api.doc.mobile.systemDoc.util.SystemDocUtil; -// import com.engine.common.util.ServiceUtil; -// import com.engine.doc.util.*; -// import com.engine.ecme.biz.EcmeRightManager; -// import com.engine.odoc.util.DocUtil; -// import org.apache.commons.io.FileUtils; -// import org.apache.commons.lang.StringEscapeUtils; -// import org.apache.commons.lang3.StringUtils; -// -// import weaver.WorkPlan.WorkPlanService; -// import weaver.alioss.AliOSSObjectManager; -// import weaver.blog.BlogDao; -// import weaver.common.DateUtil; -// import weaver.common.StringUtil; -// import weaver.conn.RecordSet; -// import weaver.cowork.CoworkDAO; -// import weaver.crm.CrmShareBase; -// import weaver.docs.EncryptDecryptFileUtil; -// import weaver.docs.category.SecCategoryComInfo; -// import weaver.docs.docs.DocManager; -// import weaver.docs.docs.AddWater.DocAddWaterForSecond; -// import weaver.email.service.MailFilePreviewService; -// import weaver.file.util.FileDeleteUtil; -// import weaver.file.util.FileManager; -// // import weaver.file.util.FileWaterManager; -// import weaver.file.util.FiledownloadUtil; -// import weaver.formmode.setup.ModeRightInfo; -// import weaver.general.BaseBean; -// import weaver.general.GCONST; -// import weaver.general.Util; -// import weaver.hrm.HrmUserVarify; -// import weaver.hrm.User; -// import weaver.hrm.resource.ResourceComInfo; -// import weaver.meeting.MeetingUtil; -// import weaver.mobile.plugin.ecology.service.AuthService; -// import weaver.rdeploy.doc.PrivateSeccategoryManager; -// import weaver.social.service.SocialIMService; -// import weaver.splitepage.operate.SpopForDoc; -// import weaver.system.SystemComInfo; -// import weaver.systeminfo.SystemEnv; -// import weaver.voting.VotingManager; -// import weaver.voting.groupchartvote.ImageCompressUtil; -// import DBstep.iMsgServer2000; -// -// import com.api.doc.detail.service.DocDetailService; -// import com.api.doc.detail.service.DocViewPermission; -// import com.api.doc.detail.util.DocCoopereateUtil; -// import com.api.doc.detail.util.DocDownloadCheckUtil; -// import com.api.doc.detail.util.ImageConvertUtil; -// import com.api.doc.upload.web.util.Json2MapUtil; -// import com.api.doc.wps.service.impl.WebOfficeServiceImpl; -// import com.api.workflow.service.RequestAuthenticationService; -// import com.engine.edc.biz.JoinCubeBiz; -// import com.weaver.formmodel.util.StringHelper; -// -// import de.schlichtherle.util.zip.ZipEntry; -// import de.schlichtherle.util.zip.ZipOutputStream; -// import weaver.wps.CommonUtil; -// import weaver.wps.doccenter.utils.Tools; -// -// public class FileDownload extends HttpServlet { -// /** -// * 是否需要记录下载次数 -// */ -// -// private boolean isCountDownloads = false; -// private String downloadFlag = ""; // 2298348 wgs -// private String agent = ""; -// private static final int BUFFER_SIZE = 1 *1024 * 1024; -// private BaseBean baseBean = new BaseBean(); -// private String systemWaterwriteLog = Util.null2s(baseBean.getPropValue("doc_custom_for_weaver","systemWaterwriteLog"),"0"); -// private String writeLogForDownload = Util.null2s(baseBean.getPropValue("doc_writelog_config","doc_download_log"),"1"); -// -// public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { -// this.doGet(req,res); -// } -// -// public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { -// -// -// User wmloginuser = (User)req.getSession(true).getAttribute("weaver_user@bean") ; -// String wmuserid=wmloginuser.getUID()+""; -// boolean wmflag = true; -// new BaseBean().writeLog("wmuserid---"+wmuserid); -// RecordSet wmrs = new RecordSet(); -// wmrs.execute("select count(1) as sl from uf_syqxryb where userid = '"+wmuserid+"'"); -// while (wmrs.next()){ -// if(Util.getIntValue(wmrs.getString("sl"))>0){ -// wmflag = false; -// } -// } -// String type = Util.null2String(req.getParameter("type")); -// Boolean _ec_ismobile = Boolean.valueOf(req.getParameter("_ec_ismobile")); -// String fromdocmobile = Util.null2String(req.getParameter("from_doc_mobile")); -// Boolean from_doc_mobile = fromdocmobile.equals("1") ? true : false; -// this.downloadFlag = Util.null2String(req.getParameter("download")); // 2298348 wgs -// writeLogs("download start!"); -// writeLogs("downloadFlag=" + downloadFlag); // 2447956 wgs -// int nolog = Util.getIntValue(Util.null2String(req.getParameter("nolog")),0); -// String res_content_disposition = Util.null2String(req.getParameter("response-content-disposition")); -// boolean isMobileDown=false; -// if(_ec_ismobile || from_doc_mobile || !"".equals(res_content_disposition)){ -// isMobileDown=true; -// } -// if("showMould".equals(type) || "editMould".equals(type) || "printMould".equals(type)){ -// downloadMould(req,res,type); -// }else if("weboffice".equals(type)){ -// downloadForWebOffice(req,res); -// }else if("doccenter".equals(type)){ -// downloadForDoccenterCoop(req,res); -// }else if("document".equals(type)){ -// User user = HrmUserVarify.getUser (req , res) ; -// downloadForDocument(req,res,user,wmflag ); -// }else if("ofd".equals(type)){ -// User user = HrmUserVarify.getUser (req , res) ; -// downloadOfd(req,res,user); -// }else if("odocExchange".equals(type)){ -// downloadForExchange(req,res); -// }else if("exportHtmlView".equals(type)){ -// ExportHtmlViewMould ehvm = new ExportHtmlViewMould(); -// int fileid = Util.getIntValue(req.getParameter("fileid")); -// Map dataMap = ehvm.toExport(fileid); -// String zipPath = dataMap.get("zipPath"); -// String filename = dataMap.get("zipName"); -// if(zipPath != null && !zipPath.isEmpty()){ -// ServletOutputStream out = null; -// InputStream imagefile = null; -// try { -// if((agent.contains("Firefox")||agent.contains(" Chrome")||agent.contains("Safari") )&& !agent.contains("Edge")){ -// res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); -// }else{ -// res.setHeader("content-disposition", "attachment; filename=\"" + -// URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\""); -// } -// } catch (Exception ecode) { -// ecode.printStackTrace(); -// } -// try { -// imagefile = new FileInputStream(zipPath); -// out = res.getOutputStream(); -// res.setContentType("application/x-download"); -// byte []data = new byte[2048]; -// int byteread = 0; -// while ((byteread = imagefile.read(data)) != -1) { -// out.write(data, 0, byteread); -// out.flush(); -// } -// } -// catch(Exception e) { -// e.printStackTrace(); -// }finally { -// if(imagefile!=null) imagefile.close(); -// if(out!=null) out.close(); -// -// ImportHtmlViewMould ihvm = new ImportHtmlViewMould(); -// ihvm.delTempFile(zipPath); -// ihvm.delTempFile(zipPath.replace(".zip","")); -// } -// } -// }else if("Email".equals(type)){ -// downloadForEmaill(req,res); -// }else if(!"netimag".equals(type)){ -// String clientEcoding = "GBK"; -// try -// { -// String acceptlanguage = Util.null2String(req.getHeader("Accept-Language")); -// if(!"".equals(acceptlanguage)) -// acceptlanguage = acceptlanguage.toLowerCase(); -// if(acceptlanguage.indexOf("zh-tw")>-1||acceptlanguage.indexOf("zh-hk")>-1) -// { -// clientEcoding = "BIG5"; -// } -// else -// { -// clientEcoding = "GBK"; -// } -// } -// catch(Exception e) -// { -// writeLogs(e); -// } -// -// agent = Util.null2String(req.getHeader("user-agent")); -// String frompdfview = Util.null2String(req.getParameter("frompdfview")); -// String downloadBatch = Util.null2String(req.getParameter("downloadBatch")); -// //只下载附件,而不是下载文档的附件 -// String onlydownloadfj = Util.null2String(req.getParameter("onlydownloadfj")); -// /*==============td26423 流程中批量下载 start=========================================================*/ -// if(downloadBatch!=null &&"1".equals(downloadBatch)){//批量下载---传入的是文档的ids -// //req.setCharacterEncoding("ISO8859-1"); -// String ipstring = Util.getIpAddr(req); -// String currentDateTime= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); -// String docids = Util.null2String(req.getParameter("fieldvalue"));//docids 以逗号隔开的 -// if(!"".equals(docids)){ -// String[] docidsarray=docids.split(","); -// if(docidsarray!=null && docidsarray.length>0){ -// String newdocids=""; -// for(String newdocid:docidsarray){ -// if(Util.getIntValue(newdocid)>0){ -// String secondAuthFileDownUrl=getSecondAuthFileDownUrl(req,isMobileDown,Util.getIntValue(newdocid)); -// if(!"".equals(secondAuthFileDownUrl)){ -// res.sendRedirect(secondAuthFileDownUrl); -// return; -// } -// if("".equals(newdocids)){ -// newdocids=newdocid; -// }else{ -// newdocids+=","+newdocid; -// } -// } -// } -// docids=newdocids; -// } -// } -// String displayUsage = Util.null2String(req.getParameter("displayUsage")); -// String tempFlag1=""; -// if(docids!=null&&!"".equals(docids)){ -// tempFlag1=docids.substring(docids.length()-1); -// } -// if(tempFlag1.equals(",")) docids=docids.substring(0,docids.length()-1); -// String delImgIds=Util.null2String(req.getParameter("delImgIds"));//imgeFileids 以逗号隔开的 -// String tempFlag=""; -// if(delImgIds!=null &&!"".equals(delImgIds)){ -// tempFlag=delImgIds.substring(delImgIds.length()-1); -// } -// if(tempFlag.equals(",")) delImgIds=delImgIds.substring(0,delImgIds.length()-1); -// -// String docSearchFlag=Util.null2String(req.getParameter("docSearchFlag"));//docSearchFlag ='1-标记为从查询文档中来批量下载多文档的多附件' -// -// String requestname =""; -// //String requestname = Util.null2String(req.getParameter("requestname"));//requestname 流程标题 -// //requestname =new String(requestname.getBytes("UTF-8")); -// RecordSet rsimagefileid =new RecordSet(); -// String requestid = Util.null2String(req.getParameter("requestid"));//requestname 流程标题 -// if(Util.getIntValue(requestid)>0){ -// String sqlrequestname="select requestname from workflow_requestbase where requestid='"+requestid+"'"; -// rsimagefileid.executeSql(sqlrequestname); -// if(rsimagefileid.next()){ -// requestname=Util.null2String(rsimagefileid.getString("requestname")); -// } -// } -// requestname = Util.StringReplace(requestname,"/","/"); -// String download = Util.null2String(req.getParameter("download")); -// -// User loginuser = (User)req.getSession(true).getAttribute("weaver_user@bean") ; -// String userid= Util.null2String(req.getParameter("f_weaver_belongto_userid")); -// if("".equals(userid) || userid == null){ -// userid=loginuser.getUID()+""; -// } -// //String loginid=loginuser.getLoginid(); -// //String[] docidsList = Util.TokenizerString2(docids, ","); -// //List docImagefileidList= new ArrayList(); -// String docImagefileids=""; -// String sqlimagefileid="select a.id,a.docsubject,b.imagefileid,b.imagefilename from DocDetail a,DocImageFile b where a.id=b.docid and a.id in ("+docids+") and b.versionId = (select MAX(c.versionId) from DocImageFile c where c.id=b.id ) order by a.id asc"; -// -// /* -// String sqlimagefileid=""; -// if("1".equals(docSearchFlag)){//处理从查询文档中 来的文档附件批量下载时只下载最新版本问题 -// sqlimagefileid="select a.id,a.docsubject,b.imagefileid,b.imagefilename from DocDetail a,DocImageFile b where a.id=b.docid and a.id in ("+docids+") and b.versionId = (select MAX(c.versionId) from DocImageFile c where c.id=b.id ) order by a.id asc"; -// }else{ -// sqlimagefileid="select a.id,a.docsubject,b.imagefileid,b.imagefilename from DocDetail a,DocImageFile b where a.id=b.docid and a.id in ("+docids+") order by a.id asc"; -// } -// */ -// String docsubject=""; -// rsimagefileid.executeSql(sqlimagefileid); -// int counts=rsimagefileid.getCounts(); -// String urlType = Util.null2String(req.getParameter("urlType")); -// if(counts<=0){ -// if("1".equals(docSearchFlag)){ -// if(urlType.equals("10")){ -// res.sendRedirect(GCONST.getContextPath()+"/docs/search/DocCommonContent.jsp?urlType=10&displayUsage="+displayUsage); -// }else{ -// res.sendRedirect(GCONST.getContextPath()+"/docs/search/DocCommonContent.jsp?urlType=6&fromUrlType=1&displayUsage="+displayUsage); -// } -// return; -// }else{ -// res.sendRedirect(GCONST.getContextPath()+"/login/BatchDownloadsEror.jsp"); -// return; -// } -// } -// int num=0; -// while(rsimagefileid.next()){ -// num++; -// if(num==counts){ -// docImagefileids += Util.null2String(rsimagefileid.getString("imagefileid")); -// }else{ -// docImagefileids += Util.null2String(rsimagefileid.getString("imagefileid"))+","; -// } -// docsubject=Util.null2String(rsimagefileid.getString("docsubject")); -// } -// List filenameList = new ArrayList(); -// List filerealpathList = new ArrayList(); -// List filerealpathTempList = new ArrayList(); -// List docidList = new ArrayList(); -// List imagefileidList = new ArrayList(); -// //List filerealpathTempParentList = new ArrayList(); -// File fileTemp=null; -// String sqlfilerealpath=""; -// ImageFileManager imageFileManager=new ImageFileManager(); -// if(delImgIds!=null &&!"".equals(delImgIds)){ -// //sqlfilerealpath="select imagefilename,filerealpath,iszip,isencrypt,imagefiletype , imagefileid, imagefile from ImageFile where imagefileid in ("+delImgIds+")"; -// sqlfilerealpath = "select t2.docid,t1.isaesencrypt,t1.comefrom,t1.aescode,t1.imagefilename,t1.filerealpath,t1.iszip,t1.isencrypt,t1.imagefiletype , t1.imagefileid, t1.imagefile,t2.imagefilename as realname from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.imagefileid in ("+delImgIds+") " +(docids.equals("")?"":" and docid in("+docids+") "); -// }else{ -// //sqlfilerealpath="select imagefilename,filerealpath,iszip,isencrypt,imagefiletype , imagefileid, imagefile from ImageFile where imagefileid in ("+docImagefileids+")"; -// sqlfilerealpath = "select t2.docid,t1.isaesencrypt,t1.comefrom,t1.aescode,t1.imagefilename,t1.filerealpath,t1.iszip,t1.isencrypt,t1.imagefiletype , t1.imagefileid, t1.imagefile,t2.imagefilename as realname from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.imagefileid in ("+docImagefileids+") " +(docids.equals("")?"":" and docid in("+docids+") "); -// } -// -// rsimagefileid.executeSql(sqlfilerealpath); -// String fromrequest = req.getParameter("fromrequest"); -// -// Map filenameMap = new HashMap(); -// String imagefileid = ""; -// String pdfimagefileid = ""; //office文档转换过来的PDFid -// Map rightDoc = new HashMap(); -// while(rsimagefileid.next()){ -// try{ -// imagefileid = Util.null2String(rsimagefileid.getString("imagefileid")); -// String filename = Util.null2String(rsimagefileid.getString("realname")); -// if(filename.equals("")){ -// filename = Util.null2String(rsimagefileid.getString("imagefilename")); -// } -// String filerealpath = Util.null2String(rsimagefileid.getString("filerealpath")); -// String iszip = Util.null2String(rsimagefileid.getString("iszip")); -// String isencrypt = Util.null2String(rsimagefileid.getString("isencrypt")); -// String isaesencrypt = Util.null2String(rsimagefileid.getString("isaesencrypt")); -// String aescode = Util.null2String(rsimagefileid.getString("aescode")); -// String _comefrom= Util.null2String(rsimagefileid.getString("comefrom")); -// String _docid = Util.null2String(rsimagefileid.getString("docid")); -// if(!_docid.isEmpty() && rightDoc.get(_docid) == null){ -// boolean hasRight = getWhetherHasRight(imagefileid,req,res,Util.getIntValue(requestid),false,null); -// if(!hasRight && !HrmUserVarify.checkUserRight("DocFileBatchDownLoad:ALL", loginuser)) -// continue; -// rightDoc.put(_docid,true); -// } -// -// int docidans1 = -1; -// /**流程下载附件,获取最新版本附件下载 start */ -// if("1".equals(fromrequest)){ -// RecordSet rs = new RecordSet(); -// rs.executeSql("select doceditionid,id from DocDetail where id=(select max(docid) from DocImageFile where imagefileid=" + imagefileid + ")"); -// if(rs.next()){ -// int doceditionid = rs.getInt("doceditionid"); -// int docid = rs.getInt("id"); -// docidans1 = docid; -// if(doceditionid > 0){ //有多版本文档,取最新版本文档 -// rs.executeSql("select id from DocDetail where doceditionid=" + doceditionid + " order by docedition desc"); -// if(rs.next()){ -// docid = rs.getInt("id"); -// } -// } -// -// //在新版本文档下取最新附件 -// rs.executeSql("select f.imagefileid,f.imagefilename,f.filerealpath,d.imagefilename realname from DocImageFile d,imagefile f where d.imagefileid=f.imagefileid and d.docid=" + docid + " order by d.versionId desc"); -// if(rs.next()){ -// imagefileid = rs.getString("imagefileid"); -// filename = Util.null2String(rsimagefileid.getString("realname")); -// if(filename.equals("")){ -// filename = Util.null2String(rsimagefileid.getString("imagefilename")); -// } -// filerealpath = Util.null2String(rsimagefileid.getString("filerealpath")); -// } -// } -// } -// /**流程下载附件,获取最新附件 end */ -// -// if(!"DocLogAction_DocLogFile".equals(_comefrom) && FiledownloadUtil.isdownloadpdf(filename) && download.equals("1")){ -// pdfimagefileid = FiledownloadUtil.getpdfidByOfficeid(imagefileid); -// if(pdfimagefileid.isEmpty()){ -// pdfimagefileid = imagefileid; -// } -// String pdffileinfosql = "select imagefilename,filerealpath from imagefile where imagefileid = ? "; -// RecordSet pdffileinfors = new RecordSet(); -// pdffileinfors.executeQuery(pdffileinfosql,pdfimagefileid); -// if(pdffileinfors.next()){ -// filename = Util.null2String(pdffileinfors.getString("imagefilename")); -// filerealpath = Util.null2String(pdffileinfors.getString("filerealpath")); -// } -// }else{ -// pdfimagefileid = imagefileid; -// } -// if(!"".equals(filename)){ -// filename = filename.replace("&","&"); -// } -// filenameList.add(filename); -// filerealpathList.add(filerealpath); -// docidList.add(docidans1); -// imagefileidList.add(imagefileid); -// //是否需要记录日志 -// if(addDownLoadLogByimageId(Util.getIntValue(imagefileid))){ -// // 记录下载日志 begin -// -// String userType = loginuser.getLogintype(); -// if ("1".equals(userType)) { // 如果是内部用户 名称就是 lastName -// // 外部则入在 firstName里面 -// downloadLog(loginuser.getUID(), loginuser.getLastname(), Util.getIntValue(imagefileid),filename, ipstring); -// } else { -// downloadLog(loginuser.getUID(), loginuser.getFirstname(), Util.getIntValue(imagefileid),filename, ipstring); -// } -// -// // 记录下载日志 end -// } -// String extName = ""; -// int byteread; -// byte data[] = new byte[1024]; -// if(filename.indexOf(".") > -1){ -// int bx = filename.lastIndexOf("."); -// if(bx>=0){ -// extName = filename.substring(bx+1, filename.length()); -// } -// } -// -// InputStream imagefile = null; -// if(!"".equals(pdfimagefileid) && !imagefileid.equals(pdfimagefileid)){ -// imageFileManager.getImageFileInfoById(Util.getIntValue(pdfimagefileid)); -// }else{ -// imageFileManager.getImageFileInfoById(Util.getIntValue(imagefileid)); -// } -// //writeLogs("452 downloadFlag=" + downloadFlag); -// imageFileManager.setDownloadFlag(downloadFlag); // 2298348 wgs -// imagefile=imageFileManager.getInputStream(); -// -// if(download.equals("1") && (isOfficeToDocument(extName))&&isMsgObjToDocument()) { -// //正文的处理 -// ByteArrayOutputStream bout = null; -// try { -// bout = new ByteArrayOutputStream() ; -// while((byteread = imagefile.read(data)) != -1) { -// bout.write(data, 0, byteread) ; -// bout.flush() ; -// } -// byte[] fileBody = bout.toByteArray(); -// iMsgServer2000 MsgObj = new iMsgServer2000(); -// MsgObj.MsgFileBody(fileBody); //将文件信息打包 -// fileBody = MsgObj.ToDocument(MsgObj.MsgFileBody()); //通过iMsgServer200 将pgf文件流转化为普通Office文件流 -// imagefile = new ByteArrayInputStream(fileBody); -// bout.close(); -// } -// catch(Exception e) { -// writeLogs(e); -// if(bout!=null) bout.close(); -// } -// } -// -// FileOutputStream out = null; -// try { -// -// SystemComInfo syscominfo = new SystemComInfo(); -// String fileFoder= syscominfo.getFilesystem(); -// String fileFoderCompare= syscominfo.getFilesystem(); -// if("".equals(fileFoder)){ -// fileFoder = GCONST.getRootPath(); -// fileFoder = fileFoder + "filesystem" + File.separatorChar+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; -// }else{ -// if(fileFoder.endsWith(File.separator) ){ -// fileFoder += "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; -// }else{ -// fileFoder += File.separator+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; -// } -// } -// -// String _fielname = UUID.randomUUID().toString(); -// if(filename.indexOf(".") > -1){ -// int bx = filename.lastIndexOf("."); -// if(bx>=0){ -// _fielname += filename.substring(bx, filename.length()); -// } -// } -// -// if("".equals(fileFoderCompare)){ -// fileFoderCompare = GCONST.getRootPath(); -// fileFoderCompare = fileFoderCompare + "filesystem" + File.separatorChar+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; -// }else{ -// if(fileFoderCompare.endsWith(File.separator)){ -// fileFoderCompare += "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; -// }else{ -// fileFoderCompare += File.separator+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; -// } -// } -// //附件文件重名加数字后缀区别:因为不加以区别的话,压缩到压缩包时只取一个文件(压缩包中不能有同名文件) 加唯一标识'_imagefileid' -// for (String m : filenameMap.keySet()) { -// String keyValue = filenameMap.get(m); -// if(keyValue.equals(filename)){ -// String tepName= filename.contains(".")? filename.substring(0, filename.indexOf(".")) : ""; -// if(tepName!=null&&!"".equals(tepName)){ -// String extNameTemp = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : ""; -// filename = tepName + "_"+imagefileid+"."+extNameTemp; -// -// } -// -// } -// } -// filenameMap.put(_fielname, filename); -// -// //String fileFoder=GCONST.getRootPath()+ "downloadBatchTemp"+File.separatorChar+userid+File.separatorChar;//获取系统的运行目录 如:d:\ecology\ -// //String fileFoderCompare=GCONST.getRootPath()+ "downloadBatchTemp"+File.separatorChar+userid+File.separatorChar+filename; -// String newFileName=_fielname; -// for(int j=0;j=0){ -// if(!"".equals(pdfimagefileid) && !imagefileid.equals(pdfimagefileid)){ -// newFileName=filename.substring(0, lastindex)+"_"+pdfimagefileid+filename.substring(lastindex); -// }else{ -// newFileName=filename.substring(0, lastindex)+"_"+imagefileid+filename.substring(lastindex); -// } -// }else{ -// if(!"".equals(pdfimagefileid) && !imagefileid.equals(pdfimagefileid)){ -// newFileName=filename+"_"+pdfimagefileid; -// }else{ -// newFileName=filename+"_"+imagefileid; -// } -// -// } -// } -// } -// fileTemp=this.fileCreate(fileFoder, newFileName);//在系统的根目录下创建了一个文件夹(downloadBatchTemp)及附件文件 -// out = new FileOutputStream(fileTemp); -// -// imagefile = FileManager.download(req,imagefileid,filerealpath,aescode,iszip,isaesencrypt,imagefile); -// //======================= -// while ((byteread = imagefile.read(data)) != -1) { -// out.write(data, 0, byteread); -// out.flush(); -// } -// String filerealpathTemp=fileTemp.getPath(); -// //String filerealpathTempParent=fileTemp.getParent(); -// //filerealpathTempParentList.add(filerealpathTempParent); -// //filerealpathTempList.add(filerealpathTemp); -// filerealpathTempList.add(fileFoder+newFileName); -// }catch(Exception e) { -// writeLogs(e); -// //do nothing -// }finally { -// if(imagefile!=null) imagefile.close(); -// if(out!=null) out.flush(); -// if(out!=null) out.close(); -// } -// }catch(Exception e){ -// BaseBean basebean = new BaseBean(); -// basebean.writeLog(e); -// continue; -// } -// } -// -// if(filerealpathList.size() == 0){ -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?v1"); -// return; -// } -// -// -// //存储下载的文件路径 把临时存放的附件 打压缩包 提供给用户下载 -// File[] files=new File[filerealpathList.size()]; -// for(int i=0;i secWmSetMap = WaterMarkUtil.getCategoryWmSet(imagefileid); -// if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD)) && "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtil.WATERCONTENTISNULL))){ -// // is = WaterMarkUtil.takefileWater(is,loginuser,filename,Util.getIntValue(fileid),extName,WaterMarkUtil.MOULDDOC); -// is = FileWaterManager.takewater(req,fileid,filename,extName,is, WaterMarkUtil.MOULDDOC,-1); -// } -// } -// -// //ZipEntry ze=new ZipEntry(filenameMap.get(files[j].getAbsolutePath()));//设置文件编码格式 -// ZipEntry ze = new ZipEntry(filenameMap.get(files[j].getName()));//设置文件编码格式 -// zout.putNextEntry(ze); -// int len; -// //读取下载文件内容 -// while((len=is.read(bt))>0){ -// zout.write(bt, 0, len); -// } -// zout.closeEntry(); -// is.close(); -// }catch(Exception e){ -// BaseBean basebean = new BaseBean(); -// basebean.writeLog(e); -// continue; -// } -// } -// zout.close(); -// this.toUpload(res, strs, tmptfilename);//调用下载方法 -// //String fileTempParent=fileTemp.getParent(); -// //this.deleteFile(fileTempParent);//下载完成后调用删除文件的方法删除downloadBatchTemp文件夹下的子文件夹 -// /* -// for(int i=0;i0){ -// fieldids = fieldids.substring(0,fieldids.length()-1); -// } -// toWriteLog("onlydownloadfj----1----批量下载--fieldids:"+fieldids+"--labelid:"+labelid+"--userid:"+userid+"--download:"+download); -// if(!"".equals(fieldids)){ -// String[] fieldidsarray=fieldids.split(","); -// String newfieldids=""; -// for(String newfileid:fieldidsarray){ -// if(Util.getIntValue(newfileid)>0){ -// if("".equals(newfieldids)){ -// newfieldids=newfileid; -// }else{ -// newfieldids+=","+newfileid; -// } -// } -// } -// fieldids=newfieldids; -// String[] newfieldidsarray=fieldids.split(","); -// RecordSet rsprop = new RecordSet(); -// String secondAuthsql = " select distinct docid from docImageFile where imagefileid in ("+fieldids+")"; -// rsprop.executeSql(secondAuthsql); -// while(rsprop.next()){ -// int docid=Util.getIntValue(rsprop.getString("docid")); -// if(docid>0){ -// String secondAuthFileDownUrl=getSecondAuthFileDownUrl(req,isMobileDown,docid); -// if(!"".equals(secondAuthFileDownUrl)){ -// res.sendRedirect(secondAuthFileDownUrl); -// return; -// } -// } -// } -// int maxDownFileCount = Util.getIntValue(rsprop.getPropValue("BatchDownFileControl","maxDownFileCount"),10); -// int maxDownFileTotalSize = Util.getIntValue(rsprop.getPropValue("BatchDownFileControl","maxDownFileTotalSize"),200); -// if(newfieldidsarray.length>maxDownFileCount){ -// res.sendRedirect(GCONST.getContextPath()+"/wui/common/page/sysRemindDocpreview.jsp?labelid="+SystemEnv.getHtmlLabelName(534454,loginuser.getLanguage())+maxDownFileCount); -// return; -// }else{ -// String dbType = rsprop.getDBType(); -// String sql = " select sum(fileSize) totalfilesize from ImageFile where imagefileid in ("+fieldids+")"; -// if("sqlserver".equals(dbType)){ -// sql = " select SUM(cast(filesize as numeric(30,0))) totalfilesize from ImageFile where imagefileid in ("+fieldids+")"; -// } -// rsprop.executeSql(sql); -// if(rsprop.next()){ -// double totalfilesize = Util.getDoubleValue(rsprop.getString("totalfilesize"),0); -// if(totalfilesize>maxDownFileTotalSize*1024*1024){ -// res.sendRedirect(GCONST.getContextPath()+"/wui/common/page/sysRemindDocpreview.jsp?labelid="+SystemEnv.getHtmlLabelName(534453,loginuser.getLanguage())+maxDownFileTotalSize); -// return; -// } -// } -// } -// }else{ -// return; -// } -// List filenameList = new ArrayList(); -// List filerealpathList = new ArrayList(); -// List filerealpathTempList = new ArrayList(); -// List fileids = new ArrayList(); -// String sqlfilerealpath=""; -// ImageFileManager imageFileManager=new ImageFileManager(); -// sqlfilerealpath = "select * from imagefile where imagefileid in("+fieldids+") "; -// RecordSet rsimagefileid =new RecordSet(); -// rsimagefileid.executeSql(sqlfilerealpath); -// String imagefileid = ""; -// String pdfimagefileid = ""; -// Map filenameMap = new HashMap(); -// while(rsimagefileid.next()){ -// String downloadpdfimagefileid = ""; -// try{ -// imagefileid = Util.null2String(rsimagefileid.getString("imagefileid")); -// String filename = Util.null2String(rsimagefileid.getString("realname")); -// if(filename.equals("")){ -// filename = Util.null2String(rsimagefileid.getString("imagefilename")); -// } -// String filerealpath = Util.null2String(rsimagefileid.getString("filerealpath")); -// String iszip = Util.null2String(rsimagefileid.getString("iszip")); -// String isencrypt = Util.null2String(rsimagefileid.getString("isencrypt")); -// String isaesencrypt = Util.null2String(rsimagefileid.getString("isaesencrypt")); -// String aescode = Util.null2String(rsimagefileid.getString("aescode")); -// String _comefrom = Util.null2String(rsimagefileid.getString("comefrom")); -// boolean hasRight = getWhetherHasRight(imagefileid,req,res,Util.getIntValue(req.getParameter("requestid")),false,null); -// toWriteLog("onlydownloadfj----2----批量下载--imagefileid:"+imagefileid+"--filename:" -// +filename+"--userid:"+userid+"--filerealpath:"+filerealpath+"--hasRight:"+hasRight); -// if(!hasRight) -// continue; -// -// if(!"DocLogAction_DocLogFile".equals(_comefrom) && FiledownloadUtil.isdownloadpdf(filename) && download.equals("1")){ -// pdfimagefileid = FiledownloadUtil.getpdfidByOfficeid(imagefileid); -// if(pdfimagefileid.isEmpty()){ -// pdfimagefileid = imagefileid; -// } -// String pdffileinfosql = "select imagefilename,filerealpath from imagefile where imagefileid = ? "; -// RecordSet pdffileinfors = new RecordSet(); -// pdffileinfors.executeQuery(pdffileinfosql,pdfimagefileid); -// if(pdffileinfors.next()){ -// filename = Util.null2String(pdffileinfors.getString("imagefilename")); -// filerealpath = Util.null2String(pdffileinfors.getString("filerealpath")); -// } -// }else{ -// pdfimagefileid = imagefileid; -// } -// String extName = ""; -// if(filename.indexOf(".") > -1) { -// int bx = filename.lastIndexOf("."); -// if (bx >= 0) { -// extName = filename.substring(bx + 1, filename.length()); -// } -// } -// if(ImageConvertUtil.canConvertPdfForDownload(extName,imagefileid)&& !frompdfview.equals("1") && download.equals("1")) { -// RecordSet rsrecord = new RecordSet(); -// PdfConvertUtil pdfConvertUtil = new PdfConvertUtil(); -// int pdfid = pdfConvertUtil.convertPdf(Util.getIntValue(imagefileid)); -// if (pdfid > 0) { -// downloadpdfimagefileid = String.valueOf(pdfid); -// String pdffileinfosql = "select imagefilename,filerealpath from imagefile where imagefileid = ? "; -// RecordSet pdffileinfors = new RecordSet(); -// pdffileinfors.executeQuery(pdffileinfosql, downloadpdfimagefileid); -// if (pdffileinfors.next()) { -// filename = filename.substring(0, filename.lastIndexOf(".")) + ".pdf"; -// filerealpath = Util.null2String(pdffileinfors.getString("filerealpath")); -// } -// } -// } -// if(downloadpdfimagefileid.isEmpty()){ -// downloadpdfimagefileid = imagefileid+""; -// } -// if(!"".equals(filename)){ -// filename = filename.replace("&","&"); -// } -// -// filenameList.add(filename); -// filerealpathList.add(filerealpath); -// fileids.add(Util.getIntValue(downloadpdfimagefileid)); -// int byteread; -// byte data[] = new byte[1024]; -// if(filename.indexOf(".") > -1){ -// int bx = filename.lastIndexOf("."); -// if(bx>=0){ -// extName = filename.substring(bx+1, filename.length()); -// } -// } -// -// InputStream imagefile = null; -// if(!"".equals(pdfimagefileid) && !imagefileid.equals(pdfimagefileid)){ -// imageFileManager.getImageFileInfoById(Util.getIntValue(pdfimagefileid)); -// }else{ -// imageFileManager.getImageFileInfoById(Util.getIntValue(imagefileid)); -// } -// //writeLogs("863 downloadFlag=" + downloadFlag); -// imageFileManager.setDownloadFlag(downloadFlag); // 2298348 wgs -// imagefile=imageFileManager.getInputStream(); -// -// if(download.equals("1") && (isOfficeToDocument(extName))&&isMsgObjToDocument()) { -// //正文的处理 -// ByteArrayOutputStream bout = null; -// try { -// bout = new ByteArrayOutputStream() ; -// while((byteread = imagefile.read(data)) != -1) { -// bout.write(data, 0, byteread) ; -// bout.flush() ; -// } -// byte[] fileBody = bout.toByteArray(); -// iMsgServer2000 MsgObj = new iMsgServer2000(); -// MsgObj.MsgFileBody(fileBody); //将文件信息打包 -// fileBody = MsgObj.ToDocument(MsgObj.MsgFileBody()); //通过iMsgServer200 将pgf文件流转化为普通Office文件流 -// imagefile = new ByteArrayInputStream(fileBody); -// bout.close(); -// } -// catch(Exception e) { -// writeLogs(e); -// if(bout!=null) bout.close(); -// } -// } -// -// FileOutputStream out = null; -// try { -// -// SystemComInfo syscominfo = new SystemComInfo(); -// String fileFoder= syscominfo.getFilesystem(); -// String fileFoderCompare= syscominfo.getFilesystem(); -// if("".equals(fileFoder)){ -// fileFoder = GCONST.getRootPath(); -// fileFoder = fileFoder + "filesystem" + File.separatorChar+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; -// }else{ -// if(fileFoder.endsWith(File.separator)){ -// fileFoder += "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; -// }else{ -// fileFoder += File.separator+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; -// } -// } -// -// -// String _fielname = UUID.randomUUID().toString(); -// if(filename.indexOf(".") > -1){ -// int bx = filename.lastIndexOf("."); -// if(bx>=0){ -// _fielname += filename.substring(bx, filename.length()); -// } -// } -// -// -// -// if("".equals(fileFoderCompare)){ -// fileFoderCompare = GCONST.getRootPath(); -// fileFoderCompare = fileFoderCompare + "filesystem" + File.separatorChar+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; -// }else{ -// if(fileFoderCompare.endsWith(File.separator)){ -// fileFoderCompare += "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; -// }else{ -// fileFoderCompare += File.separator+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; -// } -// } -// toWriteLog("onlydownloadfj----3----批量下载--imagefileid:"+imagefileid+"--filename:" -// +filename+"--userid:"+userid+"--fileFoder:"+fileFoder+"--fileFoderCompare:"+fileFoderCompare); -// //String fileFoder=GCONST.getRootPath()+ "downloadBatchTemp"+File.separatorChar+userid+File.separatorChar;//获取系统的运行目录 如:d:\ecology\ -// //附件文件重名加数字后缀区别:因为不加以区别的话,压缩到压缩包时只取一个文件(压缩包中不能有同名文件) 加唯一标识'_imagefileid' -// //String fileFoderCompare=GCONST.getRootPath()+ "downloadBatchTemp"+File.separatorChar+userid+File.separatorChar+filename; -// -// //附件文件重名加数字后缀区别:因为不加以区别的话,压缩到压缩包时只取一个文件(压缩包中不能有同名文件) 加唯一标识'_imagefileid' -// for (String m : filenameMap.keySet()) { -// String keyValue = filenameMap.get(m); -// if(keyValue.equals(filename)){ -// String tepName= filename.contains(".")? filename.substring(0, filename.indexOf(".")) : ""; -// if(tepName!=null&&!"".equals(tepName)){ -// String extNameTemp = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : ""; -// filename = tepName + "_"+imagefileid+"."+extNameTemp; -// -// } -// -// } -// } -// filenameMap.put(_fielname, filename); -// String newFileName=_fielname; -// toWriteLog("onlydownloadfj----4----批量下载--imagefileid:"+imagefileid+"--filename:" -// +filename+"--userid:"+userid+"--fileFoder:"+fileFoder+"--fileFoderCompare:"+fileFoderCompare -// +"--newFileName:"+newFileName+"--filerealpathTempList:"+filerealpathTempList+"--out:"+filerealpathTempList -// +"--imagefile:"+imagefile); -// fileTemp=this.fileCreate(fileFoder, newFileName);//在系统的根目录下创建了一个文件夹(downloadBatchTemp)及附件文件 -// out = new FileOutputStream(fileTemp); -// -// imagefile = FileManager.download(req,imagefileid,filerealpath,aescode,iszip,isaesencrypt,imagefile); -// Map secWmSetMap = WaterMarkUtilNew.getCategoryWmSet(imagefileid); -// //writeLogs("957 imagefileid=" + imagefileid); -// shouldAddFileDownLoadWm(secWmSetMap, imagefileid); // 2447956 wgs -// -// if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtilNew.SECCATEGORYDOWNLOAD))&& "1".equals(secWmSetMap.get(WaterMarkUtilNew.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtilNew.WATERCONTENTISNULL))){ -// imagefile = FileWaterManager.takewater(req,downloadpdfimagefileid,filename,extName,imagefile, WaterMarkUtil.MOULDDOC,Util.getIntValue(imagefileid)); -// } -// while ((byteread = imagefile.read(data)) != -1) { -// out.write(data, 0, byteread); -// out.flush(); -// } -// String filerealpathTemp=fileTemp.getPath(); -// //String filerealpathTempParent=fileTemp.getParent(); -// //filerealpathTempParentList.add(filerealpathTempParent); -// //filerealpathTempList.add(filerealpathTemp); -// filerealpathTempList.add(fileFoder+newFileName); -// }catch(Exception e) { -// //do nothing -// e.printStackTrace(); -// }finally { -// if(imagefile!=null) imagefile.close(); -// if(out!=null) out.flush(); -// if(out!=null) out.close(); -// } -// }catch(Exception e){ -// BaseBean basebean = new BaseBean(); -// basebean.writeLog(e); -// continue; -// } -// } -// -// if(filerealpathList.size() == 0){ -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?v2"); -// return; -// } -// toWriteLog("onlydownloadfj----5----批量下载--filerealpathList:"+filerealpathList+"--filerealpathTempList:" -// +filerealpathTempList+"--userid:"+userid); -// //存储下载的文件路径 把临时存放的附件 打压缩包 提供给用户下载 -// File[] files=new File[filerealpathList.size()]; -// for(int i=0;i secWmSetMap = WaterMarkUtil.getCategoryWmSet(imagefileid); -// //writeLogs("1053 imagefileid=" + imagefileid); -// shouldAddFileDownLoadWm(secWmSetMap, imagefileid); // 2447956 wgs -// if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD))&& "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtil.WATERCONTENTISNULL))){ -// // is = WaterMarkUtil.takefileWater(is,loginuser,filename,fileids.get(j),extName,WaterMarkUtil.MOULDDOC); -// is = FileWaterManager.takewater(req,fileids.get(j)+"",filename,extName,is, WaterMarkUtil.MOULDDOC,-1); -// } -// } -// ZipEntry ze=new ZipEntry(filenameMap.get(files[j].getName()));//设置文件编码格式 -// zout.putNextEntry(ze); -// int len; -// //读取下载文件内容 -// while((len=is.read(bt))>0){ -// zout.write(bt, 0, len); -// } -// zout.closeEntry(); -// is.close(); -// }catch(Exception e){ -// BaseBean basebean = new BaseBean(); -// basebean.writeLog(e); -// continue; -// } -// } -// zout.close(); -// this.toUpload(res, strs,tmptfilename);//调用下载方法 -// //String fileTempParent=fileTemp.getParent(); -// //this.deleteFile(fileTempParent);//下载完成后调用删除文件的方法删除downloadBatchTemp文件夹下的子文件夹 -// /* -// for(int i=0;i jsonParams = new HashMap(); -// boolean fromMobile = false; -// int userid = 0; -// jsonParams = Json2MapUtil.requestJson2Map(req); -// if(fileid <=0 ){ -// fileid = Util.getIntValue(Util.null2String(jsonParams.get("fileid"))); -// fromMobile = true; -// userid = Util.getIntValue(Util.null2String(jsonParams.get("userid"))); -// requestid = Util.getIntValue(Util.null2String(jsonParams.get("requestid"))); -// } -// -// String ddcode = req.getParameter("ddcode"); -// int codeuserid = 0; -// User userddcode = (User)req.getSession(true).getAttribute("weaver_user@bean"); -// if(ddcode != null && !ddcode.isEmpty() && userddcode==null){ -// try{ -// Map ddcodeMap = SystemDocUtil.deDdcode(userddcode,ddcode); -// String isovertime = Util.null2String(ddcodeMap.get(SystemDocUtil.ISOVERTIME)); -// if("1".equals(isovertime)){ -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?ddcodeTimeout=1"); -// return; -// }else{ -// userid = Util.getIntValue((String) ddcodeMap.get(SystemDocUtil.USERID)); -// String fileidcode = Util.null2String(ddcodeMap.get(SystemDocUtil.FILEID)); -// fileid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileidstr(fileidcode)); -// fromMobile = true; -// //如果有次账号,userid给次账号的 -// String f_weaver_belongto_userid=Util.null2s(req.getParameter("f_weaver_belongto_userid"),""); -// if(!"".equals(f_weaver_belongto_userid)){ -// userid = Util.getIntValue(f_weaver_belongto_userid); -// } -// jsonParams = Json2MapUtil.requestJson2Map(req); -// jsonParams.put("userid",userid); -// codeuserid = Util.getIntValue(Util.null2String(jsonParams.get("userid"))); -// } -// -// }catch(Exception e){ -// writeLogs(e); -// } -// } -// -// -// if(fileid <= 0){//转化为int型,防止SQL注入 -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?v3"); -// return; -// } -// RecordSet rsprop = new RecordSet(); -// String secondAuthsql = " select distinct docid from docImageFile where imagefileid =?"; -// rsprop.executeQuery(secondAuthsql,fileid); -// while(rsprop.next()){ -// int newdocid=Util.getIntValue(rsprop.getString("docid")); -// if(newdocid>0){ -// String secondAuthFileDownUrl=getSecondAuthFileDownUrl(req,isMobileDown,newdocid); -// if(!"".equals(secondAuthFileDownUrl)){ -// res.sendRedirect(secondAuthFileDownUrl); -// return; -// } -// } -// } -// /**流程下载附件,获取最新版本附件下载 start */ -// String fromrequest = req.getParameter("fromrequest"); -// if("1".equals(fromrequest)){ -// RecordSet rs = new RecordSet(); -// rs.executeSql("select doceditionid,id from DocDetail where id=(select max(docid) from DocImageFile where imagefileid=" + fileid + ")"); -// if(rs.next()){ -// int doceditionid = rs.getInt("doceditionid"); -// int docid = rs.getInt("id"); -// -// if(doceditionid > 0){ //有多版本文档,取最新版本文档 -// rs.executeSql("select id from DocDetail where doceditionid=" + doceditionid + " order by docedition desc"); -// if(rs.next()){ -// docid = rs.getInt("id"); -// } -// } -// -// rs.executeQuery("select id from DocImageFile where imagefileid=? and (isextfile is null or isextfile <> '1' ) and docfiletype <> '1'",fileid); -// -// boolean isOfficeFile = false; -// if(rs.next()){ -// isOfficeFile = true; -// } -// -// //在新版本文档下取最新附件 -// String sql = "select id,imagefileid from DocImageFile where docid=? "; -// -// if(isOfficeFile){ -// sql += " and (isextfile is null or isextfile <> '1' ) and docfiletype <> '1'"; -// }else{ -// sql += " and isextfile='1'"; -// } -// -// sql += "order by versionId desc"; -// rs.executeQuery(sql,docid); -// int firstId = 0; -// int i = 0; -// int _id = 0; -// while(rs.next()){ -// if(i == 0){ -// firstId = rs.getInt("imagefileid"); -// _id = rs.getInt("id"); -// if(isOfficeFile) -// break; -// }else{ -// if(_id != rs.getInt("id")){ //一个文档下有多个附件,则不再下载最新,按照传的id下载 -// firstId = fileid; -// break; -// } -// } -// i++; -// } -// fileid = firstId; -// } -// } -// /**流程下载附件,获取最新附件 end */ -// -// //String strSql="select docpublishtype from docdetail where id in (select docid from docimagefile where imagefileid="+fileid+") and ishistory <> 1"; -// RecordSet statement = new RecordSet(); //by ben 开启连接后知道文件下载才关闭,数据库连接时间太长 -// //RecordSet rs =new RecordSet(); -// User user = (User)req.getSession(true).getAttribute("weaver_user@bean"); -// try { -// //解决问题:一个附件或图片被一篇内部文档和外部新闻同时引用时,外部新闻可能查看不到附件或图片。 update by fanggsh fot TD5478 begin -// //调整为如下: -// //默认需要用户登录信息,不需要登录信息的情形如下: -// //1、非登录用户查看外部新闻 -// //boolean needUser= false; -// boolean needUser= true; -// int docId=0; -// String docIdsForOuterNews=""; -// //String strSql="select id from DocDetail where exists (select 1 from docimagefile where imagefileid="+fileid+" and docId=DocDetail.id) and ishistory <> 1 and (docPublishType='2' or docPublishType='3')"; -// String strSql = "SELECT t1.id FROM DocDetail t1 INNER JOIN docimagefile t2 ON t1.id = t2.docId " + -// "WHERE t2.imagefileid = ? AND t1.ishistory <> 1 AND ( t1.docPublishType = '2' OR t1.docPublishType = '3')"; -// RecordSet rs = new RecordSet(); -// rs.executeQuery(strSql,fileid); -// while(rs.next()){ -// docId=rs.getInt("id"); -// if(docId>0){ -// docIdsForOuterNews+=","+docId; -// } -// } -// -// if(!docIdsForOuterNews.equals("")){ -// docIdsForOuterNews=docIdsForOuterNews.substring(1); -// } -// -// if(!docIdsForOuterNews.equals("")){ -// String newsClause=""; -// String sqlDocExist=" select 1 from DocDetail where id in("+docIdsForOuterNews+") "; -// String sqlNewsClauseOr=""; -// boolean hasOuterNews=false; -// -// rs.executeSql("select newsClause from DocFrontPage where publishType='0'"); -// while(rs.next()){ -// hasOuterNews=true; -// newsClause=Util.null2String(rs.getString("newsClause")); -// if (newsClause.equals("0")) -// { -// //newsClause=" 1=1 "; -// needUser=false; -// break; -// } -// if(!newsClause.trim().equals("")){ -// sqlNewsClauseOr+=" ^_^ ("+newsClause+")"; -// } -// } -// ArrayList newsArr = new ArrayList(); -// if(!sqlNewsClauseOr.equals("")&&needUser){ -// //sqlNewsClauseOr=sqlNewsClauseOr.substring(sqlNewsClauseOr.indexOf("(")); -// //sqlDocExist+=" and ("+sqlNewsClauseOr+") "; -// String[] newsPage = Util.TokenizerString2(sqlNewsClauseOr,"^_^"); -// int i = 0; -// String newsWhere = ""; -// for(;i1061-->fileid"+fileid+"--->user"+user+"=userid--"); -// if(user==null){ -// AuthService as = new AuthService(); -// -// String sessionkey = ""; -// String querystring = req.getQueryString(); -// String[] parameters = StringUtils.split(querystring, '&'); -// if(parameters != null) { -// for(int i=0; i0){ -// sql = "select t1.imagefilename,t1.filerealpath,t1.signinfo,t1.hashinfo,t1.iszip,t1.isencrypt,t1.imagefiletype , t1.imagefileid, t1.imagefile,t1.isaesencrypt,t1.aescode,t2.imagefilename as realname,t1.TokenKey,t1.StorageStatus,t1.comefrom,t1.filesize from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.imagefileid = "+decryptPdfImageFileId; -// statement.execute(sql); -// if(!statement.next()){ -// return ; -// } -// } -// } -// filerealpath = Util.null2String(statement.getString("filerealpath")); -// iszip = Util.null2String(statement.getString("iszip")); -// signInfo = Util.null2String(statement.getString("signinfo")); -// hashInfo = Util.null2String(statement.getString("hashinfo")); -// isencrypt = Util.null2String(statement.getString("isencrypt")); -// isaesencrypt = Util.null2o(statement.getString("isaesencrypt")); -// aescode = Util.null2String(statement.getString("aescode")); -// tokenKey = Util.null2String(statement.getString("TokenKey")); -// storageStatus = Util.null2String(statement.getString("StorageStatus")); -// comefrom = Util.null2String(statement.getString("comefrom")); -// filesize = Util.null2String(statement.getString("filesize")); -// -// -// if(!"DocLogAction_DocLogFile".equals(comefrom) && FiledownloadUtil.isdownloadpdf(filename) && download.equals("1") ){ -// pdfimagefileid = FiledownloadUtil.getpdfidByOfficeid(fileid+""); -// if(pdfimagefileid.isEmpty()){ -// pdfimagefileid = fileid+""; -// } -// String pdffileinfosql = "select imagefilename,filerealpath,aescode,iszip,isencrypt,isaesencrypt,TokenKey,StorageStatus,filesize,comefrom,hashinfo,signinfo from imagefile where imagefileid = ? "; -// RecordSet pdffileinfors = new RecordSet(); -// pdffileinfors.executeQuery(pdffileinfosql,pdfimagefileid); -// if(pdffileinfors.next()){ -// filename = Util.null2String(pdffileinfors.getString("imagefilename")); -// filerealpath = Util.null2String(pdffileinfors.getString("filerealpath")); -// iszip = Util.null2String(pdffileinfors.getString("iszip")); -// signInfo = Util.null2String(pdffileinfors.getString("signinfo")); -// hashInfo = Util.null2String(pdffileinfors.getString("hashinfo")); -// isencrypt = Util.null2String(pdffileinfors.getString("isencrypt")); -// isaesencrypt = Util.null2String(pdffileinfors.getString("isaesencrypt")); -// aescode = Util.null2String(pdffileinfors.getString("aescode")); -// tokenKey = Util.null2String(pdffileinfors.getString("TokenKey")); -// storageStatus = Util.null2String(pdffileinfors.getString("StorageStatus")); -// comefrom = Util.null2String(pdffileinfors.getString("comefrom")); -// filesize = Util.null2String(pdffileinfors.getString("filesize")); -// } -// }else { -// pdfimagefileid = fileid+""; -// } -// -// if(filename.indexOf(".") > -1){ -// int bx = filename.lastIndexOf("."); -// if(bx>=0){ -// extName = filename.substring(bx+1, filename.length()); -// } -// } -// if(ImageConvertUtil.canConvertPdfForDownload(extName,fileid+"")&& !frompdfview.equals("1") && download.equals("1")) { -// RecordSet rsrecord = new RecordSet(); -// PdfConvertUtil pdfConvertUtil = new PdfConvertUtil(); -// int pdfid = pdfConvertUtil.convertPdf(fileid); -// if (pdfid > 0) { -// downloadpdfimagefileid = String.valueOf(pdfid); -// String pdffileinfosql = "select imagefilename,filerealpath from imagefile where imagefileid = ? "; -// RecordSet pdffileinfors = new RecordSet(); -// pdffileinfors.executeQuery(pdffileinfosql, downloadpdfimagefileid); -// if (pdffileinfors.next()) { -// filename = filename.substring(0, filename.lastIndexOf(".")) + ".pdf"; -// filerealpath = Util.null2String(pdffileinfors.getString("filerealpath")); -// } -// } -// } -// if(downloadpdfimagefileid.isEmpty()){ -// downloadpdfimagefileid = fileid+""; -// } -// -// if(filename.indexOf(".") > -1){ -// int bx = filename.lastIndexOf("."); -// if(bx>=0){ -// extName = filename.substring(bx+1, filename.length()); -// } -// } -// boolean isInline=false; -// String cacheContorl=""; -// boolean isEnableForDsp=false; -// boolean canUseAliOSS = false; -// if(!tokenKey.equals("")&&storageStatus.equals("1")&&AliOSSObjectManager.isEnableForDsp(req)){ -// isEnableForDsp=true; -// } -// if(!tokenKey.equals("")&&storageStatus.equals("1")&&AliOSSObjectManager.canUseAliOSS()){ -// canUseAliOSS=true; -// } -// boolean isPic=false; -// String lowerfilename = filename!=null ? filename.toLowerCase() : ""; -// boolean ishtmlfile = false; -// boolean needGbkCode = false; -// if(lowerfilename.endsWith(".html")||lowerfilename.endsWith(".htm")){ -// RecordSet rs_tmp = new RecordSet(); -// -// String _sql = "select i.imagefilename from DocPreviewHtml a,imagefile i " -// + "where a.imagefileid=i.imagefileid and a.htmlfileid = ?"; -// -// if("email".equals(req.getParameter("model"))){ -// _sql = "select filename as imagefilename from mailresourcefile where htmlcode=?"; -// } -// -// rs_tmp.executeQuery(_sql,fileid); -// if(rs_tmp.next()){ -// ishtmlfile = true; -// String _imagefilename = Util.null2String(rs_tmp.getString("imagefilename")); -// needGbkCode = _imagefilename.toLowerCase().endsWith(".xls") -// || _imagefilename.toLowerCase().endsWith(".xlsx") -// || _imagefilename.toLowerCase().endsWith(".doc"); -// } -// String worflowhtmlSql = " select comefrom from imagefile where imagefileid = ?"; -// rs_tmp.executeQuery(worflowhtmlSql,fileid); -// if(rs_tmp.next()){ -// String htmlcomefrom = Util.null2String(rs_tmp.getString("comefrom")); -// if("WorkflowToDoc".equals(htmlcomefrom)){ -// ishtmlfile = true; -// } -// } -// } -// filename = StringEscapeUtils.unescapeHtml(filename); -// String extendName = lowerfilename.lastIndexOf(".") != -1 ? lowerfilename.substring(lowerfilename.lastIndexOf(".") + 1) : lowerfilename; -// boolean inlineView = inlineViewFile(extendName); -// if (download.equals("") && (inlineView -// ||ishtmlfile)){ -// if(filename.toLowerCase().endsWith(".doc")) contenttype = "application/msword"; -// else if(filename.toLowerCase().endsWith(".xls")) contenttype = "application/vnd.ms-excel"; -// else if(filename.toLowerCase().endsWith(".gif")) { -// contenttype = "image/gif"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// isPic=true; -// }else if(filename.toLowerCase().endsWith(".png")) { -// contenttype = "image/png"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// isPic=true; -// }else if(filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg")) { -// contenttype = "image/jpg"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// isPic=true; -// }else if(filename.toLowerCase().endsWith(".bmp")) { -// contenttype = "image/bmp"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// isPic=true; -// }else if(filename.toLowerCase().endsWith(".svg")){ -// contenttype = "image/svg+xml"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// isPic=true; -// } -// else if(filename.toLowerCase().endsWith(".txt")) contenttype = "text/plain"; -// else if(filename.toLowerCase().endsWith(".pdf")) contenttype = "application/pdf"; -// else if(filename.toLowerCase().endsWith(".html")||filename.toLowerCase().endsWith(".htm")) contenttype = "text/html"; -// else { -// contenttype = statement.getString("imagefiletype"); -// } -// try { -// -// String _ec_browser = Util.null2String(req.getParameter("_ec_browser")); -// String _ec_os = Util.null2String(req.getParameter("_ec_os")); -// -// if("Wechat".equals(_ec_browser) && "iOS".equals(_ec_os)){ //微信 -// res.setHeader("content-disposition", "inline; filename=\"" + new String(filename.getBytes("UTF-8"), "ISO8859-1")+"\""); -// }else if(_ec_ismobile || from_doc_mobile || agent.toLowerCase().contains("emobile") || agent.toLowerCase().contains("android") || agent.toLowerCase().contains("iphone")){ -// // res.setHeader("content-disposition", "inline; filename=\"" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\""); -// filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); -// res.setHeader("Content-disposition", "inline;filename=\"" + filename + "\""); -// }else { -// if ((agent.contains("Firefox") || agent.contains(" Chrome") || agent.contains("Safari")) && !agent.contains("Edge")) { -// res.setHeader("content-disposition", "inline; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); -// } else { -// res.setHeader("content-disposition", "inline; filename=\"" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); -// } -// } -// } catch (Exception ecode) { -// writeLogs(ecode); -// } -// isInline=true; -// }else { -// contenttype = "application/octet-stream"; -// if (filename.toLowerCase().endsWith(".mp4") || filename.toLowerCase().endsWith(".mov")) { -// contenttype = "video/mp4"; -// } else if (filename.toLowerCase().endsWith(".ogg")) { -// contenttype = "video/ogg"; -// } else if (filename.toLowerCase().endsWith(".asf")) { -// contenttype = "video/x-ms-asf"; -// } else if (filename.toLowerCase().endsWith(".mp3")) { -// contenttype = "audio/mp3"; -// } else if (filename.toLowerCase().endsWith(".wav")) { -// contenttype = "audio/wav"; -// } else if (filename.toLowerCase().endsWith(".wma")) { -// contenttype = "audio/x-ms-wma"; -// } else if (filename.toLowerCase().endsWith(".au")) { -// contenttype = "audio/basic"; -// } -// -// if(filename.toLowerCase().endsWith(".pdf")) contenttype = "application/pdf"; -// try { -// // res.setHeader("Content-length", "" + filesize); -// // res.setHeader("Content-Range", "bytes"); -// // res.addHeader("Cache-Control", "no-cache"); -// -// //System.out.println(new String(new String(filename.getBytes(clientEcoding), "ISO8859_1").getBytes("ISO8859_1"),"utf-8")); -// //System.out.println(new String(filename.getBytes(clientEcoding))); -// String _ec_browser = Util.null2String(req.getParameter("_ec_browser")); -// String _ec_os = Util.null2String(req.getParameter("_ec_os")); -// if("Wechat".equals(_ec_browser) && ("iOS".equals(_ec_os) || "Mac OS".equals(_ec_os))){ //微信 -// res.setHeader("content-disposition", "inline; filename=\"" + new String(filename.getBytes("UTF-8"), "ISO8859-1")+"\""); -// }else if(agent.contains("Wechat") && (agent.contains("iOS") || agent.contains("Mac OS"))){ -// filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); -// res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); -// }else if(agent.contains("Mac OS") && !AliOSSObjectManager.isEnable()){ -// filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); -// res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); -// } else if(_ec_ismobile || from_doc_mobile||agent.toLowerCase().contains("android")){ -// if(FiledownloadUtil.isIos(req)){ -// filename = FiledownloadUtil.counthanzi(filename,extName); -// } -// -// res.setHeader("content-disposition", "attachment; filename=\"" + -// URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("%", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\""); -// }else { -// if ( (agent.contains(" Chrome")) && !agent.contains("Edge")) { -// // res.setHeader("content-disposition", "attachment;"); -// res.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(") -// .replaceAll("%29", ")").replaceAll("%7B","{").replaceAll("%7D","}").replaceAll("%5B","[").replaceAll("%5D","]").replaceAll("%40","@").replaceAll("%23","#").replaceAll("%25","%").replaceAll("%26","&") -// .replaceAll("%2B","+").replaceAll("%27","'").replaceAll("%20"," ")); -// -// // res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); -// // res.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(filename, "UTF-8")); -// // res.setContentType("application/vnd.ms-excel;charset=utf-8"); -// // res.setCharacterEncoding("UTF-8"); -// }else if(agent.contains("Safari")){ -// filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); -// res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); -// }else if(agent.contains("Firefox")){ -// // filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); -// // res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); -// -// // filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); -// // res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); -// // filename = "=?UTF-8?B?" + (new String(Base64.encodeBase64(filename.getBytes("UTF-8")))) + "?="; -// // res.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename)); -// -// res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); -// } else{ -// res.setHeader("content-disposition", "attachment; filename=\"" + -// URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); -// } -// } -// } catch (Exception ecode) { -// writeLogs(ecode); -// } -// } -// String iscompress = Util.null2String(req.getParameter("iscompress")); -// String thumbnail = Util.null2String(req.getParameter("thumbnail")); -// String targetFilePath=""; -// if(isEnableForDsp||canUseAliOSS){ -// -// //解决安卓app预览黑屏的问题 -// boolean isAndroid = agent.contains("Android") && agent.startsWith("E-Mobile7"); -// if(isAndroid && download.equals("1")){ -// if(filename.toLowerCase().endsWith(".gif")) { -// contenttype = "image/gif"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// isPic=true; -// }else if(filename.toLowerCase().endsWith(".png")) { -// contenttype = "image/png"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// isPic=true; -// }else if(filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg")) { -// contenttype = "image/jpg"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// isPic=true; -// }else if(filename.toLowerCase().endsWith(".bmp")) { -// contenttype = "image/bmp"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// isPic=true; -// }else if(filename.toLowerCase().endsWith(".svg")){ -// contenttype = "image/svg+xml"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// isPic=true; -// } -// } -// -// boolean isAliOSSToServer=AliOSSObjectManager.isAliOSSToServer(comefrom); -// boolean isOpenWaterMark = WaterMarkUtil.isOpenWmSetting(); -// boolean isSafari=agent.contains("Mac OS"); -// int imgDownByObs=Util.getIntValue(baseBean.getPropValue("FileDownload","imgDownByObs"),1); -// baseBean.writeLog("FileDownload---------1645---fileid="+fileid+";isPic="+isPic+";filename="+filename+";isAliOSSToServer="+isAliOSSToServer+";imgDownByObs="+imgDownByObs+";frompdfview="+frompdfview+";isOpenWaterMark="+isOpenWaterMark+";ishtmlfile="+ishtmlfile+";canUseAliOSS="+canUseAliOSS+";isEnableForDsp="+isEnableForDsp+";isSafari="+isSafari); -// //canUseAliOSS && !isEnableForDs :判断是否开启了阿里云并且请求端是内网地址的情况下走此逻辑 -// if(isAliOSSToServer|| (isPic && imgDownByObs !=1) || !frompdfview.isEmpty() || isOpenWaterMark || ishtmlfile || (canUseAliOSS && !isEnableForDsp)||isSafari){ -// baseBean.writeLog("FileDownload---------1648---fileid="+fileid+";isPic="+isPic+";11111"); -// InputStream imagefile = null; -// ServletOutputStream out = null; -// DocAddWaterForSecond docAddWaterForSecond = new DocAddWaterForSecond(); -// try { -// imagefile=weaver.alioss.AliOSSObjectUtil.downloadFile(tokenKey); -// if("1".equals(iscompress)){ -// ImageCompressUtil imageCompressUtil=new ImageCompressUtil(); -// targetFilePath = imageCompressUtil.getTargetFilePath(); -// imagefile=imageCompressUtil.imageCompress(imagefile,targetFilePath); -// } -// out = res.getOutputStream(); -// -// if(ishtmlfile && needGbkCode){ -// boolean loadGBK = !"0".equals(rs.getPropValue("docpreview", "loadGBK")); -// if(loadGBK){ -// res.setContentType(contenttype+";charset=GBK"); -// } -// }else{ -// res.setContentType(contenttype); -// } -// // extName = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : ""; -// if(!frompdfview.equals("1") && download.equals("1")){ -// Map secWmSetMap = WaterMarkUtilNew.getCategoryWmSet(fileid+""); -// //writeLogs("1786 fileid=" + fileid); -// shouldAddFileDownLoadWm(secWmSetMap, fileid+""); // 2447956 wgs -// if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtilNew.SECCATEGORYDOWNLOAD))&& "1".equals(secWmSetMap.get(WaterMarkUtilNew.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtilNew.WATERCONTENTISNULL))){ -// // imagefile = WaterMarkUtil.takefileWater(imagefile,user,filename,fileid,extName,WaterMarkUtil.MOULDDOC); -// imagefile = FileWaterManager.takewater(req,downloadpdfimagefileid,filename,extName,imagefile, WaterMarkUtil.MOULDDOC,fileid); -// } -// -// } -// long filetotalsize=0; -// String _ec_browser = Util.null2String(req.getParameter("_ec_browser")); -// boolean isWeChat=false; -// if(agent.contains("Wechat") || agent.contains("Android") || "Wechat".equalsIgnoreCase(_ec_browser)){ -// isWeChat=true; -// } -// baseBean.writeLog("FileDownload---------1496---fileid="+fileid+";isWeChat="+isWeChat+";_ec_browser="+_ec_browser+";agent="+agent); -// String sourceFilePath=""; -// if(isWeChat){ -// SystemComInfo syscominfo = new SystemComInfo(); -// String syspath= Util.null2String(syscominfo.getFilesystem()); -// String rootPath = Util.null2String(GCONST.getRootPath()); -// if("".equals(syspath)){ -// sourceFilePath = rootPath + "doctempfile"; -// }else{ -// if(syspath.endsWith(File.separator)){ -// sourceFilePath =syspath+ "doctempfile"; -// }else{ -// sourceFilePath =syspath+File.separator+ "doctempfile"; -// } -// } -// File sfile = new File(sourceFilePath); -// if(!sfile.exists()) sfile.mkdirs(); -// sourceFilePath += File.separator + UUID.randomUUID().toString(); -// OutputStream os = null; -// int read; -// byte[] buf = new byte[8 * 1024]; -// try{ -// os = new FileOutputStream(sourceFilePath); -// while((read = imagefile.read(buf)) != -1) { -// os.write(buf, 0, read); -// filetotalsize += read; -// } -// }catch(Exception e){ -// -// }finally{ -// if(os != null) -// os.close(); -// } -// imagefile = new FileInputStream(sourceFilePath); -// res.setHeader("Content-length", "" + filetotalsize); -// } -// -// if("1".equals(download)) { -// imagefile = FileManager.download(req,fileid+"",filerealpath,aescode,iszip,isaesencrypt,imagefile); -// } -// -// while ((byteread = imagefile.read(data)) != -1) { -// out.write(data, 0, byteread); -// out.flush(); -// } -// try{ -// if(!"".equals(sourceFilePath)){ -// File f = new File(sourceFilePath); -// if(f.exists()&&f.isFile()){ -// FileSecurityUtil.deleteFile(f); -// } -// } -// }catch(Exception e) { -// baseBean.writeLog("FileDownload---------1533---fileid="+fileid+";Exception="+e); -// } -// } -// catch(Exception e) { -// writeLogs(e); -// //do nothing -// } -// finally { -// if(imagefile!=null) imagefile.close(); -// if(out!=null) out.flush(); -// if(out!=null) out.close(); -// if("1".equals(iscompress)&& StringUtils.isNotEmpty(targetFilePath)){ -// File targetfile = new File(targetFilePath); -// if(targetfile.exists()){ -// FileSecurityUtil.deleteFile(targetfile); -// //new FileDeleteUtil().deleteFile(targetfile); -// } -// } -// } -// -// try{ -// if(needUser&&nolog==0) { -// //记录下载日志 begin -// HttpSession session = req.getSession(false); -// if (session != null) { -// user = (User) session.getAttribute("weaver_user@bean"); -// if (user != null) { -// //董平修改 文档下载日志只记录了内部员工的名字,如果是客户门户来下载,则没有记录 for TD:1644 -// String userType = user.getLogintype(); -// if ("1".equals(userType)) { //如果是内部用户 名称就是 lastName 外部则入在 firstName里面 -// downloadLog(user.getUID(), user.getLastname(), fileid, filename,ipstring); -// } else { -// downloadLog(user.getUID(), user.getFirstname(), fileid, filename,ipstring); -// } -// -// } -// } -// //记录下载日志 end -// } -// -// countDownloads(""+fileid); -// }catch(Exception ex){ -// writeLogs(ex); -// } -// return ; -// }else{ -// baseBean.writeLog("FileDownload---------1767---fileid="+fileid+";isPic="+isPic+";222222"); -// String urlString=weaver.alioss.AliOSSObjectUtil.generatePresignedUrl(tokenKey,filename,contenttype,isInline,cacheContorl,isSafari); -// if(urlString!=null){ -// try{ -// if(needUser&&nolog==0) { -// //记录下载日志 begin -// HttpSession session = req.getSession(false); -// if (session != null) { -// user = (User) session.getAttribute("weaver_user@bean"); -// if (user != null) { -// //董平修改 文档下载日志只记录了内部员工的名字,如果是客户门户来下载,则没有记录 for TD:1644 -// String userType = user.getLogintype(); -// if ("1".equals(userType)) { //如果是内部用户 名称就是 lastName 外部则入在 firstName里面 -// downloadLog(user.getUID(), user.getLastname(), fileid, filename,ipstring); -// } else { -// downloadLog(user.getUID(), user.getFirstname(), fileid, filename,ipstring); -// } -// -// } -// } -// //记录下载日志 end -// } -// -// countDownloads(""+fileid); -// }catch(Exception ex){ -// writeLogs(ex); -// } -// //urlString=urlString+"&fileid="+fileid; -// res.sendRedirect(urlString); -// return; -// } -// } -// } -// -// InputStream imagefile = null; -// ZipInputStream zin = null; -// /*if (filerealpath.equals("")) { // 旧的文件放在数据库中的方式 -// if (isoracle) -// imagefile = new BufferedInputStream(statement.getBlobBinary("imagefile")); -// else -// imagefile = new BufferedInputStream(statement.getBinaryStream("imagefile")); -// } else*/ //目前已经不可能将文件存放在数据库中了 -// -// File thefile = new File(filerealpath); -// boolean signResult = false; -// if (!filerealpath.isEmpty() && !signInfo.isEmpty() && !hashInfo.isEmpty()) { -// signResult = com.api.doc.util.DocEncryptUtil.verifyFile(hashInfo, signInfo, filerealpath); -// // 如果签名不通过,则跳转提醒页面 -// if (!signResult ) { -// res.sendRedirect(GCONST.getContextPath()+"/wui/common/page/integrityFailure.jsp?line=4&user=null"); -// return; -// } -// } -// -// if (iszip.equals("1")) { -// zin = new ZipInputStream(new FileInputStream(thefile)); -// if (zin.getNextEntry()!=null) imagefile = new BufferedInputStream(zin); -// } else{ -// imagefile = new BufferedInputStream(new FileInputStream(thefile)); -// } -// -// if(isaesencrypt.equals("1")){ -// imagefile = AESCoder.decrypt(imagefile, aescode); -// } -// -// if (signResult) { -// imagefile = com.api.doc.util.DocEncryptUtil.decryptInput(imagefile); -// if (imagefile == null) { -// res.sendRedirect(GCONST.getContextPath()+"/wui/common/page/integrityFailure.jsp?line=4&user=null"); -// return; -// } -// } -// if(download.equals("1") && (isOfficeToDocument(extName))&&isMsgObjToDocument()) { -// //正文的处理 -// ByteArrayOutputStream bout = null; -// try { -// bout = new ByteArrayOutputStream() ; -// while((byteread = imagefile.read(data)) != -1) { -// bout.write(data, 0, byteread) ; -// bout.flush() ; -// } -// byte[] fileBody = bout.toByteArray(); -// iMsgServer2000 MsgObj = new iMsgServer2000(); -// MsgObj.MsgFileBody(fileBody); //将文件信息打包 -// fileBody = MsgObj.ToDocument(MsgObj.MsgFileBody()); //通过iMsgServer200 将pgf文件流转化为普通Office文件流 -// imagefile = new ByteArrayInputStream(fileBody); -// bout.close(); -// } -// catch(Exception e) { -// writeLogs(e); -// if(bout!=null) bout.close(); -// } -// } -// ServletOutputStream out = null; -// DocAddWaterForSecond docAddWaterForSecond = new DocAddWaterForSecond(); -// try { -// out = res.getOutputStream(); -// res.setContentType(contenttype); -// -// if(ishtmlfile && needGbkCode){ -// boolean loadGBK = !"0".equals(rs.getPropValue("docpreview", "loadGBK")); -// if(loadGBK){ -// res.setContentType(contenttype+";charset=GBK"); -// } -// } -// if("1".equals(iscompress)){ -// ImageCompressUtil imageCompressUtil=new ImageCompressUtil(); -// targetFilePath = imageCompressUtil.getTargetFilePath(); -// imagefile=imageCompressUtil.imageCompress(imagefile,targetFilePath); -// }else if ("1".equals(thumbnail)){ -// imagefile = getThumbnail(fileid, imagefile); -// } -// if(!frompdfview.equals("1") && download.equals("1")){ -// Map secWmSetMap = WaterMarkUtil.getCategoryWmSet(fileid+""); -// //writeLogs("2013 fileid=" + fileid); -// shouldAddFileDownLoadWm(secWmSetMap, fileid+""); // 2447956 wgs -// if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD))&& "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtil.WATERCONTENTISNULL))){ -// // imagefile = WaterMarkUtil.takefileWater(imagefile,user,filename,fileid,extName,WaterMarkUtil.MOULDDOC); -// imagefile = FileWaterManager.takewater(req,downloadpdfimagefileid,filename,extName,imagefile, WaterMarkUtil.MOULDDOC,fileid); -// } -// } -// // 2298348 wgs -// //writeLogs("2021 downloadFlag=" + downloadFlag); -// if (!"1".equals(downloadFlag)) { -// imagefile = EncryptDecryptFileUtil.fileDecrypt(Util.getIntValue(fileid), imagefile, filename, ""); -// } -// // 2298348 wgs -// if("1".equals(download)) { -// imagefile = FileManager.download(req,fileid+"",filerealpath,aescode,iszip,isaesencrypt,imagefile); -// } -// //加密流程返回false -// if(((contenttype.contains("video")&& agent.contains("iPhone")) || contenttype.contains("audio")) && !download.equals("1") ) {//ios播放视频文件,解析range字段 -// sendVideoToIOS(req, res, imagefile, filename,filerealpath); -// }else { -// long filetotalsize=0; -// String _ec_browser = Util.null2String(req.getParameter("_ec_browser")); -// boolean isWeChat=false; -// if(agent.contains("Wechat") || agent.contains("Android") || "Wechat".equalsIgnoreCase(_ec_browser)){ -// isWeChat=true; -// } -// baseBean.writeLog("FileDownload---------1675---fileid="+fileid+";isWeChat="+isWeChat+";_ec_browser="+_ec_browser+";agent="+agent); -// String sourceFilePath=""; -// if(isWeChat){ -// SystemComInfo syscominfo = new SystemComInfo(); -// String syspath= Util.null2String(syscominfo.getFilesystem()); -// String rootPath = Util.null2String(GCONST.getRootPath()); -// if("".equals(syspath)){ -// sourceFilePath = rootPath + "doctempfile"; -// }else{ -// if(syspath.endsWith(File.separator)){ -// sourceFilePath =syspath+ "doctempfile"; -// }else{ -// sourceFilePath =syspath+File.separator+ "doctempfile"; -// } -// } -// File sfile = new File(sourceFilePath); -// if(!sfile.exists()) sfile.mkdirs(); -// sourceFilePath += File.separator + UUID.randomUUID().toString(); -// OutputStream os = null; -// int read; -// byte[] buf = new byte[8 * 1024]; -// try{ -// os = new FileOutputStream(sourceFilePath); -// while((read = imagefile.read(buf)) != -1) { -// os.write(buf, 0, read); -// filetotalsize += read; -// } -// }catch(Exception e){ -// -// }finally{ -// if(os != null) -// os.close(); -// } -// imagefile = new FileInputStream(sourceFilePath); -// res.setHeader("Content-length", "" + filetotalsize); -// } -// // 文档/流程中单个附件下载 -// while ((byteread = imagefile.read(data)) != -1) { -// out.write(data, 0, byteread); -// out.flush(); -// } -// try{ -// if(!"".equals(sourceFilePath)){ -// File f = new File(sourceFilePath); -// if(f.exists()&&f.isFile()){ -// FileSecurityUtil.deleteFile(f); -// } -// } -// }catch(Exception e) { -// baseBean.writeLog("FileDownload---------1707---fileid="+fileid+";Exception="+e); -// } -// } -// -// -// } -// catch(Exception e) { -// writeLogs(e); -// //do nothing -// } -// finally { -// if(imagefile!=null) imagefile.close(); -// if(zin!=null) zin.close(); -// if(out!=null) out.flush(); -// if(out!=null) out.close(); -// if("1".equals(iscompress)&& StringUtils.isNotEmpty(targetFilePath)){ -// File targetfile = new File(targetFilePath); -// FileSecurityUtil.deleteFile(targetfile); -// //new FileDeleteUtil().deleteFile(targetFilePath); -// } -// -// } -// -// if(needUser&&nolog==0) { -// //记录下载日志 begin -// HttpSession session = req.getSession(false); -// if (session != null) { -// user = (User) session.getAttribute("weaver_user@bean"); -// if (user != null) { -// //董平修改 文档下载日志只记录了内部员工的名字,如果是客户门户来下载,则没有记录 for TD:1644 -// String userType = user.getLogintype(); -// if ("1".equals(userType)) { //如果是内部用户 名称就是 lastName 外部则入在 firstName里面 -// downloadLog(user.getUID(), user.getLastname(), fileid, filename,ipstring); -// } else { -// downloadLog(user.getUID(), user.getFirstname(), fileid, filename,ipstring); -// } -// -// } -// } -// //记录下载日志 end -// } -// -// -// countDownloads(""+fileid); -// } -// } catch (Exception e) { -// BaseBean basebean = new BaseBean(); -// basebean.writeLog(e); -// } //错误处理 -// } -// }else{ -// String urlstr = req.getParameter("urlstr"); -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// boolean isNotUse=true; -// if(isNotUse){ -// return; -// } -// InputStream imagefile = null; -// URL url = new URL(urlstr); -// HttpURLConnection conn = (HttpURLConnection)url.openConnection(); -// conn.setRequestMethod("GET"); -// conn.setConnectTimeout(5 * 1000); -// imagefile = conn.getInputStream(); -// -// ServletOutputStream outputStream = res.getOutputStream(); -// -// byte data[] = new byte[1024]; -// int byteread; -// -// while ((byteread = imagefile.read(data)) != -1) { -// outputStream.write(data, 0, byteread); -// outputStream.flush(); -// } -// -// outputStream.close(); -// imagefile.close(); -// } -// } -// -// /** -// * 获取缩略图的流对象 -// * @param fileid -// * @param is -// * @return -// */ -// private InputStream getThumbnail(int fileid,InputStream is){ -// RecordSet rs = new RecordSet(); -// -// -// int width = Util.getIntValue(rs.getPropValue("docthumbnailfile","width"),300); -// width = width <= 0 ? 0 : width; -// -// rs.executeQuery("select thumbnailid from ImageFileThumbnail where imgfileid=? and width=?",fileid,width); -// if(rs.next()){ -// //System.out.println("id为:"+fileid+",走的缩略图"); -// return ImageFileManager.getInputStreamById(Util.getIntValue(rs.getString("thumbnailid"))); -// } -// -// ImageCompressUtil imageCompressUtil=new ImageCompressUtil(); -// -// String targetFilePath = imageCompressUtil.getTargetFilePath(); -// -// InputStream imagefile=imageCompressUtil.imageCompressPercent(is,targetFilePath,width,0.7f); -// -// ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); -// byte[] in2b = null; -// try{ -// byte[] buff = new byte[100]; -// int rc = 0; -// while ((rc = imagefile.read(buff, 0, 100)) > 0) { -// swapStream.write(buff, 0, rc); -// } -// in2b = swapStream.toByteArray(); -// }catch(Exception e){ -// -// }finally{ -// try{ -// swapStream.close(); -// }catch(Exception e){} -// try{ -// if(imagefile != null) -// imagefile.close(); -// }catch(Exception e){} -// } -// -// ImageFileManager ifm = new ImageFileManager(); -// ifm.setData(in2b); -// ifm.setImagFileName(UUID.randomUUID().toString()+ ".jpeg"); -// int thumbnailid = ifm.saveImageFile(); -// if(thumbnailid <= 0){ -// return ImageFileManager.getInputStreamById(fileid); -// } -// -// rs.executeUpdate("insert into ImageFileThumbnail(imgfileid,thumbnailid,width) values(?,?,?)",fileid,thumbnailid,width); -// -// return ImageFileManager.getInputStreamById(thumbnailid); -// } -// -// public void sendVideoToIOSJSP(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String fileName,String filerealpath) throws FileNotFoundException, IOException { -// sendVideoToIOS(request,response,inputStream,fileName,filerealpath); -// } -// -// /** -// * ios传输视频,必须要解析range字段 -// * @param request -// * @param response -// * @param inputStream -// * @param fileName -// * @param filerealpath -// */ -// private void sendVideoToIOS(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String fileName,String filerealpath) throws FileNotFoundException, IOException { -// if(filerealpath.endsWith(".zip")){ -// filerealpath = filerealpath.substring(0,filerealpath.length() - 4); -// } -// File tempfile = new File(filerealpath + "_tmp"); -// FileOutputStream fos = null; -// RandomAccessFile randomFile = null; -// ServletOutputStream out = null; -// try { -// byte[] buffer = new byte[4096]; -// int byteread = 0; -// fos = new FileOutputStream(tempfile); -// while ((byteread = inputStream.read(buffer)) != -1) { -// fos.write(buffer, 0, byteread); -// } -// fos.flush(); -// -// randomFile = new RandomAccessFile(tempfile, "r");//只读模式 -// long contentLength = randomFile.length(); -// String range = request.getHeader("Range"); -// int start = 0, end = 0; -// if(range != null && range.startsWith("bytes=")){ -// String[] values = range.split("=")[1].split("-"); -// start = Integer.parseInt(values[0]); -// if(values.length > 1){ -// end = Integer.parseInt(values[1]); -// } -// } -// int requestSize = 0; -// if(end != 0 && end > start){ -// requestSize = end - start + 1; -// } else { -// requestSize = Integer.MAX_VALUE; -// } -// response.setHeader("Accept-Ranges", "bytes"); -// response.setHeader("ETag", fileName); -// response.setHeader("Last-Modified", new Date().toString()); -// //第一次请求只返回content length来让客户端请求多次实际数据 -// if(range == null){ -// response.setHeader("Content-length", contentLength + ""); -// }else{ -// //以后的多次以断点续传的方式来返回视频数据 -// response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);//206 -// long requestStart = 0, requestEnd = 0; -// String[] ranges = range.split("="); -// if(ranges.length > 1){ -// String[] rangeDatas = ranges[1].split("-"); -// requestStart = Integer.parseInt(rangeDatas[0]); -// if(rangeDatas.length > 1){ -// requestEnd = Integer.parseInt(rangeDatas[1]); -// } -// } -// long length = 0; -// if(requestEnd > 0){ -// length = requestEnd - requestStart + 1; -// response.setHeader("Content-length", "" + length); -// response.setHeader("Content-Range", "bytes " + requestStart + "-" + requestEnd + "/" + contentLength); -// }else{ -// length = contentLength - requestStart; -// response.setHeader("Content-length", "" + length); -// response.setHeader("Content-Range", "bytes "+ requestStart + "-" + (contentLength - 1) + "/" + contentLength); -// } -// } -// out = response.getOutputStream(); -// int needSize = requestSize; -// randomFile.seek(start); -// while(needSize > 0){ -// int len = randomFile.read(buffer); -// if(needSize < buffer.length){ -// out.write(buffer, 0, needSize); -// } else { -// out.write(buffer, 0, len); -// if(len < buffer.length){ -// break; -// } -// } -// needSize -= buffer.length; -// } -// }catch (Exception e){ -// BaseBean basebean = new BaseBean(); -// basebean.writeLog(e); -// }finally { -// if(inputStream != null)inputStream.close(); -// if(fos != null)fos.close(); -// if(randomFile != null)randomFile.close(); -// if(out != null)out.close(); -// FileSecurityUtil.deleteFile(tempfile); -// //new FileDeleteUtil().deleteFile(tempfile); -// } -// } -// /** -// * ofd下载逻辑 -// * @param req -// * @param res -// */ -// //本例中传入的url是类似 http://ip:port/DownloadServlet?docId=2&imageFileId=5 -// private void downloadOfd(HttpServletRequest req, HttpServletResponse res, User user) { -// //本例中传入的url是类似 http://ip:port/DownloadServlet?docId=2&imageFileId=5 -// int docId= Util.getIntValue(req.getParameter("docId"),-1); -// int imageFileId= Util.getIntValue(req.getParameter("imageFileId"),-1); -// baseBean.writeLog("downloadOfd docId="+docId+"###imageFileId="+imageFileId); -// if (imageFileId <= 0) return; -// if(!DocUtil.hasPemissionDownload(user, imageFileId)){ -// baseBean.writeLog("---------- downloadOfd 无下载权限---------imageFileId=" + imageFileId); -// return; -// } -// InputStream is = null; -// BufferedOutputStream bos = null; -// try{ -// ImageFileManager imageFileManager=new ImageFileManager(); -// imageFileManager.getImageFileInfoById(imageFileId); -// res.setStatus(200); -// res.setContentType("APPLICATION/OCTET-STREAM; charset=UTF-8"); -// res.setHeader("Content-Disposition", "attachment; filename="+ new String(imageFileManager.getImageFileName().replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", "").getBytes("UTF-8"),"ISO-8859-1")+""); -// res.setContentType("application/ofd"); -// //writeLogs("2353 downloadFlag=" + downloadFlag); -// imageFileManager.setDownloadFlag(downloadFlag); // 2298348 wgs -// is = imageFileManager.getInputStream(); -// bos = new BufferedOutputStream(res.getOutputStream()); -// byte[] buf = new byte[BUFFER_SIZE]; -// int len = -1; -// while ((len = is.read(buf)) != -1){ -// bos.write(buf, 0, len); -// } -// bos.flush(); -// }catch(IOException exp){ -// exp.printStackTrace(); -// }finally{ -// if (is != null) -// try { -// is.close(); -// } catch (IOException e) { -// e.printStackTrace(); -// } -// if (bos != null) -// try { -// bos.close(); -// } catch (IOException e) { -// e.printStackTrace(); -// } -// } -// } -// -// private void downloadForEmaill(HttpServletRequest req, HttpServletResponse res){ -// //int fileid = Util.getIntValue(req.getParameter("fileid")); -// int fileid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileid(req), -1); -// MailFilePreviewService mfps = new MailFilePreviewService(); -// InputStream imagefile = mfps.getInputStreamByMailFileId(fileid + ""); -// -// String filename = Util.null2String(mfps.getFileNameOnly(fileid + "")); -// ServletOutputStream out = null; -// if(imagefile != null){ -// try { -// out = res.getOutputStream(); -// res.setContentType("application/octet-stream"); -// res.setHeader("content-disposition", "attachment; filename=\"" + -// URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); -// int byteread; -// byte data[] = new byte[1024]; -// while ((byteread = imagefile.read(data)) != -1) { -// out.write(data, 0, byteread); -// out.flush(); -// } -// } catch (Exception e) { -// new BaseBean().writeLog(e); -// } finally { -// if(out != null){ -// try{ -// out.close(); -// }catch(Exception e){ -// new BaseBean().writeLog(e); -// } -// } -// if(imagefile != null){ -// try{ -// imagefile.close(); -// }catch(Exception e){ -// new BaseBean().writeLog(e); -// } -// } -// } -// } -// } -// -// private void downloadForWebOffice(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ -// User user = (User)req.getSession(true).getAttribute("weaver_user@bean"); -// String fileid = Util.null2String(req.getParameter("fileid")); -// -// if(user == null){ -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?line=4&user=null"); -// return; -// } -// -// RecordSet rs = new RecordSet(); -// RecordSet rsdoc = new RecordSet(); -// rs.executeQuery("select a.id,b.docid,b.imagefilename from DocWebOffice a,DocImageFile b where a.fileid=? and a.imagefileid=b.imagefileid",fileid); -// if(rs.next()){ -// -// String docid = rs.getString("docid"); -// -// DocCoopereateUtil dcu = new DocCoopereateUtil(); -// DocViewPermission dvps = new DocViewPermission(); -// Map levelMap = dvps.getShareLevel(Util.getIntValue(docid),user,false); -// boolean canRead = levelMap.get(DocViewPermission.READ); -// boolean canCoope = dcu.jugeUserCoopeRight(docid,user,canRead); -// if(!canCoope){ -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?line=3&fileid=" + fileid); -// return; -// } -// -// Map dataMap = new HashMap(); -// InputStream in = new WebOfficeServiceImpl().getInputStream(rs.getInt("id"),dataMap); -// -// ServletOutputStream out = null; -// if(in != null){ -// rsdoc.executeQuery("select docsubject from docdetail where id = "+docid); -// rsdoc.next(); -// String docsubject = Util.null2String(rsdoc.getString("docsubject")); -// String imagefilename = Util.null2String(rs.getString("imagefilename")); -// String extname = imagefilename.contains(".")? imagefilename.substring(imagefilename.lastIndexOf(".") + 1) : ""; -// String filename =docsubject+"."+extname; -// if ( (agent.contains(" Chrome") || agent.contains("Safari")) && !agent.contains("Edge")) { -// // res.setHeader("content-disposition", "attachment;"); -// res.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(") -// .replaceAll("%29", ")").replaceAll("%7B","{").replaceAll("%7D","}").replaceAll("%5B","[").replaceAll("%5D","]").replaceAll("%40","@").replaceAll("%23","#").replaceAll("%25","%").replaceAll("%26","&") -// .replaceAll("%2B","+").replaceAll("%27","'").replaceAll("%20"," ")); -// }else if(agent.contains("Firefox")){ -// res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); -// } else{ -// res.setHeader("content-disposition", "attachment; filename=\"" + -// URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); -// } -// try { -// out = res.getOutputStream(); -// res.setContentType("application/octet-stream"); -// int byteread; -// byte data[] = new byte[1024]; -// while ((byteread = in.read(data)) != -1) { -// out.write(data, 0, byteread); -// out.flush(); -// } -// } catch (Exception e) { -// new BaseBean().writeLog(e); -// } finally { -// if(out != null){ -// try{ -// out.close(); -// }catch(Exception e){ -// new BaseBean().writeLog(e); -// } -// } -// if(in != null){ -// try{ -// in.close(); -// }catch(Exception e){ -// new BaseBean().writeLog(e); -// } -// } -// } -// }else{ -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?line=2&fileid=" + fileid); -// return; -// } -// }else{ -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?line=1&fileid=" + fileid); -// return; -// } -// -// } -// -// private void downloadForDoccenterCoop(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ -// User user = (User)req.getSession(true).getAttribute("weaver_user@bean"); -// String fileid = Util.null2String(req.getParameter("fileid")); -// String fromfileid = Util.null2String(req.getParameter("fromfileid")); -// String wpsFileid = Util.null2String(req.getParameter("wpsFileid")); -// -// if(user == null){ -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?line=4&user=null"); -// return; -// } -// -// if(fromfileid == null || fromfileid.isEmpty()){ -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?fromid=null"); -// return; -// } -// -// String docid = ""; -// int fromecfileid = Util.getIntValue(fileid); -// int ecfileid = 0; -// String mould = ""; -// String ecFileName = ""; -// -// RecordSet rs = new RecordSet(); -// String sql = "select * from wps_doccenter_fileinfo where wpsfileid = ? and fromecfileid = ? order by versionid desc"; -// rs.executeQuery(sql, wpsFileid, fromfileid); -// if(rs.next()){ -// fromecfileid = rs.getInt("fromecfileid"); -// ecfileid = rs.getInt("ecfileid"); -// mould = Util.null2String(rs.getString("mould")); -// ecFileName = Util.null2String(rs.getString("filename")); -// } else { -// ecfileid = fromecfileid; -// mould = "ecology"; -// } -// -// sql = "select docid, imagefilename from docimagefile where imagefileid = ?"; -// rs.executeQuery(sql,fromecfileid); -// if(!rs.next()) { -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?line=1&wpsFileid=" + wpsFileid); -// return; -// } -// docid = rs.getString("docid"); -// ecFileName = Util.null2String(rs.getString("imagefilename")); -// -// DocCoopereateUtil dcu = new DocCoopereateUtil(); -// DocViewPermission dvps = new DocViewPermission(); -// Map levelMap = dvps.getShareLevel(Util.getIntValue(docid),user,false); -// boolean canRead = levelMap.get(DocViewPermission.READ); -// boolean canCoope = dcu.jugeUserCoopeRight(docid,user,canRead); -// if(!canCoope){ -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?line=3&fileid=" + wpsFileid); -// return; -// } -// -// Map dataMap = new HashMap(); -// InputStream in = new weaver.wps.doccenter.utils.FileInfoUtil().getInputStream(ecfileid, mould); -// -// ServletOutputStream out = null; -// if(null == in) { -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?line=2&fileid=" + wpsFileid); -// return; -// } -// -// rs.executeQuery("select docsubject from docdetail where id = "+docid); -// rs.next(); -// String docsubject = Util.null2String(rs.getString("docsubject")); -// String extname = ecFileName.contains(".")? ecFileName.substring(ecFileName.lastIndexOf(".") + 1) : ""; -// String filename =docsubject+"."+extname; -// if ( (agent.contains(" Chrome") || agent.contains("Safari")) && !agent.contains("Edge")) { -// // res.setHeader("content-disposition", "attachment;"); -// res.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(") -// .replaceAll("%29", ")").replaceAll("%7B","{").replaceAll("%7D","}").replaceAll("%5B","[").replaceAll("%5D","]").replaceAll("%40","@").replaceAll("%23","#").replaceAll("%25","%").replaceAll("%26","&") -// .replaceAll("%2B","+").replaceAll("%27","'").replaceAll("%20"," ")); -// }else if(agent.contains("Firefox")){ -// res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); -// } else{ -// res.setHeader("content-disposition", "attachment; filename=\"" + -// URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); -// } -// try { -// out = res.getOutputStream(); -// res.setContentType("application/octet-stream"); -// int byteread; -// byte data[] = new byte[1024]; -// while ((byteread = in.read(data)) != -1) { -// out.write(data, 0, byteread); -// out.flush(); -// } -// } catch (Exception e) { -// rs.writeLog(FileDownload.class.getName(), e); -// } finally { -// Tools.cloze(out); -// Tools.cloze(in); -// } -// } -// /** -// * 文档下载 -// * @param req -// * @param res -// */ -// private void downloadForDocument(HttpServletRequest req, HttpServletResponse res,User user,boolean wmflag){ -// //int fileid = Util.getIntValue(req.getParameter("fileid")); -// int fileid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileid(req), -1); -// int isofficeview = Util.getIntValue(Util.null2String(req.getParameter("isofficeview")), -1); -// baseBean.writeLog("---------- downloadForDocument ---------fileid=" + fileid); -// if(fileid <= 0) return; -// if(!DocUtil.hasPemissionDownload(user, fileid)){ -// baseBean.writeLog("---------- downloadForDocument 无下载权限---------fileid=" + fileid); -// return; -// } -// InputStream imagefile = null; -// try { -// ImageFileManager ifm = new ImageFileManager(); -// ifm.getImageFileInfoById(fileid); -// //writeLogs("2622 downloadFlag=" + downloadFlag); -// ifm.setDownloadFlag(downloadFlag); // 2298348 wgs -// imagefile = ifm.getInputStream(); -// String filename = ifm.getImageFileName(); -// String contenttype = ""; -// if(filename.toLowerCase().endsWith(".gif")) { -// contenttype = "image/gif"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// }else if(filename.toLowerCase().endsWith(".png")) { -// contenttype = "image/png"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// }else if(filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg")) { -// contenttype = "image/jpg"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// }else if(filename.toLowerCase().endsWith(".bmp")) { -// contenttype = "image/bmp"; -// res.addHeader("Cache-Control", "private, max-age=8640000"); -// } -// if(isofficeview==1){ -// String extName = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : ""; -// Map secWmSetMap = WaterMarkUtil.getCategoryWmSet(fileid+""); -// if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYVIEW))&& "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtil.WATERCONTENTISNULL))){ -// // imagefile = WaterMarkUtil.takefileWater(imagefile,user,filename,fileid,extName,WaterMarkUtil.MOULDDOC); -// imagefile = FileWaterManager.takewater(req,fileid+"",filename,extName,imagefile, WaterMarkUtil.MOULDDOC,-1); -// } -// } -// ServletOutputStream out = res.getOutputStream(); -// res.setContentType(contenttype); -// res.setHeader("content-disposition", "attachment; filename=\"" + new String(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", "").getBytes("UTF-8"),"ISO-8859-1")+"\""); -// int byteread; -// byte data[] = new byte[1024]; -// while ((byteread = imagefile.read(data)) != -1) { -// out.write(data, 0, byteread); -// out.flush(); -// } -// out.flush(); -// out.close(); -// } catch (Exception e) { -// new BaseBean().writeLog(e); -// } finally { -// if(imagefile != null){ -// try{ -// imagefile.close(); -// }catch(Exception e){ -// new BaseBean().writeLog(e); -// } -// } -// } -// } -// -// //模板下载 -// private void downloadMould(HttpServletRequest req, HttpServletResponse res,String type){ -// //int mouldid = Util.getIntValue(req.getParameter("fileid")); -// int mouldid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileid(req), -1); -// if(mouldid <= 0) return; -// String mouldName = ""; -// String mouldPath = ""; -// String tableName = ""; -// String mouldtype = ""; -// int imagefileid = 0; -// if("showMould".equals(type)){ -// tableName = "docMould"; -// } else if ("printMould".equals(type)){ -// tableName = "OdocPrintMould"; -// }else{ -// tableName = "DocMouldFile"; -// } -// RecordSet rs = new RecordSet(); -// rs.executeQuery("select mouldName,mouldPath,imagefileid,mouldtype from "+ tableName +" where id=?",mouldid); -// if(rs.next()){ -// mouldName = rs.getString("mouldName"); -// mouldPath = rs.getString("mouldPath"); -// imagefileid = rs.getInt("imagefileid"); -// mouldtype = rs.getString("mouldtype"); -// }else{ -// return; -// } -// -// if ("printMould".equals(type) && "2".equals(mouldtype)){ -// mouldName += ".docx"; -// }else if("2".equals(mouldtype)){ -// mouldName += ".doc"; -// }else if("3".equals(mouldtype)){ -// mouldName += ".xls"; -// }else if("4".equals(mouldtype)){ -// mouldName += ".wps"; -// } -// InputStream is = null; -// try { -// if(imagefileid > 0){ -// is = ImageFileManager.getInputStreamById(imagefileid); -// }else{ -// is = new BufferedInputStream(new FileInputStream(mouldPath)); -// } -// res.setContentType("application/octet-stream"); -// ServletOutputStream out = res.getOutputStream(); -// res.setHeader("content-disposition", "attachment; filename=\"" + new String(mouldName.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", "").getBytes("UTF-8"),"ISO-8859-1")+"\""); -// int byteread; -// byte data[] = new byte[1024]; -// while ((byteread = is.read(data)) != -1) { -// out.write(data, 0, byteread); -// out.flush(); -// } -// out.flush(); -// out.close(); -// } catch (Exception e) { -// new BaseBean().writeLog(e); -// } finally { -// if(is != null){ -// try{ -// is.close(); -// }catch(Exception e){ -// new BaseBean().writeLog(e); -// } -// } -// } -// } -// -// /** -// * 交换平台下载逻辑 -// * @param req -// * @param res -// */ -// private void downloadForExchange(HttpServletRequest req, HttpServletResponse res) { -// String clientEcoding = "GBK"; -// try { -// try{ -// String acceptlanguage = req.getHeader("Accept-Language"); -// if(!"".equals(acceptlanguage)) -// acceptlanguage = acceptlanguage.toLowerCase(); -// if(acceptlanguage.indexOf("zh-tw")>-1||acceptlanguage.indexOf("zh-hk")>-1){ -// clientEcoding = "BIG5"; -// }else{ -// clientEcoding = "GBK"; -// } -// }catch(Exception e){ -// e.printStackTrace(); -// } -// User user = HrmUserVarify.getUser (req , res) ; -// agent = req.getHeader("user-agent"); -// int fileid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileid(req), -1); -// //int fileid = Util.getIntValue(req.getParameter("fileid"), -1); -// int requestid = Util.getIntValue(req.getParameter("requestid")); -// String ipstring = Util.getIpAddr(req); -// Map jsonParams = new HashMap(); -// int userid = 0; -// if(fileid <=0 ){ -// jsonParams = Json2MapUtil.requestJson2Map(req); -// fileid = Util.getIntValue(Util.null2String(jsonParams.get("fileid"))); -// userid = Util.getIntValue(Util.null2String(jsonParams.get("userid"))); -// requestid = Util.getIntValue(Util.null2String(jsonParams.get("requestid"))); -// } -// if(fileid <= 0){//转化为int型,防止SQL注入 -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?v6"); -// return; -// } -// RecordSet statement = new RecordSet(); -// try { -// boolean hasRight=false; -// try{ -// String companyId = getCompanyIdByUser(user); -// hasRight = isHaveDownloadRight(String.valueOf(fileid),companyId); -// }catch(Exception ex){ -// BaseBean basebean = new BaseBean(); -// basebean.writeLog(ex); -// hasRight=false; -// } -// if(!hasRight){ -// res.sendRedirect(GCONST.getContextPath()+"/notice/noright.jsp?v7"); -// return; -// } -// String contenttype = "application/octet-stream"; -// String filename = ""; -// String filerealpath = ""; -// String signInfo = ""; -// String hashInfo = ""; -// String iszip = ""; -// String isencrypt = ""; -// String isaesencrypt=""; -// String aescode = ""; -// String tokenKey=""; -// String storageStatus = ""; -// String comefrom=""; -// int byteread; -// byte data[] = new byte[1024]; -// String sql = "select t1.imagefilename,t1.filerealpath,t1.signinfo,t1.hashinfo,t1.iszip,t1.isencrypt,t1.imagefiletype , t1.imagefileid, t1.imagefile,t1.isaesencrypt,t1.aescode,t2.imagefilename as realname,t1.TokenKey,t1.StorageStatus,t1.comefrom from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.imagefileid = "+fileid; -// String extName = ""; -// statement.execute(sql); -// if (statement.next()) { -// filename = Util.null2String(statement.getString("imagefilename")); -// filerealpath = Util.null2String(statement.getString("filerealpath")); -// signInfo = Util.null2String(statement.getString("signinfo")); -// hashInfo = Util.null2String(statement.getString("hashinfo")); -// iszip = Util.null2String(statement.getString("iszip")); -// isencrypt = Util.null2String(statement.getString("isencrypt")); -// isaesencrypt = Util.null2o(statement.getString("isaesencrypt")); -// aescode = Util.null2String(statement.getString("aescode")); -// tokenKey = Util.null2String(statement.getString("TokenKey")); -// storageStatus = Util.null2String(statement.getString("StorageStatus")); -// comefrom = Util.null2String(statement.getString("comefrom")); -// try { -// if((agent.contains("Firefox")||agent.contains(" Chrome")||agent.contains("Safari") )&& !agent.contains("Edge")){ -// res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); -// }else{ -// res.setHeader("content-disposition", "attachment; filename=\"" + -// URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\""); -// } -// } catch (Exception ecode) { -// ecode.printStackTrace(); -// } -// InputStream imagefile = null; -// ZipInputStream zin = null; -// File thefile = new File(filerealpath); -// boolean signResult = false; -// if (!filerealpath.isEmpty() && !signInfo.isEmpty() && !hashInfo.isEmpty()) { -// signResult = com.api.doc.util.DocEncryptUtil.verifyFile(hashInfo, signInfo, filerealpath); -// // 附件下载,开始调用密码机解密 -// if (!signResult ) { -// res.sendRedirect(GCONST.getContextPath()+"/wui/common/page/integrityFailure.jsp?line=4&user=null"); -// return; -// } -// } -// if (iszip.equals("1")) { -// zin = new ZipInputStream(new FileInputStream(thefile)); -// if (zin.getNextEntry() != null) imagefile = new BufferedInputStream(zin); -// } else{ -// imagefile = new BufferedInputStream(new FileInputStream(thefile)); -// } -// ServletOutputStream out = null; -// try { -// out = res.getOutputStream(); -// res.setContentType(contenttype); -// if(isaesencrypt.equals("1")){ -// imagefile = AESCoder.decrypt(imagefile, aescode); -// } -// // 签名值校验通过,开始进行解密操作 -// if (signResult) { -// imagefile = com.api.doc.util.DocEncryptUtil.decryptInput(imagefile); -// if (imagefile == null) { -// res.sendRedirect(GCONST.getContextPath()+"/wui/common/page/integrityFailure.jsp?line=4&user=null"); -// return; -// } -// } -// while ((byteread = imagefile.read(data)) != -1) { -// out.write(data, 0, byteread); -// out.flush(); -// } -// } -// catch(Exception e) { -// e.printStackTrace(); -// }finally { -// if(imagefile!=null) imagefile.close(); -// if(zin!=null) zin.close(); -// if(out!=null) out.flush(); -// if(out!=null) out.close(); -// } -// countDownloads(""+fileid); -// } -// } catch (Exception e) { -// BaseBean basebean = new BaseBean(); -// basebean.writeLog(e); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 记录下载次数,根据传入的参数 countdownloads == 1 -// * -// */ -// private void countDownloads(String fileid) { -// if (this.isCountDownloads) { -// -// RecordSet rs = new RecordSet(); -// String sqlStr = "UPDATE ImageFile Set downloads=downloads+1 WHERE imagefileid = " + fileid; -// //System.out.println("sqlStr ==" + sqlStr); -// rs.execute(sqlStr); -// } -// } -// -// /** -// * 记录下载日志 -// * @param userid 下载的用户id -// * @param userName 下载的用户名称 -// * @param imageid 下载的文档id -// * @param imageName 下载的文档文件名称 -// */ -// private void downloadLog(int userid, String userName, int imageid, String imageName,String ipstring) { -// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// String time = format.format(new Date()); -// User user = new User(userid); -// RecordSet rs = new RecordSet(); -// String sql = "select t2.id,t2.docsubject,t1.imagefilename from DocImageFile t1, DocDetail t2 where t1.docid=t2.id and t1.docfiletype<>1 and t1.imagefileid = "+imageid; -// int docid = -1; -// String docName = ""; -// rs.executeSql(sql); -// if(rs.next()){ -// docid = rs.getInt(1); -// docName = rs.getString(2); -// imageName = Util.null2String(rs.getString("imagefilename")); -// userid = new DocViewPermission().getUserid(docid+"",user); -// if(userid<=0){ -// userid = user.getUID(); -// } -// sql = "insert into DownloadLog(userid, username, downloadtime, imageid, imagename, docid, docname,clientaddress) values(" + userid + ",'" + Util.toHtml100(userName) + "','" + time + "'," + imageid + ",'" + Util.toHtml100(imageName) + "',"+docid+",'"+Util.toHtml100(docName)+"','"+ipstring+"')"; -// rs.executeSql(sql); -// } -// -// DocDetailService dbs = new DocDetailService(); -// dbs.resizeCount(docid, DocDetailService.DOWNLOAD_COUNT); -// -// } -// -// /** -// * 判断是否有下载特定文件的权限 -// * @param fileId 文件id -// * @param req 请求 -// * @param res 响应 -// * -// * @return boolean true:有下载的权限 false:没有下载的权限 -// */ -// private boolean getWhetherHasRight(String fileId,HttpServletRequest req, HttpServletResponse res,int requestid,boolean fromMobile,Map jsonParams) throws Exception { -// toWriteLog("weaver-->2176-->fileid"+fileId+"--->ishr"+fileId); -// toWriteLog("weaver-->2176-->fileid"+fileId+"--->requestid"+requestid); -// toWriteLog("weaver-->2176-->fileid"+fileId+"--->fromMobile"+fromMobile); -// toWriteLog("weaver-->2176-->fileid"+fileId+"--->jsonParams"+jsonParams); -// jsonParams = jsonParams == null ? new HashMap() : jsonParams; -// //0:查看 -// boolean canReader = false; -// String fileid_head = fileId; -// int _userid = 0; -// String groupid = ""; -// if(fromMobile){ -// _userid = Util.getIntValue(Util.null2String(jsonParams.get("userid"))); -// groupid = Util.null2String(jsonParams.get("groupid")); -// } -// String download = Util.null2String(jsonParams.get("download")); -// User user = new User(_userid); -// if(user==null){ -// user = (User)req.getSession(true).getAttribute("weaver_user@bean") ; -// } -// //安全性检查 -// if(fileId==null||fileId.trim().equals("")){ -// return false; -// } -// -// RecordSet rs = new RecordSet(); -// //是否必须授权 1:是 0或其他:否 -// String mustAuth=Util.null2String(rs.getPropValue("FileDownload","mustAuth")); -// boolean hasRight=false; -// // boolean hasRight=true; -// if(mustAuth.equals("1")){ -// hasRight=false; -// } -// boolean isDocFile=false; -// boolean isHtmlPreview = false; -// //文档模块 附件查看权限控制 开始 -// String docId=null; -// boolean isimage=false; -// List docIdList=new ArrayList(); -// RecordSet rs2 = new RecordSet(); -// rs2.executeSql("select imagefilename,comefrom from ImageFile where imageFileId="+fileId); -// String extName=""; -// boolean isExtfile=false; -// boolean isPdf=false; -// if(rs2.next()){ -// String filename = Util.null2String(rs2.getString("imagefilename")); -// if(filename.indexOf(".") > -1){ -// int bx = filename.lastIndexOf("."); -// if(bx>=0){ -// extName = filename.substring(bx+1, filename.length()); -// } -// } -// String htmlcomefrom = Util.null2String(rs2.getString("comefrom")); -// if("WorkflowToDoc".equals(htmlcomefrom)){ -// isHtmlPreview = true; -// } -// -// if (filename.toLowerCase().endsWith(".mp4")||filename.toLowerCase().endsWith(".ogg")||filename.toLowerCase().endsWith(".asf")||filename.toLowerCase().endsWith(".mp3")||filename.toLowerCase().endsWith(".wav")||filename.toLowerCase().endsWith(".au")||filename.toLowerCase().endsWith(".wma")) { -// isHtmlPreview = true; -// } -// } -// -// if( "xls".equalsIgnoreCase(extName)||"xlsx".equalsIgnoreCase(extName) || "doc".equalsIgnoreCase(extName)|| "docx".equalsIgnoreCase(extName)||"wps".equalsIgnoreCase(extName)||"ppt".equalsIgnoreCase(extName)||"pptx".equalsIgnoreCase(extName)) { -// //isExtfile=true; -// } -// if("pdf".equals(extName.toLowerCase())) isPdf = true; -// String imgExtStr = Util.null2s(baseBean.getPropValue("doc_download_img_ext","doc_img_ext"),""); -// List imgExtList = Arrays.asList(imgExtStr.split(",")); -// for(int i=0;i=0){ -// hasRight=true; -// return hasRight; -// } -// if(comefrom.equals("DocPreview")||comefrom.equals("DocPreviewHistory")){ -// rs.executeSql("select imageFileId,docId from "+comefrom+" where (pdfFileId="+fileId+" or swfFileId="+fileId+") order by id desc"); -// if(rs.next()){ -// fileId_related=Util.getIntValue(rs.getString("imageFileId"),0); -// //docId_related=Util.getIntValue(rs.getString("docId"),0); -// } -// if(docId_related>0){ -// docIdList.add(""+docId_related); -// hasDocId=true; -// } -// }else if(comefrom.equals("DocPreviewHtml")||comefrom.equals("DocPreviewHtmlHistory")){ -// rs.executeSql("select imageFileId,docId from "+comefrom+" where htmlFileId="+fileId+" order by id desc"); -// if(rs.next()){ -// fileId_related=Util.getIntValue(rs.getString("imageFileId"),0); -// // docId_related=Util.getIntValue(rs.getString("docId"),0); -// } -// if(docId_related>0){ -// docIdList.add(""+docId_related); -// hasDocId=true; -// } -// isHtmlPreview = true; -// }else if(comefrom.equals("DocPreviewHtmlImage")){ -// rs.executeSql("select imageFileId,docId from DocPreviewHtmlImage where picFileId="+fileId+" order by id desc"); -// if(rs.next()){ -// fileId_related=Util.getIntValue(rs.getString("imageFileId"),0); -// //docId_related=Util.getIntValue(rs.getString("docId"),0); -// } -// if(docId_related>0){ -// docIdList.add(""+docId_related); -// hasDocId=true; -// } -// } -// // 处理敏感词高亮 -// if(isHtmlPreview && fileId_related > 0) { -// int originalFileId = -1; -// String querySql = "select original_fileid from imagefile where IMAGEFILEID = " + fileId_related +" and sensitive_wtype = 1"; -// rs.executeQuery(querySql); -// if(rs.next()) { -// originalFileId = rs.getInt(1); -// } -// if(originalFileId > 0) { -// fileId_related = originalFileId; -// previewSensitive = true; -// } -// } -// if(!hasDocId&&fileId_related>0){ -// rs.executeSql("select distinct docId from docImageFile where imageFileId="+fileId_related); -// while(rs.next()){ -// docId=rs.getString(1); -// if(docId!=null&&!docId.equals("")){ -// docIdList.add(docId); -// } -// } -// } -// -// if(fileId_related > 0){ -// originComeFrom = comefrom; -// rs.executeSql("select comefrom from ImageFile where imageFileId="+fileId_related); -// if(rs.next()){ -// comefrom=Util.null2String(rs.getString("comefrom")); -// } -// fileId = fileId_related + ""; -// } -// -// if(!hasDocId && fileId_related == 0){ -// extName = extName.toLowerCase(); -// if(extName.equals("jpg") || -// extName.equals("jpeg") || -// extName.equals("png") || -// extName.equals("gif") || -// extName.equals("bmp")){ -// -// int _docid = Util.getIntValue(req.getParameter("docid")); -// if(_docid > 0){ -// rs.executeQuery("select id from DocDetail where id=? and themeshowpic=?",_docid,fileId); -// if(rs.next()){ -// docIdList.add(rs.getString("id")); -// } -// } -// } -// } -// -// } -// if(docIdList.size()>0){ -// hasRight=false; -// } -// String mustLogin=Util.null2String(rs.getPropValue("FileDownload","mustLogin")); -// int votingId=Util.getIntValue(req.getParameter("votingId"),0); -// if(fromMobile && votingId<=0){ -// votingId = Util.getIntValue(Util.null2String(jsonParams.get("votingId")),0); -// } -// -// if(user==null && fromMobile){ -// user = new User(_userid); -// } -// -// if(user==null){ -// if(mustLogin.equals("1")){ -// hasRight=false; -// } -// return hasRight; -// } -// if(!fromMobile){ -// String f_weaver_belongto_userid=Util.null2String(req.getParameter("f_weaver_belongto_userid"));//需要增加的代码 -// String f_weaver_belongto_usertype=Util.null2String(req.getParameter("f_weaver_belongto_usertype"));//需要增加的代码 -// user = HrmUserVarify.getUser(req, res, f_weaver_belongto_userid, f_weaver_belongto_usertype) ;//需要增加的代码 -// } -// String workplanid=Util.null2String(req.getParameter("workplanid")); -// if(fromMobile){ -// workplanid = Util.null2String(jsonParams.get("workplanid")); -// } -// -// if(user==null){ -// user = (User)req.getSession(true).getAttribute("weaver_user@bean") ; -// } -// if(user==null){ -// if(mustLogin.equals("1")){ -// hasRight=false; -// } -// return hasRight; -// } -// String comefrom_noNeedAuth=Util.null2String(rs.getPropValue("FileDownload","comefrom_noNeedAuth")); -// if((","+comefrom_noNeedAuth+",").indexOf(","+comefrom+",")>=0){ -// hasRight=true; -// return hasRight; -// } -// if(comefrom.equals("VotingAttachment")){ // -// VotingManager votingManager = new VotingManager(); -// return votingManager.hasRightByFileid(votingId, Util.getIntValue(fileId,0), user); -// } -// -// DocManager docManager=new DocManager(); -// String docStatus=""; -// int isHistory=0; -// int secCategory=0; -// String docPublishType="";//文档发布类型 1:正常(不发布) 2:新闻 3:标题新闻 -// boolean useNewRightCheck = 1 == Util.getIntValue(baseBean.getPropValue("FileDownload","useNewRightCheck"),1); -// DocViewPermission dvp = new DocViewPermission(); -// for(int i=0;i shareLevelMap = dvp.getShareLevel(Util.getIntValue(docId), user, false); -// canReader = shareLevelMap.get(DocViewPermission.READ); -// hasRight = shareLevelMap.get(DocViewPermission.DOWNLOAD); -// } else { -// String userSeclevel = user.getSeclevel(); -// String userType = ""+user.getType(); -// String userDepartment = ""+user.getUserDepartment(); -// String userSubComany = ""+user.getUserSubCompany1(); -// String userInfo=loginType+"_"+userId+"_"+userSeclevel+"_"+userType+"_"+userDepartment+"_"+userSubComany; -// -// ArrayList PdocList = null; -// -// SpopForDoc spopForDoc=new SpopForDoc(); -// PdocList = spopForDoc.getDocOpratePopedom(""+docId,userInfo); -// -// SecCategoryComInfo secCategoryComInfo=new SecCategoryComInfo(); -// -// //1:编辑 -// boolean canEdit = false; -// //5:下载 -// if (((String)PdocList.get(0)).equals("true")) {canReader = true ;} -// if (((String)PdocList.get(1)).equals("true")) {canEdit = true ;} -// if (((String)PdocList.get(5)).equals("true")) {hasRight = true ;}//TD12005 -// -// String readerCanViewHistoryEdition=secCategoryComInfo.isReaderCanViewHistoryEdition(secCategory)?"1":"0"; -// -// if(canReader && ((!docStatus.equals("7")&&!docStatus.equals("8")) -// ||(docStatus.equals("7")&&isHistory==1&&readerCanViewHistoryEdition.equals("1")) -// )){ -// canReader = true; -// }else{ -// canReader = false; -// } -// -// if(isHistory==1) { -// if(secCategoryComInfo.isReaderCanViewHistoryEdition(secCategory)){ -// if(canReader && !canEdit) canReader = true; -// } else { -// if(canReader && !canEdit) canReader = false; -// } -// } -// -// if(canEdit && ((docStatus.equals("3") || docStatus.equals("5") || docStatus.equals("6") || docStatus.equals("7")) || isHistory==1)) { -// canEdit = false; -// canReader = true; -// } -// -// if(canEdit && (docStatus.equals("0") || docStatus.equals("1") || docStatus.equals("2") || docStatus.equals("7")) && (isHistory!=1)) -// canEdit = true; -// else -// canEdit = false; -// } -// -// if(previewSensitive && (canReader || hasRight)) { -// return true; -// } -// if((isPdf||isHtmlPreview) && !"1".equals(download) && !hasRight && canReader){ -// hasRight = true; -// } -// if(canReader){ -// //String referer = req.getHeader("Referer"); -// //String ismobile=req.getHeader("User-Agent"); -// if(isimage){ -// hasRight=true; -// } -// } -// if(hasRight) { -// return hasRight; -// } -// //E9流程判断 -// String authStr = Util.null2String(req.getParameter("authStr")); -// String authSignatureStr = Util.null2String(req.getParameter("authSignatureStr")); -// toWriteLog("weaver-->2505-->fileid"+fileId+"--->hasRight"+hasRight); -// toWriteLog("weaver-->2505-->fileid"+fileId+"--->canReader"+canReader); -// toWriteLog("weaver-->2505-->fileid"+fileId+"--->isExtfile"+isExtfile); -// toWriteLog("weaver-->2505-->fileid"+fileId+"--->authStr"+authStr); -// toWriteLog("weaver-->2505-->fileid"+fileId+"--->authSignatureStr"+authSignatureStr); -// -// if(!canReader && ((!authStr.isEmpty() && !authSignatureStr.isEmpty()) || requestid>0)){ -// RequestAuthenticationService e9wf = new RequestAuthenticationService(); -// e9wf.setUser(user); -// e9wf.setAuthResouceType(1); -// e9wf.setAuthResouceId(docId); -// hasRight = e9wf.verify(req, requestid); -// if(!hasRight){ -// rs.writeLog("^^^^^^ E9流程判断附件下载没权限(" + fileId + ")("+docId+")^^^^^^^^requestid=" + -// requestid + ",authStr=" + authStr + ",authSignatureStr=" + authSignatureStr); -// Map otherParams = new HashMap(); -// otherParams.put("requestid", requestid + ""); -// otherParams.put("ismonitor", 1 + ""); -// hasRight = e9wf.getRequestMonitorRight(otherParams,requestid); -// if(!hasRight){ -// rs.writeLog("^^^^^^ E9流程判断流程监控附件下载没权限(" + fileId + ")("+docId+")^^^^^^^^requestid=" + -// requestid + ",authStr=" + authStr + ",authSignatureStr=" + authSignatureStr); -// } -// } -// } -// -// if(!canReader&&!hasRight) {//如果没有查看权限,判断是否通过协作区赋权 -// int desrequestid = Util.getIntValue(req.getParameter("desrequestid")); -// int wfdesrequestid = Util.getIntValue(String.valueOf(req.getSession().getAttribute("desrequestid")),0); -// //System.out.println("wfdesrequestid = "+wfdesrequestid); -// int coworkid = Util.getIntValue(req.getParameter("coworkid")); -// if(fromMobile){ -// desrequestid = Util.getIntValue(Util.null2String(jsonParams.get("desrequestid"))); -// wfdesrequestid = Util.getIntValue( Util.null2String(jsonParams.get("desrequestid"))); -// coworkid = Util.getIntValue( Util.null2String(jsonParams.get("coworkid"))); -// } -// CoworkDAO coworkDAO=new CoworkDAO(coworkid); -// VotingManager votingManager=new VotingManager(); -// Map parameterMap=new HashMap(); -// parameterMap.put("docId",Util.getIntValue(docId)); -// parameterMap.put("votingId",votingId); -// parameterMap.put("userId",user.getUID()); -// //微博下载权限 -// BlogDao blogDao=new BlogDao(); -// int blogDiscussid = Util.getIntValue(req.getParameter("blogDiscussid"),0); -// if(fromMobile && blogDiscussid<=0){ -// blogDiscussid = Util.getIntValue( Util.null2String(jsonParams.get("blogDiscussid"))); -// } -// /*WFUrgerManager wfum=new WFUrgerManager(); -// RequestAnnexUpload rau=new RequestAnnexUpload(); -// if (!wfum.OperHaveDocViewRight(requestid,user.getUID(),Util.getIntValue(loginType,1),""+docId) -// &&!wfum.OperHaveDocViewRight(requestid,desrequestid,Util.getIntValue(userId),Util.getIntValue(loginType),""+docId) -// &&!wfum.getWFShareDesRight(requestid,wfdesrequestid,user,Util.getIntValue(loginType),""+docId) -// &&!wfum.getWFChatShareRight(requestid,Util.getIntValue(userId),Util.getIntValue(loginType),""+docId) -// &&!wfum.UrgerHaveDocViewRight(requestid,Util.getIntValue(userId),Util.getIntValue(loginType),""+docId) -// &&!wfum.getMonitorViewObjRight(requestid,Util.getIntValue(userId),""+docId,"0") -// &&!wfum.getWFShareViewObjRight(requestid,user,""+docId,"0") -// &&!rau.HaveAnnexDocViewRight(requestid,Util.getIntValue(userId),Util.getIntValue(loginType),Util.getIntValue(docId)) -// &&!coworkDAO.haveRightToViewDoc(userId,docId)&&!votingManager.haveViewVotingDocRight(parameterMap) -// &&!blogDao.appViewRight("doc",userId,Util.getIntValue(docId,0),blogDiscussid)){ -// hasRight=false; -// } else { -// hasRight = true ; -// }*/ -// if(!coworkDAO.haveRightToViewDoc(userId,docId)&&!votingManager.haveViewVotingDocRight(parameterMap) -// &&!blogDao.appViewRight("doc",userId,Util.getIntValue(docId,0),blogDiscussid)){ -// hasRight=false; -// } else { -// hasRight = true ; -// } -// } -// if(!canReader&&!hasRight) {//如果没有查看权限,判断是否通过会议赋权 -// int meetingid = Util.getIntValue(req.getParameter("meetingid")); -// MeetingUtil MeetingUtil = new MeetingUtil(); -// if (meetingid>0){ -// hasRight=MeetingUtil.UrgerHaveMeetingDocViewRight(meetingid+"",user,Util.getIntValue(loginType),""+docId); -// } else{ -// hasRight =MeetingUtil.UrgerHaveMeetingDocViewRight(user,Util.getIntValue(loginType),""+docId); -// } -// } -// -// if(!canReader&&!hasRight && !workplanid.equals("")) {//如果没有查看权限,判断是否通过日程赋权 -// WorkPlanService workPlanService = new WorkPlanService(); -// if (!workPlanService.UrgerHaveWorkplanDocViewRight(workplanid,user,Util.getIntValue(loginType),""+docId)){ -// hasRight=false; -// } else { -// hasRight = true ; -// } -// } -// //判断是否计划任务赋权 -// String fromworktask = Util.getFileidIn(Util.null2String(req.getParameter("fromworktask"))); -// String operatorid = Util.getFileidIn(Util.null2String(req.getParameter("operatorid"))); -// if(fromMobile){ -// fromworktask = Util.null2String(jsonParams.get("blogDiscussid")); -// operatorid = Util.null2String(jsonParams.get("operatorid")); -// } -// if("1".equals(fromworktask)) { -// /* WTRequestUtil WTRequestUtil = new WTRequestUtil(); -// if(!canReader&&!hasRight) { -// if(!WTRequestUtil.UrgerHaveWorktaskDocViewRight(requestid,Util.getIntValue(userId),Util.getIntValue(docId,0),Util.getIntValue(operatorid,0))) { -// hasRight=false; -// } else { -// hasRight = true ; -// } -// } else { -// hasRight=true; -// }*/ -// } -// //如果没有权限,看到是否具有客户联系查看权限 -// if(!canReader&&!hasRight) {//如果没有查看权限,判断是否通过会议赋权 -// CrmShareBase crmshare = new CrmShareBase(); -// String crmid = Util.null2String(req.getParameter("crmid")); -// if(fromMobile){ -// crmid = Util.null2String(jsonParams.get("crmid")); -// } -// int sharetype = crmshare.getRightLevelForCRM(userId+"",crmid,loginType); -// String crmtype = Util.null2String(req.getParameter("crmtype")); -// if(fromMobile){ -// crmtype = Util.null2String(jsonParams.get("crmtype")); -// } -// if(crmtype == null || "".equals(crmtype))crmtype = "0"; -// if (sharetype > 0 && crmshare.checkCrmFileExist(crmid, fileId, crmtype)){ -// //CoworkDAO coworkDAO = new CoworkDAO(); -// //coworkDAO.shareCoworkRelateddoc(Util.getIntValue(loginType),Util.getIntValue(docId,0),Util.getIntValue(userId)); -// hasRight= true; -// } else { -// hasRight = false; -// } -// } -// // 如果没有下载权限,查找是否协作区附件赋权 -// if(!hasRight) { -// int coworkid = Util.getIntValue(req.getParameter("coworkid")); -// if(fromMobile){ -// coworkid = Util.getIntValue(Util.null2String(jsonParams.get("coworkid"))); -// } -// CoworkDAO coworkDAO = new CoworkDAO(coworkid); -// hasRight = coworkDAO.haveRightToViewDoc(userId,docId); -// } -// -// //财务模块 发票影像 -// String cwid = req.getParameter("cwid"); -// toWriteLog("weaver-->2679-->fileid"+fileId+"--->cwid"+cwid); -// toWriteLog("weaver-->2679-->fileid"+fileId+"--->hasRight"+hasRight); -// if(!hasRight && "fna".equals(cwid)){ -// hasRight = weaver.fna.invoice.utils.ImagePermissionUtil.checkImagePermission(Util.getIntValue(fileId),user); -// if(!hasRight){ -// rs.writeLog("^^^^^^ 财务模块 发票影像 财务判断附件下载没权限(" + fileId + ")("+docId+")^^^^^^^^"); -// } -// } -// toWriteLog("weaver-->2687-->fileid"+fileId+"--->hasRight"+hasRight); -// -// //财务模块 微报账规则制度 -// if(!hasRight && "fna".equals(cwid)){ -// RecordSet rs_ruleSystem = new RecordSet(); -// //获取规则制度 -// int ruleSystem = 0; -// rs_ruleSystem.executeQuery("select ruleSystem from fnaInvoiceEnterWay "); -// if(rs.next()){ -// ruleSystem = Util.getIntValue(rs_ruleSystem.getString("ruleSystem"),0); -// } -// if(ruleSystem==Util.getIntValue(fileId) && ruleSystem!=0){ -// hasRight = true; -// } -// } -// toWriteLog("weaver-->2892-->fileid"+fileId+"--->hasRight"+hasRight); -// -// -// if(new DocViewPermission().hasRightFromOtherMould(Util.getIntValue(docId),user,req)){ -// hasRight = true; -// if("1".equals(download)){ -// hasRight=new DocViewPermission().hasDownRightFromFormMode(Util.getIntValue(docId),user,req); -// } -// } -// -// if(hasRight){ -// return hasRight; -// } -// } -// //文档模块 附件查看权限控制 结束 -// -// if("email".equals(req.getParameter("model"))){ //邮件附件转html -// -// boolean emailFlag = new MailFilePreviewService().getViewRightByHtmlCode(user.getUID(),fileId); //fileId -// -// if(emailFlag){ -// return true; -// }else{ -// rs.writeLog("^^^^^^ email判断附件下载没权限(" + fileId + ")^^^^^^^^"); -// return false; -// } -// } -// -// -// if(docIdList.size()==0 && "EMforEC".equals(comefrom)){ -// hasRight = false; -// } -// //检查社交平台附加权限 -// if(!hasRight && "EMforEC".equals(comefrom)){ -// //hasRight=SocialIMService.checkFileRight(user, fileId, isDocFile, hasRight); -// if(!groupid.isEmpty()){ -// rs.executeQuery("select groupid from social_IMFileShareGroup where groupid=? and fileid=?",groupid,Util.getIntValue(fileId)); -// if(rs.next()){ -// hasRight = true; -// } -// } -// if(!hasRight){ -// rs.executeQuery("select id from social_IMFileShare where userid=? and fileid=?",user.getUID(),Util.getIntValue(fileId)); -// if(rs.next()){ -// hasRight = true; -// } -// } -// -// -// }else if(!hasRight && "EMforECNoRight".equals(comefrom)){ -// hasRight = true; -// }else if(!hasRight){ -// hasRight=SocialIMService.checkFileRight(user, fileId, isDocFile, hasRight); -// } -// -// if(!hasRight) {//查看是否有建模关联授权 -// //表单建模判断关联授权 -// String formmodeflag = StringHelper.null2String(req.getParameter("formmode_authorize")); -// Map formmodeAuthorizeInfo = new HashMap(); -// //formmodeparas+="&formmode_authorize="+formmodeflag; -// if(formmodeflag.equals("formmode_authorize")){ -// int modeId = 0; -// int formmodebillId = 0; -// int fieldid = 0; -// int formModeReplyid = 0; -// modeId = Util.getIntValue(req.getParameter("authorizemodeId"),0); -// formmodebillId = Util.getIntValue(req.getParameter("authorizeformmodebillId"),0); -// fieldid = Util.getIntValue(req.getParameter("authorizefieldid"),0); -// formModeReplyid = Util.getIntValue(req.getParameter("authorizeformModeReplyid"),0); -// String fMReplyFName = Util.null2String(req.getParameter("authorizefMReplyFName")); -// if(fromMobile && modeId <= 0){ -// modeId = Util.getIntValue(Util.null2String(jsonParams.get("authorizemodeId"))); -// formmodebillId = Util.getIntValue(Util.null2String(jsonParams.get("authorizeformmodebillId"))); -// fieldid = Util.getIntValue(Util.null2String(jsonParams.get("authorizefieldid"))); -// formModeReplyid = Util.getIntValue(Util.null2String(jsonParams.get("authorizeformModeReplyid"))); -// fMReplyFName = Util.null2String(jsonParams.get("fMReplyFName")); -// } -// -// ModeRightInfo modeRightInfo = new ModeRightInfo(); -// modeRightInfo.setUser(user); -// if(formModeReplyid!=0){ -// formmodeAuthorizeInfo = modeRightInfo.isFormModeAuthorize(formmodeflag, modeId, formmodebillId, fieldid, Util.getIntValue(docId), formModeReplyid,fMReplyFName); -// }else{ -// formmodeAuthorizeInfo = modeRightInfo.isFormModeAuthorize(formmodeflag, modeId, formmodebillId, fieldid, Util.getIntValue(docId)); -// } -// } -// -// if("1".equals(formmodeAuthorizeInfo.get("AuthorizeFlag"))){//如果是表单建模的关联授权,那么直接有查看权限 -// hasRight = true; -// } -// } -// -// if (!hasRight) { -// //数据中心查看文档权限 -// String edcFlag = StringHelper.null2String(req.getParameter("edc_authorize")); -// if (edcFlag.equals("edc_authorize")) { -// int formid = Util.getIntValue(req.getParameter("authorizeFormId"), 0); -// int billid = Util.getIntValue(req.getParameter("authorizeBillId"), 0); -// int fieldid = Util.getIntValue(req.getParameter("authorizeFieldId"), 0); -// hasRight = JoinCubeBiz.checkDocViewPermission(user, formid, billid, fieldid, Util.getIntValue(docId)); -// } -// } -// -// //建模扩展查看文档权限 -// if (!hasRight) { -// String ecmeflag = StringHelper.null2String(req.getParameter("ecme_authorize")); -// if (ecmeflag.equals("ecme_authorize")) { -// int billid = Util.getIntValue(req.getParameter("authorizebillId"), 0); -// int fieldid = Util.getIntValue(req.getParameter("authorizefieldid"), 0); -// int feaId = Util.getIntValue(req.getParameter("authorizefeaId"), 0); -// EcmeRightManager erm = new EcmeRightManager(user,feaId); -// hasRight = erm.ecmeAuthorize( billid, fieldid,Util.getIntValue(docId)); -// } -// } -// -// //财务模块微报账记一笔 -// String cwid = req.getParameter("cwid"); -// if(!hasRight && "fnaRemember".equals(cwid)){ -// int count=0; -// rs.executeQuery("select count(id) cnt from fnaTakeOneNote where imageid=?",fileId); -// if(rs.next()){ -// count = Util.getIntValue(rs.getString("cnt"),0); -// } -// if(count>0){ -// hasRight = true; -// } -// } -// if(hasRight) { -// return hasRight; -// } -// toWriteLog("weaver-->2702-->fileid"+fileId+"--->hasRight"+hasRight); -// String isHaveDocSql = "select 1 from docimagefile where imagefileid = ?"; -// Boolean isHaveDoc = false; -// rs.executeQuery(isHaveDocSql,fileId); -// if(rs.next()) isHaveDoc = true; -// //如果附件无文档文档,且无权限看, -// if(!hasRight && !isHaveDoc){ -// String fileidStr = Util.null2s(req.getParameter("fileid"),""); -// String jmFileidStr = Util.null2s(req.getParameter("jmFileid"),""); -// String fieldidsStr = Util.null2s(req.getParameter("fieldids"),""); -// int fileid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileid(req), -1); -// String fieldids = Util.null2String(DocDownloadCheckUtil.getDownloadfileid(req)); -// //如果是加密串并且fileid存在,则可以下载 如果是批量下载,需要不含逗号,长度大于11(防止只有一个附件id的情况),并且附件id存在 -// if((fileidStr.length()>11 && fileid>0) ||(jmFileidStr.length()>11 && fileid>0) || (!fieldidsStr.contains(",") && fileId!=null && !fileId.trim().equals("") && fieldidsStr.length()>11)){ -// hasRight = true; -// } -// } -// /** -// * 判断是否来自云盘分享的下载 -// */ -// // if(!hasRight){ 加密串导致hasRight为true,从而云盘文件不进此判断逻辑 -// hasRight = FiledownloadUtil.netdiskHasright(hasRight,fileid_head,user); -// //} -// /** -// * 判断是否来自云盘的poi转换 -// */ -// if(comefrom != null && !comefrom.isEmpty() || !originComeFrom.isEmpty()) { -// String sql = ""; -// if (comefrom.isEmpty()) { -// comefrom = originComeFrom; -// } -// if("DocPreviewHtmlImage".equals(comefrom)){ -// sql ="select imageFileId from DocPreviewHtmlImage where picFileId=?"; -// }else if("DocPreviewHtml".equals(comefrom)){ -// sql = "select imagefileid from DocPreviewHtml where htmlFileId=?" ; -// }else if("pdfconvert".equals(comefrom)){ -// sql = "select imagefileid from pdf_imagefile where pdfimagefileid=?"; -// } -// if(!sql.isEmpty()){ -// rs.executeQuery(sql,fileid_head); -// if(rs.next()){ -// String _fileid = rs.getString("imagefileid"); -// hasRight = FiledownloadUtil.netdiskHasright(hasRight,_fileid,user); -// } -// } -// } -// //判断附件是否来源于回复 -// String isFromReplySql = "select 1 from reply_imagefile where imagefileid=?"; -// rs.executeQuery(isFromReplySql,fileId); -// if(rs.next()){ -// hasRight = true; -// } -// -// //pdf附件判断user权限是否一致 -// cwid = req.getParameter("cwid"); -// if("compared".equals(cwid)){ -// String sqlDetail = " select mainid from FnaDocCompareDetail where 1=1 "+ -// "and (leftSrc = ? or leftSrc2 = ? or rightSrc = ? or rightSrc2 = ? ) "; -// rs.executeQuery(sqlDetail, fileId,fileId,fileId,fileId); -// int mainId = 0; -// if(rs.next()){ -// mainId = Util.getIntValue(rs.getString("mainid"),0); -// } -// -// rs.executeQuery(" select userid from FnaDocCompare where id = ? ", mainId); -// if(rs.next()){ -// int userIdMain = Util.getIntValue(rs.getString("userid")); -// if(userIdMain != user.getUID()){ -// hasRight = false; -// }else{ -// hasRight = true; -// } -// } -// -// if(!hasRight){ -// String sqlMain = " select userid from FnaDocCompare where 1=1 and (left_entry_ids = ? or left_pdf_id = ? or right_entry_ids = ? or right_pdf_id = ?) "; -// rs.executeQuery(sqlMain, fileId,fileId,fileId,fileId); -// if(rs.next()){ -// int userIdMain = Util.getIntValue(rs.getString("userid")); -// if(userIdMain != user.getUID()){ -// hasRight = false; -// }else{ -// hasRight = true; -// } -// } -// } -// -// } -// baseBean.writeLog("weaver-->2917-->fileid"+fileId+"--->hasRight:"+hasRight); -// -// return hasRight; -// } -// -// // 下载公用方法 -// -// public void toUpload(HttpServletResponse response,String str){ -// toUpload(response,str,str); -// } -// -// public void toUpload(HttpServletResponse response,String str, String tmptfilename){ -// try { -// -// SystemComInfo syscominfo = new SystemComInfo(); -// String path= syscominfo.getFilesystem(); -// if("".equals(path)){ -// path = GCONST.getRootPath(); -// path = path + "filesystem" + File.separatorChar+ "downloadBatch"+File.separatorChar+tmptfilename; -// }else{ -// if(path.endsWith(File.separator)){ -// path += "downloadBatch"+File.separatorChar+File.separatorChar+tmptfilename; -// -// }else{ -// path += File.separator+ "downloadBatch"+File.separatorChar+File.separatorChar+tmptfilename; -// } -// } -// -// //String path=GCONST.getRootPath()+ "downloadBatch"+File.separatorChar+str; -// //String path="E:/bjls_ecology4.1_5.0/ecology/downloadBatch/"+str; -// if(!"".equals(path)){ -// File file=new File(path); -// if(file.exists()){ -// InputStream ins=null; -// BufferedInputStream bins=null; -// OutputStream outs=null; -// BufferedOutputStream bouts=null; -// try -// { -// -// ins=new FileInputStream(path); -// bins=new BufferedInputStream(ins);//放到缓冲流里面 -// outs=response.getOutputStream();//获取文件输出IO流 -// bouts=new BufferedOutputStream(outs); -// response.setContentType("application/x-download");//设置response内容的类型 -// if((agent.contains(" Chrome")||agent.contains("Safari") )&& !agent.contains("Edge")){ -// response.setHeader("content-disposition", "attachment;filename=\"" + URLEncoder.encode(str.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")").replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", "").replaceAll("\\+", "%20").replaceAll("%28", "(") -// .replaceAll("%29", ")").replaceAll("%7B","{").replaceAll("%7D","}").replaceAll("%5B","[").replaceAll("%5D","]").replaceAll("%40","@").replaceAll("%23","#").replaceAll("%25","%").replaceAll("%26","&") -// .replaceAll("%2B","+")+ "\""); -// // response.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(str.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); -// }else if(agent.contains("Firefox")){ -// // filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); -// // res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); -// -// // filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); -// // res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); -// // filename = "=?UTF-8?B?" + (new String(Base64.encodeBase64(filename.getBytes("UTF-8")))) + "?="; -// // res.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename)); -// -// response.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(str.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); -// }else{ -// response.setHeader("content-disposition", "attachment; filename=\"" + URLEncoder.encode(str.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\""); -// } -// int bytesRead = 0; -// byte[] buffer = new byte[8192]; -// //开始向网络传输文件流 -// while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) { -// bouts.write(buffer, 0, bytesRead); -// } -// bouts.flush();//这里一定要调用flush()方法 -// ins.close(); -// bins.close(); -// outs.close(); -// bouts.close(); -// } -// catch (Exception ef) -// { -// new weaver.filter.XssUtil().writeError(ef); -// } -// finally { -// -// if(ins!=null) ins.close(); -// if(bins!=null) bins.close(); -// if(outs!=null) outs.close(); -// if(bouts!=null) bouts.close(); -// } -// -// } -// else{ -// response.sendRedirect(GCONST.getContextPath()+"/login/BatchDownloadsEror.jsp"); -// } -// } -// else{ -// response.sendRedirect(GCONST.getContextPath()+"/login/BatchDownloadsEror.jsp"); -// -// //注;这里面不要用到PrintWriter out=response.getWriter();这里调用了response对象,后面下载调用时就会出错。这里要是想都用,希望大家找到解决办法。 -// } -// } catch (IOException e) { -// e.printStackTrace(); +package weaver.file; + +/** + * Title: + * Description: ,2004-6-25:增加了是否记录下载次数到数据库 + * Copyright: Copyright (c) 2002 + * Company: + * @author ,Charoes Huang + * @version 1.0,2004-6-25 + */ + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.RandomAccessFile; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.zip.ZipInputStream; + +import javax.servlet.ServletException; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import com.api.doc.detail.service.DocViewPermission; +import com.api.doc.detail.service.impl.DocWaterServiceImpl; +import com.api.doc.detail.util.PdfConvertUtil; +import com.api.doc.mobile.systemDoc.util.SystemDocUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.doc.util.*; +import com.engine.ecme.biz.EcmeRightManager; +import com.engine.odoc.util.DocUtil; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; + +import weaver.WorkPlan.WorkPlanService; +import weaver.alioss.AliOSSObjectManager; +import weaver.blog.BlogDao; +import weaver.common.DateUtil; +import weaver.common.StringUtil; +import weaver.conn.RecordSet; +import weaver.cowork.CoworkDAO; +import weaver.crm.CrmShareBase; +import weaver.docs.EncryptDecryptFileUtil; +import weaver.docs.category.SecCategoryComInfo; +import weaver.docs.docs.DocManager; +import weaver.docs.docs.AddWater.DocAddWaterForSecond; +import weaver.email.service.MailFilePreviewService; +import weaver.file.util.FileDeleteUtil; +import weaver.file.util.FileManager; +import weaver.file.util.FileWaterManager; +import weaver.file.util.FiledownloadUtil; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.general.GCONST; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.resource.ResourceComInfo; +import weaver.meeting.MeetingUtil; +import weaver.mobile.plugin.ecology.service.AuthService; +import weaver.rdeploy.doc.PrivateSeccategoryManager; +import weaver.social.service.SocialIMService; +import weaver.splitepage.operate.SpopForDoc; +import weaver.system.SystemComInfo; +import weaver.systeminfo.SystemEnv; +import weaver.voting.VotingManager; +import weaver.voting.groupchartvote.ImageCompressUtil; +import DBstep.iMsgServer2000; + +import com.api.doc.detail.service.DocDetailService; +import com.api.doc.detail.service.DocViewPermission; +import com.api.doc.detail.util.DocCoopereateUtil; +import com.api.doc.detail.util.DocDownloadCheckUtil; +import com.api.doc.detail.util.ImageConvertUtil; +import com.api.doc.upload.web.util.Json2MapUtil; +import com.api.doc.wps.service.impl.WebOfficeServiceImpl; +import com.api.workflow.service.RequestAuthenticationService; +import com.engine.edc.biz.JoinCubeBiz; +import com.weaver.formmodel.util.StringHelper; + +import de.schlichtherle.util.zip.ZipEntry; +import de.schlichtherle.util.zip.ZipOutputStream; +import weaver.wps.CommonUtil; +import weaver.wps.doccenter.utils.Tools; + +public class FileDownload extends HttpServlet { + /** + * 是否需要记录下载次数 + */ + + private boolean isCountDownloads = false; + private String downloadFlag = ""; // 2298348 wgs + private String agent = ""; + private static final int BUFFER_SIZE = 1 *1024 * 1024; + private BaseBean baseBean = new BaseBean(); + private String systemWaterwriteLog = Util.null2s(baseBean.getPropValue("doc_custom_for_weaver","systemWaterwriteLog"),"0"); + private String writeLogForDownload = Util.null2s(baseBean.getPropValue("doc_writelog_config","doc_download_log"),"1"); + + public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { + this.doGet(req,res); + } + + public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { + + + User wmloginuser = (User)req.getSession(true).getAttribute("weaver_user@bean") ; + String wmuserid=wmloginuser.getUID()+""; + boolean wmflag = true; + new BaseBean().writeLog("wmuserid---"+wmuserid); + RecordSet wmrs = new RecordSet(); + wmrs.execute("select count(1) as sl from uf_syqxryb where userid = '"+wmuserid+"'"); + while (wmrs.next()){ + if(Util.getIntValue(wmrs.getString("sl"))>0){ + wmflag = false; + } + } + String type = Util.null2String(req.getParameter("type")); + Boolean _ec_ismobile = Boolean.valueOf(req.getParameter("_ec_ismobile")); + String fromdocmobile = Util.null2String(req.getParameter("from_doc_mobile")); + Boolean from_doc_mobile = fromdocmobile.equals("1") ? true : false; + this.downloadFlag = Util.null2String(req.getParameter("download")); // 2298348 wgs + baseBean.writeLog(FileDownload.class.getName(),type); + baseBean.writeLog(FileDownload.class.getName(),_ec_ismobile); + baseBean.writeLog(FileDownload.class.getName(),fromdocmobile); + baseBean.writeLog(FileDownload.class.getName(),fromdocmobile); + baseBean.writeLog(FileDownload.class.getName(),this.downloadFlag); + baseBean.writeLog("路径"+req.getRequestURI()); + writeLogs("download start!"); + writeLogs("downloadFlag=" + downloadFlag); // 2447956 wgs + int nolog = Util.getIntValue(Util.null2String(req.getParameter("nolog")),0); + String res_content_disposition = Util.null2String(req.getParameter("response-content-disposition")); + boolean isMobileDown=false; + if(_ec_ismobile || from_doc_mobile || !"".equals(res_content_disposition)){ + isMobileDown=true; + } + if("showMould".equals(type) || "editMould".equals(type) || "printMould".equals(type)){ + downloadMould(req,res,type); + }else if("weboffice".equals(type)){ + downloadForWebOffice(req,res); + }else if("doccenter".equals(type)){ + downloadForDoccenterCoop(req,res); + }else if("document".equals(type)){ + User user = HrmUserVarify.getUser (req , res) ; + downloadForDocument(req,res,user,wmflag ); + }else if("ofd".equals(type)){ + User user = HrmUserVarify.getUser (req , res) ; + downloadOfd(req,res,user); + }else if("odocExchange".equals(type)){ + downloadForExchange(req,res); + }else if("exportHtmlView".equals(type)){ + ExportHtmlViewMould ehvm = new ExportHtmlViewMould(); + int fileid = Util.getIntValue(req.getParameter("fileid")); + Map dataMap = ehvm.toExport(fileid); + String zipPath = dataMap.get("zipPath"); + String filename = dataMap.get("zipName"); + if(zipPath != null && !zipPath.isEmpty()){ + ServletOutputStream out = null; + InputStream imagefile = null; + try { + if((agent.contains("Firefox")||agent.contains(" Chrome")||agent.contains("Safari") )&& !agent.contains("Edge")){ + res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); + }else{ + res.setHeader("content-disposition", "attachment; filename=\"" + + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\""); + } + } catch (Exception ecode) { + ecode.printStackTrace(); + } + try { + imagefile = new FileInputStream(zipPath); + out = res.getOutputStream(); + res.setContentType("application/x-download"); + byte []data = new byte[2048]; + int byteread = 0; + while ((byteread = imagefile.read(data)) != -1) { + out.write(data, 0, byteread); + out.flush(); + } + } + catch(Exception e) { + e.printStackTrace(); + }finally { + if(imagefile!=null) imagefile.close(); + if(out!=null) out.close(); + + ImportHtmlViewMould ihvm = new ImportHtmlViewMould(); + ihvm.delTempFile(zipPath); + ihvm.delTempFile(zipPath.replace(".zip","")); + } + } + }else if("Email".equals(type)){ + downloadForEmaill(req,res); + }else if(!"netimag".equals(type)){ + String clientEcoding = "GBK"; + try + { + String acceptlanguage = Util.null2String(req.getHeader("Accept-Language")); + if(!"".equals(acceptlanguage)) + acceptlanguage = acceptlanguage.toLowerCase(); + if(acceptlanguage.indexOf("zh-tw")>-1||acceptlanguage.indexOf("zh-hk")>-1) + { + clientEcoding = "BIG5"; + } + else + { + clientEcoding = "GBK"; + } + } + catch(Exception e) + { + writeLogs(e); + } + + agent = Util.null2String(req.getHeader("user-agent")); + String frompdfview = Util.null2String(req.getParameter("frompdfview")); + String downloadBatch = Util.null2String(req.getParameter("downloadBatch")); + //只下载附件,而不是下载文档的附件 + String onlydownloadfj = Util.null2String(req.getParameter("onlydownloadfj")); + /*==============td26423 流程中批量下载 start=========================================================*/ + if(downloadBatch!=null &&"1".equals(downloadBatch)){//批量下载---传入的是文档的ids + //req.setCharacterEncoding("ISO8859-1"); + String ipstring = Util.getIpAddr(req); + String currentDateTime= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); + String docids = Util.null2String(req.getParameter("fieldvalue"));//docids 以逗号隔开的 + if(!"".equals(docids)){ + String[] docidsarray=docids.split(","); + if(docidsarray!=null && docidsarray.length>0){ + String newdocids=""; + for(String newdocid:docidsarray){ + if(Util.getIntValue(newdocid)>0){ + String secondAuthFileDownUrl=getSecondAuthFileDownUrl(req,isMobileDown,Util.getIntValue(newdocid)); + if(!"".equals(secondAuthFileDownUrl)){ + res.sendRedirect(secondAuthFileDownUrl); + return; + } + if("".equals(newdocids)){ + newdocids=newdocid; + }else{ + newdocids+=","+newdocid; + } + } + } + docids=newdocids; + } + } + String displayUsage = Util.null2String(req.getParameter("displayUsage")); + String tempFlag1=""; + if(docids!=null&&!"".equals(docids)){ + tempFlag1=docids.substring(docids.length()-1); + } + if(tempFlag1.equals(",")) docids=docids.substring(0,docids.length()-1); + String delImgIds=Util.null2String(req.getParameter("delImgIds"));//imgeFileids 以逗号隔开的 + String tempFlag=""; + if(delImgIds!=null &&!"".equals(delImgIds)){ + tempFlag=delImgIds.substring(delImgIds.length()-1); + } + if(tempFlag.equals(",")) delImgIds=delImgIds.substring(0,delImgIds.length()-1); + + String docSearchFlag=Util.null2String(req.getParameter("docSearchFlag"));//docSearchFlag ='1-标记为从查询文档中来批量下载多文档的多附件' + + String requestname =""; + //String requestname = Util.null2String(req.getParameter("requestname"));//requestname 流程标题 + //requestname =new String(requestname.getBytes("UTF-8")); + RecordSet rsimagefileid =new RecordSet(); + String requestid = Util.null2String(req.getParameter("requestid"));//requestname 流程标题 + if(Util.getIntValue(requestid)>0){ + String sqlrequestname="select requestname from workflow_requestbase where requestid='"+requestid+"'"; + rsimagefileid.executeSql(sqlrequestname); + if(rsimagefileid.next()){ + requestname=Util.null2String(rsimagefileid.getString("requestname")); + } + } + requestname = Util.StringReplace(requestname,"/","/"); + String download = Util.null2String(req.getParameter("download")); + + User loginuser = (User)req.getSession(true).getAttribute("weaver_user@bean") ; + String userid= Util.null2String(req.getParameter("f_weaver_belongto_userid")); + if("".equals(userid) || userid == null){ + userid=loginuser.getUID()+""; + } + //String loginid=loginuser.getLoginid(); + //String[] docidsList = Util.TokenizerString2(docids, ","); + //List docImagefileidList= new ArrayList(); + String docImagefileids=""; + String sqlimagefileid="select a.id,a.docsubject,b.imagefileid,b.imagefilename from DocDetail a,DocImageFile b where a.id=b.docid and a.id in ("+docids+") and b.versionId = (select MAX(c.versionId) from DocImageFile c where c.id=b.id ) order by a.id asc"; + + /* + String sqlimagefileid=""; + if("1".equals(docSearchFlag)){//处理从查询文档中 来的文档附件批量下载时只下载最新版本问题 + sqlimagefileid="select a.id,a.docsubject,b.imagefileid,b.imagefilename from DocDetail a,DocImageFile b where a.id=b.docid and a.id in ("+docids+") and b.versionId = (select MAX(c.versionId) from DocImageFile c where c.id=b.id ) order by a.id asc"; + }else{ + sqlimagefileid="select a.id,a.docsubject,b.imagefileid,b.imagefilename from DocDetail a,DocImageFile b where a.id=b.docid and a.id in ("+docids+") order by a.id asc"; + } + */ + String docsubject=""; + rsimagefileid.executeSql(sqlimagefileid); + int counts=rsimagefileid.getCounts(); + String urlType = Util.null2String(req.getParameter("urlType")); + if(counts<=0){ + if("1".equals(docSearchFlag)){ + if(urlType.equals("10")){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/docs/search/DocCommonContent.jsp?urlType=10&displayUsage="+displayUsage); + }else{ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/docs/search/DocCommonContent.jsp?urlType=6&fromUrlType=1&displayUsage="+displayUsage); + } + return; + }else{ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/login/BatchDownloadsEror.jsp"); + return; + } + } + int num=0; + while(rsimagefileid.next()){ + num++; + if(num==counts){ + docImagefileids += Util.null2String(rsimagefileid.getString("imagefileid")); + }else{ + docImagefileids += Util.null2String(rsimagefileid.getString("imagefileid"))+","; + } + docsubject=Util.null2String(rsimagefileid.getString("docsubject")); + } + List filenameList = new ArrayList(); + List filerealpathList = new ArrayList(); + List filerealpathTempList = new ArrayList(); + List docidList = new ArrayList(); + List imagefileidList = new ArrayList(); + //List filerealpathTempParentList = new ArrayList(); + File fileTemp=null; + String sqlfilerealpath=""; + ImageFileManager imageFileManager=new ImageFileManager(); + if(delImgIds!=null &&!"".equals(delImgIds)){ + //sqlfilerealpath="select imagefilename,filerealpath,iszip,isencrypt,imagefiletype , imagefileid, imagefile from ImageFile where imagefileid in ("+delImgIds+")"; + sqlfilerealpath = "select t2.docid,t1.isaesencrypt,t1.comefrom,t1.aescode,t1.imagefilename,t1.filerealpath,t1.iszip,t1.isencrypt,t1.imagefiletype , t1.imagefileid, t1.imagefile,t2.imagefilename as realname from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.imagefileid in ("+delImgIds+") " +(docids.equals("")?"":" and docid in("+docids+") "); + }else{ + //sqlfilerealpath="select imagefilename,filerealpath,iszip,isencrypt,imagefiletype , imagefileid, imagefile from ImageFile where imagefileid in ("+docImagefileids+")"; + sqlfilerealpath = "select t2.docid,t1.isaesencrypt,t1.comefrom,t1.aescode,t1.imagefilename,t1.filerealpath,t1.iszip,t1.isencrypt,t1.imagefiletype , t1.imagefileid, t1.imagefile,t2.imagefilename as realname from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.imagefileid in ("+docImagefileids+") " +(docids.equals("")?"":" and docid in("+docids+") "); + } + + rsimagefileid.executeSql(sqlfilerealpath); + String fromrequest = req.getParameter("fromrequest"); + + Map filenameMap = new HashMap(); + String imagefileid = ""; + String pdfimagefileid = ""; //office文档转换过来的PDFid + Map rightDoc = new HashMap(); + while(rsimagefileid.next()){ + try{ + imagefileid = Util.null2String(rsimagefileid.getString("imagefileid")); + String filename = Util.null2String(rsimagefileid.getString("realname")); + if(filename.equals("")){ + filename = Util.null2String(rsimagefileid.getString("imagefilename")); + } + String filerealpath = Util.null2String(rsimagefileid.getString("filerealpath")); + String iszip = Util.null2String(rsimagefileid.getString("iszip")); + String isencrypt = Util.null2String(rsimagefileid.getString("isencrypt")); + String isaesencrypt = Util.null2String(rsimagefileid.getString("isaesencrypt")); + String aescode = Util.null2String(rsimagefileid.getString("aescode")); + String _comefrom= Util.null2String(rsimagefileid.getString("comefrom")); + String _docid = Util.null2String(rsimagefileid.getString("docid")); + if(!_docid.isEmpty() && rightDoc.get(_docid) == null){ + boolean hasRight = getWhetherHasRight(imagefileid,req,res,Util.getIntValue(requestid),false,null); + if(!hasRight && !HrmUserVarify.checkUserRight("DocFileBatchDownLoad:ALL", loginuser)) + continue; + rightDoc.put(_docid,true); + } + + int docidans1 = -1; + /**流程下载附件,获取最新版本附件下载 start */ + if("1".equals(fromrequest)){ + RecordSet rs = new RecordSet(); + rs.executeSql("select doceditionid,id from DocDetail where id=(select max(docid) from DocImageFile where imagefileid=" + imagefileid + ")"); + if(rs.next()){ + int doceditionid = rs.getInt("doceditionid"); + int docid = rs.getInt("id"); + docidans1 = docid; + if(doceditionid > 0){ //有多版本文档,取最新版本文档 + rs.executeSql("select id from DocDetail where doceditionid=" + doceditionid + " order by docedition desc"); + if(rs.next()){ + docid = rs.getInt("id"); + } + } + + //在新版本文档下取最新附件 + rs.executeSql("select f.imagefileid,f.imagefilename,f.filerealpath,d.imagefilename realname from DocImageFile d,imagefile f where d.imagefileid=f.imagefileid and d.docid=" + docid + " order by d.versionId desc"); + if(rs.next()){ + imagefileid = rs.getString("imagefileid"); + filename = Util.null2String(rsimagefileid.getString("realname")); + if(filename.equals("")){ + filename = Util.null2String(rsimagefileid.getString("imagefilename")); + } + filerealpath = Util.null2String(rsimagefileid.getString("filerealpath")); + } + } + } + /**流程下载附件,获取最新附件 end */ + + if(!"DocLogAction_DocLogFile".equals(_comefrom) && FiledownloadUtil.isdownloadpdf(filename) && download.equals("1")){ + pdfimagefileid = FiledownloadUtil.getpdfidByOfficeid(imagefileid); + if(pdfimagefileid.isEmpty()){ + pdfimagefileid = imagefileid; + } + String pdffileinfosql = "select imagefilename,filerealpath from imagefile where imagefileid = ? "; + RecordSet pdffileinfors = new RecordSet(); + pdffileinfors.executeQuery(pdffileinfosql,pdfimagefileid); + if(pdffileinfors.next()){ + filename = Util.null2String(pdffileinfors.getString("imagefilename")); + filerealpath = Util.null2String(pdffileinfors.getString("filerealpath")); + } + }else{ + pdfimagefileid = imagefileid; + } + if(!"".equals(filename)){ + filename = filename.replace("&","&"); + } + filenameList.add(filename); + filerealpathList.add(filerealpath); + docidList.add(docidans1); + imagefileidList.add(imagefileid); + //是否需要记录日志 + if(addDownLoadLogByimageId(Util.getIntValue(imagefileid))){ + // 记录下载日志 begin + + String userType = loginuser.getLogintype(); + if ("1".equals(userType)) { // 如果是内部用户 名称就是 lastName + // 外部则入在 firstName里面 + downloadLog(loginuser.getUID(), loginuser.getLastname(), Util.getIntValue(imagefileid),filename, ipstring); + } else { + downloadLog(loginuser.getUID(), loginuser.getFirstname(), Util.getIntValue(imagefileid),filename, ipstring); + } + + // 记录下载日志 end + } + String extName = ""; + int byteread; + byte data[] = new byte[1024]; + if(filename.indexOf(".") > -1){ + int bx = filename.lastIndexOf("."); + if(bx>=0){ + extName = filename.substring(bx+1, filename.length()); + } + } + + InputStream imagefile = null; + if(!"".equals(pdfimagefileid) && !imagefileid.equals(pdfimagefileid)){ + imageFileManager.getImageFileInfoById(Util.getIntValue(pdfimagefileid)); + }else{ + imageFileManager.getImageFileInfoById(Util.getIntValue(imagefileid)); + } + //writeLogs("452 downloadFlag=" + downloadFlag); + imageFileManager.setDownloadFlag(downloadFlag); // 2298348 wgs + imagefile=imageFileManager.getInputStream(); + + if(download.equals("1") && (isOfficeToDocument(extName))&&isMsgObjToDocument()) { + //正文的处理 + ByteArrayOutputStream bout = null; + try { + bout = new ByteArrayOutputStream() ; + while((byteread = imagefile.read(data)) != -1) { + bout.write(data, 0, byteread) ; + bout.flush() ; + } + byte[] fileBody = bout.toByteArray(); + iMsgServer2000 MsgObj = new iMsgServer2000(); + MsgObj.MsgFileBody(fileBody); //将文件信息打包 + fileBody = MsgObj.ToDocument(MsgObj.MsgFileBody()); //通过iMsgServer200 将pgf文件流转化为普通Office文件流 + imagefile = new ByteArrayInputStream(fileBody); + bout.close(); + } + catch(Exception e) { + writeLogs(e); + if(bout!=null) bout.close(); + } + } + + FileOutputStream out = null; + try { + + SystemComInfo syscominfo = new SystemComInfo(); + String fileFoder= syscominfo.getFilesystem(); + String fileFoderCompare= syscominfo.getFilesystem(); + if("".equals(fileFoder)){ + fileFoder = GCONST.getRootPath(); + fileFoder = fileFoder + "filesystem" + File.separatorChar+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; + }else{ + if(fileFoder.endsWith(File.separator) ){ + fileFoder += "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; + }else{ + fileFoder += File.separator+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; + } + } + + String _fielname = UUID.randomUUID().toString(); + if(filename.indexOf(".") > -1){ + int bx = filename.lastIndexOf("."); + if(bx>=0){ + _fielname += filename.substring(bx, filename.length()); + } + } + + if("".equals(fileFoderCompare)){ + fileFoderCompare = GCONST.getRootPath(); + fileFoderCompare = fileFoderCompare + "filesystem" + File.separatorChar+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; + }else{ + if(fileFoderCompare.endsWith(File.separator)){ + fileFoderCompare += "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; + }else{ + fileFoderCompare += File.separator+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; + } + } + //附件文件重名加数字后缀区别:因为不加以区别的话,压缩到压缩包时只取一个文件(压缩包中不能有同名文件) 加唯一标识'_imagefileid' + for (String m : filenameMap.keySet()) { + String keyValue = filenameMap.get(m); + if(keyValue.equals(filename)){ + String tepName= filename.contains(".")? filename.substring(0, filename.indexOf(".")) : ""; + if(tepName!=null&&!"".equals(tepName)){ + String extNameTemp = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : ""; + filename = tepName + "_"+imagefileid+"."+extNameTemp; + + } + + } + } + filenameMap.put(_fielname, filename); + + //String fileFoder=GCONST.getRootPath()+ "downloadBatchTemp"+File.separatorChar+userid+File.separatorChar;//获取系统的运行目录 如:d:\ecology\ + //String fileFoderCompare=GCONST.getRootPath()+ "downloadBatchTemp"+File.separatorChar+userid+File.separatorChar+filename; + String newFileName=_fielname; + for(int j=0;j=0){ + if(!"".equals(pdfimagefileid) && !imagefileid.equals(pdfimagefileid)){ + newFileName=filename.substring(0, lastindex)+"_"+pdfimagefileid+filename.substring(lastindex); + }else{ + newFileName=filename.substring(0, lastindex)+"_"+imagefileid+filename.substring(lastindex); + } + }else{ + if(!"".equals(pdfimagefileid) && !imagefileid.equals(pdfimagefileid)){ + newFileName=filename+"_"+pdfimagefileid; + }else{ + newFileName=filename+"_"+imagefileid; + } + + } + } + } + fileTemp=this.fileCreate(fileFoder, newFileName);//在系统的根目录下创建了一个文件夹(downloadBatchTemp)及附件文件 + out = new FileOutputStream(fileTemp); + + imagefile = FileManager.download(req,imagefileid,filerealpath,aescode,iszip,isaesencrypt,imagefile); + //======================= + while ((byteread = imagefile.read(data)) != -1) { + out.write(data, 0, byteread); + out.flush(); + } + String filerealpathTemp=fileTemp.getPath(); + //String filerealpathTempParent=fileTemp.getParent(); + //filerealpathTempParentList.add(filerealpathTempParent); + //filerealpathTempList.add(filerealpathTemp); + filerealpathTempList.add(fileFoder+newFileName); + }catch(Exception e) { + writeLogs(e); + //do nothing + }finally { + if(imagefile!=null) imagefile.close(); + if(out!=null) out.flush(); + if(out!=null) out.close(); + } + }catch(Exception e){ + BaseBean basebean = new BaseBean(); + basebean.writeLog(e); + continue; + } + } + + if(filerealpathList.size() == 0){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?v1"); + return; + } + + + //存储下载的文件路径 把临时存放的附件 打压缩包 提供给用户下载 + File[] files=new File[filerealpathList.size()]; + for(int i=0;i secWmSetMap = WaterMarkUtil.getCategoryWmSet(imagefileid); + if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD)) && "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtil.WATERCONTENTISNULL))){ +// is = WaterMarkUtil.takefileWater(is,loginuser,filename,Util.getIntValue(fileid),extName,WaterMarkUtil.MOULDDOC); + is = FileWaterManager.takewater(req,fileid,filename,extName,is, WaterMarkUtil.MOULDDOC,-1); + } + } + + //ZipEntry ze=new ZipEntry(filenameMap.get(files[j].getAbsolutePath()));//设置文件编码格式 + ZipEntry ze = new ZipEntry(filenameMap.get(files[j].getName()));//设置文件编码格式 + zout.putNextEntry(ze); + int len; + //读取下载文件内容 + while((len=is.read(bt))>0){ + zout.write(bt, 0, len); + } + zout.closeEntry(); + is.close(); + }catch(Exception e){ + BaseBean basebean = new BaseBean(); + basebean.writeLog(e); + continue; + } + } + zout.close(); + this.toUpload(res, strs, tmptfilename);//调用下载方法 + //String fileTempParent=fileTemp.getParent(); + //this.deleteFile(fileTempParent);//下载完成后调用删除文件的方法删除downloadBatchTemp文件夹下的子文件夹 + /* + for(int i=0;i0){ + fieldids = fieldids.substring(0,fieldids.length()-1); + } + toWriteLog("onlydownloadfj----1----批量下载--fieldids:"+fieldids+"--labelid:"+labelid+"--userid:"+userid+"--download:"+download); + if(!"".equals(fieldids)){ + String[] fieldidsarray=fieldids.split(","); + String newfieldids=""; + for(String newfileid:fieldidsarray){ + if(Util.getIntValue(newfileid)>0){ + if("".equals(newfieldids)){ + newfieldids=newfileid; + }else{ + newfieldids+=","+newfileid; + } + } + } + fieldids=newfieldids; + String[] newfieldidsarray=fieldids.split(","); + RecordSet rsprop = new RecordSet(); + String secondAuthsql = " select distinct docid from docImageFile where imagefileid in ("+fieldids+")"; + rsprop.executeSql(secondAuthsql); + while(rsprop.next()){ + int docid=Util.getIntValue(rsprop.getString("docid")); + if(docid>0){ + String secondAuthFileDownUrl=getSecondAuthFileDownUrl(req,isMobileDown,docid); + if(!"".equals(secondAuthFileDownUrl)){ + res.sendRedirect(secondAuthFileDownUrl); + return; + } + } + } + int maxDownFileCount = Util.getIntValue(rsprop.getPropValue("BatchDownFileControl","maxDownFileCount"),10); + int maxDownFileTotalSize = Util.getIntValue(rsprop.getPropValue("BatchDownFileControl","maxDownFileTotalSize"),200); + if(newfieldidsarray.length>maxDownFileCount){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/wui/common/page/sysRemindDocpreview.jsp?labelid="+SystemEnv.getHtmlLabelName(534454,loginuser.getLanguage())+maxDownFileCount); + return; + }else{ + String dbType = rsprop.getDBType(); + String sql = " select sum(fileSize) totalfilesize from ImageFile where imagefileid in ("+fieldids+")"; + if("sqlserver".equals(dbType)){ + sql = " select SUM(cast(filesize as numeric(30,0))) totalfilesize from ImageFile where imagefileid in ("+fieldids+")"; + } + rsprop.executeSql(sql); + if(rsprop.next()){ + double totalfilesize = Util.getDoubleValue(rsprop.getString("totalfilesize"),0); + if(totalfilesize>maxDownFileTotalSize*1024*1024){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/wui/common/page/sysRemindDocpreview.jsp?labelid="+SystemEnv.getHtmlLabelName(534453,loginuser.getLanguage())+maxDownFileTotalSize); + return; + } + } + } + }else{ + return; + } + List filenameList = new ArrayList(); + List filerealpathList = new ArrayList(); + List filerealpathTempList = new ArrayList(); + List fileids = new ArrayList(); + String sqlfilerealpath=""; + ImageFileManager imageFileManager=new ImageFileManager(); + sqlfilerealpath = "select * from imagefile where imagefileid in("+fieldids+") "; + RecordSet rsimagefileid =new RecordSet(); + rsimagefileid.executeSql(sqlfilerealpath); + String imagefileid = ""; + String pdfimagefileid = ""; + Map filenameMap = new HashMap(); + while(rsimagefileid.next()){ + String downloadpdfimagefileid = ""; + try{ + imagefileid = Util.null2String(rsimagefileid.getString("imagefileid")); + String filename = Util.null2String(rsimagefileid.getString("realname")); + if(filename.equals("")){ + filename = Util.null2String(rsimagefileid.getString("imagefilename")); + } + String filerealpath = Util.null2String(rsimagefileid.getString("filerealpath")); + String iszip = Util.null2String(rsimagefileid.getString("iszip")); + String isencrypt = Util.null2String(rsimagefileid.getString("isencrypt")); + String isaesencrypt = Util.null2String(rsimagefileid.getString("isaesencrypt")); + String aescode = Util.null2String(rsimagefileid.getString("aescode")); + String _comefrom = Util.null2String(rsimagefileid.getString("comefrom")); + boolean hasRight = getWhetherHasRight(imagefileid,req,res,Util.getIntValue(req.getParameter("requestid")),false,null); + toWriteLog("onlydownloadfj----2----批量下载--imagefileid:"+imagefileid+"--filename:" + +filename+"--userid:"+userid+"--filerealpath:"+filerealpath+"--hasRight:"+hasRight); + if(!hasRight) + continue; + + if(!"DocLogAction_DocLogFile".equals(_comefrom) && FiledownloadUtil.isdownloadpdf(filename) && download.equals("1")){ + pdfimagefileid = FiledownloadUtil.getpdfidByOfficeid(imagefileid); + if(pdfimagefileid.isEmpty()){ + pdfimagefileid = imagefileid; + } + String pdffileinfosql = "select imagefilename,filerealpath from imagefile where imagefileid = ? "; + RecordSet pdffileinfors = new RecordSet(); + pdffileinfors.executeQuery(pdffileinfosql,pdfimagefileid); + if(pdffileinfors.next()){ + filename = Util.null2String(pdffileinfors.getString("imagefilename")); + filerealpath = Util.null2String(pdffileinfors.getString("filerealpath")); + } + }else{ + pdfimagefileid = imagefileid; + } + String extName = ""; + if(filename.indexOf(".") > -1) { + int bx = filename.lastIndexOf("."); + if (bx >= 0) { + extName = filename.substring(bx + 1, filename.length()); + } + } + if(ImageConvertUtil.canConvertPdfForDownload(extName,imagefileid)&& !frompdfview.equals("1") && download.equals("1")) { + RecordSet rsrecord = new RecordSet(); + PdfConvertUtil pdfConvertUtil = new PdfConvertUtil(); + int pdfid = pdfConvertUtil.convertPdf(Util.getIntValue(imagefileid)); + if (pdfid > 0) { + downloadpdfimagefileid = String.valueOf(pdfid); + String pdffileinfosql = "select imagefilename,filerealpath from imagefile where imagefileid = ? "; + RecordSet pdffileinfors = new RecordSet(); + pdffileinfors.executeQuery(pdffileinfosql, downloadpdfimagefileid); + if (pdffileinfors.next()) { + filename = filename.substring(0, filename.lastIndexOf(".")) + ".pdf"; + filerealpath = Util.null2String(pdffileinfors.getString("filerealpath")); + } + } + } + if(downloadpdfimagefileid.isEmpty()){ + downloadpdfimagefileid = imagefileid+""; + } + if(!"".equals(filename)){ + filename = filename.replace("&","&"); + } + + filenameList.add(filename); + filerealpathList.add(filerealpath); + fileids.add(Util.getIntValue(downloadpdfimagefileid)); + int byteread; + byte data[] = new byte[1024]; + if(filename.indexOf(".") > -1){ + int bx = filename.lastIndexOf("."); + if(bx>=0){ + extName = filename.substring(bx+1, filename.length()); + } + } + + InputStream imagefile = null; + if(!"".equals(pdfimagefileid) && !imagefileid.equals(pdfimagefileid)){ + imageFileManager.getImageFileInfoById(Util.getIntValue(pdfimagefileid)); + }else{ + imageFileManager.getImageFileInfoById(Util.getIntValue(imagefileid)); + } + //writeLogs("863 downloadFlag=" + downloadFlag); + imageFileManager.setDownloadFlag(downloadFlag); // 2298348 wgs + imagefile=imageFileManager.getInputStream(); + + if(download.equals("1") && (isOfficeToDocument(extName))&&isMsgObjToDocument()) { + //正文的处理 + ByteArrayOutputStream bout = null; + try { + bout = new ByteArrayOutputStream() ; + while((byteread = imagefile.read(data)) != -1) { + bout.write(data, 0, byteread) ; + bout.flush() ; + } + byte[] fileBody = bout.toByteArray(); + iMsgServer2000 MsgObj = new iMsgServer2000(); + MsgObj.MsgFileBody(fileBody); //将文件信息打包 + fileBody = MsgObj.ToDocument(MsgObj.MsgFileBody()); //通过iMsgServer200 将pgf文件流转化为普通Office文件流 + imagefile = new ByteArrayInputStream(fileBody); + bout.close(); + } + catch(Exception e) { + writeLogs(e); + if(bout!=null) bout.close(); + } + } + + FileOutputStream out = null; + try { + + SystemComInfo syscominfo = new SystemComInfo(); + String fileFoder= syscominfo.getFilesystem(); + String fileFoderCompare= syscominfo.getFilesystem(); + if("".equals(fileFoder)){ + fileFoder = GCONST.getRootPath(); + fileFoder = fileFoder + "filesystem" + File.separatorChar+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; + }else{ + if(fileFoder.endsWith(File.separator)){ + fileFoder += "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; + }else{ + fileFoder += File.separator+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar; + } + } + + + String _fielname = UUID.randomUUID().toString(); + if(filename.indexOf(".") > -1){ + int bx = filename.lastIndexOf("."); + if(bx>=0){ + _fielname += filename.substring(bx, filename.length()); + } + } + + + + if("".equals(fileFoderCompare)){ + fileFoderCompare = GCONST.getRootPath(); + fileFoderCompare = fileFoderCompare + "filesystem" + File.separatorChar+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; + }else{ + if(fileFoderCompare.endsWith(File.separator)){ + fileFoderCompare += "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; + }else{ + fileFoderCompare += File.separator+ "downloadBatchTemp"+File.separatorChar+userid+currentDateTime+File.separatorChar+_fielname; + } + } + toWriteLog("onlydownloadfj----3----批量下载--imagefileid:"+imagefileid+"--filename:" + +filename+"--userid:"+userid+"--fileFoder:"+fileFoder+"--fileFoderCompare:"+fileFoderCompare); + //String fileFoder=GCONST.getRootPath()+ "downloadBatchTemp"+File.separatorChar+userid+File.separatorChar;//获取系统的运行目录 如:d:\ecology\ + //附件文件重名加数字后缀区别:因为不加以区别的话,压缩到压缩包时只取一个文件(压缩包中不能有同名文件) 加唯一标识'_imagefileid' + //String fileFoderCompare=GCONST.getRootPath()+ "downloadBatchTemp"+File.separatorChar+userid+File.separatorChar+filename; + + //附件文件重名加数字后缀区别:因为不加以区别的话,压缩到压缩包时只取一个文件(压缩包中不能有同名文件) 加唯一标识'_imagefileid' + for (String m : filenameMap.keySet()) { + String keyValue = filenameMap.get(m); + if(keyValue.equals(filename)){ + String tepName= filename.contains(".")? filename.substring(0, filename.indexOf(".")) : ""; + if(tepName!=null&&!"".equals(tepName)){ + String extNameTemp = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : ""; + filename = tepName + "_"+imagefileid+"."+extNameTemp; + + } + + } + } + filenameMap.put(_fielname, filename); + String newFileName=_fielname; + toWriteLog("onlydownloadfj----4----批量下载--imagefileid:"+imagefileid+"--filename:" + +filename+"--userid:"+userid+"--fileFoder:"+fileFoder+"--fileFoderCompare:"+fileFoderCompare + +"--newFileName:"+newFileName+"--filerealpathTempList:"+filerealpathTempList+"--out:"+filerealpathTempList + +"--imagefile:"+imagefile); + fileTemp=this.fileCreate(fileFoder, newFileName);//在系统的根目录下创建了一个文件夹(downloadBatchTemp)及附件文件 + out = new FileOutputStream(fileTemp); + + imagefile = FileManager.download(req,imagefileid,filerealpath,aescode,iszip,isaesencrypt,imagefile); + Map secWmSetMap = WaterMarkUtilNew.getCategoryWmSet(imagefileid); + //writeLogs("957 imagefileid=" + imagefileid); + shouldAddFileDownLoadWm(secWmSetMap, imagefileid); // 2447956 wgs + + if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtilNew.SECCATEGORYDOWNLOAD))&& "1".equals(secWmSetMap.get(WaterMarkUtilNew.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtilNew.WATERCONTENTISNULL))){ + imagefile = FileWaterManager.takewater(req,downloadpdfimagefileid,filename,extName,imagefile, WaterMarkUtil.MOULDDOC,Util.getIntValue(imagefileid)); + } + while ((byteread = imagefile.read(data)) != -1) { + out.write(data, 0, byteread); + out.flush(); + } + String filerealpathTemp=fileTemp.getPath(); + //String filerealpathTempParent=fileTemp.getParent(); + //filerealpathTempParentList.add(filerealpathTempParent); + //filerealpathTempList.add(filerealpathTemp); + filerealpathTempList.add(fileFoder+newFileName); + }catch(Exception e) { + //do nothing + e.printStackTrace(); + }finally { + if(imagefile!=null) imagefile.close(); + if(out!=null) out.flush(); + if(out!=null) out.close(); + } + }catch(Exception e){ + BaseBean basebean = new BaseBean(); + basebean.writeLog(e); + continue; + } + } + + if(filerealpathList.size() == 0){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?v2"); + return; + } + toWriteLog("onlydownloadfj----5----批量下载--filerealpathList:"+filerealpathList+"--filerealpathTempList:" + +filerealpathTempList+"--userid:"+userid); + //存储下载的文件路径 把临时存放的附件 打压缩包 提供给用户下载 + File[] files=new File[filerealpathList.size()]; + for(int i=0;i secWmSetMap = WaterMarkUtil.getCategoryWmSet(imagefileid); + //writeLogs("1053 imagefileid=" + imagefileid); + shouldAddFileDownLoadWm(secWmSetMap, imagefileid); // 2447956 wgs + if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD))&& "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtil.WATERCONTENTISNULL))){ +// is = WaterMarkUtil.takefileWater(is,loginuser,filename,fileids.get(j),extName,WaterMarkUtil.MOULDDOC); + is = FileWaterManager.takewater(req,fileids.get(j)+"",filename,extName,is, WaterMarkUtil.MOULDDOC,-1); + } + } + ZipEntry ze=new ZipEntry(filenameMap.get(files[j].getName()));//设置文件编码格式 + zout.putNextEntry(ze); + int len; + //读取下载文件内容 + while((len=is.read(bt))>0){ + zout.write(bt, 0, len); + } + zout.closeEntry(); + is.close(); + }catch(Exception e){ + BaseBean basebean = new BaseBean(); + basebean.writeLog(e); + continue; + } + } + zout.close(); + this.toUpload(res, strs,tmptfilename);//调用下载方法 + //String fileTempParent=fileTemp.getParent(); + //this.deleteFile(fileTempParent);//下载完成后调用删除文件的方法删除downloadBatchTemp文件夹下的子文件夹 + /* + for(int i=0;i jsonParams = new HashMap(); + boolean fromMobile = false; + int userid = 0; + jsonParams = Json2MapUtil.requestJson2Map(req); + if(fileid <=0 ){ + fileid = Util.getIntValue(Util.null2String(jsonParams.get("fileid"))); + fromMobile = true; + userid = Util.getIntValue(Util.null2String(jsonParams.get("userid"))); + requestid = Util.getIntValue(Util.null2String(jsonParams.get("requestid"))); + } + + String ddcode = req.getParameter("ddcode"); + int codeuserid = 0; + User userddcode = (User)req.getSession(true).getAttribute("weaver_user@bean"); + if(ddcode != null && !ddcode.isEmpty() && userddcode==null){ + try{ + Map ddcodeMap = SystemDocUtil.deDdcode(userddcode,ddcode); + String isovertime = Util.null2String(ddcodeMap.get(SystemDocUtil.ISOVERTIME)); + if("1".equals(isovertime)){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?ddcodeTimeout=1"); + return; + }else{ + userid = Util.getIntValue((String) ddcodeMap.get(SystemDocUtil.USERID)); + String fileidcode = Util.null2String(ddcodeMap.get(SystemDocUtil.FILEID)); + fileid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileidstr(fileidcode)); + fromMobile = true; + //如果有次账号,userid给次账号的 + String f_weaver_belongto_userid=Util.null2s(req.getParameter("f_weaver_belongto_userid"),""); + if(!"".equals(f_weaver_belongto_userid)){ + userid = Util.getIntValue(f_weaver_belongto_userid); + } + jsonParams = Json2MapUtil.requestJson2Map(req); + jsonParams.put("userid",userid); + codeuserid = Util.getIntValue(Util.null2String(jsonParams.get("userid"))); + } + + }catch(Exception e){ + writeLogs(e); + } + } + + + if(fileid <= 0){//转化为int型,防止SQL注入 + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?v3"); + return; + } + RecordSet rsprop = new RecordSet(); + String secondAuthsql = " select distinct docid from docImageFile where imagefileid =?"; + rsprop.executeQuery(secondAuthsql,fileid); + while(rsprop.next()){ + int newdocid=Util.getIntValue(rsprop.getString("docid")); + if(newdocid>0){ + String secondAuthFileDownUrl=getSecondAuthFileDownUrl(req,isMobileDown,newdocid); + if(!"".equals(secondAuthFileDownUrl)){ + res.sendRedirect(secondAuthFileDownUrl); + return; + } + } + } + /**流程下载附件,获取最新版本附件下载 start */ + String fromrequest = req.getParameter("fromrequest"); + if("1".equals(fromrequest)){ + RecordSet rs = new RecordSet(); + rs.executeSql("select doceditionid,id from DocDetail where id=(select max(docid) from DocImageFile where imagefileid=" + fileid + ")"); + if(rs.next()){ + int doceditionid = rs.getInt("doceditionid"); + int docid = rs.getInt("id"); + + if(doceditionid > 0){ //有多版本文档,取最新版本文档 + rs.executeSql("select id from DocDetail where doceditionid=" + doceditionid + " order by docedition desc"); + if(rs.next()){ + docid = rs.getInt("id"); + } + } + + rs.executeQuery("select id from DocImageFile where imagefileid=? and (isextfile is null or isextfile <> '1' ) and docfiletype <> '1'",fileid); + + boolean isOfficeFile = false; + if(rs.next()){ + isOfficeFile = true; + } + + //在新版本文档下取最新附件 + String sql = "select id,imagefileid from DocImageFile where docid=? "; + + if(isOfficeFile){ + sql += " and (isextfile is null or isextfile <> '1' ) and docfiletype <> '1'"; + }else{ + sql += " and isextfile='1'"; + } + + sql += "order by versionId desc"; + rs.executeQuery(sql,docid); + int firstId = 0; + int i = 0; + int _id = 0; + while(rs.next()){ + if(i == 0){ + firstId = rs.getInt("imagefileid"); + _id = rs.getInt("id"); + if(isOfficeFile) + break; + }else{ + if(_id != rs.getInt("id")){ //一个文档下有多个附件,则不再下载最新,按照传的id下载 + firstId = fileid; + break; + } + } + i++; + } + fileid = firstId; + } + } + /**流程下载附件,获取最新附件 end */ + + //String strSql="select docpublishtype from docdetail where id in (select docid from docimagefile where imagefileid="+fileid+") and ishistory <> 1"; + RecordSet statement = new RecordSet(); //by ben 开启连接后知道文件下载才关闭,数据库连接时间太长 + //RecordSet rs =new RecordSet(); + User user = (User)req.getSession(true).getAttribute("weaver_user@bean"); + try { + //解决问题:一个附件或图片被一篇内部文档和外部新闻同时引用时,外部新闻可能查看不到附件或图片。 update by fanggsh fot TD5478 begin + //调整为如下: + //默认需要用户登录信息,不需要登录信息的情形如下: + //1、非登录用户查看外部新闻 + //boolean needUser= false; + boolean needUser= true; + int docId=0; + String docIdsForOuterNews=""; + //String strSql="select id from DocDetail where exists (select 1 from docimagefile where imagefileid="+fileid+" and docId=DocDetail.id) and ishistory <> 1 and (docPublishType='2' or docPublishType='3')"; + String strSql = "SELECT t1.id FROM DocDetail t1 INNER JOIN docimagefile t2 ON t1.id = t2.docId " + + "WHERE t2.imagefileid = ? AND t1.ishistory <> 1 AND ( t1.docPublishType = '2' OR t1.docPublishType = '3')"; + RecordSet rs = new RecordSet(); + rs.executeQuery(strSql,fileid); + while(rs.next()){ + docId=rs.getInt("id"); + if(docId>0){ + docIdsForOuterNews+=","+docId; + } + } + + if(!docIdsForOuterNews.equals("")){ + docIdsForOuterNews=docIdsForOuterNews.substring(1); + } + + if(!docIdsForOuterNews.equals("")){ + String newsClause=""; + String sqlDocExist=" select 1 from DocDetail where id in("+docIdsForOuterNews+") "; + String sqlNewsClauseOr=""; + boolean hasOuterNews=false; + + rs.executeSql("select newsClause from DocFrontPage where publishType='0'"); + while(rs.next()){ + hasOuterNews=true; + newsClause=Util.null2String(rs.getString("newsClause")); + if (newsClause.equals("0")) + { + //newsClause=" 1=1 "; + needUser=false; + break; + } + if(!newsClause.trim().equals("")){ + sqlNewsClauseOr+=" ^_^ ("+newsClause+")"; + } + } + ArrayList newsArr = new ArrayList(); + if(!sqlNewsClauseOr.equals("")&&needUser){ + //sqlNewsClauseOr=sqlNewsClauseOr.substring(sqlNewsClauseOr.indexOf("(")); + //sqlDocExist+=" and ("+sqlNewsClauseOr+") "; + String[] newsPage = Util.TokenizerString2(sqlNewsClauseOr,"^_^"); + int i = 0; + String newsWhere = ""; + for(;i1061-->fileid"+fileid+"--->user"+user+"=userid--"); + if(user==null){ + AuthService as = new AuthService(); + + String sessionkey = ""; + String querystring = req.getQueryString(); + String[] parameters = StringUtils.split(querystring, '&'); + if(parameters != null) { + for(int i=0; i0){ + sql = "select t1.imagefilename,t1.filerealpath,t1.signinfo,t1.hashinfo,t1.iszip,t1.isencrypt,t1.imagefiletype , t1.imagefileid, t1.imagefile,t1.isaesencrypt,t1.aescode,t2.imagefilename as realname,t1.TokenKey,t1.StorageStatus,t1.comefrom,t1.filesize from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.imagefileid = "+decryptPdfImageFileId; + statement.execute(sql); + if(!statement.next()){ + return ; + } + } + } + filerealpath = Util.null2String(statement.getString("filerealpath")); + iszip = Util.null2String(statement.getString("iszip")); + signInfo = Util.null2String(statement.getString("signinfo")); + hashInfo = Util.null2String(statement.getString("hashinfo")); + isencrypt = Util.null2String(statement.getString("isencrypt")); + isaesencrypt = Util.null2o(statement.getString("isaesencrypt")); + aescode = Util.null2String(statement.getString("aescode")); + tokenKey = Util.null2String(statement.getString("TokenKey")); + storageStatus = Util.null2String(statement.getString("StorageStatus")); + comefrom = Util.null2String(statement.getString("comefrom")); + filesize = Util.null2String(statement.getString("filesize")); + + + if(!"DocLogAction_DocLogFile".equals(comefrom) && FiledownloadUtil.isdownloadpdf(filename) && download.equals("1") ){ + pdfimagefileid = FiledownloadUtil.getpdfidByOfficeid(fileid+""); + if(pdfimagefileid.isEmpty()){ + pdfimagefileid = fileid+""; + } + String pdffileinfosql = "select imagefilename,filerealpath,aescode,iszip,isencrypt,isaesencrypt,TokenKey,StorageStatus,filesize,comefrom,hashinfo,signinfo from imagefile where imagefileid = ? "; + RecordSet pdffileinfors = new RecordSet(); + pdffileinfors.executeQuery(pdffileinfosql,pdfimagefileid); + if(pdffileinfors.next()){ + filename = Util.null2String(pdffileinfors.getString("imagefilename")); + filerealpath = Util.null2String(pdffileinfors.getString("filerealpath")); + iszip = Util.null2String(pdffileinfors.getString("iszip")); + signInfo = Util.null2String(pdffileinfors.getString("signinfo")); + hashInfo = Util.null2String(pdffileinfors.getString("hashinfo")); + isencrypt = Util.null2String(pdffileinfors.getString("isencrypt")); + isaesencrypt = Util.null2String(pdffileinfors.getString("isaesencrypt")); + aescode = Util.null2String(pdffileinfors.getString("aescode")); + tokenKey = Util.null2String(pdffileinfors.getString("TokenKey")); + storageStatus = Util.null2String(pdffileinfors.getString("StorageStatus")); + comefrom = Util.null2String(pdffileinfors.getString("comefrom")); + filesize = Util.null2String(pdffileinfors.getString("filesize")); + } + }else { + pdfimagefileid = fileid+""; + } + + if(filename.indexOf(".") > -1){ + int bx = filename.lastIndexOf("."); + if(bx>=0){ + extName = filename.substring(bx+1, filename.length()); + } + } + if(ImageConvertUtil.canConvertPdfForDownload(extName,fileid+"")&& !frompdfview.equals("1") && download.equals("1")) { + RecordSet rsrecord = new RecordSet(); + PdfConvertUtil pdfConvertUtil = new PdfConvertUtil(); + int pdfid = pdfConvertUtil.convertPdf(fileid); + if (pdfid > 0) { + downloadpdfimagefileid = String.valueOf(pdfid); + String pdffileinfosql = "select imagefilename,filerealpath from imagefile where imagefileid = ? "; + RecordSet pdffileinfors = new RecordSet(); + pdffileinfors.executeQuery(pdffileinfosql, downloadpdfimagefileid); + if (pdffileinfors.next()) { + filename = filename.substring(0, filename.lastIndexOf(".")) + ".pdf"; + filerealpath = Util.null2String(pdffileinfors.getString("filerealpath")); + } + } + } + if(downloadpdfimagefileid.isEmpty()){ + downloadpdfimagefileid = fileid+""; + } + + if(filename.indexOf(".") > -1){ + int bx = filename.lastIndexOf("."); + if(bx>=0){ + extName = filename.substring(bx+1, filename.length()); + } + } + boolean isInline=false; + String cacheContorl=""; + boolean isEnableForDsp=false; + boolean canUseAliOSS = false; + if(!tokenKey.equals("")&&storageStatus.equals("1")&&AliOSSObjectManager.isEnableForDsp(req)){ + isEnableForDsp=true; + } + if(!tokenKey.equals("")&&storageStatus.equals("1")&&AliOSSObjectManager.canUseAliOSS()){ + canUseAliOSS=true; + } + boolean isPic=false; + String lowerfilename = filename!=null ? filename.toLowerCase() : ""; + boolean ishtmlfile = false; + boolean needGbkCode = false; + if(lowerfilename.endsWith(".html")||lowerfilename.endsWith(".htm")){ + RecordSet rs_tmp = new RecordSet(); + + String _sql = "select i.imagefilename from DocPreviewHtml a,imagefile i " + + "where a.imagefileid=i.imagefileid and a.htmlfileid = ?"; + + if("email".equals(req.getParameter("model"))){ + _sql = "select filename as imagefilename from mailresourcefile where htmlcode=?"; + } + + rs_tmp.executeQuery(_sql,fileid); + if(rs_tmp.next()){ + ishtmlfile = true; + String _imagefilename = Util.null2String(rs_tmp.getString("imagefilename")); + needGbkCode = _imagefilename.toLowerCase().endsWith(".xls") + || _imagefilename.toLowerCase().endsWith(".xlsx") + || _imagefilename.toLowerCase().endsWith(".doc"); + } + String worflowhtmlSql = " select comefrom from imagefile where imagefileid = ?"; + rs_tmp.executeQuery(worflowhtmlSql,fileid); + if(rs_tmp.next()){ + String htmlcomefrom = Util.null2String(rs_tmp.getString("comefrom")); + if("WorkflowToDoc".equals(htmlcomefrom)){ + ishtmlfile = true; + } + } + } + filename = StringEscapeUtils.unescapeHtml(filename); + String extendName = lowerfilename.lastIndexOf(".") != -1 ? lowerfilename.substring(lowerfilename.lastIndexOf(".") + 1) : lowerfilename; + boolean inlineView = inlineViewFile(extendName); + if (download.equals("") && (inlineView + ||ishtmlfile)){ + if(filename.toLowerCase().endsWith(".doc")) contenttype = "application/msword"; + else if(filename.toLowerCase().endsWith(".xls")) contenttype = "application/vnd.ms-excel"; + else if(filename.toLowerCase().endsWith(".gif")) { + contenttype = "image/gif"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + isPic=true; + }else if(filename.toLowerCase().endsWith(".png")) { + contenttype = "image/png"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + isPic=true; + }else if(filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg")) { + contenttype = "image/jpg"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + isPic=true; + }else if(filename.toLowerCase().endsWith(".bmp")) { + contenttype = "image/bmp"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + isPic=true; + }else if(filename.toLowerCase().endsWith(".svg")){ + contenttype = "image/svg+xml"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + isPic=true; + } + else if(filename.toLowerCase().endsWith(".txt")) contenttype = "text/plain"; + else if(filename.toLowerCase().endsWith(".pdf")) contenttype = "application/pdf"; + else if(filename.toLowerCase().endsWith(".html")||filename.toLowerCase().endsWith(".htm")) contenttype = "text/html"; + else { + contenttype = statement.getString("imagefiletype"); + } + try { + + String _ec_browser = Util.null2String(req.getParameter("_ec_browser")); + String _ec_os = Util.null2String(req.getParameter("_ec_os")); + + if("Wechat".equals(_ec_browser) && "iOS".equals(_ec_os)){ //微信 + res.setHeader("content-disposition", "inline; filename=\"" + new String(filename.getBytes("UTF-8"), "ISO8859-1")+"\""); + }else if(_ec_ismobile || from_doc_mobile || agent.toLowerCase().contains("emobile") || agent.toLowerCase().contains("android") || agent.toLowerCase().contains("iphone")){ + // res.setHeader("content-disposition", "inline; filename=\"" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\""); + filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); + res.setHeader("Content-disposition", "inline;filename=\"" + filename + "\""); + }else { + if ((agent.contains("Firefox") || agent.contains(" Chrome") || agent.contains("Safari")) && !agent.contains("Edge")) { + res.setHeader("content-disposition", "inline; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); + } else { + res.setHeader("content-disposition", "inline; filename=\"" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); + } + } + } catch (Exception ecode) { + writeLogs(ecode); + } + isInline=true; + }else { + contenttype = "application/octet-stream"; + if (filename.toLowerCase().endsWith(".mp4") || filename.toLowerCase().endsWith(".mov")) { + contenttype = "video/mp4"; + } else if (filename.toLowerCase().endsWith(".ogg")) { + contenttype = "video/ogg"; + } else if (filename.toLowerCase().endsWith(".asf")) { + contenttype = "video/x-ms-asf"; + } else if (filename.toLowerCase().endsWith(".mp3")) { + contenttype = "audio/mp3"; + } else if (filename.toLowerCase().endsWith(".wav")) { + contenttype = "audio/wav"; + } else if (filename.toLowerCase().endsWith(".wma")) { + contenttype = "audio/x-ms-wma"; + } else if (filename.toLowerCase().endsWith(".au")) { + contenttype = "audio/basic"; + } + + if(filename.toLowerCase().endsWith(".pdf")) contenttype = "application/pdf"; + try { +// res.setHeader("Content-length", "" + filesize); +// res.setHeader("Content-Range", "bytes"); +// res.addHeader("Cache-Control", "no-cache"); + + //System.out.println(new String(new String(filename.getBytes(clientEcoding), "ISO8859_1").getBytes("ISO8859_1"),"utf-8")); + //System.out.println(new String(filename.getBytes(clientEcoding))); + String _ec_browser = Util.null2String(req.getParameter("_ec_browser")); + String _ec_os = Util.null2String(req.getParameter("_ec_os")); + if("Wechat".equals(_ec_browser) && ("iOS".equals(_ec_os) || "Mac OS".equals(_ec_os))){ //微信 + res.setHeader("content-disposition", "inline; filename=\"" + new String(filename.getBytes("UTF-8"), "ISO8859-1")+"\""); + }else if(agent.contains("Wechat") && (agent.contains("iOS") || agent.contains("Mac OS"))){ + filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); + res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); + }else if(agent.contains("Mac OS") && !AliOSSObjectManager.isEnable()){ + filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); + res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); + } else if(_ec_ismobile || from_doc_mobile||agent.toLowerCase().contains("android")){ + if(FiledownloadUtil.isIos(req)){ + filename = FiledownloadUtil.counthanzi(filename,extName); + } + + res.setHeader("content-disposition", "attachment; filename=\"" + + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("%", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\""); + }else { + if ( (agent.contains(" Chrome")) && !agent.contains("Edge")) { +// res.setHeader("content-disposition", "attachment;"); + res.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(") + .replaceAll("%29", ")").replaceAll("%7B","{").replaceAll("%7D","}").replaceAll("%5B","[").replaceAll("%5D","]").replaceAll("%40","@").replaceAll("%23","#").replaceAll("%25","%").replaceAll("%26","&") + .replaceAll("%2B","+").replaceAll("%27","'").replaceAll("%20"," ")); + +// res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); +// res.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(filename, "UTF-8")); +// res.setContentType("application/vnd.ms-excel;charset=utf-8"); +// res.setCharacterEncoding("UTF-8"); + }else if(agent.contains("Safari")){ + filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); + res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); + }else if(agent.contains("Firefox")){ + // filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); + // res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); + +// filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); +// res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); + // filename = "=?UTF-8?B?" + (new String(Base64.encodeBase64(filename.getBytes("UTF-8")))) + "?="; + // res.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename)); + + res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); + } else{ + res.setHeader("content-disposition", "attachment; filename=\"" + + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); + } + } + } catch (Exception ecode) { + writeLogs(ecode); + } + } + String iscompress = Util.null2String(req.getParameter("iscompress")); + String thumbnail = Util.null2String(req.getParameter("thumbnail")); + String targetFilePath=""; + if(isEnableForDsp||canUseAliOSS){ + + //解决安卓app预览黑屏的问题 + boolean isAndroid = agent.contains("Android") && agent.startsWith("E-Mobile7"); + if(isAndroid && download.equals("1")){ + if(filename.toLowerCase().endsWith(".gif")) { + contenttype = "image/gif"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + isPic=true; + }else if(filename.toLowerCase().endsWith(".png")) { + contenttype = "image/png"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + isPic=true; + }else if(filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg")) { + contenttype = "image/jpg"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + isPic=true; + }else if(filename.toLowerCase().endsWith(".bmp")) { + contenttype = "image/bmp"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + isPic=true; + }else if(filename.toLowerCase().endsWith(".svg")){ + contenttype = "image/svg+xml"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + isPic=true; + } + } + + boolean isAliOSSToServer=AliOSSObjectManager.isAliOSSToServer(comefrom); + boolean isOpenWaterMark = WaterMarkUtil.isOpenWmSetting(); + boolean isSafari=agent.contains("Mac OS"); + int imgDownByObs=Util.getIntValue(baseBean.getPropValue("FileDownload","imgDownByObs"),1); + baseBean.writeLog("FileDownload---------1645---fileid="+fileid+";isPic="+isPic+";filename="+filename+";isAliOSSToServer="+isAliOSSToServer+";imgDownByObs="+imgDownByObs+";frompdfview="+frompdfview+";isOpenWaterMark="+isOpenWaterMark+";ishtmlfile="+ishtmlfile+";canUseAliOSS="+canUseAliOSS+";isEnableForDsp="+isEnableForDsp+";isSafari="+isSafari); + //canUseAliOSS && !isEnableForDs :判断是否开启了阿里云并且请求端是内网地址的情况下走此逻辑 + if(isAliOSSToServer|| (isPic && imgDownByObs !=1) || !frompdfview.isEmpty() || isOpenWaterMark || ishtmlfile || (canUseAliOSS && !isEnableForDsp)||isSafari){ + baseBean.writeLog("FileDownload---------1648---fileid="+fileid+";isPic="+isPic+";11111"); + InputStream imagefile = null; + ServletOutputStream out = null; + DocAddWaterForSecond docAddWaterForSecond = new DocAddWaterForSecond(); + try { + imagefile=weaver.alioss.AliOSSObjectUtil.downloadFile(tokenKey); + if("1".equals(iscompress)){ + ImageCompressUtil imageCompressUtil=new ImageCompressUtil(); + targetFilePath = imageCompressUtil.getTargetFilePath(); + imagefile=imageCompressUtil.imageCompress(imagefile,targetFilePath); + } + out = res.getOutputStream(); + + if(ishtmlfile && needGbkCode){ + boolean loadGBK = !"0".equals(rs.getPropValue("docpreview", "loadGBK")); + if(loadGBK){ + res.setContentType(contenttype+";charset=GBK"); + } + }else{ + res.setContentType(contenttype); + } +// extName = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : ""; + if(!frompdfview.equals("1") && download.equals("1")){ + Map secWmSetMap = WaterMarkUtilNew.getCategoryWmSet(fileid+""); + //writeLogs("1786 fileid=" + fileid); + shouldAddFileDownLoadWm(secWmSetMap, fileid+""); // 2447956 wgs + if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtilNew.SECCATEGORYDOWNLOAD))&& "1".equals(secWmSetMap.get(WaterMarkUtilNew.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtilNew.WATERCONTENTISNULL))){ +// imagefile = WaterMarkUtil.takefileWater(imagefile,user,filename,fileid,extName,WaterMarkUtil.MOULDDOC); + imagefile = FileWaterManager.takewater(req,downloadpdfimagefileid,filename,extName,imagefile, WaterMarkUtil.MOULDDOC,fileid); + } + + } + long filetotalsize=0; + String _ec_browser = Util.null2String(req.getParameter("_ec_browser")); + boolean isWeChat=false; + if(agent.contains("Wechat") || agent.contains("Android") || "Wechat".equalsIgnoreCase(_ec_browser)){ + isWeChat=true; + } + baseBean.writeLog("FileDownload---------1496---fileid="+fileid+";isWeChat="+isWeChat+";_ec_browser="+_ec_browser+";agent="+agent); + String sourceFilePath=""; + if(isWeChat){ + SystemComInfo syscominfo = new SystemComInfo(); + String syspath= Util.null2String(syscominfo.getFilesystem()); + String rootPath = Util.null2String(GCONST.getRootPath()); + if("".equals(syspath)){ + sourceFilePath = rootPath + "doctempfile"; + }else{ + if(syspath.endsWith(File.separator)){ + sourceFilePath =syspath+ "doctempfile"; + }else{ + sourceFilePath =syspath+File.separator+ "doctempfile"; + } + } + File sfile = new File(sourceFilePath); + if(!sfile.exists()) sfile.mkdirs(); + sourceFilePath += File.separator + UUID.randomUUID().toString(); + OutputStream os = null; + int read; + byte[] buf = new byte[8 * 1024]; + try{ + os = new FileOutputStream(sourceFilePath); + while((read = imagefile.read(buf)) != -1) { + os.write(buf, 0, read); + filetotalsize += read; + } + }catch(Exception e){ + + }finally{ + if(os != null) + os.close(); + } + imagefile = new FileInputStream(sourceFilePath); + res.setHeader("Content-length", "" + filetotalsize); + } + + if("1".equals(download)) { + imagefile = FileManager.download(req,fileid+"",filerealpath,aescode,iszip,isaesencrypt,imagefile); + } + + while ((byteread = imagefile.read(data)) != -1) { + out.write(data, 0, byteread); + out.flush(); + } + try{ + if(!"".equals(sourceFilePath)){ + File f = new File(sourceFilePath); + if(f.exists()&&f.isFile()){ + FileSecurityUtil.deleteFile(f); + } + } + }catch(Exception e) { + baseBean.writeLog("FileDownload---------1533---fileid="+fileid+";Exception="+e); + } + } + catch(Exception e) { + writeLogs(e); + //do nothing + } + finally { + if(imagefile!=null) imagefile.close(); + if(out!=null) out.flush(); + if(out!=null) out.close(); + if("1".equals(iscompress)&& StringUtils.isNotEmpty(targetFilePath)){ + File targetfile = new File(targetFilePath); + if(targetfile.exists()){ + FileSecurityUtil.deleteFile(targetfile); + //new FileDeleteUtil().deleteFile(targetfile); + } + } + } + + try{ + if(needUser&&nolog==0) { + //记录下载日志 begin + HttpSession session = req.getSession(false); + if (session != null) { + user = (User) session.getAttribute("weaver_user@bean"); + if (user != null) { + //董平修改 文档下载日志只记录了内部员工的名字,如果是客户门户来下载,则没有记录 for TD:1644 + String userType = user.getLogintype(); + if ("1".equals(userType)) { //如果是内部用户 名称就是 lastName 外部则入在 firstName里面 + downloadLog(user.getUID(), user.getLastname(), fileid, filename,ipstring); + } else { + downloadLog(user.getUID(), user.getFirstname(), fileid, filename,ipstring); + } + + } + } + //记录下载日志 end + } + + countDownloads(""+fileid); + }catch(Exception ex){ + writeLogs(ex); + } + return ; + }else{ + baseBean.writeLog("FileDownload---------1767---fileid="+fileid+";isPic="+isPic+";222222"); + String urlString=weaver.alioss.AliOSSObjectUtil.generatePresignedUrl(tokenKey,filename,contenttype,isInline,cacheContorl,isSafari); + if(urlString!=null){ + try{ + if(needUser&&nolog==0) { + //记录下载日志 begin + HttpSession session = req.getSession(false); + if (session != null) { + user = (User) session.getAttribute("weaver_user@bean"); + if (user != null) { + //董平修改 文档下载日志只记录了内部员工的名字,如果是客户门户来下载,则没有记录 for TD:1644 + String userType = user.getLogintype(); + if ("1".equals(userType)) { //如果是内部用户 名称就是 lastName 外部则入在 firstName里面 + downloadLog(user.getUID(), user.getLastname(), fileid, filename,ipstring); + } else { + downloadLog(user.getUID(), user.getFirstname(), fileid, filename,ipstring); + } + + } + } + //记录下载日志 end + } + + countDownloads(""+fileid); + }catch(Exception ex){ + writeLogs(ex); + } + //urlString=urlString+"&fileid="+fileid; + res.sendRedirect(urlString); + return; + } + } + } + + InputStream imagefile = null; + ZipInputStream zin = null; + /*if (filerealpath.equals("")) { // 旧的文件放在数据库中的方式 + if (isoracle) + imagefile = new BufferedInputStream(statement.getBlobBinary("imagefile")); + else + imagefile = new BufferedInputStream(statement.getBinaryStream("imagefile")); + } else*/ //目前已经不可能将文件存放在数据库中了 + + File thefile = new File(filerealpath); + boolean signResult = false; + if (!filerealpath.isEmpty() && !signInfo.isEmpty() && !hashInfo.isEmpty()) { + signResult = com.api.doc.util.DocEncryptUtil.verifyFile(hashInfo, signInfo, filerealpath); + // 如果签名不通过,则跳转提醒页面 + if (!signResult ) { + res.sendRedirect(GCONST.getContextPath()+"/wui/common/page/integrityFailure.jsp?line=4&user=null"); + return; + } + } + + if (iszip.equals("1")) { + zin = new ZipInputStream(new FileInputStream(thefile)); + if (zin.getNextEntry()!=null) imagefile = new BufferedInputStream(zin); + } else{ + imagefile = new BufferedInputStream(new FileInputStream(thefile)); + } + + if(isaesencrypt.equals("1")){ + imagefile = AESCoder.decrypt(imagefile, aescode); + } + + if (signResult) { + imagefile = com.api.doc.util.DocEncryptUtil.decryptInput(imagefile); + if (imagefile == null) { + res.sendRedirect(GCONST.getContextPath()+"/wui/common/page/integrityFailure.jsp?line=4&user=null"); + return; + } + } + if(download.equals("1") && (isOfficeToDocument(extName))&&isMsgObjToDocument()) { + //正文的处理 + ByteArrayOutputStream bout = null; + try { + bout = new ByteArrayOutputStream() ; + while((byteread = imagefile.read(data)) != -1) { + bout.write(data, 0, byteread) ; + bout.flush() ; + } + byte[] fileBody = bout.toByteArray(); + iMsgServer2000 MsgObj = new iMsgServer2000(); + MsgObj.MsgFileBody(fileBody); //将文件信息打包 + fileBody = MsgObj.ToDocument(MsgObj.MsgFileBody()); //通过iMsgServer200 将pgf文件流转化为普通Office文件流 + imagefile = new ByteArrayInputStream(fileBody); + bout.close(); + } + catch(Exception e) { + writeLogs(e); + if(bout!=null) bout.close(); + } + } + ServletOutputStream out = null; + DocAddWaterForSecond docAddWaterForSecond = new DocAddWaterForSecond(); + try { + out = res.getOutputStream(); + res.setContentType(contenttype); + + if(ishtmlfile && needGbkCode){ + boolean loadGBK = !"0".equals(rs.getPropValue("docpreview", "loadGBK")); + if(loadGBK){ + res.setContentType(contenttype+";charset=GBK"); + } + } + if("1".equals(iscompress)){ + ImageCompressUtil imageCompressUtil=new ImageCompressUtil(); + targetFilePath = imageCompressUtil.getTargetFilePath(); + imagefile=imageCompressUtil.imageCompress(imagefile,targetFilePath); + }else if ("1".equals(thumbnail)){ + imagefile = getThumbnail(fileid, imagefile); + } + if(!frompdfview.equals("1") && download.equals("1")){ + Map secWmSetMap = WaterMarkUtil.getCategoryWmSet(fileid+""); + //writeLogs("2013 fileid=" + fileid); + shouldAddFileDownLoadWm(secWmSetMap, fileid+""); // 2447956 wgs + if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD))&& "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtil.WATERCONTENTISNULL))){ +// imagefile = WaterMarkUtil.takefileWater(imagefile,user,filename,fileid,extName,WaterMarkUtil.MOULDDOC); + imagefile = FileWaterManager.takewater(req,downloadpdfimagefileid,filename,extName,imagefile, WaterMarkUtil.MOULDDOC,fileid); + } + } + // 2298348 wgs + //writeLogs("2021 downloadFlag=" + downloadFlag); + if (!"1".equals(downloadFlag)) { + imagefile = EncryptDecryptFileUtil.fileDecrypt(Util.getIntValue(fileid), imagefile, filename, ""); + } + // 2298348 wgs + if("1".equals(download)) { + imagefile = FileManager.download(req,fileid+"",filerealpath,aescode,iszip,isaesencrypt,imagefile); + } + //加密流程返回false + if(((contenttype.contains("video")&& agent.contains("iPhone")) || contenttype.contains("audio")) && !download.equals("1") ) {//ios播放视频文件,解析range字段 + sendVideoToIOS(req, res, imagefile, filename,filerealpath); + }else { + long filetotalsize=0; + String _ec_browser = Util.null2String(req.getParameter("_ec_browser")); + boolean isWeChat=false; + if(agent.contains("Wechat") || agent.contains("Android") || "Wechat".equalsIgnoreCase(_ec_browser)){ + isWeChat=true; + } + baseBean.writeLog("FileDownload---------1675---fileid="+fileid+";isWeChat="+isWeChat+";_ec_browser="+_ec_browser+";agent="+agent); + String sourceFilePath=""; + if(isWeChat){ + SystemComInfo syscominfo = new SystemComInfo(); + String syspath= Util.null2String(syscominfo.getFilesystem()); + String rootPath = Util.null2String(GCONST.getRootPath()); + if("".equals(syspath)){ + sourceFilePath = rootPath + "doctempfile"; + }else{ + if(syspath.endsWith(File.separator)){ + sourceFilePath =syspath+ "doctempfile"; + }else{ + sourceFilePath =syspath+File.separator+ "doctempfile"; + } + } + File sfile = new File(sourceFilePath); + if(!sfile.exists()) sfile.mkdirs(); + sourceFilePath += File.separator + UUID.randomUUID().toString(); + OutputStream os = null; + int read; + byte[] buf = new byte[8 * 1024]; + try{ + os = new FileOutputStream(sourceFilePath); + while((read = imagefile.read(buf)) != -1) { + os.write(buf, 0, read); + filetotalsize += read; + } + }catch(Exception e){ + + }finally{ + if(os != null) + os.close(); + } + imagefile = new FileInputStream(sourceFilePath); + res.setHeader("Content-length", "" + filetotalsize); + } + // 文档/流程中单个附件下载 + while ((byteread = imagefile.read(data)) != -1) { + out.write(data, 0, byteread); + out.flush(); + } + try{ + if(!"".equals(sourceFilePath)){ + File f = new File(sourceFilePath); + if(f.exists()&&f.isFile()){ + FileSecurityUtil.deleteFile(f); + } + } + }catch(Exception e) { + baseBean.writeLog("FileDownload---------1707---fileid="+fileid+";Exception="+e); + } + } + + + } + catch(Exception e) { + writeLogs(e); + //do nothing + } + finally { + if(imagefile!=null) imagefile.close(); + if(zin!=null) zin.close(); + if(out!=null) out.flush(); + if(out!=null) out.close(); + if("1".equals(iscompress)&& StringUtils.isNotEmpty(targetFilePath)){ + File targetfile = new File(targetFilePath); + FileSecurityUtil.deleteFile(targetfile); + //new FileDeleteUtil().deleteFile(targetFilePath); + } + + } + + if(needUser&&nolog==0) { + //记录下载日志 begin + HttpSession session = req.getSession(false); + if (session != null) { + user = (User) session.getAttribute("weaver_user@bean"); + if (user != null) { + //董平修改 文档下载日志只记录了内部员工的名字,如果是客户门户来下载,则没有记录 for TD:1644 + String userType = user.getLogintype(); + if ("1".equals(userType)) { //如果是内部用户 名称就是 lastName 外部则入在 firstName里面 + downloadLog(user.getUID(), user.getLastname(), fileid, filename,ipstring); + } else { + downloadLog(user.getUID(), user.getFirstname(), fileid, filename,ipstring); + } + + } + } + //记录下载日志 end + } + + + countDownloads(""+fileid); + } + } catch (Exception e) { + BaseBean basebean = new BaseBean(); + basebean.writeLog(e); + } //错误处理 + } + }else{ + String urlstr = req.getParameter("urlstr"); + res.addHeader("Cache-Control", "private, max-age=8640000"); + boolean isNotUse=true; + if(isNotUse){ + return; + } + InputStream imagefile = null; + URL url = new URL(urlstr); + HttpURLConnection conn = (HttpURLConnection)url.openConnection(); + conn.setRequestMethod("GET"); + conn.setConnectTimeout(5 * 1000); + imagefile = conn.getInputStream(); + + ServletOutputStream outputStream = res.getOutputStream(); + + byte data[] = new byte[1024]; + int byteread; + + while ((byteread = imagefile.read(data)) != -1) { + outputStream.write(data, 0, byteread); + outputStream.flush(); + } + + outputStream.close(); + imagefile.close(); + } + } + + /** + * 获取缩略图的流对象 + * @param fileid + * @param is + * @return + */ + private InputStream getThumbnail(int fileid,InputStream is){ + RecordSet rs = new RecordSet(); + + + int width = Util.getIntValue(rs.getPropValue("docthumbnailfile","width"),300); + width = width <= 0 ? 0 : width; + + rs.executeQuery("select thumbnailid from ImageFileThumbnail where imgfileid=? and width=?",fileid,width); + if(rs.next()){ + //System.out.println("id为:"+fileid+",走的缩略图"); + return ImageFileManager.getInputStreamById(Util.getIntValue(rs.getString("thumbnailid"))); + } + + ImageCompressUtil imageCompressUtil=new ImageCompressUtil(); + + String targetFilePath = imageCompressUtil.getTargetFilePath(); + + InputStream imagefile=imageCompressUtil.imageCompressPercent(is,targetFilePath,width,0.7f); + + ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); + byte[] in2b = null; + try{ + byte[] buff = new byte[100]; + int rc = 0; + while ((rc = imagefile.read(buff, 0, 100)) > 0) { + swapStream.write(buff, 0, rc); + } + in2b = swapStream.toByteArray(); + }catch(Exception e){ + + }finally{ + try{ + swapStream.close(); + }catch(Exception e){} + try{ + if(imagefile != null) + imagefile.close(); + }catch(Exception e){} + } + + ImageFileManager ifm = new ImageFileManager(); + ifm.setData(in2b); + ifm.setImagFileName(UUID.randomUUID().toString()+ ".jpeg"); + int thumbnailid = ifm.saveImageFile(); + if(thumbnailid <= 0){ + return ImageFileManager.getInputStreamById(fileid); + } + + rs.executeUpdate("insert into ImageFileThumbnail(imgfileid,thumbnailid,width) values(?,?,?)",fileid,thumbnailid,width); + + return ImageFileManager.getInputStreamById(thumbnailid); + } + + public void sendVideoToIOSJSP(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String fileName,String filerealpath) throws FileNotFoundException, IOException { + sendVideoToIOS(request,response,inputStream,fileName,filerealpath); + } + + /** + * ios传输视频,必须要解析range字段 + * @param request + * @param response + * @param inputStream + * @param fileName + * @param filerealpath + */ + private void sendVideoToIOS(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String fileName,String filerealpath) throws FileNotFoundException, IOException { + if(filerealpath.endsWith(".zip")){ + filerealpath = filerealpath.substring(0,filerealpath.length() - 4); + } + File tempfile = new File(filerealpath + "_tmp"); + FileOutputStream fos = null; + RandomAccessFile randomFile = null; + ServletOutputStream out = null; + try { + byte[] buffer = new byte[4096]; + int byteread = 0; + fos = new FileOutputStream(tempfile); + while ((byteread = inputStream.read(buffer)) != -1) { + fos.write(buffer, 0, byteread); + } + fos.flush(); + + randomFile = new RandomAccessFile(tempfile, "r");//只读模式 + long contentLength = randomFile.length(); + String range = request.getHeader("Range"); + int start = 0, end = 0; + if(range != null && range.startsWith("bytes=")){ + String[] values = range.split("=")[1].split("-"); + start = Integer.parseInt(values[0]); + if(values.length > 1){ + end = Integer.parseInt(values[1]); + } + } + int requestSize = 0; + if(end != 0 && end > start){ + requestSize = end - start + 1; + } else { + requestSize = Integer.MAX_VALUE; + } + response.setHeader("Accept-Ranges", "bytes"); + response.setHeader("ETag", fileName); + response.setHeader("Last-Modified", new Date().toString()); + //第一次请求只返回content length来让客户端请求多次实际数据 + if(range == null){ + response.setHeader("Content-length", contentLength + ""); + }else{ + //以后的多次以断点续传的方式来返回视频数据 + response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);//206 + long requestStart = 0, requestEnd = 0; + String[] ranges = range.split("="); + if(ranges.length > 1){ + String[] rangeDatas = ranges[1].split("-"); + requestStart = Integer.parseInt(rangeDatas[0]); + if(rangeDatas.length > 1){ + requestEnd = Integer.parseInt(rangeDatas[1]); + } + } + long length = 0; + if(requestEnd > 0){ + length = requestEnd - requestStart + 1; + response.setHeader("Content-length", "" + length); + response.setHeader("Content-Range", "bytes " + requestStart + "-" + requestEnd + "/" + contentLength); + }else{ + length = contentLength - requestStart; + response.setHeader("Content-length", "" + length); + response.setHeader("Content-Range", "bytes "+ requestStart + "-" + (contentLength - 1) + "/" + contentLength); + } + } + out = response.getOutputStream(); + int needSize = requestSize; + randomFile.seek(start); + while(needSize > 0){ + int len = randomFile.read(buffer); + if(needSize < buffer.length){ + out.write(buffer, 0, needSize); + } else { + out.write(buffer, 0, len); + if(len < buffer.length){ + break; + } + } + needSize -= buffer.length; + } + }catch (Exception e){ + BaseBean basebean = new BaseBean(); + basebean.writeLog(e); + }finally { + if(inputStream != null)inputStream.close(); + if(fos != null)fos.close(); + if(randomFile != null)randomFile.close(); + if(out != null)out.close(); + FileSecurityUtil.deleteFile(tempfile); + //new FileDeleteUtil().deleteFile(tempfile); + } + } + /** + * ofd下载逻辑 + * @param req + * @param res + */ + //本例中传入的url是类似 http://ip:port/DownloadServlet?docId=2&imageFileId=5 + private void downloadOfd(HttpServletRequest req, HttpServletResponse res, User user) { + //本例中传入的url是类似 http://ip:port/DownloadServlet?docId=2&imageFileId=5 + int docId= Util.getIntValue(req.getParameter("docId"),-1); + int imageFileId= Util.getIntValue(req.getParameter("imageFileId"),-1); + baseBean.writeLog("downloadOfd docId="+docId+"###imageFileId="+imageFileId); + if (imageFileId <= 0) return; + if(!DocUtil.hasPemissionDownload(user, imageFileId)){ + baseBean.writeLog("---------- downloadOfd 无下载权限---------imageFileId=" + imageFileId); + return; + } + InputStream is = null; + BufferedOutputStream bos = null; + try{ + ImageFileManager imageFileManager=new ImageFileManager(); + imageFileManager.getImageFileInfoById(imageFileId); + res.setStatus(200); + res.setContentType("APPLICATION/OCTET-STREAM; charset=UTF-8"); + res.setHeader("Content-Disposition", "attachment; filename="+ new String(imageFileManager.getImageFileName().replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", "").getBytes("UTF-8"),"ISO-8859-1")+""); + res.setContentType("application/ofd"); + //writeLogs("2353 downloadFlag=" + downloadFlag); + imageFileManager.setDownloadFlag(downloadFlag); // 2298348 wgs + is = imageFileManager.getInputStream(); + bos = new BufferedOutputStream(res.getOutputStream()); + byte[] buf = new byte[BUFFER_SIZE]; + int len = -1; + while ((len = is.read(buf)) != -1){ + bos.write(buf, 0, len); + } + bos.flush(); + }catch(IOException exp){ + exp.printStackTrace(); + }finally{ + if (is != null) + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + if (bos != null) + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + private void downloadForEmaill(HttpServletRequest req, HttpServletResponse res){ + //int fileid = Util.getIntValue(req.getParameter("fileid")); + int fileid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileid(req), -1); + MailFilePreviewService mfps = new MailFilePreviewService(); + InputStream imagefile = mfps.getInputStreamByMailFileId(fileid + ""); + + String filename = Util.null2String(mfps.getFileNameOnly(fileid + "")); + ServletOutputStream out = null; + if(imagefile != null){ + try { + out = res.getOutputStream(); + res.setContentType("application/octet-stream"); + res.setHeader("content-disposition", "attachment; filename=\"" + + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); + int byteread; + byte data[] = new byte[1024]; + while ((byteread = imagefile.read(data)) != -1) { + out.write(data, 0, byteread); + out.flush(); + } + } catch (Exception e) { + new BaseBean().writeLog(e); + } finally { + if(out != null){ + try{ + out.close(); + }catch(Exception e){ + new BaseBean().writeLog(e); + } + } + if(imagefile != null){ + try{ + imagefile.close(); + }catch(Exception e){ + new BaseBean().writeLog(e); + } + } + } + } + } + + private void downloadForWebOffice(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ + User user = (User)req.getSession(true).getAttribute("weaver_user@bean"); + String fileid = Util.null2String(req.getParameter("fileid")); + + if(user == null){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?line=4&user=null"); + return; + } + + RecordSet rs = new RecordSet(); + RecordSet rsdoc = new RecordSet(); + rs.executeQuery("select a.id,b.docid,b.imagefilename from DocWebOffice a,DocImageFile b where a.fileid=? and a.imagefileid=b.imagefileid",fileid); + if(rs.next()){ + + String docid = rs.getString("docid"); + + DocCoopereateUtil dcu = new DocCoopereateUtil(); + DocViewPermission dvps = new DocViewPermission(); + Map levelMap = dvps.getShareLevel(Util.getIntValue(docid),user,false); + boolean canRead = levelMap.get(DocViewPermission.READ); + boolean canCoope = dcu.jugeUserCoopeRight(docid,user,canRead); + if(!canCoope){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?line=3&fileid=" + fileid); + return; + } + + Map dataMap = new HashMap(); + InputStream in = new WebOfficeServiceImpl().getInputStream(rs.getInt("id"),dataMap); + + ServletOutputStream out = null; + if(in != null){ + rsdoc.executeQuery("select docsubject from docdetail where id = "+docid); + rsdoc.next(); + String docsubject = Util.null2String(rsdoc.getString("docsubject")); + String imagefilename = Util.null2String(rs.getString("imagefilename")); + String extname = imagefilename.contains(".")? imagefilename.substring(imagefilename.lastIndexOf(".") + 1) : ""; + String filename =docsubject+"."+extname; + if ( (agent.contains(" Chrome") || agent.contains("Safari")) && !agent.contains("Edge")) { +// res.setHeader("content-disposition", "attachment;"); + res.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(") + .replaceAll("%29", ")").replaceAll("%7B","{").replaceAll("%7D","}").replaceAll("%5B","[").replaceAll("%5D","]").replaceAll("%40","@").replaceAll("%23","#").replaceAll("%25","%").replaceAll("%26","&") + .replaceAll("%2B","+").replaceAll("%27","'").replaceAll("%20"," ")); + }else if(agent.contains("Firefox")){ + res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); + } else{ + res.setHeader("content-disposition", "attachment; filename=\"" + + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); + } + try { + out = res.getOutputStream(); + res.setContentType("application/octet-stream"); + int byteread; + byte data[] = new byte[1024]; + while ((byteread = in.read(data)) != -1) { + out.write(data, 0, byteread); + out.flush(); + } + } catch (Exception e) { + new BaseBean().writeLog(e); + } finally { + if(out != null){ + try{ + out.close(); + }catch(Exception e){ + new BaseBean().writeLog(e); + } + } + if(in != null){ + try{ + in.close(); + }catch(Exception e){ + new BaseBean().writeLog(e); + } + } + } + }else{ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?line=2&fileid=" + fileid); + return; + } + }else{ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?line=1&fileid=" + fileid); + return; + } + + } + + private void downloadForDoccenterCoop(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ + User user = (User)req.getSession(true).getAttribute("weaver_user@bean"); + String fileid = Util.null2String(req.getParameter("fileid")); + String fromfileid = Util.null2String(req.getParameter("fromfileid")); + String wpsFileid = Util.null2String(req.getParameter("wpsFileid")); + + if(user == null){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?line=4&user=null"); + return; + } + + if(fromfileid == null || fromfileid.isEmpty()){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?fromid=null"); + return; + } + + String docid = ""; + int fromecfileid = Util.getIntValue(fileid); + int ecfileid = 0; + String mould = ""; + String ecFileName = ""; + + RecordSet rs = new RecordSet(); + String sql = "select * from wps_doccenter_fileinfo where wpsfileid = ? and fromecfileid = ? order by versionid desc"; + rs.executeQuery(sql, wpsFileid, fromfileid); + if(rs.next()){ + fromecfileid = rs.getInt("fromecfileid"); + ecfileid = rs.getInt("ecfileid"); + mould = Util.null2String(rs.getString("mould")); + ecFileName = Util.null2String(rs.getString("filename")); + } else { + ecfileid = fromecfileid; + mould = "ecology"; + } + + sql = "select docid, imagefilename from docimagefile where imagefileid = ?"; + rs.executeQuery(sql,fromecfileid); + if(!rs.next()) { + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?line=1&wpsFileid=" + wpsFileid); + return; + } + docid = rs.getString("docid"); + ecFileName = Util.null2String(rs.getString("imagefilename")); + + DocCoopereateUtil dcu = new DocCoopereateUtil(); + DocViewPermission dvps = new DocViewPermission(); + Map levelMap = dvps.getShareLevel(Util.getIntValue(docid),user,false); + boolean canRead = levelMap.get(DocViewPermission.READ); + boolean canCoope = dcu.jugeUserCoopeRight(docid,user,canRead); + if(!canCoope){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?line=3&fileid=" + wpsFileid); + return; + } + + Map dataMap = new HashMap(); + InputStream in = new weaver.wps.doccenter.utils.FileInfoUtil().getInputStream(ecfileid, mould); + + ServletOutputStream out = null; + if(null == in) { + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?line=2&fileid=" + wpsFileid); + return; + } + + rs.executeQuery("select docsubject from docdetail where id = "+docid); + rs.next(); + String docsubject = Util.null2String(rs.getString("docsubject")); + String extname = ecFileName.contains(".")? ecFileName.substring(ecFileName.lastIndexOf(".") + 1) : ""; + String filename =docsubject+"."+extname; + if ( (agent.contains(" Chrome") || agent.contains("Safari")) && !agent.contains("Edge")) { +// res.setHeader("content-disposition", "attachment;"); + res.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(") + .replaceAll("%29", ")").replaceAll("%7B","{").replaceAll("%7D","}").replaceAll("%5B","[").replaceAll("%5D","]").replaceAll("%40","@").replaceAll("%23","#").replaceAll("%25","%").replaceAll("%26","&") + .replaceAll("%2B","+").replaceAll("%27","'").replaceAll("%20"," ")); + }else if(agent.contains("Firefox")){ + res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); + } else{ + res.setHeader("content-disposition", "attachment; filename=\"" + + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); + } + try { + out = res.getOutputStream(); + res.setContentType("application/octet-stream"); + int byteread; + byte data[] = new byte[1024]; + while ((byteread = in.read(data)) != -1) { + out.write(data, 0, byteread); + out.flush(); + } + } catch (Exception e) { + rs.writeLog(FileDownload.class.getName(), e); + } finally { + Tools.cloze(out); + Tools.cloze(in); + } + } + /** + * 文档下载 + * @param req + * @param res + */ + private void downloadForDocument(HttpServletRequest req, HttpServletResponse res,User user,boolean wmflag){ + //int fileid = Util.getIntValue(req.getParameter("fileid")); + int fileid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileid(req), -1); + int isofficeview = Util.getIntValue(Util.null2String(req.getParameter("isofficeview")), -1); + baseBean.writeLog("---------- downloadForDocument ---------fileid=" + fileid); + if(fileid <= 0) return; + if(!DocUtil.hasPemissionDownload(user, fileid)){ + baseBean.writeLog("---------- downloadForDocument 无下载权限---------fileid=" + fileid); + return; + } + InputStream imagefile = null; + try { + ImageFileManager ifm = new ImageFileManager(); + ifm.getImageFileInfoById(fileid); + //writeLogs("2622 downloadFlag=" + downloadFlag); + ifm.setDownloadFlag(downloadFlag); // 2298348 wgs + imagefile = ifm.getInputStream(); + String filename = ifm.getImageFileName(); + String contenttype = ""; + if(filename.toLowerCase().endsWith(".gif")) { + contenttype = "image/gif"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + }else if(filename.toLowerCase().endsWith(".png")) { + contenttype = "image/png"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + }else if(filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg")) { + contenttype = "image/jpg"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + }else if(filename.toLowerCase().endsWith(".bmp")) { + contenttype = "image/bmp"; + res.addHeader("Cache-Control", "private, max-age=8640000"); + } + if(isofficeview==1){ + String extName = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : ""; + Map secWmSetMap = WaterMarkUtil.getCategoryWmSet(fileid+""); + if(wmflag && "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYVIEW))&& "1".equals(secWmSetMap.get(WaterMarkUtil.SECCATEGORYWMISOPEN)) && "0".equals(secWmSetMap.get(WaterMarkUtil.WATERCONTENTISNULL))){ +// imagefile = WaterMarkUtil.takefileWater(imagefile,user,filename,fileid,extName,WaterMarkUtil.MOULDDOC); + imagefile = FileWaterManager.takewater(req,fileid+"",filename,extName,imagefile, WaterMarkUtil.MOULDDOC,-1); + } + } + ServletOutputStream out = res.getOutputStream(); + res.setContentType(contenttype); + res.setHeader("content-disposition", "attachment; filename=\"" + new String(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", "").getBytes("UTF-8"),"ISO-8859-1")+"\""); + int byteread; + byte data[] = new byte[1024]; + while ((byteread = imagefile.read(data)) != -1) { + out.write(data, 0, byteread); + out.flush(); + } + out.flush(); + out.close(); + } catch (Exception e) { + new BaseBean().writeLog(e); + } finally { + if(imagefile != null){ + try{ + imagefile.close(); + }catch(Exception e){ + new BaseBean().writeLog(e); + } + } + } + } + + //模板下载 + private void downloadMould(HttpServletRequest req, HttpServletResponse res,String type){ + //int mouldid = Util.getIntValue(req.getParameter("fileid")); + int mouldid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileid(req), -1); + if(mouldid <= 0) return; + String mouldName = ""; + String mouldPath = ""; + String tableName = ""; + String mouldtype = ""; + int imagefileid = 0; + if("showMould".equals(type)){ + tableName = "docMould"; + } else if ("printMould".equals(type)){ + tableName = "OdocPrintMould"; + }else{ + tableName = "DocMouldFile"; + } + RecordSet rs = new RecordSet(); + rs.executeQuery("select mouldName,mouldPath,imagefileid,mouldtype from "+ tableName +" where id=?",mouldid); + if(rs.next()){ + mouldName = rs.getString("mouldName"); + mouldPath = rs.getString("mouldPath"); + imagefileid = rs.getInt("imagefileid"); + mouldtype = rs.getString("mouldtype"); + }else{ + return; + } + + if ("printMould".equals(type) && "2".equals(mouldtype)){ + mouldName += ".docx"; + }else if("2".equals(mouldtype)){ + mouldName += ".doc"; + }else if("3".equals(mouldtype)){ + mouldName += ".xls"; + }else if("4".equals(mouldtype)){ + mouldName += ".wps"; + } + InputStream is = null; + try { + if(imagefileid > 0){ + is = ImageFileManager.getInputStreamById(imagefileid); + }else{ + is = new BufferedInputStream(new FileInputStream(mouldPath)); + } + res.setContentType("application/octet-stream"); + ServletOutputStream out = res.getOutputStream(); + res.setHeader("content-disposition", "attachment; filename=\"" + new String(mouldName.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", "").getBytes("UTF-8"),"ISO-8859-1")+"\""); + int byteread; + byte data[] = new byte[1024]; + while ((byteread = is.read(data)) != -1) { + out.write(data, 0, byteread); + out.flush(); + } + out.flush(); + out.close(); + } catch (Exception e) { + new BaseBean().writeLog(e); + } finally { + if(is != null){ + try{ + is.close(); + }catch(Exception e){ + new BaseBean().writeLog(e); + } + } + } + } + + /** + * 交换平台下载逻辑 + * @param req + * @param res + */ + private void downloadForExchange(HttpServletRequest req, HttpServletResponse res) { + String clientEcoding = "GBK"; + try { + try{ + String acceptlanguage = req.getHeader("Accept-Language"); + if(!"".equals(acceptlanguage)) + acceptlanguage = acceptlanguage.toLowerCase(); + if(acceptlanguage.indexOf("zh-tw")>-1||acceptlanguage.indexOf("zh-hk")>-1){ + clientEcoding = "BIG5"; + }else{ + clientEcoding = "GBK"; + } + }catch(Exception e){ + e.printStackTrace(); + } + User user = HrmUserVarify.getUser (req , res) ; + agent = req.getHeader("user-agent"); + int fileid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileid(req), -1); + //int fileid = Util.getIntValue(req.getParameter("fileid"), -1); + int requestid = Util.getIntValue(req.getParameter("requestid")); + String ipstring = Util.getIpAddr(req); + Map jsonParams = new HashMap(); + int userid = 0; + if(fileid <=0 ){ + jsonParams = Json2MapUtil.requestJson2Map(req); + fileid = Util.getIntValue(Util.null2String(jsonParams.get("fileid"))); + userid = Util.getIntValue(Util.null2String(jsonParams.get("userid"))); + requestid = Util.getIntValue(Util.null2String(jsonParams.get("requestid"))); + } + if(fileid <= 0){//转化为int型,防止SQL注入 + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?v6"); + return; + } + RecordSet statement = new RecordSet(); + try { + boolean hasRight=false; + try{ + String companyId = getCompanyIdByUser(user); + hasRight = isHaveDownloadRight(String.valueOf(fileid),companyId); + }catch(Exception ex){ + BaseBean basebean = new BaseBean(); + basebean.writeLog(ex); + hasRight=false; + } + if(!hasRight){ + res.sendRedirect(weaver.general.GCONST.getContextPath()+"/notice/noright.jsp?v7"); + return; + } + String contenttype = "application/octet-stream"; + String filename = ""; + String filerealpath = ""; + String signInfo = ""; + String hashInfo = ""; + String iszip = ""; + String isencrypt = ""; + String isaesencrypt=""; + String aescode = ""; + String tokenKey=""; + String storageStatus = ""; + String comefrom=""; + int byteread; + byte data[] = new byte[1024]; + String sql = "select t1.imagefilename,t1.filerealpath,t1.signinfo,t1.hashinfo,t1.iszip,t1.isencrypt,t1.imagefiletype , t1.imagefileid, t1.imagefile,t1.isaesencrypt,t1.aescode,t2.imagefilename as realname,t1.TokenKey,t1.StorageStatus,t1.comefrom from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.imagefileid = "+fileid; + String extName = ""; + statement.execute(sql); + if (statement.next()) { + filename = Util.null2String(statement.getString("imagefilename")); + filerealpath = Util.null2String(statement.getString("filerealpath")); + signInfo = Util.null2String(statement.getString("signinfo")); + hashInfo = Util.null2String(statement.getString("hashinfo")); + iszip = Util.null2String(statement.getString("iszip")); + isencrypt = Util.null2String(statement.getString("isencrypt")); + isaesencrypt = Util.null2o(statement.getString("isaesencrypt")); + aescode = Util.null2String(statement.getString("aescode")); + tokenKey = Util.null2String(statement.getString("TokenKey")); + storageStatus = Util.null2String(statement.getString("StorageStatus")); + comefrom = Util.null2String(statement.getString("comefrom")); + try { + if((agent.contains("Firefox")||agent.contains(" Chrome")||agent.contains("Safari") )&& !agent.contains("Edge")){ + res.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); + }else{ + res.setHeader("content-disposition", "attachment; filename=\"" + + URLEncoder.encode(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\""); + } + } catch (Exception ecode) { + ecode.printStackTrace(); + } + InputStream imagefile = null; + ZipInputStream zin = null; + File thefile = new File(filerealpath); + boolean signResult = false; + if (!filerealpath.isEmpty() && !signInfo.isEmpty() && !hashInfo.isEmpty()) { + signResult = com.api.doc.util.DocEncryptUtil.verifyFile(hashInfo, signInfo, filerealpath); + // 附件下载,开始调用密码机解密 + if (!signResult ) { + res.sendRedirect(GCONST.getContextPath()+"/wui/common/page/integrityFailure.jsp?line=4&user=null"); + return; + } + } + if (iszip.equals("1")) { + zin = new ZipInputStream(new FileInputStream(thefile)); + if (zin.getNextEntry() != null) imagefile = new BufferedInputStream(zin); + } else{ + imagefile = new BufferedInputStream(new FileInputStream(thefile)); + } + ServletOutputStream out = null; + try { + out = res.getOutputStream(); + res.setContentType(contenttype); + if(isaesencrypt.equals("1")){ + imagefile = AESCoder.decrypt(imagefile, aescode); + } + // 签名值校验通过,开始进行解密操作 + if (signResult) { + imagefile = com.api.doc.util.DocEncryptUtil.decryptInput(imagefile); + if (imagefile == null) { + res.sendRedirect(GCONST.getContextPath()+"/wui/common/page/integrityFailure.jsp?line=4&user=null"); + return; + } + } + while ((byteread = imagefile.read(data)) != -1) { + out.write(data, 0, byteread); + out.flush(); + } + } + catch(Exception e) { + e.printStackTrace(); + }finally { + if(imagefile!=null) imagefile.close(); + if(zin!=null) zin.close(); + if(out!=null) out.flush(); + if(out!=null) out.close(); + } + countDownloads(""+fileid); + } + } catch (Exception e) { + BaseBean basebean = new BaseBean(); + basebean.writeLog(e); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 记录下载次数,根据传入的参数 countdownloads == 1 + * + */ + private void countDownloads(String fileid) { + if (this.isCountDownloads) { + + RecordSet rs = new RecordSet(); + String sqlStr = "UPDATE ImageFile Set downloads=downloads+1 WHERE imagefileid = " + fileid; + //System.out.println("sqlStr ==" + sqlStr); + rs.execute(sqlStr); + } + } + + /** + * 记录下载日志 + * @param userid 下载的用户id + * @param userName 下载的用户名称 + * @param imageid 下载的文档id + * @param imageName 下载的文档文件名称 + */ + private void downloadLog(int userid, String userName, int imageid, String imageName,String ipstring) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String time = format.format(new Date()); + User user = new User(userid); + RecordSet rs = new RecordSet(); + String sql = "select t2.id,t2.docsubject,t1.imagefilename from DocImageFile t1, DocDetail t2 where t1.docid=t2.id and t1.docfiletype<>1 and t1.imagefileid = "+imageid; + int docid = -1; + String docName = ""; + rs.executeSql(sql); + if(rs.next()){ + docid = rs.getInt(1); + docName = rs.getString(2); + imageName = Util.null2String(rs.getString("imagefilename")); + userid = new DocViewPermission().getUserid(docid+"",user); + if(userid<=0){ + userid = user.getUID(); + } + sql = "insert into DownloadLog(userid, username, downloadtime, imageid, imagename, docid, docname,clientaddress) values(" + userid + ",'" + Util.toHtml100(userName) + "','" + time + "'," + imageid + ",'" + Util.toHtml100(imageName) + "',"+docid+",'"+Util.toHtml100(docName)+"','"+ipstring+"')"; + rs.executeSql(sql); + } + + DocDetailService dbs = new DocDetailService(); + dbs.resizeCount(docid, DocDetailService.DOWNLOAD_COUNT); + + } + + /** + * 判断是否有下载特定文件的权限 + * @param fileId 文件id + * @param req 请求 + * @param res 响应 + * + * @return boolean true:有下载的权限 false:没有下载的权限 + */ + private boolean getWhetherHasRight(String fileId,HttpServletRequest req, HttpServletResponse res,int requestid,boolean fromMobile,Map jsonParams) throws Exception { + toWriteLog("weaver-->2176-->fileid"+fileId+"--->ishr"+fileId); + toWriteLog("weaver-->2176-->fileid"+fileId+"--->requestid"+requestid); + toWriteLog("weaver-->2176-->fileid"+fileId+"--->fromMobile"+fromMobile); + toWriteLog("weaver-->2176-->fileid"+fileId+"--->jsonParams"+jsonParams); + jsonParams = jsonParams == null ? new HashMap() : jsonParams; + //0:查看 + boolean canReader = false; + String fileid_head = fileId; + int _userid = 0; + String groupid = ""; + if(fromMobile){ + _userid = Util.getIntValue(Util.null2String(jsonParams.get("userid"))); + groupid = Util.null2String(jsonParams.get("groupid")); + } + String download = Util.null2String(jsonParams.get("download")); + User user = new User(_userid); + if(user==null){ + user = (User)req.getSession(true).getAttribute("weaver_user@bean") ; + } + //安全性检查 + if(fileId==null||fileId.trim().equals("")){ + return false; + } + + RecordSet rs = new RecordSet(); + //是否必须授权 1:是 0或其他:否 + String mustAuth=Util.null2String(rs.getPropValue("FileDownload","mustAuth")); + boolean hasRight=false; +// boolean hasRight=true; + if(mustAuth.equals("1")){ + hasRight=false; + } + boolean isDocFile=false; + boolean isHtmlPreview = false; + //文档模块 附件查看权限控制 开始 + String docId=null; + boolean isimage=false; + List docIdList=new ArrayList(); + RecordSet rs2 = new RecordSet(); + rs2.executeSql("select imagefilename,comefrom from ImageFile where imageFileId="+fileId); + String extName=""; + boolean isExtfile=false; + boolean isPdf=false; + if(rs2.next()){ + String filename = Util.null2String(rs2.getString("imagefilename")); + if(filename.indexOf(".") > -1){ + int bx = filename.lastIndexOf("."); + if(bx>=0){ + extName = filename.substring(bx+1, filename.length()); + } + } + String htmlcomefrom = Util.null2String(rs2.getString("comefrom")); + if("WorkflowToDoc".equals(htmlcomefrom)){ + isHtmlPreview = true; + } + + if (filename.toLowerCase().endsWith(".mp4")||filename.toLowerCase().endsWith(".ogg")||filename.toLowerCase().endsWith(".asf")||filename.toLowerCase().endsWith(".mp3")||filename.toLowerCase().endsWith(".wav")||filename.toLowerCase().endsWith(".au")||filename.toLowerCase().endsWith(".wma")) { + isHtmlPreview = true; + } + } + + if( "xls".equalsIgnoreCase(extName)||"xlsx".equalsIgnoreCase(extName) || "doc".equalsIgnoreCase(extName)|| "docx".equalsIgnoreCase(extName)||"wps".equalsIgnoreCase(extName)||"ppt".equalsIgnoreCase(extName)||"pptx".equalsIgnoreCase(extName)) { + //isExtfile=true; + } + if("pdf".equals(extName.toLowerCase())) isPdf = true; + String imgExtStr = Util.null2s(baseBean.getPropValue("doc_download_img_ext","doc_img_ext"),""); + List imgExtList = Arrays.asList(imgExtStr.split(",")); + for(int i=0;i-1){ -// // FileUtils.deleteDirectory(targetFile); -// new FileDeleteUtil().deleteFolder(targetFile); -// } -// } else if (targetFile.isFile()) { -// FileSecurityUtil.deleteFile(targetFile); -// //new FileDeleteUtil().deleteFile(targetFile); -// } -// } -// /* -// * -// */ -// public boolean addDownLoadLogByimageId( int fileid){ -// boolean needUser = true; -// int docId = 0; -// String docIdsForOuterNews = ""; -// // String strSql = "select id from DocDetail where exists (select 1 from docimagefile where imagefileid=" + fileid + " and docId=DocDetail.id) and ishistory <> 1 and (docPublishType='2' or docPublishType='3')"; -// String strSql = "SELECT t1.id FROM DocDetail t1 INNER JOIN docimagefile t2 ON t1.id = t2.docId " + -// "WHERE t2.imagefileid = ? AND t1.ishistory <> 1 AND ( t1.docPublishType = '2' OR t1.docPublishType = '3')"; -// RecordSet rs = new RecordSet(); -// rs.executeQuery(strSql,fileid); -// while (rs.next()) { -// docId = rs.getInt("id"); -// if (docId > 0) { -// docIdsForOuterNews += "," + docId; -// } -// } -// -// if (!docIdsForOuterNews.equals("")) { -// docIdsForOuterNews = docIdsForOuterNews.substring(1); -// } -// -// if (!docIdsForOuterNews.equals("")) { -// String newsClause = ""; -// String sqlDocExist = " select 1 from DocDetail where id in(" + docIdsForOuterNews + ") "; -// String sqlNewsClauseOr = ""; -// boolean hasOuterNews = false; -// -// rs.executeSql("select newsClause from DocFrontPage where publishType='0'"); -// while (rs.next()) { -// hasOuterNews = true; -// newsClause = Util.null2String(rs.getString("newsClause")); -// if (newsClause.equals("")) { -// // newsClause=" 1=1 "; -// needUser = false; -// break; -// } -// if (!newsClause.trim().equals("")) { -// sqlNewsClauseOr += " ^_^ (" + newsClause + ")"; -// } -// } -// ArrayList newsArr = new ArrayList(); -// if (!sqlNewsClauseOr.equals("") && needUser) { -// // sqlNewsClauseOr=sqlNewsClauseOr.substring(sqlNewsClauseOr.indexOf("(")); -// // sqlDocExist+=" and ("+sqlNewsClauseOr+") "; -// String[] newsPage = Util.TokenizerString2(sqlNewsClauseOr, "^_^"); -// int i = 0; -// String newsWhere = ""; -// for (; i < newsPage.length; i++) { -// if (i % 10 == 0) { -// newsArr.add(newsWhere); -// newsWhere = ""; -// newsWhere += newsPage[i]; -// } else -// newsWhere += " or " + newsPage[i]; -// } -// newsArr.add(newsWhere); -// } -// // System.out.print(sqlDocExist); -// if (hasOuterNews && needUser) { -// for (int j = 1; j < newsArr.size(); j++) { -// String newsp = newsArr.get(j).toString(); -// if (j == 1) -// newsp = newsp.substring(newsp.indexOf("or") + 2); -// sqlDocExist += "and(" + newsp + ")"; -// rs.executeSql(sqlDocExist); -// sqlDocExist = " select 1 from DocDetail where id in(" + docIdsForOuterNews + ") "; -// if (rs.next()) { -// needUser = false; -// break; -// } -// } -// } -// } -// -// // 处理外网查看默认图片 -// rs.executeSql("SELECT * FROM DocPicUpload WHERE Imagefileid=" + fileid); -// if (rs.next()) { -// needUser = false; -// } -// -// return needUser; -// } -// /** -// * creat Folder and File. -// * @param String fileFoder, String fileName -// * Copyright (c) 2010 -// * Company weaver -// * Create Time 2010-11-25 -// * @author caizhijun001 -// * @return File -// */ -// public File fileCreate(String fileFoder, String fileName){ -// File foder = new File(fileFoder);//E:\dlxdq_ecology4.5\ecology\filesystem\201012\S 1450623393_.xls -// File file = new File(fileFoder+fileName); -// //如果文件夹不存在,则创建文件夹 -// if(foder.exists()==false){ -// foder.mkdirs();//多级目录 -// //foder.mkdir();//只创建一级目录 -// } -// -// if(file.exists()==true){//删除以前同名的txt文件 -// try{ -// FileSecurityUtil.deleteFile(file); -// //new FileDeleteUtil().deleteFile(file); -// }catch(Exception e){ -// e.printStackTrace(); -// } -// } -// //如果文件不存在,则创建文件 -// if(file.exists()==false){ -// try{ -// file.createNewFile(); -// }catch(IOException e){ -// e.printStackTrace(); -// } -// } -// return file; -// } -// -// private boolean isMsgObjToDocument(){ -// boolean isMsgObjToDocument=true; -// -// BaseBean basebean = new BaseBean(); -// String mClientName=Util.null2String(basebean.getPropValue("weaver_obj","iWebOfficeClientName")); -// boolean isIWebOffice2003 = (mClientName.indexOf("iWebOffice2003")>-1)?true:false; -// String isHandWriteForIWebOffice2009=Util.null2String(basebean.getPropValue("weaver_obj","isHandWriteForIWebOffice2009")); -// if(isIWebOffice2003||isHandWriteForIWebOffice2009.equals("0")){ -// isMsgObjToDocument=false; -// } -// if(mClientName.indexOf("iWebOffice2009")>-1) -// { -// isMsgObjToDocument=true; -// } -// -// return isMsgObjToDocument; -// } -// -// private boolean isOfficeToDocument(String extName){ -// boolean isOfficeForToDocument=false; -// if("xls".equalsIgnoreCase(extName) || "doc".equalsIgnoreCase(extName)||"wps".equalsIgnoreCase(extName)||"ppt".equalsIgnoreCase(extName)||"docx".equalsIgnoreCase(extName)||"xlsx".equalsIgnoreCase(extName)||"pptx".equalsIgnoreCase(extName)){ -// isOfficeForToDocument=true; -// } -// return isOfficeForToDocument; -// } -// -// /** -// *通过文件编号和单位编号判断此单位是否对此文件有下载权限 -// * @param fileId 文件编号对应imagefile表中的imagefileId -// * @param companyId 单位编号 -// * @return true:有下载权限 false:无下载权限 -// */ -// private boolean isHaveDownloadRight(String fileId,String companyId){ -// boolean isHaveDownloadRight = false; -// if(StringUtil.isNull(fileId,companyId)){ -// baseBean.writeLog("方法:FileDownloadForOdocExchange.isHaveDownloadRight 参数:fileId="+fileId+" companyId="+companyId); -// return isHaveDownloadRight; -// } -// /**如何判断当前用户有下载权限*/ -// RecordSet rs = new RecordSet(); -// /**1:作废的文不允许下载 2:撤销的文不允许接收方下载*/ -// /** -// * 1:判断是否是发送方 -// * 2:判断是否是接收方 -// */ -// String getIsSendDepartmentSql = ""; -// String dbType = rs.getDBType(); -// if("sqlserver".equals(dbType)){ -// getIsSendDepartmentSql = "select * from odoc_exchange_docbase where send_companyid=? and (docimagefileid=? or ',' + attachimagefileids + ',' like '%,' + ? + ',%') and status!=5"; -// }else if("mysql".equals(dbType)){ -// getIsSendDepartmentSql = "select * from odoc_exchange_docbase where send_companyid=? and (docimagefileid=? or CONCAT(',',attachimagefileids,',') like CONCAT('%,',?,',%')) and status!=5"; -// }else{ -// getIsSendDepartmentSql = "select * from odoc_exchange_docbase where send_companyid=? and (docimagefileid=? or ',' || attachimagefileids || ',' like '%,' || ? || ',%') and status!=5"; -// } -// -// boolean isGetIsSendDepartmentSql = rs.executeQuery(getIsSendDepartmentSql,companyId,fileId,fileId); -// if(isGetIsSendDepartmentSql&&rs.next()){ -// isHaveDownloadRight = true; -// }else{ -// baseBean.writeLog("方法:FileDownloadForOdocExchange.isHaveDownloadRight 执行sql:getIsSendDepartmentSql="+getIsSendDepartmentSql+" 无数据/作废状态的文不允许下载"); -// } -// String getIsReceiveDepartmentSql = ""; -// if("sqlserver".equals(dbType)){ -// getIsReceiveDepartmentSql = "select b.status from odoc_exchange_docbase a left join odoc_exchange_recieveinfo b on a.document_identifier=b.document_identifier where b.receive_companyid=? and (a.docimagefileid=? or ',' + a.attachimagefileids + ',' like '%,' + ? + ',%') and a.status!=5 and b.status!=4"; -// }else if("mysql".equals(dbType)){ -// getIsReceiveDepartmentSql = "select b.status from odoc_exchange_docbase a left join odoc_exchange_recieveinfo b on a.document_identifier=b.document_identifier where b.receive_companyid=? and (a.docimagefileid=? or CONCAT(',',attachimagefileids,',') like CONCAT('%,',?,',%')) and a.status!=5 and b.status!=4"; -// }else{ -// getIsReceiveDepartmentSql = "select b.status from odoc_exchange_docbase a left join odoc_exchange_recieveinfo b on a.document_identifier=b.document_identifier where b.receive_companyid=? and (a.docimagefileid=? or ',' || a.attachimagefileids || ',' like '%,' || ? || ',%') and a.status!=5 and b.status!=4"; -// } -// boolean isGetIsReceiveDepartmentSql = rs.executeQuery(getIsReceiveDepartmentSql,companyId,fileId,fileId); -// if(isGetIsReceiveDepartmentSql&&rs.next()){ -// isHaveDownloadRight = true; -// }else{ -// baseBean.writeLog("方法:FileDownloadForOdocExchange.isHaveDownloadRight 执行sql:getIsReceiveDepartmentSql="+getIsReceiveDepartmentSql+"无数据/作废/撤销状态的文不允许下载"); -// } -// return isHaveDownloadRight; -// } -// -// /** -// * 通过当前登录用户获取当前登陆用户所在单位编号 -// * @param uesr 当前登录用户 -// * @return 单位编号 -// */ -// private String getCompanyIdByUser(User user){ -// String companyId = ""; -// if(null==user){ -// baseBean.writeLog("FileDownloadForOdocExchange.getCompanyIdByUser 参数:user"+user); -// return companyId; -// } -// String sqlForReceiveOrSendUser="SELECT exchange_companyid FROM odoc_exchange_com_user WHERE userid=?"; -// String sqlForCompanyAdminUser="SELECT exchange_companyid FROM odoc_exchange_com_admin WHERE admin_userid=?"; -// RecordSet rs = new RecordSet(); -// boolean isSqlForReceiveOrSendUser = rs.executeQuery(sqlForReceiveOrSendUser,user.getUID()); -// if(isSqlForReceiveOrSendUser&&rs.next()){ -// companyId = rs.getString("exchange_companyid"); -// if(StringUtil.isNull(companyId)) { -// boolean isSqlForCompanyAdminUser = rs.executeQuery(sqlForCompanyAdminUser,user.getUID()); -// if(isSqlForCompanyAdminUser&&rs.next()){ -// companyId = rs.getString("exchange_companyid"); -// }else{ -// baseBean.writeLog("FileDownloadForOdocExchange.getCompanyIdByUser 执行sql:sqlForCompanyAdminUser"+sqlForCompanyAdminUser+"参数:user.getUID()="+user.getUID()+"失败或查询数据为空"); -// } -// }else{ -// baseBean.writeLog("FileDownloadForOdocExchange.getCompanyIdByUser 执行sql:sqlForReceiveOrSendUser"+sqlForReceiveOrSendUser+"参数:user.getUID()="+user.getUID()+"查询的单位编号为空"); -// } -// }else{ -// baseBean.writeLog("FileDownloadForOdocExchange.getCompanyIdByUser 执行sql:sqlForReceiveOrSendUser"+sqlForReceiveOrSendUser+"参数:user.getUID()="+user.getUID()+"失败或查询数据为空"); -// } -// return companyId; -// } -// -// /** -// * 判断此后缀是否允许inline模式打开 -// * @param extname -// * @return -// */ -// private boolean inlineViewFile(String extname){ -// if(extname.isEmpty()) return false; -// String whiteListstr = Util.null2s(baseBean.getPropValue("doc_upload_suffix_limit","inline_ext"),"pdf,jpg,jpeg,png,bmp,gif"); -// String [] whiteList = whiteListstr.split(","); -// String ext = ""; -// for(int i=0;i0){ -// Map encryptInfo = DocEncryptUtil.EncryptInfo(docid); -// if(encryptInfo!=null){ -// String isEnableSecondAuth=Util.null2String(encryptInfo.get(DocEncryptUtil.ISENABLESECONDAUTH),"0"); -// if("1".equals(isEnableSecondAuth)){ -// StringBuilder requParamStr = new StringBuilder(); -// Enumeration paramNames = req.getParameterNames(); -// while (paramNames.hasMoreElements()) { -// String paramName = (String) paramNames.nextElement(); -// String paramValue = Util.null2String(req.getParameter(paramName)); -// if(paramName.contains("request_header_user_agent") || paramName.contains("param_ip")) continue; -// requParamStr.append("&").append(paramName).append("=").append(paramValue); -// } -// if(fromMobile){ -// secondAuthFileDownUrl= GCONST.getContextPath()+"/spa/custom/static4mobile/index.html#/cs/app/2e1b09c0329c4e839002365027216f64_baseTable?isSecondAuth=1"+requParamStr; -// }else{ -// secondAuthFileDownUrl= GCONST.getContextPath()+"/spa/custom/static/index.html#/main/cs/app/759eb4fa5ce742c2a0b96877972ceae0_baseTable?isSecondAuth=1"+requParamStr; -// } -// toWriteLog("FileDownload-------------getSecondAuthFileDownUrl------docid------"+docid+";fromMobile="+fromMobile+";secondAuthFileDownUrl="+secondAuthFileDownUrl); -// } -// } -// } -// }catch(Exception e){ -// toWriteLog("FileDownload-------------getSecondAuthFileDownUrl------docid------"+docid+";fromMobile="+fromMobile+";Exception="+e); -// } -// return secondAuthFileDownUrl; -// } -// -// /** -// * 2447956 wgs 当是下载文件请求,并且文件所在目录开启下载水印时, -// * 验证文件加密类型,如果是加密文件, -// * 不允许通过服务加水印(服务加水印是在文件解密后操作的,这样下载的就不是原加密文件了) -// */ -// public void shouldAddFileDownLoadWm(Map secWmSetMap, String imageFileId) { -// RecordSet rs = new RecordSet(); -// try { -// String wmfordownload = Util.null2String(secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD)); -// rs.writeLog("shouldAddFileDownLoadWm 1 wmfordownload=" + wmfordownload); -// if (secWmSetMap == null || secWmSetMap.size() == 0 || !"1".equals(downloadFlag) || !"1".equals(wmfordownload)) { -// return; -// } -// rs.executeQuery("select encryptType from imagefile where imagefileid=?", imageFileId); -// rs.next(); -// String encryptType = rs.getString("encryptType"); -// rs.writeLog("shouldAddFileDownLoadWm 1 encryptType=" + encryptType + ",imageFileId=" + imageFileId); -// if (StringUtils.isBlank(encryptType)) { -// EncryptDecryptFileUtil.updateFileEncryptInfo(Util.getIntValue(imageFileId)); -// rs.executeQuery("select encryptType from imagefile where imagefileid=?", imageFileId); -// rs.next(); -// encryptType = rs.getString("encryptType"); -// } -// rs.writeLog("shouldAddFileDownLoadWm 2 encryptType=" + encryptType); -// if (StringUtils.isNotBlank(encryptType) && !"1".equals(encryptType)) { -// secWmSetMap.put(WaterMarkUtil.SECCATEGORYDOWNLOAD, "0"); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// rs.writeLog("2 secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD)=" + secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD)); -// } -// } \ No newline at end of file + rs.executeSql("select docId from docImageFile where imageFileId="+fileId); + while(rs.next()){ + hasRight=false; + docId=rs.getString(1); + if(docId!=null&&!docId.equals("")){ + docIdList.add(docId); + } + } + boolean previewSensitive = false; + String comefrom=""; + String originComeFrom=""; + if(docIdList.size()==0){ + int fileId_related=0; + int docId_related=0; + boolean hasDocId=false; + rs.executeSql("select comefrom from ImageFile where imageFileId="+fileId); + if(rs.next()){ + comefrom=Util.null2String(rs.getString("comefrom")); + } + String comefrom_noNeedLogin=Util.null2String(rs.getPropValue("FileDownload","comefrom_noNeedLogin")); + if((","+comefrom_noNeedLogin+",").indexOf(","+comefrom+",")>=0){ + hasRight=true; + return hasRight; + } + if(comefrom.equals("DocPreview")||comefrom.equals("DocPreviewHistory")){ + rs.executeSql("select imageFileId,docId from "+comefrom+" where (pdfFileId="+fileId+" or swfFileId="+fileId+") order by id desc"); + if(rs.next()){ + fileId_related=Util.getIntValue(rs.getString("imageFileId"),0); + //docId_related=Util.getIntValue(rs.getString("docId"),0); + } + if(docId_related>0){ + docIdList.add(""+docId_related); + hasDocId=true; + } + }else if(comefrom.equals("DocPreviewHtml")||comefrom.equals("DocPreviewHtmlHistory")){ + rs.executeSql("select imageFileId,docId from "+comefrom+" where htmlFileId="+fileId+" order by id desc"); + if(rs.next()){ + fileId_related=Util.getIntValue(rs.getString("imageFileId"),0); + // docId_related=Util.getIntValue(rs.getString("docId"),0); + } + if(docId_related>0){ + docIdList.add(""+docId_related); + hasDocId=true; + } + isHtmlPreview = true; + }else if(comefrom.equals("DocPreviewHtmlImage")){ + rs.executeSql("select imageFileId,docId from DocPreviewHtmlImage where picFileId="+fileId+" order by id desc"); + if(rs.next()){ + fileId_related=Util.getIntValue(rs.getString("imageFileId"),0); + //docId_related=Util.getIntValue(rs.getString("docId"),0); + } + if(docId_related>0){ + docIdList.add(""+docId_related); + hasDocId=true; + } + } + // 处理敏感词高亮 + if(isHtmlPreview && fileId_related > 0) { + int originalFileId = -1; + String querySql = "select original_fileid from imagefile where IMAGEFILEID = " + fileId_related +" and sensitive_wtype = 1"; + rs.executeQuery(querySql); + if(rs.next()) { + originalFileId = rs.getInt(1); + } + if(originalFileId > 0) { + fileId_related = originalFileId; + previewSensitive = true; + } + } + if(!hasDocId&&fileId_related>0){ + rs.executeSql("select distinct docId from docImageFile where imageFileId="+fileId_related); + while(rs.next()){ + docId=rs.getString(1); + if(docId!=null&&!docId.equals("")){ + docIdList.add(docId); + } + } + } + + if(fileId_related > 0){ + originComeFrom = comefrom; + rs.executeSql("select comefrom from ImageFile where imageFileId="+fileId_related); + if(rs.next()){ + comefrom=Util.null2String(rs.getString("comefrom")); + } + fileId = fileId_related + ""; + } + + if(!hasDocId && fileId_related == 0){ + extName = extName.toLowerCase(); + if(extName.equals("jpg") || + extName.equals("jpeg") || + extName.equals("png") || + extName.equals("gif") || + extName.equals("bmp")){ + + int _docid = Util.getIntValue(req.getParameter("docid")); + if(_docid > 0){ + rs.executeQuery("select id from DocDetail where id=? and themeshowpic=?",_docid,fileId); + if(rs.next()){ + docIdList.add(rs.getString("id")); + } + } + } + } + + } + if(docIdList.size()>0){ + hasRight=false; + } + String mustLogin=Util.null2String(rs.getPropValue("FileDownload","mustLogin")); + int votingId=Util.getIntValue(req.getParameter("votingId"),0); + if(fromMobile && votingId<=0){ + votingId = Util.getIntValue(Util.null2String(jsonParams.get("votingId")),0); + } + + if(user==null && fromMobile){ + user = new User(_userid); + } + + if(user==null){ + if(mustLogin.equals("1")){ + hasRight=false; + } + return hasRight; + } + if(!fromMobile){ + String f_weaver_belongto_userid=Util.null2String(req.getParameter("f_weaver_belongto_userid"));//需要增加的代码 + String f_weaver_belongto_usertype=Util.null2String(req.getParameter("f_weaver_belongto_usertype"));//需要增加的代码 + user = HrmUserVarify.getUser(req, res, f_weaver_belongto_userid, f_weaver_belongto_usertype) ;//需要增加的代码 + } + String workplanid=Util.null2String(req.getParameter("workplanid")); + if(fromMobile){ + workplanid = Util.null2String(jsonParams.get("workplanid")); + } + + if(user==null){ + user = (User)req.getSession(true).getAttribute("weaver_user@bean") ; + } + if(user==null){ + if(mustLogin.equals("1")){ + hasRight=false; + } + return hasRight; + } + String comefrom_noNeedAuth=Util.null2String(rs.getPropValue("FileDownload","comefrom_noNeedAuth")); + if((","+comefrom_noNeedAuth+",").indexOf(","+comefrom+",")>=0){ + hasRight=true; + return hasRight; + } + if(comefrom.equals("VotingAttachment")){ // + VotingManager votingManager = new VotingManager(); + return votingManager.hasRightByFileid(votingId, Util.getIntValue(fileId,0), user); + } + + DocManager docManager=new DocManager(); + String docStatus=""; + int isHistory=0; + int secCategory=0; + String docPublishType="";//文档发布类型 1:正常(不发布) 2:新闻 3:标题新闻 + boolean useNewRightCheck = 1 == Util.getIntValue(baseBean.getPropValue("FileDownload","useNewRightCheck"),1); + DocViewPermission dvp = new DocViewPermission(); + for(int i=0;i shareLevelMap = dvp.getShareLevel(Util.getIntValue(docId), user, false); + canReader = shareLevelMap.get(DocViewPermission.READ); + hasRight = shareLevelMap.get(DocViewPermission.DOWNLOAD); + } else { + String userSeclevel = user.getSeclevel(); + String userType = ""+user.getType(); + String userDepartment = ""+user.getUserDepartment(); + String userSubComany = ""+user.getUserSubCompany1(); + String userInfo=loginType+"_"+userId+"_"+userSeclevel+"_"+userType+"_"+userDepartment+"_"+userSubComany; + + ArrayList PdocList = null; + + SpopForDoc spopForDoc=new SpopForDoc(); + PdocList = spopForDoc.getDocOpratePopedom(""+docId,userInfo); + + SecCategoryComInfo secCategoryComInfo=new SecCategoryComInfo(); + + //1:编辑 + boolean canEdit = false; + //5:下载 + if (((String)PdocList.get(0)).equals("true")) {canReader = true ;} + if (((String)PdocList.get(1)).equals("true")) {canEdit = true ;} + if (((String)PdocList.get(5)).equals("true")) {hasRight = true ;}//TD12005 + + String readerCanViewHistoryEdition=secCategoryComInfo.isReaderCanViewHistoryEdition(secCategory)?"1":"0"; + + if(canReader && ((!docStatus.equals("7")&&!docStatus.equals("8")) + ||(docStatus.equals("7")&&isHistory==1&&readerCanViewHistoryEdition.equals("1")) + )){ + canReader = true; + }else{ + canReader = false; + } + + if(isHistory==1) { + if(secCategoryComInfo.isReaderCanViewHistoryEdition(secCategory)){ + if(canReader && !canEdit) canReader = true; + } else { + if(canReader && !canEdit) canReader = false; + } + } + + if(canEdit && ((docStatus.equals("3") || docStatus.equals("5") || docStatus.equals("6") || docStatus.equals("7")) || isHistory==1)) { + canEdit = false; + canReader = true; + } + + if(canEdit && (docStatus.equals("0") || docStatus.equals("1") || docStatus.equals("2") || docStatus.equals("7")) && (isHistory!=1)) + canEdit = true; + else + canEdit = false; + } + + if(previewSensitive && (canReader || hasRight)) { + return true; + } + if((isPdf||isHtmlPreview) && !"1".equals(download) && !hasRight && canReader){ + hasRight = true; + } + if(canReader){ + //String referer = req.getHeader("Referer"); + //String ismobile=req.getHeader("User-Agent"); + if(isimage){ + hasRight=true; + } + } + if(hasRight) { + return hasRight; + } + //E9流程判断 + String authStr = Util.null2String(req.getParameter("authStr")); + String authSignatureStr = Util.null2String(req.getParameter("authSignatureStr")); + toWriteLog("weaver-->2505-->fileid"+fileId+"--->hasRight"+hasRight); + toWriteLog("weaver-->2505-->fileid"+fileId+"--->canReader"+canReader); + toWriteLog("weaver-->2505-->fileid"+fileId+"--->isExtfile"+isExtfile); + toWriteLog("weaver-->2505-->fileid"+fileId+"--->authStr"+authStr); + toWriteLog("weaver-->2505-->fileid"+fileId+"--->authSignatureStr"+authSignatureStr); + + if(!canReader && ((!authStr.isEmpty() && !authSignatureStr.isEmpty()) || requestid>0)){ + RequestAuthenticationService e9wf = new RequestAuthenticationService(); + e9wf.setUser(user); + e9wf.setAuthResouceType(1); + e9wf.setAuthResouceId(docId); + hasRight = e9wf.verify(req, requestid); + if(!hasRight){ + rs.writeLog("^^^^^^ E9流程判断附件下载没权限(" + fileId + ")("+docId+")^^^^^^^^requestid=" + + requestid + ",authStr=" + authStr + ",authSignatureStr=" + authSignatureStr); + Map otherParams = new HashMap(); + otherParams.put("requestid", requestid + ""); + otherParams.put("ismonitor", 1 + ""); + hasRight = e9wf.getRequestMonitorRight(otherParams,requestid); + if(!hasRight){ + rs.writeLog("^^^^^^ E9流程判断流程监控附件下载没权限(" + fileId + ")("+docId+")^^^^^^^^requestid=" + + requestid + ",authStr=" + authStr + ",authSignatureStr=" + authSignatureStr); + } + } + } + + if(!canReader&&!hasRight) {//如果没有查看权限,判断是否通过协作区赋权 + int desrequestid = Util.getIntValue(req.getParameter("desrequestid")); + int wfdesrequestid = Util.getIntValue(String.valueOf(req.getSession().getAttribute("desrequestid")),0); + //System.out.println("wfdesrequestid = "+wfdesrequestid); + int coworkid = Util.getIntValue(req.getParameter("coworkid")); + if(fromMobile){ + desrequestid = Util.getIntValue(Util.null2String(jsonParams.get("desrequestid"))); + wfdesrequestid = Util.getIntValue( Util.null2String(jsonParams.get("desrequestid"))); + coworkid = Util.getIntValue( Util.null2String(jsonParams.get("coworkid"))); + } + CoworkDAO coworkDAO=new CoworkDAO(coworkid); + VotingManager votingManager=new VotingManager(); + Map parameterMap=new HashMap(); + parameterMap.put("docId",Util.getIntValue(docId)); + parameterMap.put("votingId",votingId); + parameterMap.put("userId",user.getUID()); + //微博下载权限 + BlogDao blogDao=new BlogDao(); + int blogDiscussid = Util.getIntValue(req.getParameter("blogDiscussid"),0); + if(fromMobile && blogDiscussid<=0){ + blogDiscussid = Util.getIntValue( Util.null2String(jsonParams.get("blogDiscussid"))); + } + /*WFUrgerManager wfum=new WFUrgerManager(); + RequestAnnexUpload rau=new RequestAnnexUpload(); + if (!wfum.OperHaveDocViewRight(requestid,user.getUID(),Util.getIntValue(loginType,1),""+docId) + &&!wfum.OperHaveDocViewRight(requestid,desrequestid,Util.getIntValue(userId),Util.getIntValue(loginType),""+docId) + &&!wfum.getWFShareDesRight(requestid,wfdesrequestid,user,Util.getIntValue(loginType),""+docId) + &&!wfum.getWFChatShareRight(requestid,Util.getIntValue(userId),Util.getIntValue(loginType),""+docId) + &&!wfum.UrgerHaveDocViewRight(requestid,Util.getIntValue(userId),Util.getIntValue(loginType),""+docId) + &&!wfum.getMonitorViewObjRight(requestid,Util.getIntValue(userId),""+docId,"0") + &&!wfum.getWFShareViewObjRight(requestid,user,""+docId,"0") + &&!rau.HaveAnnexDocViewRight(requestid,Util.getIntValue(userId),Util.getIntValue(loginType),Util.getIntValue(docId)) + &&!coworkDAO.haveRightToViewDoc(userId,docId)&&!votingManager.haveViewVotingDocRight(parameterMap) + &&!blogDao.appViewRight("doc",userId,Util.getIntValue(docId,0),blogDiscussid)){ + hasRight=false; + } else { + hasRight = true ; + }*/ + if(!coworkDAO.haveRightToViewDoc(userId,docId)&&!votingManager.haveViewVotingDocRight(parameterMap) + &&!blogDao.appViewRight("doc",userId,Util.getIntValue(docId,0),blogDiscussid)){ + hasRight=false; + } else { + hasRight = true ; + } + } + if(!canReader&&!hasRight) {//如果没有查看权限,判断是否通过会议赋权 + int meetingid = Util.getIntValue(req.getParameter("meetingid")); + MeetingUtil MeetingUtil = new MeetingUtil(); + if (meetingid>0){ + hasRight=MeetingUtil.UrgerHaveMeetingDocViewRight(meetingid+"",user,Util.getIntValue(loginType),""+docId); + } else{ + hasRight =MeetingUtil.UrgerHaveMeetingDocViewRight(user,Util.getIntValue(loginType),""+docId); + } + } + + if(!canReader&&!hasRight && !workplanid.equals("")) {//如果没有查看权限,判断是否通过日程赋权 + WorkPlanService workPlanService = new WorkPlanService(); + if (!workPlanService.UrgerHaveWorkplanDocViewRight(workplanid,user,Util.getIntValue(loginType),""+docId)){ + hasRight=false; + } else { + hasRight = true ; + } + } + //判断是否计划任务赋权 + String fromworktask = Util.getFileidIn(Util.null2String(req.getParameter("fromworktask"))); + String operatorid = Util.getFileidIn(Util.null2String(req.getParameter("operatorid"))); + if(fromMobile){ + fromworktask = Util.null2String(jsonParams.get("blogDiscussid")); + operatorid = Util.null2String(jsonParams.get("operatorid")); + } + if("1".equals(fromworktask)) { + /* WTRequestUtil WTRequestUtil = new WTRequestUtil(); + if(!canReader&&!hasRight) { + if(!WTRequestUtil.UrgerHaveWorktaskDocViewRight(requestid,Util.getIntValue(userId),Util.getIntValue(docId,0),Util.getIntValue(operatorid,0))) { + hasRight=false; + } else { + hasRight = true ; + } + } else { + hasRight=true; + }*/ + } + //如果没有权限,看到是否具有客户联系查看权限 + if(!canReader&&!hasRight) {//如果没有查看权限,判断是否通过会议赋权 + CrmShareBase crmshare = new CrmShareBase(); + String crmid = Util.null2String(req.getParameter("crmid")); + if(fromMobile){ + crmid = Util.null2String(jsonParams.get("crmid")); + } + int sharetype = crmshare.getRightLevelForCRM(userId+"",crmid,loginType); + String crmtype = Util.null2String(req.getParameter("crmtype")); + if(fromMobile){ + crmtype = Util.null2String(jsonParams.get("crmtype")); + } + if(crmtype == null || "".equals(crmtype))crmtype = "0"; + if (sharetype > 0 && crmshare.checkCrmFileExist(crmid, fileId, crmtype)){ + //CoworkDAO coworkDAO = new CoworkDAO(); + //coworkDAO.shareCoworkRelateddoc(Util.getIntValue(loginType),Util.getIntValue(docId,0),Util.getIntValue(userId)); + hasRight= true; + } else { + hasRight = false; + } + } + // 如果没有下载权限,查找是否协作区附件赋权 + if(!hasRight) { + int coworkid = Util.getIntValue(req.getParameter("coworkid")); + if(fromMobile){ + coworkid = Util.getIntValue(Util.null2String(jsonParams.get("coworkid"))); + } + CoworkDAO coworkDAO = new CoworkDAO(coworkid); + hasRight = coworkDAO.haveRightToViewDoc(userId,docId); + } + + //财务模块 发票影像 + String cwid = req.getParameter("cwid"); + toWriteLog("weaver-->2679-->fileid"+fileId+"--->cwid"+cwid); + toWriteLog("weaver-->2679-->fileid"+fileId+"--->hasRight"+hasRight); + if(!hasRight && "fna".equals(cwid)){ + hasRight = weaver.fna.invoice.utils.ImagePermissionUtil.checkImagePermission(Util.getIntValue(fileId),user); + if(!hasRight){ + rs.writeLog("^^^^^^ 财务模块 发票影像 财务判断附件下载没权限(" + fileId + ")("+docId+")^^^^^^^^"); + } + } + toWriteLog("weaver-->2687-->fileid"+fileId+"--->hasRight"+hasRight); + + //财务模块 微报账规则制度 + if(!hasRight && "fna".equals(cwid)){ + RecordSet rs_ruleSystem = new RecordSet(); + //获取规则制度 + int ruleSystem = 0; + rs_ruleSystem.executeQuery("select ruleSystem from fnaInvoiceEnterWay "); + if(rs.next()){ + ruleSystem = Util.getIntValue(rs_ruleSystem.getString("ruleSystem"),0); + } + if(ruleSystem==Util.getIntValue(fileId) && ruleSystem!=0){ + hasRight = true; + } + } + toWriteLog("weaver-->2892-->fileid"+fileId+"--->hasRight"+hasRight); + + + if(new DocViewPermission().hasRightFromOtherMould(Util.getIntValue(docId),user,req)){ + hasRight = true; + if("1".equals(download)){ + hasRight=new DocViewPermission().hasDownRightFromFormMode(Util.getIntValue(docId),user,req); + } + } + + if(hasRight){ + return hasRight; + } + } + //文档模块 附件查看权限控制 结束 + + if("email".equals(req.getParameter("model"))){ //邮件附件转html + + boolean emailFlag = new MailFilePreviewService().getViewRightByHtmlCode(user.getUID(),fileId); //fileId + + if(emailFlag){ + return true; + }else{ + rs.writeLog("^^^^^^ email判断附件下载没权限(" + fileId + ")^^^^^^^^"); + return false; + } + } + + + if(docIdList.size()==0 && "EMforEC".equals(comefrom)){ + hasRight = false; + } + //检查社交平台附加权限 + if(!hasRight && "EMforEC".equals(comefrom)){ + //hasRight=SocialIMService.checkFileRight(user, fileId, isDocFile, hasRight); + if(!groupid.isEmpty()){ + rs.executeQuery("select groupid from social_IMFileShareGroup where groupid=? and fileid=?",groupid,Util.getIntValue(fileId)); + if(rs.next()){ + hasRight = true; + } + } + if(!hasRight){ + rs.executeQuery("select id from social_IMFileShare where userid=? and fileid=?",user.getUID(),Util.getIntValue(fileId)); + if(rs.next()){ + hasRight = true; + } + } + + + }else if(!hasRight && "EMforECNoRight".equals(comefrom)){ + hasRight = true; + }else if(!hasRight){ + hasRight=SocialIMService.checkFileRight(user, fileId, isDocFile, hasRight); + } + + if(!hasRight) {//查看是否有建模关联授权 + //表单建模判断关联授权 + String formmodeflag = StringHelper.null2String(req.getParameter("formmode_authorize")); + Map formmodeAuthorizeInfo = new HashMap(); + //formmodeparas+="&formmode_authorize="+formmodeflag; + if(formmodeflag.equals("formmode_authorize")){ + int modeId = 0; + int formmodebillId = 0; + int fieldid = 0; + int formModeReplyid = 0; + modeId = Util.getIntValue(req.getParameter("authorizemodeId"),0); + formmodebillId = Util.getIntValue(req.getParameter("authorizeformmodebillId"),0); + fieldid = Util.getIntValue(req.getParameter("authorizefieldid"),0); + formModeReplyid = Util.getIntValue(req.getParameter("authorizeformModeReplyid"),0); + String fMReplyFName = Util.null2String(req.getParameter("authorizefMReplyFName")); + if(fromMobile && modeId <= 0){ + modeId = Util.getIntValue(Util.null2String(jsonParams.get("authorizemodeId"))); + formmodebillId = Util.getIntValue(Util.null2String(jsonParams.get("authorizeformmodebillId"))); + fieldid = Util.getIntValue(Util.null2String(jsonParams.get("authorizefieldid"))); + formModeReplyid = Util.getIntValue(Util.null2String(jsonParams.get("authorizeformModeReplyid"))); + fMReplyFName = Util.null2String(jsonParams.get("fMReplyFName")); + } + + ModeRightInfo modeRightInfo = new ModeRightInfo(); + modeRightInfo.setUser(user); + if(formModeReplyid!=0){ + formmodeAuthorizeInfo = modeRightInfo.isFormModeAuthorize(formmodeflag, modeId, formmodebillId, fieldid, Util.getIntValue(docId), formModeReplyid,fMReplyFName); + }else{ + formmodeAuthorizeInfo = modeRightInfo.isFormModeAuthorize(formmodeflag, modeId, formmodebillId, fieldid, Util.getIntValue(docId)); + } + } + + if("1".equals(formmodeAuthorizeInfo.get("AuthorizeFlag"))){//如果是表单建模的关联授权,那么直接有查看权限 + hasRight = true; + } + } + + if (!hasRight) { + //数据中心查看文档权限 + String edcFlag = StringHelper.null2String(req.getParameter("edc_authorize")); + if (edcFlag.equals("edc_authorize")) { + int formid = Util.getIntValue(req.getParameter("authorizeFormId"), 0); + int billid = Util.getIntValue(req.getParameter("authorizeBillId"), 0); + int fieldid = Util.getIntValue(req.getParameter("authorizeFieldId"), 0); + hasRight = JoinCubeBiz.checkDocViewPermission(user, formid, billid, fieldid, Util.getIntValue(docId)); + } + } + + //建模扩展查看文档权限 + if (!hasRight) { + String ecmeflag = StringHelper.null2String(req.getParameter("ecme_authorize")); + if (ecmeflag.equals("ecme_authorize")) { + int billid = Util.getIntValue(req.getParameter("authorizebillId"), 0); + int fieldid = Util.getIntValue(req.getParameter("authorizefieldid"), 0); + int feaId = Util.getIntValue(req.getParameter("authorizefeaId"), 0); + EcmeRightManager erm = new EcmeRightManager(user,feaId); + hasRight = erm.ecmeAuthorize( billid, fieldid,Util.getIntValue(docId)); + } + } + + //财务模块微报账记一笔 + String cwid = req.getParameter("cwid"); + if(!hasRight && "fnaRemember".equals(cwid)){ + int count=0; + rs.executeQuery("select count(id) cnt from fnaTakeOneNote where imageid=?",fileId); + if(rs.next()){ + count = Util.getIntValue(rs.getString("cnt"),0); + } + if(count>0){ + hasRight = true; + } + } + if(hasRight) { + return hasRight; + } + toWriteLog("weaver-->2702-->fileid"+fileId+"--->hasRight"+hasRight); + String isHaveDocSql = "select 1 from docimagefile where imagefileid = ?"; + Boolean isHaveDoc = false; + rs.executeQuery(isHaveDocSql,fileId); + if(rs.next()) isHaveDoc = true; + //如果附件无文档文档,且无权限看, + if(!hasRight && !isHaveDoc){ + String fileidStr = Util.null2s(req.getParameter("fileid"),""); + String jmFileidStr = Util.null2s(req.getParameter("jmFileid"),""); + String fieldidsStr = Util.null2s(req.getParameter("fieldids"),""); + int fileid = Util.getIntValue(DocDownloadCheckUtil.getDownloadfileid(req), -1); + String fieldids = Util.null2String(DocDownloadCheckUtil.getDownloadfileid(req)); + //如果是加密串并且fileid存在,则可以下载 如果是批量下载,需要不含逗号,长度大于11(防止只有一个附件id的情况),并且附件id存在 + if((fileidStr.length()>11 && fileid>0) ||(jmFileidStr.length()>11 && fileid>0) || (!fieldidsStr.contains(",") && fileId!=null && !fileId.trim().equals("") && fieldidsStr.length()>11)){ + hasRight = true; + } + } + /** + * 判断是否来自云盘分享的下载 + */ + // if(!hasRight){ 加密串导致hasRight为true,从而云盘文件不进此判断逻辑 + hasRight = FiledownloadUtil.netdiskHasright(hasRight,fileid_head,user); + //} + /** + * 判断是否来自云盘的poi转换 + */ + if(comefrom != null && !comefrom.isEmpty() || !originComeFrom.isEmpty()) { + String sql = ""; + if (comefrom.isEmpty()) { + comefrom = originComeFrom; + } + if("DocPreviewHtmlImage".equals(comefrom)){ + sql ="select imageFileId from DocPreviewHtmlImage where picFileId=?"; + }else if("DocPreviewHtml".equals(comefrom)){ + sql = "select imagefileid from DocPreviewHtml where htmlFileId=?" ; + }else if("pdfconvert".equals(comefrom)){ + sql = "select imagefileid from pdf_imagefile where pdfimagefileid=?"; + } + if(!sql.isEmpty()){ + rs.executeQuery(sql,fileid_head); + if(rs.next()){ + String _fileid = rs.getString("imagefileid"); + hasRight = FiledownloadUtil.netdiskHasright(hasRight,_fileid,user); + } + } + } + //判断附件是否来源于回复 + String isFromReplySql = "select 1 from reply_imagefile where imagefileid=?"; + rs.executeQuery(isFromReplySql,fileId); + if(rs.next()){ + hasRight = true; + } + + //pdf附件判断user权限是否一致 + cwid = req.getParameter("cwid"); + if("compared".equals(cwid)){ + String sqlDetail = " select mainid from FnaDocCompareDetail where 1=1 "+ + "and (leftSrc = ? or leftSrc2 = ? or rightSrc = ? or rightSrc2 = ? ) "; + rs.executeQuery(sqlDetail, fileId,fileId,fileId,fileId); + int mainId = 0; + if(rs.next()){ + mainId = Util.getIntValue(rs.getString("mainid"),0); + } + + rs.executeQuery(" select userid from FnaDocCompare where id = ? ", mainId); + if(rs.next()){ + int userIdMain = Util.getIntValue(rs.getString("userid")); + if(userIdMain != user.getUID()){ + hasRight = false; + }else{ + hasRight = true; + } + } + + if(!hasRight){ + String sqlMain = " select userid from FnaDocCompare where 1=1 and (left_entry_ids = ? or left_pdf_id = ? or right_entry_ids = ? or right_pdf_id = ?) "; + rs.executeQuery(sqlMain, fileId,fileId,fileId,fileId); + if(rs.next()){ + int userIdMain = Util.getIntValue(rs.getString("userid")); + if(userIdMain != user.getUID()){ + hasRight = false; + }else{ + hasRight = true; + } + } + } + + } + baseBean.writeLog("weaver-->2917-->fileid"+fileId+"--->hasRight:"+hasRight); + + return hasRight; + } + + // 下载公用方法 + + public void toUpload(HttpServletResponse response,String str){ + toUpload(response,str,str); + } + + public void toUpload(HttpServletResponse response,String str, String tmptfilename){ + try { + + SystemComInfo syscominfo = new SystemComInfo(); + String path= syscominfo.getFilesystem(); + if("".equals(path)){ + path = GCONST.getRootPath(); + path = path + "filesystem" + File.separatorChar+ "downloadBatch"+File.separatorChar+tmptfilename; + }else{ + if(path.endsWith(File.separator)){ + path += "downloadBatch"+File.separatorChar+File.separatorChar+tmptfilename; + + }else{ + path += File.separator+ "downloadBatch"+File.separatorChar+File.separatorChar+tmptfilename; + } + } + + //String path=GCONST.getRootPath()+ "downloadBatch"+File.separatorChar+str; + //String path="E:/bjls_ecology4.1_5.0/ecology/downloadBatch/"+str; + if(!"".equals(path)){ + File file=new File(path); + if(file.exists()){ + InputStream ins=null; + BufferedInputStream bins=null; + OutputStream outs=null; + BufferedOutputStream bouts=null; + try + { + + ins=new FileInputStream(path); + bins=new BufferedInputStream(ins);//放到缓冲流里面 + outs=response.getOutputStream();//获取文件输出IO流 + bouts=new BufferedOutputStream(outs); + response.setContentType("application/x-download");//设置response内容的类型 + if((agent.contains(" Chrome")||agent.contains("Safari") )&& !agent.contains("Edge")){ + response.setHeader("content-disposition", "attachment;filename=\"" + URLEncoder.encode(str.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")").replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", "").replaceAll("\\+", "%20").replaceAll("%28", "(") + .replaceAll("%29", ")").replaceAll("%7B","{").replaceAll("%7D","}").replaceAll("%5B","[").replaceAll("%5D","]").replaceAll("%40","@").replaceAll("%23","#").replaceAll("%25","%").replaceAll("%26","&") + .replaceAll("%2B","+")+ "\""); +// response.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(str.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); + }else if(agent.contains("Firefox")){ + // filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); + // res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); + +// filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); +// res.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\""); + // filename = "=?UTF-8?B?" + (new String(Base64.encodeBase64(filename.getBytes("UTF-8")))) + "?="; + // res.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename)); + + response.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(str.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); + }else{ + response.setHeader("content-disposition", "attachment; filename=\"" + URLEncoder.encode(str.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""),"UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")+"\""); + } + int bytesRead = 0; + byte[] buffer = new byte[8192]; + //开始向网络传输文件流 + while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) { + bouts.write(buffer, 0, bytesRead); + } + bouts.flush();//这里一定要调用flush()方法 + ins.close(); + bins.close(); + outs.close(); + bouts.close(); + } + catch (Exception ef) + { + new weaver.filter.XssUtil().writeError(ef); + } + finally { + + if(ins!=null) ins.close(); + if(bins!=null) bins.close(); + if(outs!=null) outs.close(); + if(bouts!=null) bouts.close(); + } + + } + else{ + response.sendRedirect(weaver.general.GCONST.getContextPath()+"/login/BatchDownloadsEror.jsp"); + } + } + else{ + response.sendRedirect(weaver.general.GCONST.getContextPath()+"/login/BatchDownloadsEror.jsp"); + + //注;这里面不要用到PrintWriter out=response.getWriter();这里调用了response对象,后面下载调用时就会出错。这里要是想都用,希望大家找到解决办法。 + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + *3:打包完成后删除原来的目中的文件 + * @param + * @param + * @throws Exception + */ + public void deleteFile(String targetPath) throws IOException { + File targetFile = new File(targetPath); + if (targetFile.isDirectory()) { + if(targetPath.indexOf("downloadBatchTemp")>-1){ + // FileUtils.deleteDirectory(targetFile); + new FileDeleteUtil().deleteFolder(targetFile); + } + } else if (targetFile.isFile()) { + FileSecurityUtil.deleteFile(targetFile); + //new FileDeleteUtil().deleteFile(targetFile); + } + } + /* + * + */ + public boolean addDownLoadLogByimageId( int fileid){ + boolean needUser = true; + int docId = 0; + String docIdsForOuterNews = ""; + // String strSql = "select id from DocDetail where exists (select 1 from docimagefile where imagefileid=" + fileid + " and docId=DocDetail.id) and ishistory <> 1 and (docPublishType='2' or docPublishType='3')"; + String strSql = "SELECT t1.id FROM DocDetail t1 INNER JOIN docimagefile t2 ON t1.id = t2.docId " + + "WHERE t2.imagefileid = ? AND t1.ishistory <> 1 AND ( t1.docPublishType = '2' OR t1.docPublishType = '3')"; + RecordSet rs = new RecordSet(); + rs.executeQuery(strSql,fileid); + while (rs.next()) { + docId = rs.getInt("id"); + if (docId > 0) { + docIdsForOuterNews += "," + docId; + } + } + + if (!docIdsForOuterNews.equals("")) { + docIdsForOuterNews = docIdsForOuterNews.substring(1); + } + + if (!docIdsForOuterNews.equals("")) { + String newsClause = ""; + String sqlDocExist = " select 1 from DocDetail where id in(" + docIdsForOuterNews + ") "; + String sqlNewsClauseOr = ""; + boolean hasOuterNews = false; + + rs.executeSql("select newsClause from DocFrontPage where publishType='0'"); + while (rs.next()) { + hasOuterNews = true; + newsClause = Util.null2String(rs.getString("newsClause")); + if (newsClause.equals("")) { + // newsClause=" 1=1 "; + needUser = false; + break; + } + if (!newsClause.trim().equals("")) { + sqlNewsClauseOr += " ^_^ (" + newsClause + ")"; + } + } + ArrayList newsArr = new ArrayList(); + if (!sqlNewsClauseOr.equals("") && needUser) { + // sqlNewsClauseOr=sqlNewsClauseOr.substring(sqlNewsClauseOr.indexOf("(")); + // sqlDocExist+=" and ("+sqlNewsClauseOr+") "; + String[] newsPage = Util.TokenizerString2(sqlNewsClauseOr, "^_^"); + int i = 0; + String newsWhere = ""; + for (; i < newsPage.length; i++) { + if (i % 10 == 0) { + newsArr.add(newsWhere); + newsWhere = ""; + newsWhere += newsPage[i]; + } else + newsWhere += " or " + newsPage[i]; + } + newsArr.add(newsWhere); + } + // System.out.print(sqlDocExist); + if (hasOuterNews && needUser) { + for (int j = 1; j < newsArr.size(); j++) { + String newsp = newsArr.get(j).toString(); + if (j == 1) + newsp = newsp.substring(newsp.indexOf("or") + 2); + sqlDocExist += "and(" + newsp + ")"; + rs.executeSql(sqlDocExist); + sqlDocExist = " select 1 from DocDetail where id in(" + docIdsForOuterNews + ") "; + if (rs.next()) { + needUser = false; + break; + } + } + } + } + + // 处理外网查看默认图片 + rs.executeSql("SELECT * FROM DocPicUpload WHERE Imagefileid=" + fileid); + if (rs.next()) { + needUser = false; + } + + return needUser; + } + /** + * creat Folder and File. + * @param String fileFoder, String fileName + * Copyright (c) 2010 + * Company weaver + * Create Time 2010-11-25 + * @author caizhijun001 + * @return File + */ + public File fileCreate(String fileFoder, String fileName){ + File foder = new File(fileFoder);//E:\dlxdq_ecology4.5\ecology\filesystem\201012\S 1450623393_.xls + File file = new File(fileFoder+fileName); + //如果文件夹不存在,则创建文件夹 + if(foder.exists()==false){ + foder.mkdirs();//多级目录 + //foder.mkdir();//只创建一级目录 + } + + if(file.exists()==true){//删除以前同名的txt文件 + try{ + FileSecurityUtil.deleteFile(file); + //new FileDeleteUtil().deleteFile(file); + }catch(Exception e){ + e.printStackTrace(); + } + } + //如果文件不存在,则创建文件 + if(file.exists()==false){ + try{ + file.createNewFile(); + }catch(IOException e){ + e.printStackTrace(); + } + } + return file; + } + + private boolean isMsgObjToDocument(){ + boolean isMsgObjToDocument=true; + + BaseBean basebean = new BaseBean(); + String mClientName=Util.null2String(basebean.getPropValue("weaver_obj","iWebOfficeClientName")); + boolean isIWebOffice2003 = (mClientName.indexOf("iWebOffice2003")>-1)?true:false; + String isHandWriteForIWebOffice2009=Util.null2String(basebean.getPropValue("weaver_obj","isHandWriteForIWebOffice2009")); + if(isIWebOffice2003||isHandWriteForIWebOffice2009.equals("0")){ + isMsgObjToDocument=false; + } + if(mClientName.indexOf("iWebOffice2009")>-1) + { + isMsgObjToDocument=true; + } + + return isMsgObjToDocument; + } + + private boolean isOfficeToDocument(String extName){ + boolean isOfficeForToDocument=false; + if("xls".equalsIgnoreCase(extName) || "doc".equalsIgnoreCase(extName)||"wps".equalsIgnoreCase(extName)||"ppt".equalsIgnoreCase(extName)||"docx".equalsIgnoreCase(extName)||"xlsx".equalsIgnoreCase(extName)||"pptx".equalsIgnoreCase(extName)){ + isOfficeForToDocument=true; + } + return isOfficeForToDocument; + } + + /** + *通过文件编号和单位编号判断此单位是否对此文件有下载权限 + * @param fileId 文件编号对应imagefile表中的imagefileId + * @param companyId 单位编号 + * @return true:有下载权限 false:无下载权限 + */ + private boolean isHaveDownloadRight(String fileId,String companyId){ + boolean isHaveDownloadRight = false; + if(StringUtil.isNull(fileId,companyId)){ + baseBean.writeLog("方法:FileDownloadForOdocExchange.isHaveDownloadRight 参数:fileId="+fileId+" companyId="+companyId); + return isHaveDownloadRight; + } + /**如何判断当前用户有下载权限*/ + RecordSet rs = new RecordSet(); + /**1:作废的文不允许下载 2:撤销的文不允许接收方下载*/ + /** + * 1:判断是否是发送方 + * 2:判断是否是接收方 + */ + String getIsSendDepartmentSql = ""; + String dbType = rs.getDBType(); + if("sqlserver".equals(dbType)){ + getIsSendDepartmentSql = "select * from odoc_exchange_docbase where send_companyid=? and (docimagefileid=? or ',' + attachimagefileids + ',' like '%,' + ? + ',%') and status!=5"; + }else if("mysql".equals(dbType)){ + getIsSendDepartmentSql = "select * from odoc_exchange_docbase where send_companyid=? and (docimagefileid=? or CONCAT(',',attachimagefileids,',') like CONCAT('%,',?,',%')) and status!=5"; + }else{ + getIsSendDepartmentSql = "select * from odoc_exchange_docbase where send_companyid=? and (docimagefileid=? or ',' || attachimagefileids || ',' like '%,' || ? || ',%') and status!=5"; + } + + boolean isGetIsSendDepartmentSql = rs.executeQuery(getIsSendDepartmentSql,companyId,fileId,fileId); + if(isGetIsSendDepartmentSql&&rs.next()){ + isHaveDownloadRight = true; + }else{ + baseBean.writeLog("方法:FileDownloadForOdocExchange.isHaveDownloadRight 执行sql:getIsSendDepartmentSql="+getIsSendDepartmentSql+" 无数据/作废状态的文不允许下载"); + } + String getIsReceiveDepartmentSql = ""; + if("sqlserver".equals(dbType)){ + getIsReceiveDepartmentSql = "select b.status from odoc_exchange_docbase a left join odoc_exchange_recieveinfo b on a.document_identifier=b.document_identifier where b.receive_companyid=? and (a.docimagefileid=? or ',' + a.attachimagefileids + ',' like '%,' + ? + ',%') and a.status!=5 and b.status!=4"; + }else if("mysql".equals(dbType)){ + getIsReceiveDepartmentSql = "select b.status from odoc_exchange_docbase a left join odoc_exchange_recieveinfo b on a.document_identifier=b.document_identifier where b.receive_companyid=? and (a.docimagefileid=? or CONCAT(',',attachimagefileids,',') like CONCAT('%,',?,',%')) and a.status!=5 and b.status!=4"; + }else{ + getIsReceiveDepartmentSql = "select b.status from odoc_exchange_docbase a left join odoc_exchange_recieveinfo b on a.document_identifier=b.document_identifier where b.receive_companyid=? and (a.docimagefileid=? or ',' || a.attachimagefileids || ',' like '%,' || ? || ',%') and a.status!=5 and b.status!=4"; + } + boolean isGetIsReceiveDepartmentSql = rs.executeQuery(getIsReceiveDepartmentSql,companyId,fileId,fileId); + if(isGetIsReceiveDepartmentSql&&rs.next()){ + isHaveDownloadRight = true; + }else{ + baseBean.writeLog("方法:FileDownloadForOdocExchange.isHaveDownloadRight 执行sql:getIsReceiveDepartmentSql="+getIsReceiveDepartmentSql+"无数据/作废/撤销状态的文不允许下载"); + } + return isHaveDownloadRight; + } + + /** + * 通过当前登录用户获取当前登陆用户所在单位编号 + * @param uesr 当前登录用户 + * @return 单位编号 + */ + private String getCompanyIdByUser(User user){ + String companyId = ""; + if(null==user){ + baseBean.writeLog("FileDownloadForOdocExchange.getCompanyIdByUser 参数:user"+user); + return companyId; + } + String sqlForReceiveOrSendUser="SELECT exchange_companyid FROM odoc_exchange_com_user WHERE userid=?"; + String sqlForCompanyAdminUser="SELECT exchange_companyid FROM odoc_exchange_com_admin WHERE admin_userid=?"; + RecordSet rs = new RecordSet(); + boolean isSqlForReceiveOrSendUser = rs.executeQuery(sqlForReceiveOrSendUser,user.getUID()); + if(isSqlForReceiveOrSendUser&&rs.next()){ + companyId = rs.getString("exchange_companyid"); + if(StringUtil.isNull(companyId)) { + boolean isSqlForCompanyAdminUser = rs.executeQuery(sqlForCompanyAdminUser,user.getUID()); + if(isSqlForCompanyAdminUser&&rs.next()){ + companyId = rs.getString("exchange_companyid"); + }else{ + baseBean.writeLog("FileDownloadForOdocExchange.getCompanyIdByUser 执行sql:sqlForCompanyAdminUser"+sqlForCompanyAdminUser+"参数:user.getUID()="+user.getUID()+"失败或查询数据为空"); + } + }else{ + baseBean.writeLog("FileDownloadForOdocExchange.getCompanyIdByUser 执行sql:sqlForReceiveOrSendUser"+sqlForReceiveOrSendUser+"参数:user.getUID()="+user.getUID()+"查询的单位编号为空"); + } + }else{ + baseBean.writeLog("FileDownloadForOdocExchange.getCompanyIdByUser 执行sql:sqlForReceiveOrSendUser"+sqlForReceiveOrSendUser+"参数:user.getUID()="+user.getUID()+"失败或查询数据为空"); + } + return companyId; + } + + /** + * 判断此后缀是否允许inline模式打开 + * @param extname + * @return + */ + private boolean inlineViewFile(String extname){ + if(extname.isEmpty()) return false; + String whiteListstr = Util.null2s(baseBean.getPropValue("doc_upload_suffix_limit","inline_ext"),"pdf,jpg,jpeg,png,bmp,gif"); + String [] whiteList = whiteListstr.split(","); + String ext = ""; + for(int i=0;i0){ + Map encryptInfo = DocEncryptUtil.EncryptInfo(docid); + if(encryptInfo!=null){ + String isEnableSecondAuth=Util.null2String(encryptInfo.get(DocEncryptUtil.ISENABLESECONDAUTH),"0"); + if("1".equals(isEnableSecondAuth)){ + StringBuilder requParamStr = new StringBuilder(); + Enumeration paramNames = req.getParameterNames(); + while (paramNames.hasMoreElements()) { + String paramName = (String) paramNames.nextElement(); + String paramValue = Util.null2String(req.getParameter(paramName)); + if(paramName.contains("request_header_user_agent") || paramName.contains("param_ip")) continue; + requParamStr.append("&").append(paramName).append("=").append(paramValue); + } + if(fromMobile){ + secondAuthFileDownUrl=weaver.general.GCONST.getContextPath()+"/spa/custom/static4mobile/index.html#/cs/app/2e1b09c0329c4e839002365027216f64_baseTable?isSecondAuth=1"+requParamStr; + }else{ + secondAuthFileDownUrl=weaver.general.GCONST.getContextPath()+"/spa/custom/static/index.html#/main/cs/app/759eb4fa5ce742c2a0b96877972ceae0_baseTable?isSecondAuth=1"+requParamStr; + } + toWriteLog("FileDownload-------------getSecondAuthFileDownUrl------docid------"+docid+";fromMobile="+fromMobile+";secondAuthFileDownUrl="+secondAuthFileDownUrl); + } + } + } + }catch(Exception e){ + toWriteLog("FileDownload-------------getSecondAuthFileDownUrl------docid------"+docid+";fromMobile="+fromMobile+";Exception="+e); + } + return secondAuthFileDownUrl; + } + + /** + * 2447956 wgs 当是下载文件请求,并且文件所在目录开启下载水印时, + * 验证文件加密类型,如果是加密文件, + * 不允许通过服务加水印(服务加水印是在文件解密后操作的,这样下载的就不是原加密文件了) + */ + public void shouldAddFileDownLoadWm(Map secWmSetMap, String imageFileId) { + RecordSet rs = new RecordSet(); + try { + String wmfordownload = Util.null2String(secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD)); + rs.writeLog("shouldAddFileDownLoadWm 1 wmfordownload=" + wmfordownload); + if (secWmSetMap == null || secWmSetMap.size() == 0 || !"1".equals(downloadFlag) || !"1".equals(wmfordownload)) { + return; + } + rs.executeQuery("select encryptType from imagefile where imagefileid=?", imageFileId); + rs.next(); + String encryptType = rs.getString("encryptType"); + rs.writeLog("shouldAddFileDownLoadWm 1 encryptType=" + encryptType + ",imageFileId=" + imageFileId); + if (StringUtils.isBlank(encryptType)) { + EncryptDecryptFileUtil.updateFileEncryptInfo(Util.getIntValue(imageFileId)); + rs.executeQuery("select encryptType from imagefile where imagefileid=?", imageFileId); + rs.next(); + encryptType = rs.getString("encryptType"); + } + rs.writeLog("shouldAddFileDownLoadWm 2 encryptType=" + encryptType); + if (StringUtils.isNotBlank(encryptType) && !"1".equals(encryptType)) { + secWmSetMap.put(WaterMarkUtil.SECCATEGORYDOWNLOAD, "0"); + } + } catch (Exception e) { + e.printStackTrace(); + } + rs.writeLog("2 secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD)=" + secWmSetMap.get(WaterMarkUtil.SECCATEGORYDOWNLOAD)); + } +} \ No newline at end of file diff --git a/weaver/interfaces/workflow/action/javacode/Action20231013103613.java b/weaver/interfaces/workflow/action/javacode/Action20231013103613.java new file mode 100644 index 0000000..4629dd7 --- /dev/null +++ b/weaver/interfaces/workflow/action/javacode/Action20231013103613.java @@ -0,0 +1,127 @@ +package weaver.interfaces.workflow.action.javacode; + +import com.api.formmode.page.util.Util; +import com.icbc.api.internal.apache.http.E; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.Action; +import weaver.general.BaseBean; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.*; + +/** + * Online custom action interface + * 增加平行流程已协办部门 + */ +public class Action20231013103613 extends BaseBean implements Action { + /** + * After selecting aciton after the process path node, this method will be executed after the node is submitted. + */ + @Override + public String execute(RequestInfo request) { + + String requestId = request.getRequestid(); + String tablename = request.getRequestManager().getBillTableName(); + + RecordSet rs = new RecordSet(); + try { + rs.executeQuery("select MAINREQUESTID from workflow_requestbase where requestid = ?" , requestId); + //查询主流程 + String mainrequestid = ""; + if(rs.next()){ + mainrequestid = Util.null2String(rs.getString("MAINREQUESTID")); + } + //查询平行流程request + ArrayList siblingRequestIds = new ArrayList<>(); + rs.executeQuery("select requestid from workflow_requestbase where MAINREQUESTID = ?" , mainrequestid); + while(rs.next()){ + String siblingRequestId = Util.null2String(rs.getString("requestid")); + siblingRequestIds.add(siblingRequestId); + } + writeLog("平行流程"+siblingRequestIds); + //当前流程的协办部门 + rs.execute("select * from " + tablename + " where requestid = " + requestId); + rs.next(); + String xbbm = rs.getString("xbbm"); + + // + HashMap xbbmMap = new HashMap<>(); + rs.execute("select * from " + tablename + " where requestid in (" + String.join(",",siblingRequestIds)+" )"); + while ( rs.next()){ + String mainid = rs.getString("id"); + String ycfxbbm = rs.getString("ycfxbbm"); + String newycfxbbm = mergeWithoutDuplicates(xbbm, ycfxbbm); + xbbmMap.put(mainid,newycfxbbm); + } + writeLog("修改平行流程"+xbbmMap); + xbbmMap.forEach((key,value) ->{ + rs.executeUpdate("update "+ tablename +" set ycfxbbm = ? where id = ?",value,key); + }); + }catch (Exception e){ + boolean error = true; + if (error) { + request.getRequestManager().setMessageid("90001"); + request.getRequestManager().setMessagecontent("System Abnormal Termination Process Submission!"); + } + } + return Action.SUCCESS; + } + + + + // public static String mergeWithoutDuplicates(String a, String b) { + // if (b == null || b.isEmpty()) { + // return a; + // } + // + // String[] idsA = a.split(","); + // String[] idsB = b.split(","); + // + // for (String idA : idsA) { + // boolean exists = false; + // for (String idB : idsB) { + // if (idA.equals(idB)) { + // exists = true; + // break; + // } + // } + // if (!exists) { + // b += "," + idA; + // } + // } + // return b; + // } + + + public static void main(String[] args) { + String a = "1,2,3,4,5"; + String b = "3,4,5,6,7"; + + b = mergeWithoutDuplicates(a, b); + System.out.println(b); // 输出: 3,4,5,6,7,1,2 + } + + public static String mergeWithoutDuplicates(String a, String b) { + Set setB = new HashSet<>(); + StringBuilder result = new StringBuilder(b); + + if (b != null && !b.isEmpty()) { + for (String id : b.split(",")) { + setB.add(id.trim()); + } + } + + for (String idA : a.split(",")) { + idA = idA.trim(); + if (!setB.contains(idA)) { + if (result.length() > 0) { + result.append(","); + } + result.append(idA); + } + } + + return result.toString(); + } + +} diff --git a/weaver/interfaces/workflow/action/javacode/Action20231015024217.java b/weaver/interfaces/workflow/action/javacode/Action20231015024217.java new file mode 100644 index 0000000..fac5258 --- /dev/null +++ b/weaver/interfaces/workflow/action/javacode/Action20231015024217.java @@ -0,0 +1,339 @@ +package weaver.interfaces.workflow.action.javacode; + +import com.dcfs.fts.common.error.FtpException; +import com.engine.custom.hg.util.HgUtils; +import com.engine.custom.sl.entity.*; +// import com.engine.util.SocketClientUtil; +import com.engine.util.SocketClientUtil; +import com.engine.util.XMLUtils; +import com.icbc.api.internal.apache.http.impl.cookie.S; +import com.weaver.general.Util; +import org.jsoup.Jsoup; +import weaver.conn.RecordSet; +import weaver.file.ImageFileManager; +import weaver.general.StringUtil; +import weaver.hrm.User; +import weaver.interfaces.workflow.action.Action; +import weaver.general.BaseBean; +import weaver.soa.workflow.request.RequestInfo; + +import java.io.*; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * 推送商旅节点后附加操作(推送商旅节点后附加操作 + * 生产环境 + */ +public class Action20231015024217 extends BaseBean implements Action { + /** + * After selecting aciton after the process path node, this method will be executed after the node is submitted. + */ + @Override + public String execute(RequestInfo request) { + writeLog("推送商旅节点后附加操作====>"); + // if(error) { + // request.getRequestManager().setMessageid("90001"); + // request.getRequestManager().setMessagecontent("System Abnormal Termination Process Submission!"); + // } + String requestId = request.getRequestid(); + String tablename = request.getRequestManager().getBillTableName(); + TravelToEsbBean toEsbBean = new TravelToEsbBean(); + //封装主表数据 + RecordSet rs = new RecordSet(); + String mainId = setMainForm(requestId, tablename, rs, toEsbBean); + writeLog("toEsbBean1====>"+toEsbBean); + writeLog("上传附件到ESB服务器====>"); + try { + fileToEsb(toEsbBean,requestId); + } catch (Exception e) { + request.getRequestManager().setMessageid("10001"); + request.getRequestManager().setMessagecontent(e.getMessage()); + return Action.FAILURE_AND_CONTINUE; + } + setFormDt1(mainId,tablename,rs,toEsbBean); + writeLog("toEsbBean2====>"+toEsbBean); + setFormDt2(mainId,tablename,rs,toEsbBean); + writeLog("toEsbBean3====>"+toEsbBean); + String Service_Body = ""+ toEsbBean.toXMLString()+"" ; + writeLog("toEsbBean4====>"+Service_Body); + try{ + EsbRequestHeader esbRequestHeader = new EsbRequestHeader(Util.getIntValue(mainId)); + writeLog("esbRequestHeader====>"+esbRequestHeader); + String Service_Header = TravelToEsbBean.convertObjectToXml(esbRequestHeader,"Service_Header"); + writeLog("esbRequestHeaderXML====>"+Service_Header); + String serviceXML = ""; + serviceXML = serviceXML + Service_Header + Service_Body; + serviceXML = serviceXML + ""; + writeLog("esbRequestHeaderXML====>"+serviceXML); + int byteArray = serviceXML.getBytes("UTF-8").length; + + // Calculate the length of the byte array + // int bytelength = byteArray.length; + String length = String.format("%08d", byteArray); + writeLog("XMLlength"+ length); + serviceXML = length + serviceXML; + writeLog("serviceXML==="+ serviceXML); + // serviceXML = new String(serviceXML.getBytes(StandardCharsets.UTF_8)); + writeLog("UTF_8_serviceXML==="+ serviceXML); + SocketClientUtil scketClient = new SocketClientUtil("14.1.71.90",10149); + String send = scketClient.send(serviceXML); + String substring = send.substring(0, 8); + String substring1 = send.substring(8); + Map map = XMLUtils.parseXMLToMap(substring1); + String retCd = map.get("retCd"); + String retCdDsc = map.get("retCdDsc"); + if ("9999".equals(retCd)){ + request.getRequestManager().setMessageid("9999"); + request.getRequestManager().setMessagecontent(retCdDsc); + return Action.FAILURE_AND_CONTINUE; + } + }catch (Exception e){ + e.printStackTrace(); + writeLog("构建XML异常"+e.getMessage()); + request.getRequestManager().setMessageid("10001"); + request.getRequestManager().setMessagecontent(e.getMessage()); + return Action.FAILURE_AND_CONTINUE; + } + // setFormDt1(); + return Action.SUCCESS; + } + + private void fileToEsb(TravelToEsbBean toEsbBean, String requestId) throws Exception { + // HashMap filePathMap = new HashMap<>(); + List acsryArray = toEsbBean.getAcsryArray(); + for (acsryItem acsryItem : acsryArray) { + String acsryNm = acsryItem.getAcsryNm(); + writeLog("acsryNm"+acsryNm); + ImageFileManager ifm = new ImageFileManager(); + ifm.getImageFileInfoById(Util.getIntValue(acsryNm,0)); + InputStream inputStream = ifm.getInputStream(); + String imageFileName = ifm.getImageFileName(); + writeLog("imageFileName"+imageFileName); + String[] filename = imageFileName.split("\\."); + String tempFilePath = ""; + try { + File tempFile = File.createTempFile(filename[0],filename.length ==2 ?filename[1]:""); + + // 创建一个输出流,将数据写入临时文件 + OutputStream outputStream = new FileOutputStream(tempFile); + + // 将输入流中的数据复制到输出流(即临时文件) + byte[] buffer = new byte[2048]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + tempFilePath = tempFile.getAbsolutePath(); + writeLog( "临时文件位置"+tempFilePath); + // 关闭输入流和输出流 + inputStream.close(); + outputStream.close(); + }catch (Exception e){ + e.printStackTrace(); + writeLog( "创建本地文件异常"+e.getMessage()); + throw new Exception("创建本地文件异常"); + } + //推送ESB服务器 + String ftpPath = ""; + try { + ftpPath = HgUtils.putFile(tempFilePath, requestId + File.separator + imageFileName); + } catch (FtpException e) { + e.printStackTrace(); + writeLog( "传输ESBftp异常"+e.getMessage()); + throw new Exception("传输ESBftp异常"); + } catch (IOException e) { + e.printStackTrace(); + writeLog( "传输ESBIO异常"+e.getMessage()); + throw new Exception("传输ESBftp异常"); + } + acsryItem.setAcsryNm(imageFileName); + acsryItem.setSavePath(ftpPath); + } + + } + + private String setMainForm(String requestId, String tablename, RecordSet rs ,TravelToEsbBean toEsbBean) { + rs.execute("select * from " + tablename + " where requestid = " + requestId); + String mainid = ""; + String fj = ""; + String spdfj = ""; + //表单数据 + if (rs.next()) { + mainid = rs.getString("id"); + //OA差旅报销单单据编号 + toEsbBean.setOaTrvlBnsExpnsAcctNo(rs.getString(Util.null2String("djbh"))); + //经办人工号 + toEsbBean.setOperatorNo(Util.null2String(rs.getString("jbrgh"))); + //经办人姓名 id + toEsbBean.setOperatorName(Util.null2String(rs.getString("jbrxm"))); + String lastname = new User(Util.getIntValue(toEsbBean.getOperatorName())).getLastname(); + toEsbBean.setOperatorName(lastname); + + //附件张数 + toEsbBean.setAcsryNums(Util.null2String(rs.getString("fjzs"))); + //报销金额 + toEsbBean.setExpnsAmt(multiply100(Util.null2String(rs.getString("bxjedwf")))); + //报销事由 Jsoup.parse(htmlContent).text() + String expnsRsn = Util.null2String(rs.getString("bxsy")); + String text = Jsoup.parse(expnsRsn).text(); + toEsbBean.setExpnsRsn(text); + //备注 + toEsbBean.setRemark(Util.null2String(rs.getString("bz"))); + fj = Util.null2String(rs.getString("fj")); + spdfj = Util.null2String(rs.getString("spdfj")); + // String formData = rs.getString("formData"); + } + // 封装文件数组 + //现在是id + List fjids = new ArrayList<>( Arrays.asList(fj.split(","))); + // + writeLog("fjids"+fjids); + try { + if (!StringUtil.isEmpty(spdfj)){ + fjids.add(spdfj); + } + ArrayList acsryArray = new ArrayList<>(); + for (String fjid : fjids) { + acsryItem acsryItem = new acsryItem(); + acsryItem.setAcsryNm(getimgid(fjid,rs)); + acsryArray.add(acsryItem); + } + toEsbBean.setAcsryArray(acsryArray); + //重新设置下附件张数为数组长度 + toEsbBean.setAcsryNums(acsryArray.size()+""); + }catch (Exception e){ + e.printStackTrace(); + writeLog("fjidsException"+e); + } + + return mainid; + } + + + private void setFormDt1(String mainid, String tablename, RecordSet rs , TravelToEsbBean toEsbBean) { + rs.execute("select * from " + tablename + "_dt1 where mainid = " + mainid); + List expenseArray = new ArrayList<>(); + while (rs.next()) { + ExpenseItem expenseItem = new ExpenseItem(); + // 支出类型 + expenseItem.setExpndType(getpartyBuildCostCode(Util.getIntValue(rs.getString("zclx"),0))); + //不含税金额 + expenseItem.setExclsvTaxAmt(multiply100(Util.null2String(rs.getString("bhsjedwf")))); + // //不含税金额 + expenseItem.setTaxAmt(multiply100(Util.null2String(rs.getString("sedwf")))); + //价税合计金额 + expenseItem.setPrcTotAmt(multiply100(Util.null2String(rs.getString("jshjjedwf")))); + //记账摘要 Jsoup.parse(expnsRsn).text() + String jzzy = Util.null2String(rs.getString("jzzy")); + String text = Jsoup.parse(jzzy).text(); + expenseItem.setAcctingAbstct(text); + expenseArray.add(expenseItem); + } + toEsbBean.setExpndArray(expenseArray); + } + + + private void setFormDt2(String mainid, String tablename, RecordSet rs , TravelToEsbBean toEsbBean) { + rs.execute("select * from " + tablename + "_dt2 where mainid = " + mainid); + List jrnyInfoArray = new ArrayList<>(); + while (rs.next()) { + JourneyInfo journeyInfo = new JourneyInfo(); + // 开始日期 + journeyInfo.setStartDate(formatDate(Util.null2String(rs.getString("ksrq")))); + // 结束日期 + journeyInfo.setEndDate(formatDate(Util.null2String(rs.getString("jsrq")))); + // 出差天数 + journeyInfo.setBsnTrpDays(Util.null2String(rs.getString("ccts"))); + //行程路线 + journeyInfo.setJrnyPath(Util.null2String(rs.getString("hclx"))); + //行程说明 + journeyInfo.setJrnyExpln(Util.null2String(rs.getString("hcsm"))); + //记账摘要 + journeyInfo.setRemark(Util.null2String(rs.getString("bz"))); + jrnyInfoArray.add(journeyInfo); + } + toEsbBean.setJrnyInfoArray(jrnyInfoArray); + } + + //获取支出类型 + private String getpartyBuildCostCode(int index){ + if(index == 0){ + return "FEE_BUILD"; + }else if(index == 1){ + return "BIZ_FEE"; + }else if(index == 2){ + return "PARTY_BUILD_EXPENSE"; + } + return ""; + } + + public String getimgid(String docid, RecordSet rs){ + String sql = "select docid,df.imagefileid imgid from docimagefile df left join imagefile imf on df.imagefileid = imf.imagefileid where DOCID = ?"; + writeLog("getimgidsql"+sql+"===="+docid); + rs.executeQuery(sql,docid); + if (rs.next()){ + writeLog("imgid"+Util.null2String(rs.getString("imgid"))); + return Util.null2String(rs.getString("imgid")); + } + return ""; + }; + //生成流水号 + public static String generateTimestamp() { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + Date currentDate = new Date(); + return dateFormat.format(currentDate); + } + + public static String multiply100(String s) { + s = s.replace(",", ""); // 移除逗号 + if (StringUtil.isEmpty(s)){ + return "0"; + } + BigDecimal value = new BigDecimal(s); + BigDecimal multipliedValue = value.multiply(new BigDecimal("100")); + int result = multipliedValue.intValue(); + System.out.println(result); // 输出:123456 + return String.valueOf(result); // 输出:123456 + } + + public static String formatDate(String input) { + // String input = "2023-09-20 19:29"; + try { + SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + // 使用SimpleDateFormat解析输入字符串 + if (!input.contains(" ")){ + datetimeFormat = new SimpleDateFormat("yyyy-MM-dd"); + } + + Date date = datetimeFormat.parse(input); + // 使用另一个SimpleDateFormat对象格式化Date为所需的输出格式 + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + String output = dateFormat.format(date); + + return output; // 输出: 2023-09-20 + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + + + + public static void main(String[] args) { + String htmlContent = "2023-10-05 07:00" ; + + System.out.println(htmlContent.contains(" ")); + if (htmlContent.indexOf(" ") == -1){ + + } + } + + + + + +} diff --git a/weaver/ofs/manager/OfsTodoDataManagerNew.java b/weaver/ofs/manager/OfsTodoDataManagerNew.java index c6904cd..dc4fee8 100644 --- a/weaver/ofs/manager/OfsTodoDataManagerNew.java +++ b/weaver/ofs/manager/OfsTodoDataManagerNew.java @@ -2735,6 +2735,9 @@ public class OfsTodoDataManagerNew implements IOfsTodoDataManager { if (!StringUtils.isEmpty(title)) { message.setTitle(title); } + // message.setMessageGroupType(); + // message.setAgentId("86"); + // message.setMessageGroupTypeName("[dfefgr]"); // message.setDetailTitle(""); // message.setDetailTitleParams(null); }