From 2857d0a3df691bf50a7c50941c91ef1bb1e9e089 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Thu, 16 Feb 2023 19:00:32 +0800 Subject: [PATCH] =?UTF-8?q?ssl=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javascript/common/dev.js | 59 ++ .../youhong.ai/pcn/workflow_code_block.js | 156 ++++- .../aiyh/utils/action/SafeCusBaseAction.java | 543 +++++++++-------- .../utils/excention/CustomerException.java | 88 +-- .../java/aiyh/utils/httpUtil/HttpManager.java | 193 +++--- .../java/aiyh/utils/httpUtil/ResponeVo.java | 569 +++++++++--------- .../aiyh/utils/httpUtil/util/HttpUtils.java | 314 +++++----- .../java/aiyh/utils/tool/ASCIIStrCache.java | 30 + src/main/java/aiyh/utils/tool/Assert.java | 289 +++++++++ src/main/java/aiyh/utils/tool/CharUtil.java | 336 +++++++++++ .../java/aiyh/utils/tool/StrFormatter.java | 364 +++++++++++ .../controller/RaceTrackController.java | 47 ++ .../ai/pcn/racetrack/dto/RaceTrackEvent.java | 32 + .../pcn/racetrack/mapper/RacetrackMapper.java | 50 ++ .../racetrack/service/RaceTrackService.java | 59 ++ .../ai/pcn/racetrack/vo/RaceTrackVo.java | 27 + .../mapper/ApaLevelByScoreMapper.java | 10 +- .../service/ApaLevelByScoreService.java | 7 +- .../vo/ApaDataBtnShowVo.java | 22 + .../action/CaElectronicSignatureAction.java | 81 +++ .../SendEmailToExternalPersonnelAction.java | 175 +++--- 常用信息.md | 34 +- 22 files changed, 2556 insertions(+), 929 deletions(-) create mode 100644 src/main/java/aiyh/utils/tool/ASCIIStrCache.java create mode 100644 src/main/java/aiyh/utils/tool/Assert.java create mode 100644 src/main/java/aiyh/utils/tool/CharUtil.java create mode 100644 src/main/java/aiyh/utils/tool/StrFormatter.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/racetrack/controller/RaceTrackController.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/racetrack/dto/RaceTrackEvent.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/racetrack/mapper/RacetrackMapper.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/racetrack/service/RaceTrackService.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/racetrack/vo/RaceTrackVo.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/vo/ApaDataBtnShowVo.java create mode 100644 src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java diff --git a/javascript/common/dev.js b/javascript/common/dev.js index c414c7a..cb46f64 100644 --- a/javascript/common/dev.js +++ b/javascript/common/dev.js @@ -27,6 +27,11 @@ WfForm.OPER_SAVECOMPLETE = '保存后页面跳转前 KB900210501' WfForm.OPER_WITHDRAW = '撤回 KB900201101' WfForm.OPER_CLOSE = '页面关闭' +/** + * 注册流程事件 + * @param type + * @param callback + */ WfForm.registerCheckEvent = (type, callback = (callback) = {}) => { // WfForm.registerCheckEvent(WfForm.OPER_SAVE+","+WfForm.OPER_SUBMIT,function(callback){ // //... 执行自定义逻辑 @@ -164,6 +169,60 @@ WfForm.getDetailAllRowIndexStr = function (detailMark) { // } } +/** + 添加明细行并设置初始值 + * 参数 参数类型 必须 说明 + * detailMark String 是 明细表标示,明细1就是detail_1,以此递增类推 + * initAddRowData JSON 否 给新增后设置初始值,格式为{field110:{value:”11”},field112:{value:”22”},…},注意key不带下划线标示 + * @param detailMark + * @param initAddRowData + */ +WfForm.addDetailRow = function (detailMark, initAddRowData = {}) { +// //明细2添加一行并给新添加的行字段field111赋值 +// WfForm.addDetailRow("detail_2",{field111:{value:"初始值"}}); +// //添加一行并给浏览按钮字段赋值 +// WfForm.addDetailRow("detail_2",{field222:{ +// value: "2,3", +// specialobj:[ +// {id:"2",name:"张三"}, +// {id:"3",name:"李四"} +// ] +// }}); +// //动态字段赋值,明细1添加一行并给字段名称为begindate的字段赋值 +// var begindatefield = WfForm.convertFieldNameToId("begindate", "detail_1"); +// var addObj = {}; +// addObj[begindatefield] = {value:"2019-03-01"}; +// WfForm.addDetailRow("detail_1", addObj); +// //不推荐这种动态键值写法,IE不支持,避免掉 +// WfForm.addDetailRow("detail_1",{[begindatefield]:{value:"2019-03-01"}}) +} + +/** + * 系统样式的Confirm确认框 + * 参数 参数类型 必须 说明 + * content String 是 确认信息 + * okEvent Function 是 点击确认事件 + * cancelEvent Function 否 点击取消事件 + * otherInfo Object 否 自定义信息(按钮名称) + * @param content + * @param okEvent + * @param cancelEvent + * @param otherInfo + */ +WfForm.showConfirm = function (content, okEvent, cancelEvent, otherInfo = {}) { + // WfForm.showConfirm("确认删除吗?", function(){ + // alert("删除成功"); + // }); + // WfForm.showConfirm("请问你是否需要技术协助?",function(){ + // alert("点击确认调用的事件"); + // },function(){ + // alert("点击取消调用的事件"); + // },{ + // title:"信息确认", //弹确认框的title,仅PC端有效 + // okText:"需要", //自定义确认按钮名称 + // cancelText:"不需要" //自定义取消按钮名称 + // }); +} /* ******************* 建模表开发依赖 ******************* */ diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index 56892b0..59bbd3f 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -305,52 +305,133 @@ $(() => { $(() => { const workflowInsertValueConfig = [ { - table: '', - targetTable: '', + table: 'detail_1', + targetTable: 'detail_3', filedMapping: [{ - source: '', - target: '' + source: 'mbmc', + target: 'name' + }, { + source: 'mbms', + target: 'description' + }, { + source: 'zp', + target: 'score' + }, { + source: 'zwpj', + target: 'grpj' + }, { + source: 'mbmc', + target: 'ldpf' + }, { + source: 'ldpj', + target: 'ldpj' }] }, { - table: '', - targetTable: '', - filedMapping: [] + table: 'detail_2', + targetTable: 'detail_3', + filedMapping: [{ + source: 'xx', + target: 'name' + }, { + source: 'ms', + target: 'description' + }, { + source: 'zp', + target: 'score' + }, { + source: 'zwpj', + target: 'grpj' + }, { + source: 'mbmc', + target: 'ldpf' + }, { + source: 'ldpj', + target: 'ldpj' + }] } ] - (function start() { + /** + * 执行提交时将配置中的明细表数据合并到指定的明细表中 + */ + WfForm.registerCheckEvent(WfForm.OPER_SUBMIT, (continueRun) => { + start() + continueRun() + }) + + + /** + * 开始执行合并操作 + */ + function start() { let mappingResult = [] workflowInsertValueConfig.forEach(item => { let valueMapping = getDetailValueMapping(item) mappingResult = [...mappingResult, ...valueMapping] }) - })() - - function setValue(valueMapping) { - + setValue(mappingResult) } + + /** + * 设置表数据到指定的明细表中 + * @param valueMapping 值映射数组 + */ + function setValue(valueMapping) { + valueMapping.forEach(row => { + let rowData = {} + row.forEach(item => { + if (!rowData[item.targetTable]) { + rowData[item.targetTable] = {} + } + rowData[item.targetTable][Utils.convertNameToIdUtil({ + fieldName: item.targetField, + table: item.targetTable + })] = { + value: item.value + } + }) + Object.keys(rowData).forEach(key => { + WfForm.addDetailRow(key, rowData[key]); + }) + }) + } + + /** + * 获取明细值和对应字段的映射数组 + * @param configItem 配置项 + * @returns {*[]} 明细字段和对应值的映射数组 + */ function getDetailValueMapping(configItem) { let detailIdsStr = WfForm.getDetailAllRowIndexStr(configItem.table); let detailIdArr = detailIdsStr.split(",") let result = [] for (let i = 0; i < detailIdArr.length; i++) { - let fieldValueMapping = getValueByConfig(configItem.filedMapping, configItem.table, i) + let fieldValueMapping = getValueByConfig(configItem.filedMapping, configItem.table, detailIdArr[i], configItem.targetTable) result.push(fieldValueMapping) } return result } - function getValueByConfig(fieldMapping, tableName, detailIndex) { + /** + * 通过配置数据获取值 + * @param fieldMapping 字段映射规则数组 + * @param tableName 表名称 + * @param detailIndex 明细表下标 + * @param targetTable 目标表 + * @returns {*[]} 对应明细行的值数组 + */ + function getValueByConfig(fieldMapping, tableName, detailIndex, targetTable) { let result = [] fieldMapping.forEach(item => { let fieldValue = Utils.getFiledValueByName({ fieldName: item.source, - TableName: tableName + table: tableName }, detailIndex) result.push({ targetField: item.target, - value: fieldValue + value: fieldValue, + targetTable: targetTable }) }) return result @@ -360,3 +441,46 @@ $(() => { }) /* ******************* 流程明细数据整合插入end ******************* */ + + +/* ******************* 当明细数据未加载完成时 控制流程提交 start ******************* */ +$(() => { + const config = { + table: 'detail_1', + field: ['fj'] + } + + function check() { + let detailRowIndexStr = WfForm.getDetailAllRowIndexStr(config.table); + let rowIndexArr = detailRowIndexStr.split(","); + try { + rowIndexArr.forEach(item => { + config.field.forEach(field => { + let value = WfForm.getFieldValue(WfForm.convertFieldNameToId(field,
) + "_" + item) + if (value == '' || value == null) { + throw field + " is can not be null!"; + } + }) + + }) + } catch (err) { + return false + } + return true + } + + WfForm.registerCheckEvent(WfForm.OPER_SUBMIT, callback => { + if (check()) { + callback() + } else { + WfForm.showConfirm("~`~` " + "7 模版文件生成中,请稍后在提交! " + " `~`8 Template file generation, please submit later! " + "`~`~", function () { + }, function () { + }, { + title: "~`~` " + "7 提交检查提示 " + "`~` 8 Submit check prompt " + "`~`~", //弹确认框的title,仅PC端有效 + okText: "OK", //自定义确认按钮名称 + cancelText: "Cancel" //自定义取消按钮名称 + }); + } + }) +}) +/* ******************* 当明细数据未加载完成时 控制流程提交 end ******************* */ \ No newline at end of file diff --git a/src/main/java/aiyh/utils/action/SafeCusBaseAction.java b/src/main/java/aiyh/utils/action/SafeCusBaseAction.java index e97c6d7..c1e81df 100644 --- a/src/main/java/aiyh/utils/action/SafeCusBaseAction.java +++ b/src/main/java/aiyh/utils/action/SafeCusBaseAction.java @@ -2,7 +2,7 @@ package aiyh.utils.action; import aiyh.utils.Util; import aiyh.utils.excention.CustomerException; -import org.apache.commons.lang3.StringUtils; +import com.google.common.base.Strings; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import weaver.hrm.User; @@ -12,7 +12,6 @@ import weaver.workflow.request.RequestManager; import weaver.workflow.workflow.WorkflowBillComInfo; import weaver.workflow.workflow.WorkflowComInfo; -import java.io.IOException; import java.util.*; /** @@ -21,269 +20,279 @@ import java.util.*; * @author EBU7-dev-1 aiyh */ public abstract class SafeCusBaseAction implements Action { - - - /** - * 全局日志对象 - */ - protected final Logger log = Util.getLogger(); - private final Map actionHandleMethod = new HashMap<>(); - - /** - *

初始化流程默认的处理方法

- */ - private void initHandleMethod() { - // 提交 - actionHandleMethod.put(ActionRunType.SUBMIT, this::doSubmit); - // 退回 - actionHandleMethod.put(ActionRunType.REJECT, this::doReject); - // 撤回 - actionHandleMethod.put(ActionRunType.WITHDRAW, this::doWithdraw); - // 强制收回 - actionHandleMethod.put(ActionRunType.DRAW_BACK, this::doDrawBack); - } - - - @Override - public final String execute(RequestInfo requestInfo) { - RequestManager requestManager = requestInfo.getRequestManager(); - String billTable = requestManager.getBillTableName(); - String requestId = requestInfo.getRequestid(); - User user = requestInfo.getRequestManager().getUser(); - int workflowId = requestManager.getWorkflowid(); - // 操作类型 submit - 提交 reject - 退回 等 - String src = requestManager.getSrc(); - if ("".equals(billTable)) { - WorkflowComInfo workflowComInfo = new WorkflowComInfo(); - String formId = workflowComInfo.getFormId(String.valueOf(workflowId)); - WorkflowBillComInfo workflowBillComInfo = new WorkflowBillComInfo(); - billTable = workflowBillComInfo.getTablename(formId); - } - try { - Util.verifyRequiredField(this); - if (StringUtils.isEmpty(src)) { - src = "submit"; - } - // 初始化默认的流程处理方法 - initHandleMethod(); - // 提供自定义注册处理方法 - registerHandler(actionHandleMethod); - // 获取流程对应的处理方法 - SafeCusBaseActionHandleFunction cusBaseActionHandleFunction = actionHandleMethod.get(src); - // 默认没有直接成功不做拦截 - if (null == cusBaseActionHandleFunction) { - return Action.SUCCESS; - } - cusBaseActionHandleFunction.handle(requestId, billTable, workflowId, user, requestInfo); - } catch (CustomerException e) { - if (e.getCode() != null && e.getCode() == 500) { - Util.actionFail(requestManager, e.getMessage()); - return Action.FAILURE_AND_CONTINUE; - } - if (this.exceptionCallback(e, requestManager)) { - return Action.FAILURE_AND_CONTINUE; - } - } catch (Exception e) { - if (this.exceptionCallback(e, requestManager)) { - return Action.FAILURE_AND_CONTINUE; - } - } - return Action.SUCCESS; - } - - - /** - *

程序执行异常回调

- * - * @param e 异常信息 - * @param requestManager requestManager对象 - * @return 是否阻止action往下提交,true- 阻止, false-放行 - */ - public boolean exceptionCallback(Exception e, RequestManager requestManager) { - e.printStackTrace(); - log.error(Util.logStr("getDataId action fail, exception message is [{}], error stack trace msg is: \n{}", - e.getMessage(), Util.getErrString(e))); - Util.actionFail(requestManager, e.getMessage()); - return true; - } - - - /** - *

流程其他流转类型处理方法注册

- * - * @param actionHandleMethod 处理方法对应map - */ - public void registerHandler(Map actionHandleMethod) { - } - - - /** - *

action 提交流程业务处理方法

- *

具体业务逻辑实现 - * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 - *

- * - * @param requestId 流程请求ID - * @param billTable 流程对应主表名称 - * @param workflowId 流程对应流程ID - * @param user 当前节点操作者用户 - * @param requestInfo 请求管理对象 - */ - - public abstract void doSubmit(String requestId, String billTable, int workflowId, - User user, RequestInfo requestInfo); - - - /** - *

action 退回流程业务处理方法

- *

具体业务逻辑实现 - * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 - *

- * - * @param requestId 流程请求ID - * @param billTable 流程对应主表名称 - * @param workflowId 流程对应流程ID - * @param user 当前节点操作者用户 - * @param requestInfo 请求管理对象 - */ - public void doReject(String requestId, String billTable, int workflowId, - User user, RequestInfo requestInfo) { - } - - /** - *

action 撤回、撤回流程流程业务处理方法

- *

具体业务逻辑实现 - * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 - *

- * - * @param requestId 流程请求ID - * @param billTable 流程对应主表名称 - * @param workflowId 流程对应流程ID - * @param user 当前节点操作者用户 - * @param requestInfo 请求管理对象 - */ - public void doWithdraw(String requestId, String billTable, int workflowId, - User user, RequestInfo requestInfo) { - } - - - /** - *

action 强制收回流程业务处理方法

- *

具体业务逻辑实现 - * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 - *

- * - * @param requestId 流程请求ID - * @param billTable 流程对应主表名称 - * @param workflowId 流程对应流程ID - * @param user 当前节点操作者用户 - * @param requestInfo 请求管理对象 - */ - public void doDrawBack(String requestId, String billTable, int workflowId, - User user, RequestInfo requestInfo) { - } - - /** - *

获取流程主表数据

- * - * @return 流程主表数据 - */ - protected Map getMainTableValue(RequestInfo requestInfo) { - // 获取主表数据 - Property[] propertyArr = requestInfo.getMainTableInfo().getProperty(); - return getStringMap(propertyArr); - } - - @NotNull - private Map getStringMap(Property[] propertyArr) { - if (null == propertyArr) { - return Collections.emptyMap(); - } - Map mainTable = new HashMap<>((int) Math.ceil(propertyArr.length * 1.4)); - for (Property property : propertyArr) { - String fieldName = property.getName(); - String value = property.getValue(); - mainTable.put(fieldName, value); - } - return mainTable; - } - - - /** - *

获取所有明细数据

- * - * @return 以明细表需要为键,以明细表数据为值的键值对明细数据信息 - */ - protected Map>> getDetailTableValue(RequestInfo requestInfo) { - DetailTable[] detailTableArr = requestInfo.getDetailTableInfo().getDetailTable(); - return getListMap(detailTableArr); - } - - - @NotNull - private Map>> getListMap(DetailTable[] detailTableArr) { - Map>> detailDataList = new HashMap<>((int) Math.ceil(detailTableArr.length * 1.4)); - for (DetailTable detailTable : detailTableArr) { - List> detailData = getDetailValue(detailTable); - detailDataList.put(detailTable.getId(), detailData); - } - return detailDataList; - } - - - /** - *

获取指定明细表的表数据

- * - * @param detailNo 明细表编号 - * @return 明细数据 - */ - protected List> getDetailTableValueByDetailNo(int detailNo, RequestInfo requestInfo) { - DetailTable detailTable = requestInfo.getDetailTableInfo().getDetailTable(detailNo); - return getDetailValue(detailTable); - } - - /** - *

根据明细表信息获取明细表数据

- * - * @param detailTable 明细表对象 - * @return 明细表数据 - */ - @NotNull - private List> getDetailValue(DetailTable detailTable) { - Row[] rowArr = detailTable.getRow(); - List> detailData = new ArrayList<>(rowArr.length); - for (Row row : rowArr) { - Cell[] cellArr = row.getCell(); - Map rowData = new HashMap<>((int) Math.ceil(cellArr.length * (1 + 0.4))); - rowData.put("id", row.getId()); - for (Cell cell : cellArr) { - String fieldName = cell.getName(); - String value = cell.getValue(); - rowData.put(fieldName, value); - } - detailData.add(rowData); - } - return detailData; - } - - - public static final class ActionRunType { - /** - * 退回 - */ - public static final String REJECT = "reject"; - /** - * 撤回 - */ - public static final String WITHDRAW = "withdraw"; - /** - * 强制收回 - */ - public static final String DRAW_BACK = "drawBack"; - /** - * 提交 - */ - public static final String SUBMIT = "submit"; - } - + + + /** + * 全局日志对象 + */ + protected final Logger log = Util.getLogger(); + private final Map actionHandleMethod = new HashMap<>(); + + /** + *

初始化流程默认的处理方法

+ */ + private void initHandleMethod() { + // 提交 + actionHandleMethod.put(ActionRunType.SUBMIT, this::doSubmit); + // 退回 + actionHandleMethod.put(ActionRunType.REJECT, this::doReject); + // 撤回 + actionHandleMethod.put(ActionRunType.WITHDRAW, this::doWithdraw); + // 强制收回 + actionHandleMethod.put(ActionRunType.DRAW_BACK, this::doDrawBack); + } + + + @Override + public final String execute(RequestInfo requestInfo) { + RequestManager requestManager = requestInfo.getRequestManager(); + String billTable = requestManager.getBillTableName(); + String requestId = requestInfo.getRequestid(); + User user = requestInfo.getRequestManager().getUser(); + int workflowId = requestManager.getWorkflowid(); + // 操作类型 submit - 提交 reject - 退回 等 + String src = requestManager.getSrc(); + if ("".equals(billTable)) { + WorkflowComInfo workflowComInfo = new WorkflowComInfo(); + String formId = workflowComInfo.getFormId(String.valueOf(workflowId)); + WorkflowBillComInfo workflowBillComInfo = new WorkflowBillComInfo(); + billTable = workflowBillComInfo.getTablename(formId); + } + try { + Util.verifyRequiredField(this); + if (!Strings.isNullOrEmpty(src)) { + src = "submit"; + } + // 初始化默认的流程处理方法 + initHandleMethod(); + // 提供自定义注册处理方法 + registerHandler(actionHandleMethod); + // 获取流程对应的处理方法 + SafeCusBaseActionHandleFunction cusBaseActionHandleFunction = actionHandleMethod.get(src); + // 默认没有直接成功不做拦截 + if (null == cusBaseActionHandleFunction) { + return Action.SUCCESS; + } + cusBaseActionHandleFunction.handle(requestId, billTable, workflowId, user, requestInfo); + } catch (CustomerException e) { + if (e.getCode() != null && e.getCode() == 500) { + Util.actionFail(requestManager, e.getMessage()); + return Action.FAILURE_AND_CONTINUE; + } + if (this.exceptionCallback(e, requestManager)) { + return Action.FAILURE_AND_CONTINUE; + } + } catch (Exception e) { + if (this.exceptionCallback(e, requestManager)) { + return Action.FAILURE_AND_CONTINUE; + } + } + return Action.SUCCESS; + } + + + /** + *

程序执行异常回调

+ * + * @param e 异常信息 + * @param requestManager requestManager对象 + * @return 是否阻止action往下提交,true- 阻止, false-放行 + */ + public boolean exceptionCallback(Exception e, RequestManager requestManager) { + e.printStackTrace(); + log.error(Util.logStr("execute action fail, exception message is [{}], error stack trace msg is: \n{}", + e.getMessage(), Util.getErrString(e))); + Util.actionFail(requestManager, e.getMessage()); + return true; + } + + + /** + *

流程其他流转类型处理方法注册

+ * + * @param actionHandleMethod 处理方法对应map + */ + public void registerHandler(Map actionHandleMethod) { + } + + + /** + *

action 提交流程业务处理方法

+ *

具体业务逻辑实现 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + *

+ * + * @param requestId 流程请求ID + * @param billTable 流程对应主表名称 + * @param workflowId 流程对应流程ID + * @param user 当前节点操作者用户 + * @param requestInfo 请求管理对象 + */ + + public abstract void doSubmit(String requestId, String billTable, int workflowId, + User user, RequestInfo requestInfo); + + + /** + *

action 退回流程业务处理方法

+ *

具体业务逻辑实现 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + *

+ * + * @param requestId 流程请求ID + * @param billTable 流程对应主表名称 + * @param workflowId 流程对应流程ID + * @param user 当前节点操作者用户 + * @param requestInfo 请求管理对象 + */ + public void doReject(String requestId, String billTable, int workflowId, + User user, RequestInfo requestInfo) { + } + + /** + *

action 撤回、撤回流程流程业务处理方法

+ *

具体业务逻辑实现 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + *

+ * + * @param requestId 流程请求ID + * @param billTable 流程对应主表名称 + * @param workflowId 流程对应流程ID + * @param user 当前节点操作者用户 + * @param requestInfo 请求管理对象 + */ + public void doWithdraw(String requestId, String billTable, int workflowId, + User user, RequestInfo requestInfo) { + } + + + /** + *

action 强制收回流程业务处理方法

+ *

具体业务逻辑实现 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + *

+ * + * @param requestId 流程请求ID + * @param billTable 流程对应主表名称 + * @param workflowId 流程对应流程ID + * @param user 当前节点操作者用户 + * @param requestInfo 请求管理对象 + */ + public void doDrawBack(String requestId, String billTable, int workflowId, + User user, RequestInfo requestInfo) { + } + + /** + *

获取流程主表数据

+ * + * @return 流程主表数据 + */ + protected Map getMainTableValue(RequestInfo requestInfo) { + // 获取主表数据 + Property[] propertyArr = requestInfo.getMainTableInfo().getProperty(); + return getStringMap(propertyArr); + } + + @NotNull + private Map getStringMap(Property[] propertyArr) { + if (null == propertyArr) { + return Collections.emptyMap(); + } + Map mainTable = new HashMap<>((int) Math.ceil(propertyArr.length * 1.4)); + for (Property property : propertyArr) { + String fieldName = property.getName(); + String value = property.getValue(); + mainTable.put(fieldName, value); + } + return mainTable; + } + + /** + *

获取流程主表数据

+ * + * @return 流程主表数据 + */ + protected Map getObjMainTableValue(RequestInfo requestInfo) { + Map mainTableValue = getMainTableValue(requestInfo); + return new HashMap<>(mainTableValue); + } + + + /** + *

获取所有明细数据

+ * + * @return 以明细表需要为键,以明细表数据为值的键值对明细数据信息 + */ + protected Map>> getDetailTableValue(RequestInfo requestInfo) { + DetailTable[] detailTableArr = requestInfo.getDetailTableInfo().getDetailTable(); + return getListMap(detailTableArr); + } + + + @NotNull + private Map>> getListMap(DetailTable[] detailTableArr) { + Map>> detailDataList = new HashMap<>((int) Math.ceil(detailTableArr.length * 1.4)); + for (DetailTable detailTable : detailTableArr) { + List> detailData = getDetailValue(detailTable); + detailDataList.put(detailTable.getId(), detailData); + } + return detailDataList; + } + + + /** + *

获取指定明细表的表数据

+ * + * @param detailNo 明细表编号 + * @return 明细数据 + */ + protected List> getDetailTableValueByDetailNo(int detailNo, RequestInfo requestInfo) { + DetailTable detailTable = requestInfo.getDetailTableInfo().getDetailTable(detailNo); + return getDetailValue(detailTable); + } + + /** + *

根据明细表信息获取明细表数据

+ * + * @param detailTable 明细表对象 + * @return 明细表数据 + */ + @NotNull + private List> getDetailValue(DetailTable detailTable) { + Row[] rowArr = detailTable.getRow(); + List> detailData = new ArrayList<>(rowArr.length); + for (Row row : rowArr) { + Cell[] cellArr = row.getCell(); + Map rowData = new HashMap<>((int) Math.ceil(cellArr.length * (1 + 0.4))); + rowData.put("id", row.getId()); + for (Cell cell : cellArr) { + String fieldName = cell.getName(); + String value = cell.getValue(); + rowData.put(fieldName, value); + } + detailData.add(rowData); + } + return detailData; + } + + + public static final class ActionRunType { + /** + * 退回 + */ + public static final String REJECT = "reject"; + /** + * 撤回 + */ + public static final String WITHDRAW = "withdraw"; + /** + * 强制收回 + */ + public static final String DRAW_BACK = "drawBack"; + /** + * 提交 + */ + public static final String SUBMIT = "submit"; + } + } diff --git a/src/main/java/aiyh/utils/excention/CustomerException.java b/src/main/java/aiyh/utils/excention/CustomerException.java index 1984afa..e2292c9 100644 --- a/src/main/java/aiyh/utils/excention/CustomerException.java +++ b/src/main/java/aiyh/utils/excention/CustomerException.java @@ -10,47 +10,49 @@ import org.apache.log4j.Logger; * @author ayh */ -public class CustomerException extends RuntimeException{ - private Logger logger = Util.getLogger(); - private String msg; - private Throwable throwable; - private Integer code; - - public CustomerException(String msg){ - super(msg); - this.msg = msg; - } - - public CustomerException(String msg,Integer code){ - super(msg); - this.code = code; - this.msg = msg; - } - public CustomerException(String msg, Integer code, Throwable throwable){ - super(msg); - this.code= code; - this.msg = msg; - } - public CustomerException(String msg, Throwable throwable){ - super(msg,throwable); - this.msg = msg; - this.throwable = throwable; - } - - @Override - public void printStackTrace() { - logger.error("二开自定义异常:" + this.msg); - if(this.throwable != null){ - logger.error("异常信息: " + Util.getErrString(this.throwable)); - } - } - - public Integer getCode (){ - return this.code; - } - - @Override - public String getMessage() { - return this.msg; - } +public class CustomerException extends RuntimeException { + private final Logger logger = Util.getLogger(); + private final String msg; + private Throwable throwable; + private Integer code = -1; + + public CustomerException(String msg) { + super(msg); + this.msg = msg; + } + + public CustomerException(String msg, Integer code) { + super(msg); + this.code = code; + this.msg = msg; + } + + public CustomerException(String msg, Integer code, Throwable throwable) { + super(msg); + this.code = code; + this.msg = msg; + } + + public CustomerException(String msg, Throwable throwable) { + super(msg, throwable); + this.msg = msg; + this.throwable = throwable; + } + + @Override + public void printStackTrace() { + logger.error("二开自定义异常:" + this.msg); + if (this.throwable != null) { + logger.error("异常信息: " + Util.getErrString(this.throwable)); + } + } + + public Integer getCode() { + return this.code; + } + + @Override + public String getMessage() { + return this.msg; + } } diff --git a/src/main/java/aiyh/utils/httpUtil/HttpManager.java b/src/main/java/aiyh/utils/httpUtil/HttpManager.java index bf3c81c..d01fffc 100644 --- a/src/main/java/aiyh/utils/httpUtil/HttpManager.java +++ b/src/main/java/aiyh/utils/httpUtil/HttpManager.java @@ -4,17 +4,22 @@ import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.SSLContexts; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; +import java.io.File; +import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; /** @@ -22,76 +27,122 @@ import java.security.NoSuchAlgorithmException; * @since 2021/08/30 17:56 **/ public class HttpManager { - - /** - * 创建连接池管理对象 - */ - - - private static final int CONNECT_TIMEOUT = 1000 * 60 * 3; - private static final int CONNECTION_REQUEST_TIMEOUT = 1000 * 60 * 3; - private static final int SOCKET_TIMEOUT = 10000 * 60 * 3; - private static final int MAX_TOTAL = 500; - private static final int MAX_PRE_ROUTE = 500; - - /** - * 设置请求配置 - */ - static RequestConfig requestConfig = RequestConfig.custom() - //网络请求的超时时间 - .setConnectTimeout(CONNECT_TIMEOUT) - //连接池去获取连接的超时时间 - .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) - //设置socket超时时间 - .setSocketTimeout(SOCKET_TIMEOUT) - .build(); - static PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(); - static { - // 配置最大的连接数 - manager.setMaxTotal(MAX_TOTAL); - // 每个路由最大连接数(路由是根据host来管理的,大小不好控制) - manager.setDefaultMaxPerRoute(MAX_PRE_ROUTE); - } - - /** - * 获取连接对象 从连接池里面去获取,根据url创建对应的对象,http / https - * @param url 请求地址 - * @return 连接对象 - */ - public static CloseableHttpClient getHttpConnection(String url, CredentialsProvider credentialsProvider){ - if(url.trim().toUpperCase().startsWith(HttpArgsType.HTTP_HTTPS.toUpperCase())){ - SSLContext sslContext; - SSLConnectionSocketFactory sslsf = null; - try { - sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> { + + /** + * 创建连接池管理对象 + */ + + + private static final int CONNECT_TIMEOUT = 1000 * 60 * 3; + private static final int CONNECTION_REQUEST_TIMEOUT = 1000 * 60 * 3; + private static final int SOCKET_TIMEOUT = 10000 * 60 * 3; + private static final int MAX_TOTAL = 500; + private static final int MAX_PRE_ROUTE = 500; + + /** + * 设置请求配置 + */ + static RequestConfig requestConfig = RequestConfig.custom() + // 网络请求的超时时间 + .setConnectTimeout(CONNECT_TIMEOUT) + // 连接池去获取连接的超时时间 + .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) + // 设置socket超时时间 + .setSocketTimeout(SOCKET_TIMEOUT) + .build(); + static PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(); + + static { + // 配置最大的连接数 + manager.setMaxTotal(MAX_TOTAL); + // 每个路由最大连接数(路由是根据host来管理的,大小不好控制) + manager.setDefaultMaxPerRoute(MAX_PRE_ROUTE); + } + + /** + * 获取连接对象 从连接池里面去获取,根据url创建对应的对象,http / https + * + * @param url 请求地址 + * @return 连接对象 + */ + public static CloseableHttpClient getHttpConnection(String url, CredentialsProvider credentialsProvider) { + if (url.trim().toUpperCase().startsWith(HttpArgsType.HTTP_HTTPS.toUpperCase())) { + SSLContext sslContext; + SSLConnectionSocketFactory sslsf = null; + try { + sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> { // 绕过所有验证 - return true; - }).build(); - HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; - sslsf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier); - } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { - e.printStackTrace(); - } - HttpClientBuilder httpClientBuilder = HttpClients.custom() - .setSSLSocketFactory(sslsf) - .setConnectionManager(manager) - .setConnectionManagerShared(true) - .setDefaultRequestConfig(requestConfig); - if(credentialsProvider != null){ - httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); - } - return httpClientBuilder - .build(); - }else{ - HttpClientBuilder httpClientBuilder = HttpClients.custom() - .setConnectionManager(manager) - .setDefaultRequestConfig(requestConfig) - .setConnectionManagerShared(true); - if(credentialsProvider != null){ - httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); - } - return httpClientBuilder - .build(); - } - } + return true; + }).build(); + HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; + sslsf = new SSLConnectionSocketFactory(sslContext, + new String[]{"TLSv1"}, + null, + hostnameVerifier); + } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { + throw new RuntimeException(e); + } + HttpClientBuilder httpClientBuilder = HttpClients.custom() + .setSSLSocketFactory(sslsf) + .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) + .setConnectionManager(manager) + .setConnectionManagerShared(true) + .setDefaultRequestConfig(requestConfig); + if (credentialsProvider != null) { + httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); + } + return httpClientBuilder + .build(); + } else { + HttpClientBuilder httpClientBuilder = HttpClients.custom() + .setConnectionManager(manager) + .setDefaultRequestConfig(requestConfig) + .setConnectionManagerShared(true); + if (credentialsProvider != null) { + httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); + } + return httpClientBuilder + .build(); + } + } + + public static CloseableHttpClient getHttpConnection(String url, CredentialsProvider credentialsProvider, String sslPath, String password) { + if (url.trim().toUpperCase().startsWith(HttpArgsType.HTTP_HTTPS.toUpperCase())) { + SSLContext sslContext; + SSLConnectionSocketFactory sslsf = null; + try { + sslContext = SSLContexts.custom() + .loadTrustMaterial(new File(sslPath), password.toCharArray(), + new TrustSelfSignedStrategy()) + .build(); + sslsf = new SSLConnectionSocketFactory(sslContext, + new String[]{"TLSv1"}, + null, + SSLConnectionSocketFactory.getDefaultHostnameVerifier()); + } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException | + IOException e) { + throw new RuntimeException(e); + } + HttpClientBuilder httpClientBuilder = HttpClients.custom() + .setSSLSocketFactory(sslsf) + .setConnectionManager(manager) + .setConnectionManagerShared(true) + .setDefaultRequestConfig(requestConfig); + if (credentialsProvider != null) { + httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); + } + return httpClientBuilder + .build(); + } else { + HttpClientBuilder httpClientBuilder = HttpClients.custom() + .setConnectionManager(manager) + .setDefaultRequestConfig(requestConfig) + .setConnectionManagerShared(true); + if (credentialsProvider != null) { + httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); + } + return httpClientBuilder + .build(); + } + } } diff --git a/src/main/java/aiyh/utils/httpUtil/ResponeVo.java b/src/main/java/aiyh/utils/httpUtil/ResponeVo.java index dcc34b3..3029b96 100644 --- a/src/main/java/aiyh/utils/httpUtil/ResponeVo.java +++ b/src/main/java/aiyh/utils/httpUtil/ResponeVo.java @@ -1,7 +1,9 @@ package aiyh.utils.httpUtil; +import aiyh.utils.Util; import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -19,284 +21,293 @@ import java.util.Map; */ public class ResponeVo implements HttpResponse { - /** - * 相应状态码 - */ - private int code; - /** - * 相应内容 - */ - private String entityString; - - private Map entityMap; - /** - * 相应头信息 - */ - - private Locale locale; - - private InputStream content; - - private byte[] contentByteArr; - - private Map requestData; - - private HttpResponse response; - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public void setResponse(HttpResponse response) { - this.response = response; - } - - public Map getRequestData() { - return requestData; - } - - public void setRequestData(Map requestData) { - this.requestData = requestData; - } - - /** - * 根据相应结果转化为map集合 - * - * @return 资源皇后的map集合 - * @throws JsonProcessingException JSON转换异常 - */ - @Deprecated - public Map getEntityMap() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(this.getEntityString(), Map.class); - } - - public Map getResponseMap(){ - return this.entityMap; - } - /** - * 根据相应结果,转化为实体类 - * - * @param clazz 需要映射的实体类 - * @param 需要转换实体类的泛型 - * @return 转换后的实体类 - * @throws JsonProcessingException JSON转换异常 - */ - @Deprecated - public T getEntity(Class clazz) throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(this.getEntityString(), clazz); - } - - public T getResponseEntity(Class clazz) { - ObjectMapper mapper = new ObjectMapper(); - try { - return mapper.readValue(this.getEntityString(), clazz); - } catch (JsonProcessingException e) { - return null; - } - } - - /** - * 根据相应结果,转化为实体类 - * - * @param 需要转换实体类的泛型处理器 - * @return 转换后的实体类 - * @throws JsonProcessingException JSON转换异常 - */ - public T getEntity(TypeReference typeReference) throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(this.getEntityString(), typeReference); - } - - public String getEntityString() { - return entityString; - } - - public void setEntityString(String entityString) { - this.entityString = entityString; - try{ - ObjectMapper mapper = new ObjectMapper(); - this.entityMap = mapper.readValue(this.getEntityString(), Map.class); - }catch (Exception ignore){ - - } - } - - public InputStream getContent() { - return content; - } - - public void setContent(InputStream content) { - this.content = content; - } - - public byte[] getContentByteArr() { - return contentByteArr; - } - - public void setContentByteArr(byte[] contentByteArr) { - this.contentByteArr = contentByteArr; - } - - @Override - public String toString() { - return "ResponeVo{" + - "code=" + code + - ", entityString='" + entityString + '\'' + - ", otherParam=" + requestData + - '}'; - } - - /** - * 根据相应结果转化为实体集合 - * - * @param clazz 需要映射的实体类 - * @param 需要转换的实体类的泛型 - * @return 转换后的实体类的集合 - */ - public List getEntityArray(Class clazz) { - return JSON.parseArray(this.getEntityString(), clazz); - } - - @Override - public StatusLine getStatusLine() { - return this.response.getStatusLine(); - } - - @Override - public void setStatusLine(StatusLine statusLine) { - - } - - @Override - public void setStatusLine(ProtocolVersion protocolVersion, int i) { - - } - - @Override - public void setStatusLine(ProtocolVersion protocolVersion, int i, String s) { - - } - - @Override - public void setStatusCode(int i) throws IllegalStateException { - - } - - @Override - public void setReasonPhrase(String s) throws IllegalStateException { - - } - - @Override - public HttpEntity getEntity() { - return null; - } - - @Override - public void setEntity(HttpEntity httpEntity) { - - } - - public Locale getLocale() { - return locale; - } - - public void setLocale(Locale locale) { - this.locale = locale; - } - - @Override - public ProtocolVersion getProtocolVersion() { - return this.response.getProtocolVersion(); - } - - @Override - public boolean containsHeader(String s) { - return response.containsHeader(s); - } - - @Override - public Header[] getHeaders(String s) { - return response.getHeaders(s); - } - - @Override - public Header getFirstHeader(String s) { - return response.getFirstHeader(s); - } - - @Override - public Header getLastHeader(String s) { - return response.getLastHeader(s); - } - - public Header[] getAllHeaders() { - return response.getAllHeaders(); - } - - @Override - public void addHeader(Header header) { - - } - - @Override - public void addHeader(String s, String s1) { - - } - - @Override - public void setHeader(Header header) { - - } - - @Override - public void setHeader(String s, String s1) { - - } - - @Override - public void setHeaders(Header[] headers) { - - } - - @Override - public void removeHeader(Header header) { - - } - - @Override - public void removeHeaders(String s) { - - } - - @Override - public HeaderIterator headerIterator() { - return response.headerIterator(); - } - - @Override - public HeaderIterator headerIterator(String s) { - return response.headerIterator(s); - } - - @Override - @Deprecated - public HttpParams getParams() { - return response.getParams(); - } - - @Override - public void setParams(HttpParams httpParams) { - - } - - - + /** + * 相应状态码 + */ + private int code; + /** + * 相应内容 + */ + private String entityString; + + private Map entityMap; + + private List resultList; + /** + * 相应头信息 + */ + + private Locale locale; + + private InputStream content; + + private byte[] contentByteArr; + + private Map requestData; + + private HttpResponse response; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public void setResponse(HttpResponse response) { + this.response = response; + } + + public Map getRequestData() { + return requestData; + } + + public List getResult() { + return resultList; + } + + + public void setRequestData(Map requestData) { + this.requestData = requestData; + } + + /** + * 根据相应结果转化为map集合 + * + * @return 资源皇后的map集合 + * @throws JsonProcessingException JSON转换异常 + */ + @Deprecated + public Map getEntityMap() throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(this.getEntityString(), Map.class); + } + + public Map getResponseMap() { + return this.entityMap; + } + + /** + * 根据相应结果,转化为实体类 + * + * @param clazz 需要映射的实体类 + * @param 需要转换实体类的泛型 + * @return 转换后的实体类 + * @throws JsonProcessingException JSON转换异常 + */ + @Deprecated + public T getEntity(Class clazz) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(this.getEntityString(), clazz); + } + + public T getResponseEntity(Class clazz) { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.readValue(this.getEntityString(), clazz); + } catch (JsonProcessingException e) { + return null; + } + } + + /** + * 根据相应结果,转化为实体类 + * + * @param 需要转换实体类的泛型处理器 + * @return 转换后的实体类 + * @throws JsonProcessingException JSON转换异常 + */ + public T getEntity(TypeReference typeReference) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(this.getEntityString(), typeReference); + } + + public String getEntityString() { + return entityString; + } + + public void setEntityString(String entityString) { + this.entityString = entityString; + try { + ObjectMapper mapper = new ObjectMapper(); + this.entityMap = mapper.readValue(this.getEntityString(), Map.class); + } catch (JsonProcessingException ignored) { + this.resultList = (List) JSONArray.parseArray(this.getEntityString(), Map.class); + } catch (Exception e) { + Util.getLogger().error("Unable to convert the response result to map or array!" + Util.getErrString(e)); + } + } + + public InputStream getContent() { + return content; + } + + public void setContent(InputStream content) { + this.content = content; + } + + public byte[] getContentByteArr() { + return contentByteArr; + } + + public void setContentByteArr(byte[] contentByteArr) { + this.contentByteArr = contentByteArr; + } + + @Override + public String toString() { + return "ResponeVo{" + + "code=" + code + + ", entityString='" + entityString + '\'' + + ", otherParam=" + requestData + + '}'; + } + + /** + * 根据相应结果转化为实体集合 + * + * @param clazz 需要映射的实体类 + * @param 需要转换的实体类的泛型 + * @return 转换后的实体类的集合 + */ + public List getEntityArray(Class clazz) { + return JSON.parseArray(this.getEntityString(), clazz); + } + + @Override + public StatusLine getStatusLine() { + return this.response.getStatusLine(); + } + + @Override + public void setStatusLine(StatusLine statusLine) { + + } + + @Override + public void setStatusLine(ProtocolVersion protocolVersion, int i) { + + } + + @Override + public void setStatusLine(ProtocolVersion protocolVersion, int i, String s) { + + } + + @Override + public void setStatusCode(int i) throws IllegalStateException { + + } + + @Override + public void setReasonPhrase(String s) throws IllegalStateException { + + } + + @Override + public HttpEntity getEntity() { + return null; + } + + @Override + public void setEntity(HttpEntity httpEntity) { + + } + + public Locale getLocale() { + return locale; + } + + public void setLocale(Locale locale) { + this.locale = locale; + } + + @Override + public ProtocolVersion getProtocolVersion() { + return this.response.getProtocolVersion(); + } + + @Override + public boolean containsHeader(String s) { + return response.containsHeader(s); + } + + @Override + public Header[] getHeaders(String s) { + return response.getHeaders(s); + } + + @Override + public Header getFirstHeader(String s) { + return response.getFirstHeader(s); + } + + @Override + public Header getLastHeader(String s) { + return response.getLastHeader(s); + } + + public Header[] getAllHeaders() { + return response.getAllHeaders(); + } + + @Override + public void addHeader(Header header) { + + } + + @Override + public void addHeader(String s, String s1) { + + } + + @Override + public void setHeader(Header header) { + + } + + @Override + public void setHeader(String s, String s1) { + + } + + @Override + public void setHeaders(Header[] headers) { + + } + + @Override + public void removeHeader(Header header) { + + } + + @Override + public void removeHeaders(String s) { + + } + + @Override + public HeaderIterator headerIterator() { + return response.headerIterator(); + } + + @Override + public HeaderIterator headerIterator(String s) { + return response.headerIterator(s); + } + + @Override + @Deprecated + public HttpParams getParams() { + return response.getParams(); + } + + @Override + public void setParams(HttpParams httpParams) { + + } + + } diff --git a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java index 36c94ea..7d750b5 100644 --- a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java +++ b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java @@ -55,11 +55,24 @@ public class HttpUtils { private final PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter(); // 默认编码 private String DEFAULT_ENCODING = "UTF-8"; + private String sslKeyPath = ""; + + private String password = ""; + + public void setSslKeyPath(String sslKeyPath) { + this.sslKeyPath = sslKeyPath; + } + + + public void setPassword(String password) { + this.password = password; + } + /** * basic 认证 */ private CredentialsProvider credentialsProvider = null; - + { // private final ExecutorService executorService = Executors.newFixedThreadPool(3); ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); @@ -72,19 +85,19 @@ public class HttpUtils { String[] excludeProperties = {"locale", "contentByteArr", "response"}; excludefilter.addExcludes(excludeProperties); } - + public HttpUtils() { - + } - + public HttpUtils(CredentialsProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; } - + public HttpUtils(String DEFAULT_ENCODING) { this.DEFAULT_ENCODING = DEFAULT_ENCODING; } - + public static String urlHandle(String url, Map params) { if (params == null || params.size() <= 0) { return url; @@ -106,7 +119,7 @@ public class HttpUtils { } return getUrl; } - + private static String serializeParams(Map params) { if (params != null && params.size() > 0) { StringBuilder builder = new StringBuilder(); @@ -120,7 +133,7 @@ public class HttpUtils { } return ""; } - + private static String removeSeparator(StringBuilder sqlBuilder) { String str = sqlBuilder.toString().trim(); String removeSeparator = "&"; @@ -134,41 +147,56 @@ public class HttpUtils { } return str; } - + public void setCredentialsProvider(CredentialsProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; } - + public GlobalCache getGlobalCache() { return globalCache; } - + public void setDEFAULT_ENCODING() { this.DEFAULT_ENCODING = DEFAULT_ENCODING; } - + public HttpPost getHttpPost(String url) { HttpPost httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(10000) - .setConnectionRequestTimeout(10000) - .setRedirectsEnabled(true) - .build(); + .setConnectTimeout(10000) + .setConnectionRequestTimeout(10000) + .setRedirectsEnabled(true) + .build(); httpPost.setConfig(requestConfig); return httpPost; } - + public HttpGet getHttpGet(String url) { HttpGet httpGet = new HttpGet(url); RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(10000) - .setConnectionRequestTimeout(10000) - .setRedirectsEnabled(true) - .build(); + .setConnectTimeout(10000) + .setConnectionRequestTimeout(10000) + .setRedirectsEnabled(true) + .build(); httpGet.setConfig(requestConfig); return httpGet; } - + + + /** + * 获取httpclient对象 + * + * @param url 请求地址 + * @return 对象 + */ + private CloseableHttpClient getHttpClient(String url) { + if (Strings.isNullOrEmpty(this.sslKeyPath)) { + return HttpManager.getHttpConnection(url, this.credentialsProvider); + } else { + return HttpManager.getHttpConnection(url, this.credentialsProvider, sslKeyPath, password); + } + } + /** * get请求 * @@ -177,7 +205,7 @@ public class HttpUtils { * @throws IOException io异常 */ public ResponeVo apiGet(String url) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map params = paramsHandle(null); String getUrl = urlHandle(url, params); Map headers = headersHandle(null); @@ -193,11 +221,11 @@ public class HttpUtils { httpUtilParamInfo.setParams(params); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); } catch (Exception ignore) { - + } return baseRequest(httpConnection, httpGet); } - + /** * delete请求 * @@ -206,7 +234,7 @@ public class HttpUtils { * @throws IOException io异常 */ public ResponeVo apiDelete(String url) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map params = paramsHandle(null); String getUrl = urlHandle(url, params); Map headers = headersHandle(null); @@ -222,11 +250,11 @@ public class HttpUtils { httpUtilParamInfo.setUrl(getUrl.trim()); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); } catch (Exception ignore) { - + } return baseRequest(httpConnection, httpDelete); } - + /** * get请求 * @@ -236,7 +264,7 @@ public class HttpUtils { * @throws IOException io异常 */ public ResponeVo apiGet(String url, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map params = paramsHandle(null); String getUrl = urlHandle(url, params); Map headerMap = headersHandle(headers); @@ -252,13 +280,13 @@ public class HttpUtils { httpUtilParamInfo.setUrl(getUrl.trim()); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); } catch (Exception ignore) { - + } return baseRequest(httpConnection, httpGet); } - + public ResponeVo apiDelete(String url, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map params = paramsHandle(null); String getUrl = urlHandle(url, params); Map headerMap = headersHandle(headers); @@ -274,16 +302,16 @@ public class HttpUtils { httpUtilParamInfo.setUrl(getUrl.trim()); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); } catch (Exception ignore) { - + } return baseRequest(httpConnection, httpDelete); } - + public ResponeVo apiGet(String url, Map params, Map headers) throws IOException { Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); String getUrl = urlHandle(url, paramsMap); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); HttpGet httpGet = new HttpGet(getUrl.trim()); for (Map.Entry entry : headerMap.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); @@ -296,16 +324,16 @@ public class HttpUtils { httpUtilParamInfo.setUrl(getUrl.trim()); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); } catch (Exception ignore) { - + } return baseRequest(httpConnection, httpGet); } - + public ResponeVo apiDelete(String url, Map params, Map headers) throws IOException { Map paramsMap = paramsHandle(params); String getUrl = urlHandle(url, paramsMap); Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); HttpDelete httpDelete = new HttpDelete(getUrl.trim()); for (Map.Entry entry : headerMap.entrySet()) { httpDelete.setHeader(entry.getKey(), entry.getValue()); @@ -318,11 +346,11 @@ public class HttpUtils { httpUtilParamInfo.setUrl(getUrl.trim()); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); } catch (Exception ignore) { - + } return baseRequest(httpConnection, httpDelete); } - + /** * 回调方法 * @@ -336,7 +364,7 @@ public class HttpUtils { Map paramsMap = paramsHandle(params); String getUrl = urlHandle(url, paramsMap); Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); HttpGet httpGet = new HttpGet(getUrl.trim()); for (Map.Entry entry : headerMap.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); @@ -349,11 +377,11 @@ public class HttpUtils { httpUtilParamInfo.setUrl(getUrl.trim()); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); } catch (Exception ignore) { - + } callBackRequest(httpConnection, httpGet, consumer); } - + /** * 回调方法 * @@ -367,7 +395,7 @@ public class HttpUtils { Map paramsMap = paramsHandle(params); String getUrl = urlHandle(url, paramsMap); Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); HttpDelete httpDelete = new HttpDelete(getUrl.trim()); for (Map.Entry entry : headerMap.entrySet()) { httpDelete.setHeader(entry.getKey(), entry.getValue()); @@ -380,57 +408,57 @@ public class HttpUtils { httpUtilParamInfo.setUrl(getUrl.trim()); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); } catch (Exception ignore) { - + } callBackRequest(httpConnection, httpDelete, consumer); } - + public ResponeVo apiPost(String url, Map params) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(null); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); return baseRequest(httpConnection, httpPost); } - + public ResponeVo apiPut(String url, Map params) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(null); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); return baseRequest(httpConnection, httpPut); } - + public ResponeVo apiPost(String url, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); return baseRequest(httpConnection, httpPost); } - + public ResponeVo apiPost(String url, List params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map headerMap = headersHandle(headers); HttpPost httpPost = handleHttpPost(url, headerMap, params); return baseRequest(httpConnection, httpPost); } - + public ResponeVo apiPostObject(String url, Object params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map headerMap = headersHandle(headers); HttpPost httpPost = handleHttpPostObject(url, headerMap, params); return baseRequest(httpConnection, httpPost); } - + public ResponeVo apiPut(String url, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); return baseRequest(httpConnection, httpPut); } - + /** *

上传单文件

* @@ -443,10 +471,10 @@ public class HttpUtils { * @return 响应实体 * @throws IOException IO异常 */ - + public ResponeVo apiUploadFile(String url, InputStream inputStream, String fileKey, String fileName, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpMultipartFile multipartFile = new HttpMultipartFile(); @@ -457,8 +485,8 @@ public class HttpUtils { HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); return baseRequest(httpConnection, httpPost); } - - + + /** *

上传多附件

* @@ -471,14 +499,14 @@ public class HttpUtils { */ public ResponeVo apiUploadFiles(String url, List multipartFileList, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPost httpPost = uploadFileByInputStream(url, multipartFileList, paramsMap, headerMap); return baseRequest(httpConnection, httpPost); } - - + + /** *

上传多附件

* @@ -491,13 +519,13 @@ public class HttpUtils { */ public ResponeVo apiPutUploadFiles(String url, List multipartFileList, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPut httpPut = uploadFileByInputStreamPut(url, multipartFileList, paramsMap, headerMap); return baseRequest(httpConnection, httpPut); } - + /** *

异步上传文集爱你

* @@ -512,7 +540,7 @@ public class HttpUtils { */ public Future apiUploadFileAsync(String url, InputStream inputStream, String fileKey, String fileName, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpMultipartFile multipartFile = new HttpMultipartFile(); @@ -523,7 +551,7 @@ public class HttpUtils { HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); } - + /** *

上传文件

* @@ -538,13 +566,13 @@ public class HttpUtils { */ public ResponeVo apiUploadFile(String url, File file, String fileKey, String fileName, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPost httpPost = uploadFileByInputStream(url, file, fileKey, fileName, paramsMap, headerMap); return baseRequest(httpConnection, httpPost); } - + /** *

通过ImageFileId上传文件

* @@ -557,10 +585,10 @@ public class HttpUtils { * @return 响应信息 * @throws IOException IO异常 */ - + public ResponeVo apiUploadFileById(String url, int id, String fileKey, String fileName, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); InputStream inputStream = ImageFileManager.getInputStreamById(id); @@ -572,7 +600,7 @@ public class HttpUtils { HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); return baseRequest(httpConnection, httpPost); } - + /** * @param url 请求地址 * @param params 请求参数 @@ -581,29 +609,29 @@ public class HttpUtils { * @throws IOException io异常 */ public void apiPost(String url, Map params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); callBackRequest(httpConnection, httpPost, consumer); } - + public ResponeVo apiPost(String url, Map params, Map headers, Function consumer) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); return callBackRequest(httpConnection, httpPost, consumer); } - + public ResponeVo apiPost(String url, Map params, Map headers, BiFunction, CloseableHttpResponse, ResponeVo> consumer) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); return callBackRequest(paramsMap, httpConnection, httpPost, consumer); } - + /** * @param url 请求地址 * @param params 请求参数 @@ -612,13 +640,13 @@ public class HttpUtils { * @throws IOException io异常 */ public void apiPut(String url, Map params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); callBackRequest(httpConnection, httpPut, consumer); } - + private void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer consumer) throws IOException { CloseableHttpResponse response = null; try { @@ -633,7 +661,7 @@ public class HttpUtils { ExtendedIOUtils.closeQuietly(response); } } - + private ResponeVo callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Function consumer) throws IOException { CloseableHttpResponse response = null; ResponeVo apply = null; @@ -662,7 +690,7 @@ public class HttpUtils { SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); } catch (Exception ignore) { - + } HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); ExtendedIOUtils.closeQuietly(httpClient); @@ -670,7 +698,7 @@ public class HttpUtils { } return apply; } - + private ResponeVo callBackRequest(Map requestParam, CloseableHttpClient httpClient, HttpUriRequest request, BiFunction, CloseableHttpResponse, ResponeVo> consumer) throws IOException { CloseableHttpResponse response = null; ResponeVo apply = null; @@ -700,14 +728,14 @@ public class HttpUtils { SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); } catch (Exception ignore) { - + } ExtendedIOUtils.closeQuietly(httpClient); ExtendedIOUtils.closeQuietly(response); } return apply; } - + public ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException { ResponeVo responeVo = new ResponeVo(); CloseableHttpResponse response = null; @@ -738,7 +766,7 @@ public class HttpUtils { SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); } catch (Exception ignore) { - + } } catch (Exception e) { toolUtil.writeErrorLog(" http调用失败:" + Util.getErrString(e)); @@ -750,7 +778,7 @@ public class HttpUtils { SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); } catch (Exception ignore) { - + } throw e; } finally { @@ -759,7 +787,7 @@ public class HttpUtils { } return responeVo; } - + /** * get请求 * @@ -768,7 +796,7 @@ public class HttpUtils { * @throws IOException io异常 */ public Future asyncApiGet(String url) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map params = paramsHandle(null); String getUrl = urlHandle(url, params); Map headers = headersHandle(null); @@ -778,7 +806,7 @@ public class HttpUtils { } return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); } - + /** * delete请求 * @@ -787,7 +815,7 @@ public class HttpUtils { * @throws IOException io异常 */ public Future asyncApiDelete(String url) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map params = paramsHandle(null); String getUrl = urlHandle(url, params); Map headers = headersHandle(null); @@ -797,7 +825,7 @@ public class HttpUtils { } return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); } - + /** * get请求 * @@ -807,7 +835,7 @@ public class HttpUtils { * @throws IOException io异常 */ public Future asyncApiGet(String url, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map params = paramsHandle(null); String getUrl = urlHandle(url, params); Map headerMap = headersHandle(headers); @@ -817,9 +845,9 @@ public class HttpUtils { } return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); } - + public Future asyncApiDelete(String url, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map params = paramsHandle(null); String getUrl = urlHandle(url, params); Map headerMap = headersHandle(headers); @@ -829,31 +857,31 @@ public class HttpUtils { } return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); } - + public Future asyncApiGet(String url, Map params, Map headers) throws IOException { Map paramsMap = paramsHandle(params); String getUrl = urlHandle(url, paramsMap); Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); HttpGet httpGet = new HttpGet(getUrl.trim()); for (Map.Entry entry : headerMap.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); } return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); } - + public Future asyncApiDelete(String url, Map params, Map headers) throws IOException { Map paramsMap = paramsHandle(params); String getUrl = urlHandle(url, paramsMap); Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); HttpDelete httpDelete = new HttpDelete(getUrl.trim()); for (Map.Entry entry : headerMap.entrySet()) { httpDelete.setHeader(entry.getKey(), entry.getValue()); } return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); } - + /** * 回调方法 * @@ -867,7 +895,7 @@ public class HttpUtils { Map paramsMap = paramsHandle(params); String getUrl = urlHandle(url, paramsMap); Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); HttpGet httpGet = new HttpGet(getUrl.trim()); for (Map.Entry entry : headerMap.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); @@ -881,7 +909,7 @@ public class HttpUtils { command.setHttpUtilParamInfo(httpUtilParamInfo); executorService.execute(command); } - + /** * @param url 请求地址 * @param params 请求参数 @@ -893,7 +921,7 @@ public class HttpUtils { Map paramsMap = paramsHandle(params); String getUrl = urlHandle(url, paramsMap); Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); HttpDelete httpDelete = new HttpDelete(getUrl.trim()); for (Map.Entry entry : headerMap.entrySet()) { httpDelete.setHeader(entry.getKey(), entry.getValue()); @@ -907,39 +935,39 @@ public class HttpUtils { command.setHttpUtilParamInfo(httpUtilParamInfo); executorService.execute(command); } - + public Future asyncApiPost(String url, Map params) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(null); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); } - + public Future asyncApiPut(String url, Map params) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(null); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); } - + public Future asyncApiPost(String url, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); } - + public Future asyncApiPut(String url, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); } - + /** * @param url 请求地址 * @param params 请求参数 @@ -948,7 +976,7 @@ public class HttpUtils { * @throws IOException io异常 */ public void asyncApiPost(String url, Map params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); @@ -961,7 +989,7 @@ public class HttpUtils { command.setHttpUtilParamInfo(httpUtilParamInfo); executorService.execute(command); } - + /** * @param url 请求地址 * @param params 请求参数 @@ -970,7 +998,7 @@ public class HttpUtils { * @throws IOException io异常 */ public void asyncApiPut(String url, Map params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + CloseableHttpClient httpConnection = getHttpClient(url); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); @@ -983,7 +1011,7 @@ public class HttpUtils { command.setHttpUtilParamInfo(httpUtilParamInfo); executorService.execute(command); } - + private HttpPost handleHttpPostObject(String url, Map headerMap, Object paramsMap) throws UnsupportedEncodingException { HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); httpUtilParamInfo.setParams(paramsMap); @@ -1010,9 +1038,9 @@ public class HttpUtils { if (Strings.isNullOrEmpty(contentType)) { List nvps = new ArrayList<>(); for (Map.Entry entry : params.entrySet()) { - //nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); - - //修复请求form表单提交时,参数值被双引号括了起来 + // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + + // 修复请求form表单提交时,参数值被双引号括了起来 nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); } httpPost.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE); @@ -1020,9 +1048,9 @@ public class HttpUtils { } else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) { List nvps = new ArrayList<>(); for (Map.Entry entry : params.entrySet()) { - //nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); - - //修复请求form表单提交时,参数值被双引号括了起来 + // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + + // 修复请求form表单提交时,参数值被双引号括了起来 nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); } httpPost.setEntity(new UrlEncodedFormEntity(nvps)); @@ -1039,15 +1067,15 @@ public class HttpUtils { HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); return httpPost; } - + private HttpPost handleHttpPost(String url, Map headerMap, Map paramsMap) throws UnsupportedEncodingException { return handleHttpPostObject(url, headerMap, paramsMap); } - + private HttpPost handleHttpPost(String url, Map headerMap, List params) throws UnsupportedEncodingException { return handleHttpPostObject(url, headerMap, params); } - + /** *

上传文件

* @@ -1059,7 +1087,7 @@ public class HttpUtils { */ private HttpPost uploadFileByInputStream(String url, List multipartFileList, Map params, Map headers) { - //log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, + // log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, // excludefilter, // SerializerFeature.PrettyFormat, // SerializerFeature.WriteDateUseDateFormat), @@ -1090,7 +1118,7 @@ public class HttpUtils { builder.addPart(param.getKey(), stringBody); } HttpPost httpPost = new HttpPost(url.trim()); - + for (Map.Entry entry : headers.entrySet()) { if ("Content-Type".equalsIgnoreCase(entry.getKey())) { continue; @@ -1101,8 +1129,8 @@ public class HttpUtils { httpPost.setEntity(entity); return httpPost; } - - + + /** *

上传文件

* @@ -1145,7 +1173,7 @@ public class HttpUtils { builder.addPart(param.getKey(), stringBody); } HttpPut httpPut = new HttpPut(url.trim()); - + for (Map.Entry entry : headers.entrySet()) { if ("Content-Type".equalsIgnoreCase(entry.getKey())) { continue; @@ -1156,11 +1184,11 @@ public class HttpUtils { httpPut.setEntity(entity); return httpPut; } - + private HttpPost uploadFileByInputStream(String url, File file, String fileKey, String fileName, Map params, Map headers) { log.info(Util.logStr("start request : url is [{}], params is [{}], header is [{}]; fileKey is [{}], fileName is [{}]" + - "", url, JSON.toJSONString(params), JSON.toJSONString(headers), fileKey, fileName)); + "", url, JSON.toJSONString(params), JSON.toJSONString(headers), fileKey, fileName)); HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); httpUtilParamInfo.setParams(params); httpUtilParamInfo.setUrl(url); @@ -1175,7 +1203,7 @@ public class HttpUtils { builder.addPart(param.getKey(), stringBody); } HttpPost httpPost = new HttpPost(url.trim()); - + for (Map.Entry entry : headers.entrySet()) { if ("Content-Type".equalsIgnoreCase(entry.getKey())) { continue; @@ -1186,7 +1214,7 @@ public class HttpUtils { httpPost.setEntity(entity); return httpPost; } - + private HttpPut handleHttpPut(String url, Map headerMap, Map paramsMap) throws UnsupportedEncodingException { HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); httpUtilParamInfo.setParams(paramsMap); @@ -1204,8 +1232,8 @@ public class HttpUtils { if (Strings.isNullOrEmpty(contentType)) { List nvps = new ArrayList<>(); for (Map.Entry entry : paramsMap.entrySet()) { - //nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); - //修复请求form表单提交时,参数值被双引号括了起来 + // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + // 修复请求form表单提交时,参数值被双引号括了起来 nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); } httpPut.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE); @@ -1213,8 +1241,8 @@ public class HttpUtils { } else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) { List nvps = new ArrayList<>(); for (Map.Entry entry : paramsMap.entrySet()) { - //nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); - //修复请求form表单提交时,参数值被双引号括了起来 + // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + // 修复请求form表单提交时,参数值被双引号括了起来 nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); } httpPut.setEntity(new UrlEncodedFormEntity(nvps)); @@ -1225,7 +1253,7 @@ public class HttpUtils { HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); return httpPut; } - + private String inputStreamToString(InputStream is) { String line = ""; StringBuilder total = new StringBuilder(); @@ -1239,7 +1267,7 @@ public class HttpUtils { } return total.toString(); } - + public Map headersHandle(Map headers) { Map map = new HashMap<>(); if (headers != null && headers.size() > 0) { @@ -1252,7 +1280,7 @@ public class HttpUtils { } return map; } - + public Map paramsHandle(Map params) { Map map = new HashMap<>(); if (params != null && params.size() > 0) { diff --git a/src/main/java/aiyh/utils/tool/ASCIIStrCache.java b/src/main/java/aiyh/utils/tool/ASCIIStrCache.java new file mode 100644 index 0000000..61dee2e --- /dev/null +++ b/src/main/java/aiyh/utils/tool/ASCIIStrCache.java @@ -0,0 +1,30 @@ +package aiyh.utils.tool; + +/** + * ASCII字符对应的字符串缓存 + * + * @author looly + * @since 4.0.1 + */ +public class ASCIIStrCache { + + private static final int ASCII_LENGTH = 128; + private static final String[] CACHE = new String[ASCII_LENGTH]; + + static { + for (char c = 0; c < ASCII_LENGTH; c++) { + CACHE[c] = String.valueOf(c); + } + } + + /** + * 字符转为字符串
+ * 如果为ASCII字符,使用缓存 + * + * @param c 字符 + * @return 字符串 + */ + public static String toString(char c) { + return c < ASCII_LENGTH ? CACHE[c] : String.valueOf(c); + } +} diff --git a/src/main/java/aiyh/utils/tool/Assert.java b/src/main/java/aiyh/utils/tool/Assert.java new file mode 100644 index 0000000..742d3f1 --- /dev/null +++ b/src/main/java/aiyh/utils/tool/Assert.java @@ -0,0 +1,289 @@ +package aiyh.utils.tool; + + +import java.util.Collection; +import java.util.Map; +import java.util.Objects; + +public class Assert { + public Assert() { + } + + public static void isTrue(boolean expression, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + if (!expression) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } + } + + private static boolean isEmpty(T[] array) { + return array == null || array.length == 0; + } + + private static String format(CharSequence template, Object... params) { + if (null == template) { + return null; + } + if (isEmpty(params) || isBlank(template)) { + return template.toString(); + } + return StrFormatter.format(template.toString(), params); + } + + private static boolean isBlank(CharSequence str) { + int length; + + if ((str == null) || ((length = str.length()) == 0)) { + return true; + } + + for (int i = 0; i < length; i++) { + // 只要有一个非空字符即为非空字符串 + if (!CharUtil.isBlankChar(str.charAt(i))) { + return false; + } + } + return true; + } + + public static void isTrue(boolean expression) throws IllegalArgumentException { + isTrue(expression, "[Assertion failed] - this expression must be true"); + } + + public static void isFalse(boolean expression, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + if (expression) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } + } + + public static void isFalse(boolean expression) throws IllegalArgumentException { + isFalse(expression, "[Assertion failed] - this expression must be false"); + } + + public static void isNull(Object object, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + if (object != null) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } + } + + public static void isNull(Object object) throws IllegalArgumentException { + isNull(object, "[Assertion failed] - the object argument must be null"); + } + + public static T notNull(T object, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + if (object == null) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } else { + return object; + } + } + + public static T notNull(T object) throws IllegalArgumentException { + return notNull(object, "[Assertion failed] - this argument is required; it must not be null"); + } + + public static T notEmpty(T text, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + if (isEmpty(text)) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } else { + return text; + } + } + + private static boolean isEmpty(CharSequence str) { + return str == null || str.length() == 0; + } + + public static T notEmpty(T text) throws IllegalArgumentException { + return notEmpty(text, "[Assertion failed] - this String argument must have length; it must not be null or empty"); + } + + public static T notBlank(T text, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + if (StrFormatter.isBlank(text)) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } else { + return text; + } + } + + public static T notBlank(T text) throws IllegalArgumentException { + return notBlank(text, "[Assertion failed] - this String argument must have text; it must not be null, empty, or blank"); + } + + public static String notContain(String textToSearch, String substring, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + if (isNotEmpty(textToSearch) && isNotEmpty(substring) && textToSearch.contains(substring)) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } else { + return substring; + } + } + + private static boolean isNotEmpty(CharSequence str) { + return !isEmpty(str); + } + + public static String notContain(String textToSearch, String substring) throws IllegalArgumentException { + return notContain(textToSearch, substring, "[Assertion failed] - this String argument must not contain the substring [{}]", substring); + } + + public static Object[] notEmpty(Object[] array, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + if (Objects.isNull(array) || array.length == 0) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } else { + return array; + } + } + + public static Object[] notEmpty(Object[] array) throws IllegalArgumentException { + return notEmpty(array, "[Assertion failed] - this array must not be empty: it must contain at least 1 element"); + } + + public static T[] noNullElements(T[] array, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + if (hasNull(array)) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } else { + return array; + } + } + + private static boolean hasNull(T... array) { + if (isNotEmpty(array)) { + Object[] var1 = array; + int var2 = array.length; + + for (int var3 = 0; var3 < var2; ++var3) { + T element = (T) var1[var3]; + if (null == element) { + return true; + } + } + } + + return false; + } + + public static boolean isNotEmpty(T[] array) { + return array != null && array.length != 0; + } + + public static T[] noNullElements(T[] array) throws IllegalArgumentException { + return noNullElements(array, "[Assertion failed] - this array must not contain any null elements"); + } + + public static Collection notEmpty(Collection collection, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + if (collection == null || collection.isEmpty()) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } else { + return collection; + } + } + + public static Collection notEmpty(Collection collection) throws IllegalArgumentException { + return notEmpty(collection, "[Assertion failed] - this collection must not be empty: it must contain at least 1 element"); + } + + public static Map notEmpty(Map map, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + if (Objects.isNull(map) || map.isEmpty()) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } else { + return map; + } + } + + public static Map notEmpty(Map map) throws IllegalArgumentException { + return notEmpty(map, "[Assertion failed] - this map must not be empty; it must contain at least one entry"); + } + + public static T isInstanceOf(Class type, T obj) { + return isInstanceOf(type, obj, "Object [{}] is not instanceof [{}]", obj, type); + } + + public static T isInstanceOf(Class type, T obj, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + notNull(type, "Type to check against must not be null"); + if (!type.isInstance(obj)) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } else { + return obj; + } + } + + public static void isAssignable(Class superType, Class subType) throws IllegalArgumentException { + isAssignable(superType, subType, "{} is not assignable to {})", subType, superType); + } + + public static void isAssignable(Class superType, Class subType, String errorMsgTemplate, Object... params) throws IllegalArgumentException { + notNull(superType, "Type to check against must not be null"); + if (subType == null || !superType.isAssignableFrom(subType)) { + throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params)); + } + } + + public static void state(boolean expression, String errorMsgTemplate, Object... params) throws IllegalStateException { + if (!expression) { + throw new IllegalStateException(StrFormatter.format(errorMsgTemplate, params)); + } + } + + public static void state(boolean expression) throws IllegalStateException { + state(expression, "[Assertion failed] - this state invariant must be true"); + } + + public static int checkIndex(int index, int size) throws IllegalArgumentException, IndexOutOfBoundsException { + return checkIndex(index, size, "[Assertion failed]"); + } + + public static int checkIndex(int index, int size, String errorMsgTemplate, Object... params) throws IllegalArgumentException, IndexOutOfBoundsException { + if (index >= 0 && index < size) { + return index; + } else { + throw new IndexOutOfBoundsException(badIndexMsg(index, size, errorMsgTemplate, params)); + } + } + + public static int checkBetween(int value, int min, int max) { + if (value >= min && value <= max) { + return value; + } else { + throw new IllegalArgumentException(StrFormatter.format("Length must be between {} and {}.", min, max)); + } + } + + public static long checkBetween(long value, long min, long max) { + if (value >= min && value <= max) { + return value; + } else { + throw new IllegalArgumentException(StrFormatter.format("Length must be between {} and {}.", min, max)); + } + } + + public static double checkBetween(double value, double min, double max) { + if (!(value < min) && !(value > max)) { + return value; + } else { + throw new IllegalArgumentException(StrFormatter.format("Length must be between {} and {}.", min, max)); + } + } + + public static Number checkBetween(Number value, Number min, Number max) { + notNull(value); + notNull(min); + notNull(max); + double valueDouble = value.doubleValue(); + double minDouble = min.doubleValue(); + double maxDouble = max.doubleValue(); + if (!(valueDouble < minDouble) && !(valueDouble > maxDouble)) { + return value; + } else { + throw new IllegalArgumentException(StrFormatter.format("Length must be between {} and {}.", min, max)); + } + } + + private static String badIndexMsg(int index, int size, String desc, Object... params) { + if (index < 0) { + return StrFormatter.format("{} ({}) must not be negative", StrFormatter.format(desc, params), index); + } else if (size < 0) { + throw new IllegalArgumentException("negative size: " + size); + } else { + return StrFormatter.format("{} ({}) must be less than size ({})", StrFormatter.format(desc, params), index, size); + } + } +} diff --git a/src/main/java/aiyh/utils/tool/CharUtil.java b/src/main/java/aiyh/utils/tool/CharUtil.java new file mode 100644 index 0000000..4057b09 --- /dev/null +++ b/src/main/java/aiyh/utils/tool/CharUtil.java @@ -0,0 +1,336 @@ +package aiyh.utils.tool; + + +import cn.hutool.core.text.ASCIIStrCache; + +/** + * 字符工具类
+ * 部分工具来自于Apache Commons系列 + * + * @author looly + * @since 4.0.1 + */ +public class CharUtil { + + public static final char SPACE = ' '; + public static final char TAB = ' '; + public static final char DOT = '.'; + public static final char SLASH = '/'; + public static final char BACKSLASH = '\\'; + public static final char CR = '\r'; + public static final char LF = '\n'; + public static final char UNDERLINE = '_'; + public static final char DASHED = '-'; + public static final char COMMA = ','; + public static final char DELIM_START = '{'; + public static final char DELIM_END = '}'; + public static final char BRACKET_START = '['; + public static final char BRACKET_END = ']'; + public static final char COLON = ':'; + public static final char DOUBLE_QUOTES = '"'; + public static final char SINGLE_QUOTE = '\''; + public static final char AMP = '&'; + + /** + * 是否为ASCII字符,ASCII字符位于0~127之间 + * + *
+	 *   CharUtil.isAscii('a')  = true
+	 *   CharUtil.isAscii('A')  = true
+	 *   CharUtil.isAscii('3')  = true
+	 *   CharUtil.isAscii('-')  = true
+	 *   CharUtil.isAscii('\n') = true
+	 *   CharUtil.isAscii('©') = false
+	 * 
+ * + * @param ch 被检查的字符处 + * @return true表示为ASCII字符,ASCII字符位于0~127之间 + */ + public static boolean isAscii(char ch) { + return ch < 128; + } + + /** + * 是否为可见ASCII字符,可见字符位于32~126之间 + * + *
+	 *   CharUtil.isAsciiPrintable('a')  = true
+	 *   CharUtil.isAsciiPrintable('A')  = true
+	 *   CharUtil.isAsciiPrintable('3')  = true
+	 *   CharUtil.isAsciiPrintable('-')  = true
+	 *   CharUtil.isAsciiPrintable('\n') = false
+	 *   CharUtil.isAsciiPrintable('©') = false
+	 * 
+ * + * @param ch 被检查的字符处 + * @return true表示为ASCII可见字符,可见字符位于32~126之间 + */ + public static boolean isAsciiPrintable(char ch) { + return ch >= 32 && ch < 127; + } + + /** + * 是否为ASCII控制符(不可见字符),控制符位于0~31和127 + * + *
+	 *   CharUtil.isAsciiControl('a')  = false
+	 *   CharUtil.isAsciiControl('A')  = false
+	 *   CharUtil.isAsciiControl('3')  = false
+	 *   CharUtil.isAsciiControl('-')  = false
+	 *   CharUtil.isAsciiControl('\n') = true
+	 *   CharUtil.isAsciiControl('©') = false
+	 * 
+ * + * @param ch 被检查的字符 + * @return true表示为控制符,控制符位于0~31和127 + */ + public static boolean isAsciiControl(final char ch) { + return ch < 32 || ch == 127; + } + + /** + * 判断是否为字母(包括大写字母和小写字母)
+ * 字母包括A~Z和a~z + * + *
+	 *   CharUtil.isLetter('a')  = true
+	 *   CharUtil.isLetter('A')  = true
+	 *   CharUtil.isLetter('3')  = false
+	 *   CharUtil.isLetter('-')  = false
+	 *   CharUtil.isLetter('\n') = false
+	 *   CharUtil.isLetter('©') = false
+	 * 
+ * + * @param ch 被检查的字符 + * @return true表示为字母(包括大写字母和小写字母)字母包括A~Z和a~z + */ + public static boolean isLetter(char ch) { + return isLetterUpper(ch) || isLetterLower(ch); + } + + /** + *

+ * 判断是否为大写字母,大写字母包括A~Z + *

+ * + *
+	 *   CharUtil.isLetterUpper('a')  = false
+	 *   CharUtil.isLetterUpper('A')  = true
+	 *   CharUtil.isLetterUpper('3')  = false
+	 *   CharUtil.isLetterUpper('-')  = false
+	 *   CharUtil.isLetterUpper('\n') = false
+	 *   CharUtil.isLetterUpper('©') = false
+	 * 
+ * + * @param ch 被检查的字符 + * @return true表示为大写字母,大写字母包括A~Z + */ + public static boolean isLetterUpper(final char ch) { + return ch >= 'A' && ch <= 'Z'; + } + + /** + *

+ * 检查字符是否为小写字母,小写字母指a~z + *

+ * + *
+	 *   CharUtil.isLetterLower('a')  = true
+	 *   CharUtil.isLetterLower('A')  = false
+	 *   CharUtil.isLetterLower('3')  = false
+	 *   CharUtil.isLetterLower('-')  = false
+	 *   CharUtil.isLetterLower('\n') = false
+	 *   CharUtil.isLetterLower('©') = false
+	 * 
+ * + * @param ch 被检查的字符 + * @return true表示为小写字母,小写字母指a~z + */ + public static boolean isLetterLower(final char ch) { + return ch >= 'a' && ch <= 'z'; + } + + /** + *

+ * 检查是否为数字字符,数字字符指0~9 + *

+ * + *
+	 *   CharUtil.isNumber('a')  = false
+	 *   CharUtil.isNumber('A')  = false
+	 *   CharUtil.isNumber('3')  = true
+	 *   CharUtil.isNumber('-')  = false
+	 *   CharUtil.isNumber('\n') = false
+	 *   CharUtil.isNumber('©') = false
+	 * 
+ * + * @param ch 被检查的字符 + * @return true表示为数字字符,数字字符指0~9 + */ + public static boolean isNumber(char ch) { + return ch >= '0' && ch <= '9'; + } + + /** + * 是否为16进制规范的字符,判断是否为如下字符 + *
+	 * 1. 0~9
+	 * 2. a~f
+	 * 4. A~F
+	 * 
+ * + * @param c 字符 + * @return 是否为16进制规范的字符 + * @since 4.1.5 + */ + public static boolean isHexChar(char c) { + return isNumber(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + } + + /** + * 是否为字符或数字,包括A~Z、a~z、0~9 + * + *
+	 *   CharUtil.isLetterOrNumber('a')  = true
+	 *   CharUtil.isLetterOrNumber('A')  = true
+	 *   CharUtil.isLetterOrNumber('3')  = true
+	 *   CharUtil.isLetterOrNumber('-')  = false
+	 *   CharUtil.isLetterOrNumber('\n') = false
+	 *   CharUtil.isLetterOrNumber('©') = false
+	 * 
+ * + * @param ch 被检查的字符 + * @return true表示为字符或数字,包括A~Z、a~z、0~9 + */ + public static boolean isLetterOrNumber(final char ch) { + return isLetter(ch) || isNumber(ch); + } + + /** + * 字符转为字符串
+ * 如果为ASCII字符,使用缓存 + * + * @param c 字符 + * @return 字符串 + * @see ASCIIStrCache#toString(char) + */ + public static String toString(char c) { + return ASCIIStrCache.toString(c); + } + + /** + * 给定类名是否为字符类,字符类包括: + * + *
+	 * Character.class
+	 * char.class
+	 * 
+ * + * @param clazz 被检查的类 + * @return true表示为字符类 + */ + public static boolean isCharClass(Class clazz) { + return clazz == Character.class || clazz == char.class; + } + + /** + * 给定对象对应的类是否为字符类,字符类包括: + * + *
+	 * Character.class
+	 * char.class
+	 * 
+ * + * @param value 被检查的对象 + * @return true表示为字符类 + */ + public static boolean isChar(Object value) { + // noinspection ConstantConditions + return value instanceof Character || value.getClass() == char.class; + } + + /** + * 是否空白符
+ * 空白符包括空格、制表符、全角空格和不间断空格
+ * + * @param c 字符 + * @return 是否空白符 + * @see Character#isWhitespace(int) + * @see Character#isSpaceChar(int) + * @since 4.0.10 + */ + public static boolean isBlankChar(char c) { + return isBlankChar((int) c); + } + + /** + * 是否空白符
+ * 空白符包括空格、制表符、全角空格和不间断空格
+ * + * @param c 字符 + * @return 是否空白符 + * @see Character#isWhitespace(int) + * @see Character#isSpaceChar(int) + * @since 4.0.10 + */ + public static boolean isBlankChar(int c) { + return Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\ufeff' || c == '\u202a'; + } + + /** + * 判断是否为emoji表情符
+ * + * @param c 字符 + * @return 是否为emoji + * @since 4.0.8 + */ + public static boolean isEmoji(char c) { + // noinspection ConstantConditions + return !((c == 0x0) || // + (c == 0x9) || // + (c == 0xA) || // + (c == 0xD) || // + ((c >= 0x20) && (c <= 0xD7FF)) || // + ((c >= 0xE000) && (c <= 0xFFFD)) || // + ((c >= 0x100000) && (c <= 0x10FFFF))); + } + + /** + * 是否为Windows或者Linux(Unix)文件分隔符
+ * Windows平台下分隔符为\,Linux(Unix)为/ + * + * @param c 字符 + * @return 是否为Windows或者Linux(Unix)文件分隔符 + * @since 4.1.11 + */ + public static boolean isFileSeparator(char c) { + return SLASH == c || BACKSLASH == c; + } + + /** + * 比较两个字符是否相同 + * + * @param c1 字符1 + * @param c2 字符2 + * @param ignoreCase 是否忽略大小写 + * @return 是否相同 + * @since 4.0.3 + */ + public static boolean equals(char c1, char c2, boolean ignoreCase) { + if (ignoreCase) { + return Character.toLowerCase(c1) == Character.toLowerCase(c2); + } + return c1 == c2; + } + + /** + * 获取字符类型 + * + * @param c 字符 + * @return 字符类型 + * @since 5.2.3 + */ + public static int getType(int c) { + return Character.getType(c); + } +} diff --git a/src/main/java/aiyh/utils/tool/StrFormatter.java b/src/main/java/aiyh/utils/tool/StrFormatter.java new file mode 100644 index 0000000..0798447 --- /dev/null +++ b/src/main/java/aiyh/utils/tool/StrFormatter.java @@ -0,0 +1,364 @@ +package aiyh.utils.tool; + +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; + +/** + * 字符串格式化工具 + * + * @author Looly + */ +public class StrFormatter { + public static final String ISO_8859_1 = "ISO-8859-1"; + /** + * UTF-8 + */ + public static final String UTF_8 = "UTF-8"; + /** + * GBK + */ + public static final String GBK = "GBK"; + + /** + * ISO-8859-1 + */ + public static final Charset CHARSET_ISO_8859_1 = StandardCharsets.ISO_8859_1; + /** + * UTF-8 + */ + public static final Charset CHARSET_UTF_8 = StandardCharsets.UTF_8; + public static final int INDEX_NOT_FOUND = -1; + + public static final char C_SPACE = CharUtil.SPACE; + public static final char C_TAB = CharUtil.TAB; + public static final char C_DOT = CharUtil.DOT; + public static final char C_SLASH = CharUtil.SLASH; + public static final char C_BACKSLASH = CharUtil.BACKSLASH; + public static final char C_CR = CharUtil.CR; + public static final char C_LF = CharUtil.LF; + public static final char C_UNDERLINE = CharUtil.UNDERLINE; + public static final char C_COMMA = CharUtil.COMMA; + public static final char C_DELIM_START = CharUtil.DELIM_START; + public static final char C_DELIM_END = CharUtil.DELIM_END; + public static final char C_BRACKET_START = CharUtil.BRACKET_START; + public static final char C_BRACKET_END = CharUtil.BRACKET_END; + public static final char C_COLON = CharUtil.COLON; + public static final String SPACE = " "; + public static final String TAB = " "; + public static final String DOT = "."; + public static final String DOUBLE_DOT = ".."; + public static final String SLASH = "/"; + public static final String BACKSLASH = "\\"; + public static final String EMPTY = ""; + public static final String NULL = "null"; + public static final String CR = "\r"; + public static final String LF = "\n"; + public static final String CRLF = "\r\n"; + public static final String UNDERLINE = "_"; + public static final String DASHED = "-"; + public static final String COMMA = ","; + public static final String DELIM_START = "{"; + public static final String DELIM_END = "}"; + public static final String BRACKET_START = "["; + public static final String BRACKET_END = "]"; + public static final String COLON = ":"; + + public static final String HTML_NBSP = " "; + public static final String HTML_AMP = "&"; + public static final String HTML_QUOTE = """; + public static final String HTML_APOS = "'"; + public static final String HTML_LT = "<"; + public static final String HTML_GT = ">"; + + public static final String EMPTY_JSON = "{}"; + + public static boolean isBlank(CharSequence str) { + final int length; + if ((str == null) || ((length = str.length()) == 0)) { + return true; + } + + for (int i = 0; i < length; i++) { + // 只要有一个非空字符即为非空字符串 + if (!isBlankChar(str.charAt(i))) { + return false; + } + } + + return true; + } + + public static boolean isBlankChar(char c) { + return isBlankChar((int) c); + } + + public static boolean isBlankChar(int c) { + return Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\ufeff' || c == '\u202a'; + } + + /** + * 格式化字符串
+ * 此方法只是简单将占位符 {} 按照顺序替换为参数
+ * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
+ * 例:
+ * 通常使用:format("this is {} for {}", "a", "b") =》 this is a for b
+ * 转义{}: format("this is \\{} for {}", "a", "b") =》 this is \{} for a
+ * 转义\: format("this is \\\\{} for {}", "a", "b") =》 this is \a for b
+ * + * @param strPattern 字符串模板 + * @param argArray 参数列表 + * @return 结果 + */ + public static String format(String strPattern, Object... argArray) { + return formatWith(strPattern, EMPTY_JSON, argArray); + } + + public static boolean isEmpty(T[] array) { + return array == null || array.length == 0; + } + + /** + * 格式化字符串
+ * 此方法只是简单将指定占位符 按照顺序替换为参数
+ * 如果想输出占位符使用 \\转义即可,如果想输出占位符之前的 \ 使用双转义符 \\\\ 即可
+ * 例:
+ * 通常使用:format("this is {} for {}", "{}", "a", "b") =》 this is a for b
+ * 转义{}: format("this is \\{} for {}", "{}", "a", "b") =》 this is {} for a
+ * 转义\: format("this is \\\\{} for {}", "{}", "a", "b") =》 this is \a for b
+ * + * @param strPattern 字符串模板 + * @param placeHolder 占位符,例如{} + * @param argArray 参数列表 + * @return 结果 + * @since 5.7.14 + */ + public static String formatWith(String strPattern, String placeHolder, Object... argArray) { + if (isBlank(strPattern) || isBlank(placeHolder) || isEmpty(argArray)) { + return strPattern; + } + final int strPatternLength = strPattern.length(); + final int placeHolderLength = placeHolder.length(); + + // 初始化定义好的长度以获得更好的性能 + final StringBuilder sbuf = new StringBuilder(strPatternLength + 50); + + int handledPosition = 0;// 记录已经处理到的位置 + int delimIndex;// 占位符所在位置 + for (int argIndex = 0; argIndex < argArray.length; argIndex++) { + delimIndex = strPattern.indexOf(placeHolder, handledPosition); + if (delimIndex == -1) {// 剩余部分无占位符 + if (handledPosition == 0) { // 不带占位符的模板直接返回 + return strPattern; + } + // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果 + sbuf.append(strPattern, handledPosition, strPatternLength); + return sbuf.toString(); + } + + // 转义符 + if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) {// 转义符 + if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) {// 双转义符 + // 转义符之前还有一个转义符,占位符依旧有效 + sbuf.append(strPattern, handledPosition, delimIndex - 1); + sbuf.append(utf8Str(argArray[argIndex])); + handledPosition = delimIndex + placeHolderLength; + } else { + // 占位符被转义 + argIndex--; + sbuf.append(strPattern, handledPosition, delimIndex - 1); + sbuf.append(placeHolder.charAt(0)); + handledPosition = delimIndex + 1; + } + } else {// 正常占位符 + sbuf.append(strPattern, handledPosition, delimIndex); + sbuf.append(utf8Str(argArray[argIndex])); + handledPosition = delimIndex + placeHolderLength; + } + } + + // 加入最后一个占位符后所有的字符 + sbuf.append(strPattern, handledPosition, strPatternLength); + + return sbuf.toString(); + } + + public static String utf8Str(Object obj) { + return str(obj, CHARSET_UTF_8); + } + + public static String str(Object obj, Charset charset) { + if (null == obj) { + return null; + } + + if (obj instanceof String) { + return (String) obj; + } else if (obj instanceof byte[]) { + return str(obj, charset); + } else if (obj instanceof Byte[]) { + return str(obj, charset); + } else if (obj instanceof ByteBuffer) { + return str(obj, charset); + } else if (isArray(obj)) { + return toString(obj); + } + + return obj.toString(); + } + + public static String toString(Object obj) { + if (null == obj) { + return null; + } + + if (obj instanceof long[]) { + return Arrays.toString((long[]) obj); + } else if (obj instanceof int[]) { + return Arrays.toString((int[]) obj); + } else if (obj instanceof short[]) { + return Arrays.toString((short[]) obj); + } else if (obj instanceof char[]) { + return Arrays.toString((char[]) obj); + } else if (obj instanceof byte[]) { + return Arrays.toString((byte[]) obj); + } else if (obj instanceof boolean[]) { + return Arrays.toString((boolean[]) obj); + } else if (obj instanceof float[]) { + return Arrays.toString((float[]) obj); + } else if (obj instanceof double[]) { + return Arrays.toString((double[]) obj); + } else if (isArray(obj)) { + // 对象数组 + try { + return Arrays.deepToString((Object[]) obj); + } catch (Exception ignore) { + // ignore + } + } + + return obj.toString(); + } + + public static boolean isArray(Object obj) { + return null != obj && obj.getClass().isArray(); + } + + + /** + * 格式化文本,使用 {varName} 占位
+ * map = {a: "aValue", b: "bValue"} format("{a} and {b}", map) ---=》 aValue and bValue + * + * @param template 文本模板,被替换的部分用 {key} 表示 + * @param map 参数值对 + * @param ignoreNull 是否忽略 {@code null} 值,忽略则 {@code null} 值对应的变量不被替换,否则替换为"" + * @return 格式化后的文本 + * @since 5.7.10 + */ + public static String format(CharSequence template, Map map, boolean ignoreNull) { + if (null == template) { + return null; + } + if (null == map || map.isEmpty()) { + return template.toString(); + } + + String template2 = template.toString(); + String value; + for (Map.Entry entry : map.entrySet()) { + value = utf8Str(entry.getValue()); + if (null == value && ignoreNull) { + continue; + } + template2 = replace(template2, "{" + entry.getKey() + "}", value); + } + return template2; + } + + public static boolean isSubEquals(CharSequence str1, int start1, CharSequence str2, int start2, int length, boolean ignoreCase) { + if (null == str1 || null == str2) { + return false; + } + + return str1.toString().regionMatches(ignoreCase, start1, str2.toString(), start2, length); + } + + public static int indexOf(final CharSequence str, CharSequence searchStr, int fromIndex, boolean ignoreCase) { + if (str == null || searchStr == null) { + return INDEX_NOT_FOUND; + } + if (fromIndex < 0) { + fromIndex = 0; + } + + final int endLimit = str.length() - searchStr.length() + 1; + if (fromIndex > endLimit) { + return INDEX_NOT_FOUND; + } + if (searchStr.length() == 0) { + return fromIndex; + } + + if (!ignoreCase) { + // 不忽略大小写调用JDK方法 + return str.toString().indexOf(searchStr.toString(), fromIndex); + } + + for (int i = fromIndex; i < endLimit; i++) { + if (isSubEquals(str, i, searchStr, 0, searchStr.length(), true)) { + return i; + } + } + return INDEX_NOT_FOUND; + } + + public static String str(CharSequence cs) { + return null == cs ? null : cs.toString(); + } + + public static boolean isEmpty(CharSequence str) { + return str == null || str.length() == 0; + } + + public static String replace(CharSequence str, CharSequence searchStr, CharSequence replacement) { + return replace(str, 0, searchStr, replacement, false); + } + + public static String replace(CharSequence str, int fromIndex, CharSequence searchStr, CharSequence replacement, boolean ignoreCase) { + if (isEmpty(str) || isEmpty(searchStr)) { + return str(str); + } + if (null == replacement) { + replacement = EMPTY; + } + + final int strLength = str.length(); + final int searchStrLength = searchStr.length(); + if (fromIndex > strLength) { + return str(str); + } else if (fromIndex < 0) { + fromIndex = 0; + } + + final StringBuilder result = new StringBuilder(strLength + 16); + if (0 != fromIndex) { + result.append(str.subSequence(0, fromIndex)); + } + + int preIndex = fromIndex; + int index; + while ((index = indexOf(str, searchStr, preIndex, ignoreCase)) > -1) { + result.append(str.subSequence(preIndex, index)); + result.append(replacement); + preIndex = index + searchStrLength; + } + + if (preIndex < strLength) { + // 结尾部分 + result.append(str.subSequence(preIndex, strLength)); + } + return result.toString(); + } +} diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/controller/RaceTrackController.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/controller/RaceTrackController.java new file mode 100644 index 0000000..5438a33 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/controller/RaceTrackController.java @@ -0,0 +1,47 @@ +package com.api.youhong.ai.pcn.racetrack.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.youhong.ai.pcn.racetrack.service.RaceTrackService; +import org.apache.log4j.Logger; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +/** + *

赛道图接口

+ * + *

create: 2023/2/14 11:58

+ * + * @author youHong.ai + */ +@Path("aiyh/race-track") +public class RaceTrackController { + + private final Logger log = Util.getLogger(); + + private final RaceTrackService service = new RaceTrackService(); + + @GET + @Path("/get/event-list") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getEventList(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + try { + return ApiResult.success(service.getEventList(user)); + } catch (Exception e) { + log.info("race track get event list error!\n" + Util.getErrString(e)); + return ApiResult.error("race track get event list error!"); + } + } + +} diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/dto/RaceTrackEvent.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/dto/RaceTrackEvent.java new file mode 100644 index 0000000..900d61b --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/dto/RaceTrackEvent.java @@ -0,0 +1,32 @@ +package com.api.youhong.ai.pcn.racetrack.dto; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + *

+ * + *

create: 2023/2/14 17:19

+ * + * @author youHong.ai + */ +@Setter +@Getter +@ToString +public class RaceTrackEvent { + /** id */ + private Integer id; + + /** 标题 */ + private String title; + + /** 副标题 */ + private String subtitle; + + /** 日期 */ + private String date; + + /** 月份 */ + private String month; +} diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/mapper/RacetrackMapper.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/mapper/RacetrackMapper.java new file mode 100644 index 0000000..f9b9867 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/mapper/RacetrackMapper.java @@ -0,0 +1,50 @@ +package com.api.youhong.ai.pcn.racetrack.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; +import com.api.youhong.ai.pcn.racetrack.dto.RaceTrackEvent; + +import java.util.List; + +/** + *

+ * + *

create: 2023/2/14 15:07

+ * + * @author youHong.ai + */ +@SqlMapper +public interface RacetrackMapper { + + /** + *

查询当前年的事件列表

+ * + * @param raceTrackEventListTable 事件所属表 + * @param raceTrackEventListDateField 事件日期字段 + * @param raceTrackEventListTitleField 事件标题字段 + * @param raceTrackEventListSubtitleField 事件副标题字段 + * @return 事件列表 + * @author youhong.ai + */ + @Select("select id, $t{raceTrackEventListDateField} date," + + "$t{raceTrackEventListTitleField} title," + + "MONTH($t{raceTrackEventListDateField}) month," + + "$t{raceTrackEventListSubtitleField} subtitle " + + " from $t{raceTrackEventListTable} where " + + "year($t{raceTrackEventListDateField}) = YEAR(NOW())") + List selectEventList(@ParamMapper("raceTrackEventListTable") String raceTrackEventListTable, + @ParamMapper("raceTrackEventListDateField") String raceTrackEventListDateField, + @ParamMapper("raceTrackEventListTitleField") String raceTrackEventListTitleField, + @ParamMapper("raceTrackEventListSubtitleField") String raceTrackEventListSubtitleField); + + /** + *

查询入职时间

+ * + * @param userId 用户ID + * @return 入职年限 + * @author youhong.ai + */ + @Select("select companyworkyear from hrmresource where id = #{userId}") + String selectLengthOfEntryTime(@ParamMapper("userId") Integer userId); +} diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/service/RaceTrackService.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/service/RaceTrackService.java new file mode 100644 index 0000000..046d023 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/service/RaceTrackService.java @@ -0,0 +1,59 @@ +package com.api.youhong.ai.pcn.racetrack.service; + +import aiyh.utils.Util; +import cn.hutool.core.lang.Assert; +import com.api.youhong.ai.pcn.racetrack.dto.RaceTrackEvent; +import com.api.youhong.ai.pcn.racetrack.mapper.RacetrackMapper; +import com.api.youhong.ai.pcn.racetrack.vo.RaceTrackVo; +import ebu7common.youhong.ai.bean.Builder; +import weaver.hrm.User; + +import java.util.List; + +/** + *

业务处理

+ * + *

create: 2023/2/14 12:13

+ * + * @author youHong.ai + */ +public class RaceTrackService { + + private final RacetrackMapper mapper = Util.getMapper(RacetrackMapper.class); + + /** + *

查询一年中的事件列表

+ * + * @return 事件列表 + * @author youhong.ai + */ + public Object getEventList(User user) { + /* ******************* 查询配置参数并且校验是否有值 ******************* */ + String raceTrackEventListTable = Util.getCusConfigValue("RACE_TRACK_EVENT_LIST_TABLE"); + Assert.notBlank(raceTrackEventListTable, + "race track event list table can not be null! check configuration [RACE_TRACK_EVENT_LIST_TABLE] in uf_cus_dev_config table!"); + String raceTrackEventListDateField = Util.getCusConfigValue("RACE_TRACK_EVENT_LIST_DATE_FIELD"); + Assert.notBlank(raceTrackEventListDateField, + "race track event list table date field can not be null! check configuration [RACE_TRACK_EVENT_LIST_DATE_FIELD] in uf_cus_dev_config table!"); + String raceTrackEventListTitleField = Util.getCusConfigValue("RACE_TRACK_EVENT_LIST_TITLE_FIELD"); + Assert.notBlank(raceTrackEventListTitleField, + "race track event list table title field can not be null! check configuration [RACE_TRACK_EVENT_LIST_TITLE_FIELD] in uf_cus_dev_config table!"); + String raceTrackEventListSubtitleField = Util.getCusConfigValue("RACE_TRACK_EVENT_LIST_SUBTITLE_FIELD"); + Assert.notBlank(raceTrackEventListSubtitleField, + "race track event list table subtitle field can not be null! check configuration [RACE_TRACK_EVENT_LIST_SUBTITLE_FIELD] in uf_cus_dev_config table!"); + + List raceTrackEventList = mapper.selectEventList(raceTrackEventListTable, raceTrackEventListDateField, + raceTrackEventListTitleField, raceTrackEventListSubtitleField); + String workYear = mapper.selectLengthOfEntryTime(user.getUID()); + double workYearD = Double.parseDouble(workYear); + double workMonth = workYearD * 12; + String lengthOfEntryTime = ""; + lengthOfEntryTime += Math.floor(workMonth / 12); + lengthOfEntryTime += " Year And " + Math.floor(workMonth % 12); + lengthOfEntryTime += " Month"; + return Builder.builder(RaceTrackVo::new) + .with(RaceTrackVo::setEventList, raceTrackEventList) + .with(RaceTrackVo::setLengthOfEntryTime, lengthOfEntryTime) + .build(); + } +} diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/RaceTrackVo.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/RaceTrackVo.java new file mode 100644 index 0000000..70e1a1b --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/RaceTrackVo.java @@ -0,0 +1,27 @@ +package com.api.youhong.ai.pcn.racetrack.vo; + +import com.api.youhong.ai.pcn.racetrack.dto.RaceTrackEvent; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +/** + *

+ * + *

create: 2023/2/14 15:08

+ * + * @author youHong.ai + */ +@Setter +@Getter +@ToString +public class RaceTrackVo { + + /** 事件列表 */ + List eventList; + + /** 入职时长 */ + private String lengthOfEntryTime; +} diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java index 4d5b9d3..81930b3 100644 --- a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java @@ -3,6 +3,7 @@ package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper; import aiyh.utils.annotation.recordset.ParamMapper; import aiyh.utils.annotation.recordset.Select; import aiyh.utils.annotation.recordset.SqlMapper; +import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.vo.ApaDataBtnShowVo; /** *

@@ -28,8 +29,9 @@ public interface ApaLevelByScoreMapper { Integer selectLevelByScore(Double score); - @Select("select id from $t{tableName} where $t{userField} = #{uId}") - Integer selectLevelByUserId(@ParamMapper("uId") int uid, - @ParamMapper("tableName") String tableName, - @ParamMapper("userField") String userField); + @Select("select id, $t{statusField} status from $t{tableName} where $t{userField} = #{uId} order by id desc limit 1") + ApaDataBtnShowVo selectLevelByUserId(@ParamMapper("uId") int uid, + @ParamMapper("tableName") String tableName, + @ParamMapper("statusField") String statusField, + @ParamMapper("userField") String userField); } diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java index 5a54b73..14e5b2b 100644 --- a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java @@ -4,6 +4,7 @@ import aiyh.utils.Util; import aiyh.utils.excention.CustomerException; import cn.hutool.core.lang.Assert; import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper.ApaLevelByScoreMapper; +import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.vo.ApaDataBtnShowVo; import weaver.hrm.User; /** @@ -34,11 +35,13 @@ public class ApaLevelByScoreService { return level; } - public Integer getApaLastDateId(User user) { + public ApaDataBtnShowVo getApaLastDateId(User user) { String apaLastIdTableName = Util.getCusConfigValue("APA_LAST_ID_TABLE_NAME"); String apaLastIdUserField = Util.getCusConfigValue("APA_LAST_ID_USER_FIELD"); + String apaLastIdStatusField = Util.getCusConfigValue("APA_LAST_ID_STATUS_FIELD"); Assert.notBlank(apaLastIdTableName, "can not get config [APA_LAST_ID_TABLE_NAME] from uf_cus_dev_config!"); Assert.notBlank(apaLastIdUserField, "can not get config [APA_LAST_ID_USER_FIELD] from uf_cus_dev_config!"); - return mapper.selectLevelByUserId(user.getUID(), apaLastIdTableName, apaLastIdUserField); + Assert.notBlank(apaLastIdStatusField, "can not get config [APA_LAST_ID_STATUS_FIELD] from uf_cus_dev_config!"); + return mapper.selectLevelByUserId(user.getUID(), apaLastIdTableName, apaLastIdStatusField, apaLastIdUserField); } } diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/vo/ApaDataBtnShowVo.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/vo/ApaDataBtnShowVo.java new file mode 100644 index 0000000..8074a5e --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/vo/ApaDataBtnShowVo.java @@ -0,0 +1,22 @@ +package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.vo; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + *

apa台账创建流程按钮显示隐藏控制Vo实体

+ * + *

create: 2023/2/13 16:39

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +public class ApaDataBtnShowVo { + + private Integer id; + + private Integer status; +} diff --git a/src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java b/src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java new file mode 100644 index 0000000..8641e7d --- /dev/null +++ b/src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java @@ -0,0 +1,81 @@ +package weaver.youhong.ai.intellectualproperty.action; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.ActionDefaultTestValue; +import aiyh.utils.annotation.ActionOptionalParam; +import aiyh.utils.annotation.PrintParamMark; +import aiyh.utils.annotation.RequiredMark; +import aiyh.utils.excention.CustomerException; +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtils; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.xiao.commons.config.entity.RequestMappingConfig; +import weaver.xiao.commons.config.service.DealWithMapping; + +import javax.ws.rs.core.MediaType; +import java.util.Map; + +/** + *

知识产权局ca电子签

+ * + *

create: 2023/2/16 15:22

+ * + * @author youHong.ai + */ +@Setter +@Getter +@ToString +public class CaElectronicSignatureAction extends SafeCusBaseAction { + @PrintParamMark + @ActionOptionalParam(value = "false", desc = "是否自动提交流程") + @ActionDefaultTestValue("false") + private String submitAction = "false"; + + @PrintParamMark + @ActionOptionalParam(value = "true", desc = "是否失败后阻断流程") + @ActionDefaultTestValue("true") + private String block = "true"; + + + @PrintParamMark + @RequiredMark("请求接口参数配置表中的唯一标识字段的值") + private String onlyMark; + + private final DealWithMapping dealWithMapping = new DealWithMapping(); + + private final HttpUtils httpUtils = new HttpUtils(); + + { + httpUtils.getGlobalCache().header.put("Content-Type", MediaType.APPLICATION_JSON); + } + + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + try { + dealWithMapping.setMainTable(billTable); + RequestMappingConfig requestMappingConfig = dealWithMapping.treeDealWithUniqueCode(onlyMark); + String requestUrl = requestMappingConfig.getRequestUrl(); + Map requestParam = dealWithMapping.getRequestParam(super.getObjMainTableValue(requestInfo), requestMappingConfig); + ResponeVo responeVo = httpUtils.apiPost(requestUrl, requestParam); + Map responseMap = responeVo.getResponseMap(); + } catch (Exception e) { + if (Boolean.parseBoolean(block)) { + throw new CustomerException(e.getMessage(), e); + } + } finally { + if (Boolean.parseBoolean(submitAction)) { + this.submitWorkflow(requestId, user.getUID()); + } + } + } + + public void submitWorkflow(String requestId, Integer userId) { + Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "电子签自动提交流程"); + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/sendemail/SendEmailToExternalPersonnelAction.java b/src/main/java/weaver/youhong/ai/pcn/actioin/sendemail/SendEmailToExternalPersonnelAction.java index f7b0b54..8ba5a13 100644 --- a/src/main/java/weaver/youhong/ai/pcn/actioin/sendemail/SendEmailToExternalPersonnelAction.java +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/sendemail/SendEmailToExternalPersonnelAction.java @@ -2,13 +2,10 @@ package weaver.youhong.ai.pcn.actioin.sendemail; import aiyh.utils.Util; import aiyh.utils.action.SafeCusBaseAction; -import aiyh.utils.annotation.ActionDesc; -import aiyh.utils.annotation.ActionOptionalParam; -import aiyh.utils.annotation.PrintParamMark; -import aiyh.utils.annotation.RequiredMark; +import aiyh.utils.annotation.*; import aiyh.utils.entity.DocImageInfo; import aiyh.utils.excention.CustomerException; -import cn.hutool.core.lang.Assert; +import aiyh.utils.tool.Assert; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -34,86 +31,90 @@ import java.util.stream.Collectors; @ToString @ActionDesc(value = "发送邮件到外部人员邮箱", author = "youhong.ai") public class SendEmailToExternalPersonnelAction extends SafeCusBaseAction { - - - @PrintParamMark - @ActionOptionalParam(value = "false", desc = "是否自动提交流程") - private String submitAction = "false"; - - @PrintParamMark - @ActionOptionalParam(value = "true", desc = "是否失败后阻断流程") - private String block = "true"; - - - @PrintParamMark - @RequiredMark("用户邮箱对应表单字段") - private String emailField; - - @PrintParamMark - @ActionOptionalParam(value = "", desc = "发送邮箱内容自定义表单表单字段,不填则默认使用开发参数配置表(uf_cus_dev_config)中唯一标识为" + - "`SendEmailToExternalPersonnelEmail`的值的邮件内容") - private String customerContentField; - - @PrintParamMark - @ActionOptionalParam(value = "", desc = "邮箱携带附件字段,不填则没有附件") - private String emailFileField; - - @PrintParamMark - @ActionOptionalParam(value = "", desc = "邮件标题字段,不填写则默认使用`defaultEmailSubject`的参数值") - private String emailSubjectField; - - @PrintParamMark - @ActionOptionalParam(value = "", desc = "邮件标题默认") - private String defaultEmailSubject = ""; - - - @Override - public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { - try { - - Map mainTableValue = super.getMainTableValue(requestInfo); - String content = ""; - String email = mainTableValue.get(emailField); - String emailSubject = StringUtils.isNullOrEmpty(emailSubjectField) ? defaultEmailSubject : mainTableValue.get(emailSubjectField); - if (StringUtils.isNullOrEmpty(customerContentField)) { - content = Util.getCusConfigDefaultValue("SendEmailToExternalPersonnelEmail", ""); - } else { - content = mainTableValue.get(customerContentField); - } - if (StringUtils.isNullOrEmpty(emailFileField)) { - EmailWorkRunnable.threadModeReminder(email, emailSubject, content); - if (Boolean.parseBoolean(submitAction)) { - this.submitWorkflow(requestId, user.getUID()); - } - return; - } - String docIds = mainTableValue.get(emailFileField); - if (StringUtils.isNullOrEmpty(docIds)) { - EmailWorkRunnable.threadModeReminder(email, emailSubject, content); - if (Boolean.parseBoolean(submitAction)) { - this.submitWorkflow(requestId, user.getUID()); - } - return; - } - List docImageInfos = Util.selectImageInfoByDocIds(docIds); - Assert.notEmpty(docImageInfos, "can not query docImageInfo by Util.selectImageInfoByDocIds method, param is [{}]", docIds); - List imageIdList = docImageInfos.stream().map(DocImageInfo::getImageFileId).collect(Collectors.toList()); - EmailWorkRunnable.threadModeReminder(email, "", "", - emailSubject, content, Util.intJoin(imageIdList, ",")); - if (Boolean.parseBoolean(submitAction)) { - this.submitWorkflow(requestId, user.getUID()); - } - } catch (Exception e) { - if (Boolean.parseBoolean(block)) { - throw new CustomerException(e.getMessage(), e); - } - } - } - - - public void submitWorkflow(String requestId, Integer userId) { - - Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "批量签署自动提交流程!"); - } - + + + @PrintParamMark + @ActionOptionalParam(value = "false", desc = "是否自动提交流程") + private String submitAction = "false"; + + @PrintParamMark + @ActionOptionalParam(value = "true", desc = "是否失败后阻断流程") + private String block = "true"; + + + @PrintParamMark + @RequiredMark("用户邮箱对应表单字段") + @ActionDefaultTestValue("yx") + private String emailField; + + @PrintParamMark + @ActionOptionalParam(value = "", desc = "发送邮箱内容自定义表单表单字段,不填则默认使用开发参数配置表(uf_cus_dev_config)中唯一标识为" + + "`SendEmailToExternalPersonnelEmail`的值的邮件内容") + @ActionDefaultTestValue("nr") + private String customerContentField; + + @PrintParamMark + @ActionOptionalParam(value = "", desc = "邮箱携带附件字段,不填则没有附件") + @ActionDefaultTestValue("fj") + private String emailFileField; + + @PrintParamMark + @ActionOptionalParam(value = "", desc = "邮件标题字段,不填写则默认使用`defaultEmailSubject`的参数值") + @ActionDefaultTestValue("bt") + private String emailSubjectField; + + @PrintParamMark + @ActionOptionalParam(value = "", desc = "邮件标题默认") + private String defaultEmailSubject = ""; + + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + try { + + Map mainTableValue = super.getMainTableValue(requestInfo); + String content = ""; + String email = mainTableValue.get(emailField); + String emailSubject = StringUtils.isNullOrEmpty(emailSubjectField) ? defaultEmailSubject : mainTableValue.get(emailSubjectField); + if (StringUtils.isNullOrEmpty(customerContentField)) { + content = Util.getCusConfigDefaultValue("SendEmailToExternalPersonnelEmail", ""); + } else { + content = mainTableValue.get(customerContentField); + } + if (StringUtils.isNullOrEmpty(emailFileField)) { + EmailWorkRunnable.threadModeReminder(email, emailSubject, content); + if (Boolean.parseBoolean(submitAction)) { + this.submitWorkflow(requestId, user.getUID()); + } + return; + } + String docIds = mainTableValue.get(emailFileField); + if (StringUtils.isNullOrEmpty(docIds)) { + EmailWorkRunnable.threadModeReminder(email, emailSubject, content); + if (Boolean.parseBoolean(submitAction)) { + this.submitWorkflow(requestId, user.getUID()); + } + return; + } + List docImageInfos = Util.selectImageInfoByDocIds(docIds); + Assert.notEmpty(docImageInfos, "can not query docImageInfo by Util.selectImageInfoByDocIds method, param is [{}]", docIds); + List imageIdList = docImageInfos.stream().map(DocImageInfo::getImageFileId).collect(Collectors.toList()); + EmailWorkRunnable.threadModeReminder(email, "", "", + emailSubject, content, Util.intJoin(imageIdList, ",")); + if (Boolean.parseBoolean(submitAction)) { + this.submitWorkflow(requestId, user.getUID()); + } + } catch (Exception e) { + if (Boolean.parseBoolean(block)) { + throw new CustomerException(e.getMessage(), e); + } + } + } + + + public void submitWorkflow(String requestId, Integer userId) { + + Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "邮件发送附件提交流程!"); + } + } diff --git a/常用信息.md b/常用信息.md index e9d0518..2d95acb 100644 --- a/常用信息.md +++ b/常用信息.md @@ -77,7 +77,7 @@ getQueryString = (name) => { **5.通过js获取react组件,操作组件内部数据** ```javascript -function FindReact(dom, traverseUp = 0) { +function findReact(dom, traverseUp = 0) { const key = Object.keys(dom).find(key => { return key.startsWith("__reactFiber$") // react 17+ || key.startsWith("__reactInternalInstance$"); // react <17 @@ -502,10 +502,10 @@ from workflow_nodebase nb ```java //@Context HttpServletRequest request, @Context HttpServletResponse response User logInUser=HrmUserVarify.getUser(request,response); - // 传入id会将此人员信息带出 - User user=new User(id); - // 获取人员id - user.getUID(); + // 传入id会将此人员信息带出 + User user=new User(id); + // 获取人员id + user.getUID(); ``` **2.发送邮件** @@ -548,8 +548,8 @@ EmailWorkRunnable.threadModeReminder(sendTo,sendCc,sendBcc,subject,content,image @param imageFileIds 附件id */ EmailWorkRunnable emailWorkRunable=new EmailWorkRunnable(sendTo,sendCc,sendBcc,subject,content); - emailWorkRunable.setImagefileids(imageFileIds); - MailCommonUtils.executeThreadPool(EmailPoolSubTypeEnum.EMAIL_SYS_ALTER.toString(),emailWorkRunable); + emailWorkRunable.setImagefileids(imageFileIds); + MailCommonUtils.executeThreadPool(EmailPoolSubTypeEnum.EMAIL_SYS_ALTER.toString(),emailWorkRunable); ``` **3.短信服务** @@ -557,11 +557,11 @@ EmailWorkRunnable emailWorkRunable=new EmailWorkRunnable(sendTo,sendCc,sendBcc,s ```java public class SendSms implements SmsService { - @Override - public boolean sendSMS(String smsId, String number, String msg) { - //执行短信调用接口逻辑 - return SMSUtil.sendSms(number, msg, url, sn, pwd); - } + @Override + public boolean sendSMS(String smsId, String number, String msg) { + //执行短信调用接口逻辑 + return SMSUtil.sendSms(number, msg, url, sn, pwd); + } } ``` @@ -571,9 +571,9 @@ public class SendSms implements SmsService { ```java //wps转PDF: DocImagefileToPdfUseWps toPdfUseWps=new DocImagefileToPdfUseWps(); - newimagefileid=toPdfUseWps.officeDocumetnToPdfByImagefileid(docimagefileid); - - //永中转PDF: - DocImagefileToPdf yozoToPdf=new DocImagefileToPdf(); - newimagefileid=yozoToPdf.officeDocumetnToPdfByImagefileid(docimagefileid); + newimagefileid=toPdfUseWps.officeDocumetnToPdfByImagefileid(docimagefileid); + + //永中转PDF: + DocImagefileToPdf yozoToPdf=new DocImagefileToPdf(); + newimagefileid=yozoToPdf.officeDocumetnToPdfByImagefileid(docimagefileid); ``` \ No newline at end of file