ssl测试

main
youHong.ai 2023-02-16 19:00:32 +08:00
parent 3d513ac8cc
commit 2857d0a3df
22 changed files with 2556 additions and 929 deletions

View File

@ -27,6 +27,11 @@ WfForm.OPER_SAVECOMPLETE = '保存后页面跳转前 KB900210501'
WfForm.OPER_WITHDRAW = '撤回 KB900201101' WfForm.OPER_WITHDRAW = '撤回 KB900201101'
WfForm.OPER_CLOSE = '页面关闭' WfForm.OPER_CLOSE = '页面关闭'
/**
* 注册流程事件
* @param type
* @param callback
*/
WfForm.registerCheckEvent = (type, callback = (callback) = {}) => { WfForm.registerCheckEvent = (type, callback = (callback) = {}) => {
// WfForm.registerCheckEvent(WfForm.OPER_SAVE+","+WfForm.OPER_SUBMIT,function(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:"不需要" //自定义取消按钮名称
// });
}
/* ******************* 建模表开发依赖 ******************* */ /* ******************* 建模表开发依赖 ******************* */

View File

@ -305,52 +305,133 @@ $(() => {
$(() => { $(() => {
const workflowInsertValueConfig = [ const workflowInsertValueConfig = [
{ {
table: '', table: 'detail_1',
targetTable: '', targetTable: 'detail_3',
filedMapping: [{ filedMapping: [{
source: '', source: 'mbmc',
target: '' target: 'name'
}, {
source: 'mbms',
target: 'description'
}, {
source: 'zp',
target: 'score'
}, {
source: 'zwpj',
target: 'grpj'
}, {
source: 'mbmc',
target: 'ldpf'
}, {
source: 'ldpj',
target: 'ldpj'
}] }]
}, { }, {
table: '', table: 'detail_2',
targetTable: '', targetTable: 'detail_3',
filedMapping: [] 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 = [] let mappingResult = []
workflowInsertValueConfig.forEach(item => { workflowInsertValueConfig.forEach(item => {
let valueMapping = getDetailValueMapping(item) let valueMapping = getDetailValueMapping(item)
mappingResult = [...mappingResult, ...valueMapping] mappingResult = [...mappingResult, ...valueMapping]
}) })
})() setValue(mappingResult)
function setValue(valueMapping) {
} }
/**
* 设置表数据到指定的明细表中
* @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) { function getDetailValueMapping(configItem) {
let detailIdsStr = WfForm.getDetailAllRowIndexStr(configItem.table); let detailIdsStr = WfForm.getDetailAllRowIndexStr(configItem.table);
let detailIdArr = detailIdsStr.split(",") let detailIdArr = detailIdsStr.split(",")
let result = [] let result = []
for (let i = 0; i < detailIdArr.length; i++) { 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) result.push(fieldValueMapping)
} }
return result return result
} }
function getValueByConfig(fieldMapping, tableName, detailIndex) { /**
* 通过配置数据获取值
* @param fieldMapping 字段映射规则数组
* @param tableName 表名称
* @param detailIndex 明细表下标
* @param targetTable 目标表
* @returns {*[]} 对应明细行的值数组
*/
function getValueByConfig(fieldMapping, tableName, detailIndex, targetTable) {
let result = [] let result = []
fieldMapping.forEach(item => { fieldMapping.forEach(item => {
let fieldValue = Utils.getFiledValueByName({ let fieldValue = Utils.getFiledValueByName({
fieldName: item.source, fieldName: item.source,
TableName: tableName table: tableName
}, detailIndex) }, detailIndex)
result.push({ result.push({
targetField: item.target, targetField: item.target,
value: fieldValue value: fieldValue,
targetTable: targetTable
}) })
}) })
return result return result
@ -360,3 +441,46 @@ $(() => {
}) })
/* ******************* 流程明细数据整合插入end ******************* */ /* ******************* 流程明细数据整合插入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, <table></table>) + "_" + 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 ******************* */

View File

@ -2,7 +2,7 @@ package aiyh.utils.action;
import aiyh.utils.Util; import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException; import aiyh.utils.excention.CustomerException;
import org.apache.commons.lang3.StringUtils; import com.google.common.base.Strings;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import weaver.hrm.User; import weaver.hrm.User;
@ -12,7 +12,6 @@ import weaver.workflow.request.RequestManager;
import weaver.workflow.workflow.WorkflowBillComInfo; import weaver.workflow.workflow.WorkflowBillComInfo;
import weaver.workflow.workflow.WorkflowComInfo; import weaver.workflow.workflow.WorkflowComInfo;
import java.io.IOException;
import java.util.*; import java.util.*;
/** /**
@ -21,269 +20,279 @@ import java.util.*;
* @author EBU7-dev-1 aiyh * @author EBU7-dev-1 aiyh
*/ */
public abstract class SafeCusBaseAction implements Action { public abstract class SafeCusBaseAction implements Action {
/** /**
* *
*/ */
protected final Logger log = Util.getLogger(); protected final Logger log = Util.getLogger();
private final Map<String, SafeCusBaseActionHandleFunction> actionHandleMethod = new HashMap<>(); private final Map<String, SafeCusBaseActionHandleFunction> actionHandleMethod = new HashMap<>();
/** /**
* <h2></h2> * <h2></h2>
*/ */
private void initHandleMethod() { private void initHandleMethod() {
// 提交 // 提交
actionHandleMethod.put(ActionRunType.SUBMIT, this::doSubmit); actionHandleMethod.put(ActionRunType.SUBMIT, this::doSubmit);
// 退回 // 退回
actionHandleMethod.put(ActionRunType.REJECT, this::doReject); actionHandleMethod.put(ActionRunType.REJECT, this::doReject);
// 撤回 // 撤回
actionHandleMethod.put(ActionRunType.WITHDRAW, this::doWithdraw); actionHandleMethod.put(ActionRunType.WITHDRAW, this::doWithdraw);
// 强制收回 // 强制收回
actionHandleMethod.put(ActionRunType.DRAW_BACK, this::doDrawBack); actionHandleMethod.put(ActionRunType.DRAW_BACK, this::doDrawBack);
} }
@Override @Override
public final String execute(RequestInfo requestInfo) { public final String execute(RequestInfo requestInfo) {
RequestManager requestManager = requestInfo.getRequestManager(); RequestManager requestManager = requestInfo.getRequestManager();
String billTable = requestManager.getBillTableName(); String billTable = requestManager.getBillTableName();
String requestId = requestInfo.getRequestid(); String requestId = requestInfo.getRequestid();
User user = requestInfo.getRequestManager().getUser(); User user = requestInfo.getRequestManager().getUser();
int workflowId = requestManager.getWorkflowid(); int workflowId = requestManager.getWorkflowid();
// 操作类型 submit - 提交 reject - 退回 等 // 操作类型 submit - 提交 reject - 退回 等
String src = requestManager.getSrc(); String src = requestManager.getSrc();
if ("".equals(billTable)) { if ("".equals(billTable)) {
WorkflowComInfo workflowComInfo = new WorkflowComInfo(); WorkflowComInfo workflowComInfo = new WorkflowComInfo();
String formId = workflowComInfo.getFormId(String.valueOf(workflowId)); String formId = workflowComInfo.getFormId(String.valueOf(workflowId));
WorkflowBillComInfo workflowBillComInfo = new WorkflowBillComInfo(); WorkflowBillComInfo workflowBillComInfo = new WorkflowBillComInfo();
billTable = workflowBillComInfo.getTablename(formId); billTable = workflowBillComInfo.getTablename(formId);
} }
try { try {
Util.verifyRequiredField(this); Util.verifyRequiredField(this);
if (StringUtils.isEmpty(src)) { if (!Strings.isNullOrEmpty(src)) {
src = "submit"; src = "submit";
} }
// 初始化默认的流程处理方法 // 初始化默认的流程处理方法
initHandleMethod(); initHandleMethod();
// 提供自定义注册处理方法 // 提供自定义注册处理方法
registerHandler(actionHandleMethod); registerHandler(actionHandleMethod);
// 获取流程对应的处理方法 // 获取流程对应的处理方法
SafeCusBaseActionHandleFunction cusBaseActionHandleFunction = actionHandleMethod.get(src); SafeCusBaseActionHandleFunction cusBaseActionHandleFunction = actionHandleMethod.get(src);
// 默认没有直接成功不做拦截 // 默认没有直接成功不做拦截
if (null == cusBaseActionHandleFunction) { if (null == cusBaseActionHandleFunction) {
return Action.SUCCESS; return Action.SUCCESS;
} }
cusBaseActionHandleFunction.handle(requestId, billTable, workflowId, user, requestInfo); cusBaseActionHandleFunction.handle(requestId, billTable, workflowId, user, requestInfo);
} catch (CustomerException e) { } catch (CustomerException e) {
if (e.getCode() != null && e.getCode() == 500) { if (e.getCode() != null && e.getCode() == 500) {
Util.actionFail(requestManager, e.getMessage()); Util.actionFail(requestManager, e.getMessage());
return Action.FAILURE_AND_CONTINUE; return Action.FAILURE_AND_CONTINUE;
} }
if (this.exceptionCallback(e, requestManager)) { if (this.exceptionCallback(e, requestManager)) {
return Action.FAILURE_AND_CONTINUE; return Action.FAILURE_AND_CONTINUE;
} }
} catch (Exception e) { } catch (Exception e) {
if (this.exceptionCallback(e, requestManager)) { if (this.exceptionCallback(e, requestManager)) {
return Action.FAILURE_AND_CONTINUE; return Action.FAILURE_AND_CONTINUE;
} }
} }
return Action.SUCCESS; return Action.SUCCESS;
} }
/** /**
* <h2></h2> * <h2></h2>
* *
* @param e * @param e
* @param requestManager requestManager * @param requestManager requestManager
* @return actiontrue- false- * @return actiontrue- false-
*/ */
public boolean exceptionCallback(Exception e, RequestManager requestManager) { public boolean exceptionCallback(Exception e, RequestManager requestManager) {
e.printStackTrace(); e.printStackTrace();
log.error(Util.logStr("getDataId action fail, exception message is [{}], error stack trace msg is: \n{}", log.error(Util.logStr("execute action fail, exception message is [{}], error stack trace msg is: \n{}",
e.getMessage(), Util.getErrString(e))); e.getMessage(), Util.getErrString(e)));
Util.actionFail(requestManager, e.getMessage()); Util.actionFail(requestManager, e.getMessage());
return true; return true;
} }
/** /**
* <h2></h2> * <h2></h2>
* *
* @param actionHandleMethod map * @param actionHandleMethod map
*/ */
public void registerHandler(Map<String, SafeCusBaseActionHandleFunction> actionHandleMethod) { public void registerHandler(Map<String, SafeCusBaseActionHandleFunction> actionHandleMethod) {
} }
/** /**
* <h2>action </h2> * <h2>action </h2>
* <p> * <p>
* log Util.actionFailException(requestManager,"error msg"); action * log Util.actionFailException(requestManager,"error msg"); action
* </p> * </p>
* *
* @param requestId ID * @param requestId ID
* @param billTable * @param billTable
* @param workflowId ID * @param workflowId ID
* @param user * @param user
* @param requestInfo * @param requestInfo
*/ */
public abstract void doSubmit(String requestId, String billTable, int workflowId, public abstract void doSubmit(String requestId, String billTable, int workflowId,
User user, RequestInfo requestInfo); User user, RequestInfo requestInfo);
/** /**
* <h2>action 退</h2> * <h2>action 退</h2>
* <p> * <p>
* log Util.actionFailException(requestManager,"error msg"); action * log Util.actionFailException(requestManager,"error msg"); action
* </p> * </p>
* *
* @param requestId ID * @param requestId ID
* @param billTable * @param billTable
* @param workflowId ID * @param workflowId ID
* @param user * @param user
* @param requestInfo * @param requestInfo
*/ */
public void doReject(String requestId, String billTable, int workflowId, public void doReject(String requestId, String billTable, int workflowId,
User user, RequestInfo requestInfo) { User user, RequestInfo requestInfo) {
} }
/** /**
* <h2>action </h2> * <h2>action </h2>
* <p> * <p>
* log Util.actionFailException(requestManager,"error msg"); action * log Util.actionFailException(requestManager,"error msg"); action
* </p> * </p>
* *
* @param requestId ID * @param requestId ID
* @param billTable * @param billTable
* @param workflowId ID * @param workflowId ID
* @param user * @param user
* @param requestInfo * @param requestInfo
*/ */
public void doWithdraw(String requestId, String billTable, int workflowId, public void doWithdraw(String requestId, String billTable, int workflowId,
User user, RequestInfo requestInfo) { User user, RequestInfo requestInfo) {
} }
/** /**
* <h2>action </h2> * <h2>action </h2>
* <p> * <p>
* log Util.actionFailException(requestManager,"error msg"); action * log Util.actionFailException(requestManager,"error msg"); action
* </p> * </p>
* *
* @param requestId ID * @param requestId ID
* @param billTable * @param billTable
* @param workflowId ID * @param workflowId ID
* @param user * @param user
* @param requestInfo * @param requestInfo
*/ */
public void doDrawBack(String requestId, String billTable, int workflowId, public void doDrawBack(String requestId, String billTable, int workflowId,
User user, RequestInfo requestInfo) { User user, RequestInfo requestInfo) {
} }
/** /**
* <h2></h2> * <h2></h2>
* *
* @return * @return
*/ */
protected Map<String, String> getMainTableValue(RequestInfo requestInfo) { protected Map<String, String> getMainTableValue(RequestInfo requestInfo) {
// 获取主表数据 // 获取主表数据
Property[] propertyArr = requestInfo.getMainTableInfo().getProperty(); Property[] propertyArr = requestInfo.getMainTableInfo().getProperty();
return getStringMap(propertyArr); return getStringMap(propertyArr);
} }
@NotNull @NotNull
private Map<String, String> getStringMap(Property[] propertyArr) { private Map<String, String> getStringMap(Property[] propertyArr) {
if (null == propertyArr) { if (null == propertyArr) {
return Collections.emptyMap(); return Collections.emptyMap();
} }
Map<String, String> mainTable = new HashMap<>((int) Math.ceil(propertyArr.length * 1.4)); Map<String, String> mainTable = new HashMap<>((int) Math.ceil(propertyArr.length * 1.4));
for (Property property : propertyArr) { for (Property property : propertyArr) {
String fieldName = property.getName(); String fieldName = property.getName();
String value = property.getValue(); String value = property.getValue();
mainTable.put(fieldName, value); mainTable.put(fieldName, value);
} }
return mainTable; return mainTable;
} }
/**
/** * <h2></h2>
* <h2></h2> *
* * @return
* @return */
*/ protected Map<String, Object> getObjMainTableValue(RequestInfo requestInfo) {
protected Map<String, List<Map<String, String>>> getDetailTableValue(RequestInfo requestInfo) { Map<String, String> mainTableValue = getMainTableValue(requestInfo);
DetailTable[] detailTableArr = requestInfo.getDetailTableInfo().getDetailTable(); return new HashMap<>(mainTableValue);
return getListMap(detailTableArr); }
}
/**
@NotNull * <h2></h2>
private Map<String, List<Map<String, String>>> getListMap(DetailTable[] detailTableArr) { *
Map<String, List<Map<String, String>>> detailDataList = new HashMap<>((int) Math.ceil(detailTableArr.length * 1.4)); * @return
for (DetailTable detailTable : detailTableArr) { */
List<Map<String, String>> detailData = getDetailValue(detailTable); protected Map<String, List<Map<String, String>>> getDetailTableValue(RequestInfo requestInfo) {
detailDataList.put(detailTable.getId(), detailData); DetailTable[] detailTableArr = requestInfo.getDetailTableInfo().getDetailTable();
} return getListMap(detailTableArr);
return detailDataList; }
}
@NotNull
/** private Map<String, List<Map<String, String>>> getListMap(DetailTable[] detailTableArr) {
* <h2></h2> Map<String, List<Map<String, String>>> detailDataList = new HashMap<>((int) Math.ceil(detailTableArr.length * 1.4));
* for (DetailTable detailTable : detailTableArr) {
* @param detailNo List<Map<String, String>> detailData = getDetailValue(detailTable);
* @return detailDataList.put(detailTable.getId(), detailData);
*/ }
protected List<Map<String, String>> getDetailTableValueByDetailNo(int detailNo, RequestInfo requestInfo) { return detailDataList;
DetailTable detailTable = requestInfo.getDetailTableInfo().getDetailTable(detailNo); }
return getDetailValue(detailTable);
}
/**
/** * <h2></h2>
* <h2></h2> *
* * @param detailNo
* @param detailTable * @return
* @return */
*/ protected List<Map<String, String>> getDetailTableValueByDetailNo(int detailNo, RequestInfo requestInfo) {
@NotNull DetailTable detailTable = requestInfo.getDetailTableInfo().getDetailTable(detailNo);
private List<Map<String, String>> getDetailValue(DetailTable detailTable) { return getDetailValue(detailTable);
Row[] rowArr = detailTable.getRow(); }
List<Map<String, String>> detailData = new ArrayList<>(rowArr.length);
for (Row row : rowArr) { /**
Cell[] cellArr = row.getCell(); * <h2></h2>
Map<String, String> rowData = new HashMap<>((int) Math.ceil(cellArr.length * (1 + 0.4))); *
rowData.put("id", row.getId()); * @param detailTable
for (Cell cell : cellArr) { * @return
String fieldName = cell.getName(); */
String value = cell.getValue(); @NotNull
rowData.put(fieldName, value); private List<Map<String, String>> getDetailValue(DetailTable detailTable) {
} Row[] rowArr = detailTable.getRow();
detailData.add(rowData); List<Map<String, String>> detailData = new ArrayList<>(rowArr.length);
} for (Row row : rowArr) {
return detailData; Cell[] cellArr = row.getCell();
} Map<String, String> rowData = new HashMap<>((int) Math.ceil(cellArr.length * (1 + 0.4)));
rowData.put("id", row.getId());
for (Cell cell : cellArr) {
public static final class ActionRunType { String fieldName = cell.getName();
/** String value = cell.getValue();
* 退 rowData.put(fieldName, value);
*/ }
public static final String REJECT = "reject"; detailData.add(rowData);
/** }
* return detailData;
*/ }
public static final String WITHDRAW = "withdraw";
/**
* public static final class ActionRunType {
*/ /**
public static final String DRAW_BACK = "drawBack"; * 退
/** */
* public static final String REJECT = "reject";
*/ /**
public static final String SUBMIT = "submit"; *
} */
public static final String WITHDRAW = "withdraw";
/**
*
*/
public static final String DRAW_BACK = "drawBack";
/**
*
*/
public static final String SUBMIT = "submit";
}
} }

View File

@ -10,47 +10,49 @@ import org.apache.log4j.Logger;
* @author ayh * @author ayh
*/ */
public class CustomerException extends RuntimeException{ public class CustomerException extends RuntimeException {
private Logger logger = Util.getLogger(); private final Logger logger = Util.getLogger();
private String msg; private final String msg;
private Throwable throwable; private Throwable throwable;
private Integer code; private Integer code = -1;
public CustomerException(String msg){ public CustomerException(String msg) {
super(msg); super(msg);
this.msg = msg; this.msg = msg;
} }
public CustomerException(String msg,Integer code){ public CustomerException(String msg, Integer code) {
super(msg); super(msg);
this.code = code; this.code = code;
this.msg = msg; this.msg = msg;
} }
public CustomerException(String msg, Integer code, Throwable throwable){
super(msg); public CustomerException(String msg, Integer code, Throwable throwable) {
this.code= code; super(msg);
this.msg = msg; this.code = code;
} this.msg = msg;
public CustomerException(String msg, Throwable throwable){ }
super(msg,throwable);
this.msg = msg; public CustomerException(String msg, Throwable throwable) {
this.throwable = throwable; super(msg, throwable);
} this.msg = msg;
this.throwable = throwable;
@Override }
public void printStackTrace() {
logger.error("二开自定义异常:" + this.msg); @Override
if(this.throwable != null){ public void printStackTrace() {
logger.error("异常信息: " + Util.getErrString(this.throwable)); logger.error("二开自定义异常:" + this.msg);
} if (this.throwable != null) {
} logger.error("异常信息: " + Util.getErrString(this.throwable));
}
public Integer getCode (){ }
return this.code;
} public Integer getCode() {
return this.code;
@Override }
public String getMessage() {
return this.msg; @Override
} public String getMessage() {
return this.msg;
}
} }

View File

@ -4,17 +4,22 @@ import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
/** /**
@ -22,76 +27,122 @@ import java.security.NoSuchAlgorithmException;
* @since 2021/08/30 17:56 * @since 2021/08/30 17:56
**/ **/
public class HttpManager { public class HttpManager {
/** /**
* *
*/ */
private static final int CONNECT_TIMEOUT = 1000 * 60 * 3; private static final int CONNECT_TIMEOUT = 1000 * 60 * 3;
private static final int CONNECTION_REQUEST_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 SOCKET_TIMEOUT = 10000 * 60 * 3;
private static final int MAX_TOTAL = 500; private static final int MAX_TOTAL = 500;
private static final int MAX_PRE_ROUTE = 500; private static final int MAX_PRE_ROUTE = 500;
/** /**
* *
*/ */
static RequestConfig requestConfig = RequestConfig.custom() static RequestConfig requestConfig = RequestConfig.custom()
//网络请求的超时时间 // 网络请求的超时时间
.setConnectTimeout(CONNECT_TIMEOUT) .setConnectTimeout(CONNECT_TIMEOUT)
//连接池去获取连接的超时时间 // 连接池去获取连接的超时时间
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
//设置socket超时时间 // 设置socket超时时间
.setSocketTimeout(SOCKET_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT)
.build(); .build();
static PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(); static PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
static {
// 配置最大的连接数 static {
manager.setMaxTotal(MAX_TOTAL); // 配置最大的连接数
// 每个路由最大连接数路由是根据host来管理的大小不好控制 manager.setMaxTotal(MAX_TOTAL);
manager.setDefaultMaxPerRoute(MAX_PRE_ROUTE); // 每个路由最大连接数路由是根据host来管理的大小不好控制
} manager.setDefaultMaxPerRoute(MAX_PRE_ROUTE);
}
/**
* urlhttp / https /**
* @param url * urlhttp / https
* @return *
*/ * @param url
public static CloseableHttpClient getHttpConnection(String url, CredentialsProvider credentialsProvider){ * @return
if(url.trim().toUpperCase().startsWith(HttpArgsType.HTTP_HTTPS.toUpperCase())){ */
SSLContext sslContext; public static CloseableHttpClient getHttpConnection(String url, CredentialsProvider credentialsProvider) {
SSLConnectionSocketFactory sslsf = null; if (url.trim().toUpperCase().startsWith(HttpArgsType.HTTP_HTTPS.toUpperCase())) {
try { SSLContext sslContext;
sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> { SSLConnectionSocketFactory sslsf = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> {
// 绕过所有验证 // 绕过所有验证
return true; return true;
}).build(); }).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
sslsf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier); sslsf = new SSLConnectionSocketFactory(sslContext,
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { new String[]{"TLSv1"},
e.printStackTrace(); null,
} hostnameVerifier);
HttpClientBuilder httpClientBuilder = HttpClients.custom() } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
.setSSLSocketFactory(sslsf) throw new RuntimeException(e);
.setConnectionManager(manager) }
.setConnectionManagerShared(true) HttpClientBuilder httpClientBuilder = HttpClients.custom()
.setDefaultRequestConfig(requestConfig); .setSSLSocketFactory(sslsf)
if(credentialsProvider != null){ .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); .setConnectionManager(manager)
} .setConnectionManagerShared(true)
return httpClientBuilder .setDefaultRequestConfig(requestConfig);
.build(); if (credentialsProvider != null) {
}else{ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
HttpClientBuilder httpClientBuilder = HttpClients.custom() }
.setConnectionManager(manager) return httpClientBuilder
.setDefaultRequestConfig(requestConfig) .build();
.setConnectionManagerShared(true); } else {
if(credentialsProvider != null){ HttpClientBuilder httpClientBuilder = HttpClients.custom()
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); .setConnectionManager(manager)
} .setDefaultRequestConfig(requestConfig)
return httpClientBuilder .setConnectionManagerShared(true);
.build(); 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();
}
}
} }

View File

@ -1,7 +1,9 @@
package aiyh.utils.httpUtil; package aiyh.utils.httpUtil;
import aiyh.utils.Util;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@ -19,284 +21,293 @@ import java.util.Map;
*/ */
public class ResponeVo implements HttpResponse { public class ResponeVo implements HttpResponse {
/** /**
* *
*/ */
private int code; private int code;
/** /**
* *
*/ */
private String entityString; private String entityString;
private Map<String, Object> entityMap; private Map<String, Object> entityMap;
/**
* private List<Map> resultList;
*/ /**
*
private Locale locale; */
private InputStream content; private Locale locale;
private byte[] contentByteArr; private InputStream content;
private Map<String, Object> requestData; private byte[] contentByteArr;
private HttpResponse response; private Map<String, Object> requestData;
public int getCode() { private HttpResponse response;
return code;
} public int getCode() {
return code;
public void setCode(int code) { }
this.code = code;
} public void setCode(int code) {
this.code = code;
public void setResponse(HttpResponse response) { }
this.response = response;
} public void setResponse(HttpResponse response) {
this.response = response;
public Map<String, Object> getRequestData() { }
return requestData;
} public Map<String, Object> getRequestData() {
return requestData;
public void setRequestData(Map<String, Object> requestData) { }
this.requestData = requestData;
} public List<Map> getResult() {
return resultList;
/** }
* map
*
* @return map public void setRequestData(Map<String, Object> requestData) {
* @throws JsonProcessingException JSON this.requestData = requestData;
*/ }
@Deprecated
public Map<String, Object> getEntityMap() throws JsonProcessingException { /**
ObjectMapper mapper = new ObjectMapper(); * map
return mapper.readValue(this.getEntityString(), Map.class); *
} * @return map
* @throws JsonProcessingException JSON
public Map<String, Object> getResponseMap(){ */
return this.entityMap; @Deprecated
} public Map<String, Object> getEntityMap() throws JsonProcessingException {
/** ObjectMapper mapper = new ObjectMapper();
* return mapper.readValue(this.getEntityString(), Map.class);
* }
* @param clazz
* @param <T> public Map<String, Object> getResponseMap() {
* @return return this.entityMap;
* @throws JsonProcessingException JSON }
*/
@Deprecated /**
public <T> T getEntity(Class<T> clazz) throws JsonProcessingException { *
ObjectMapper mapper = new ObjectMapper(); *
return mapper.readValue(this.getEntityString(), clazz); * @param clazz
} * @param <T>
* @return
public <T> T getResponseEntity(Class<T> clazz) { * @throws JsonProcessingException JSON
ObjectMapper mapper = new ObjectMapper(); */
try { @Deprecated
return mapper.readValue(this.getEntityString(), clazz); public <T> T getEntity(Class<T> clazz) throws JsonProcessingException {
} catch (JsonProcessingException e) { ObjectMapper mapper = new ObjectMapper();
return null; return mapper.readValue(this.getEntityString(), clazz);
} }
}
public <T> T getResponseEntity(Class<T> clazz) {
/** ObjectMapper mapper = new ObjectMapper();
* try {
* return mapper.readValue(this.getEntityString(), clazz);
* @param <T> } catch (JsonProcessingException e) {
* @return return null;
* @throws JsonProcessingException JSON }
*/ }
public <T> T getEntity(TypeReference<T> typeReference) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper(); /**
return mapper.readValue(this.getEntityString(), typeReference); *
} *
* @param <T>
public String getEntityString() { * @return
return entityString; * @throws JsonProcessingException JSON
} */
public <T> T getEntity(TypeReference<T> typeReference) throws JsonProcessingException {
public void setEntityString(String entityString) { ObjectMapper mapper = new ObjectMapper();
this.entityString = entityString; return mapper.readValue(this.getEntityString(), typeReference);
try{ }
ObjectMapper mapper = new ObjectMapper();
this.entityMap = mapper.readValue(this.getEntityString(), Map.class); public String getEntityString() {
}catch (Exception ignore){ return entityString;
}
}
} public void setEntityString(String entityString) {
this.entityString = entityString;
public InputStream getContent() { try {
return content; ObjectMapper mapper = new ObjectMapper();
} this.entityMap = mapper.readValue(this.getEntityString(), Map.class);
} catch (JsonProcessingException ignored) {
public void setContent(InputStream content) { this.resultList = (List<Map>) JSONArray.parseArray(this.getEntityString(), Map.class);
this.content = content; } catch (Exception e) {
} Util.getLogger().error("Unable to convert the response result to map or array" + Util.getErrString(e));
}
public byte[] getContentByteArr() { }
return contentByteArr;
} public InputStream getContent() {
return content;
public void setContentByteArr(byte[] contentByteArr) { }
this.contentByteArr = contentByteArr;
} public void setContent(InputStream content) {
this.content = content;
@Override }
public String toString() {
return "ResponeVo{" + public byte[] getContentByteArr() {
"code=" + code + return contentByteArr;
", entityString='" + entityString + '\'' + }
", otherParam=" + requestData +
'}'; public void setContentByteArr(byte[] contentByteArr) {
} this.contentByteArr = contentByteArr;
}
/**
* @Override
* public String toString() {
* @param clazz return "ResponeVo{" +
* @param <T> "code=" + code +
* @return ", entityString='" + entityString + '\'' +
*/ ", otherParam=" + requestData +
public <T> List<T> getEntityArray(Class<T> clazz) { '}';
return JSON.parseArray(this.getEntityString(), clazz); }
}
/**
@Override *
public StatusLine getStatusLine() { *
return this.response.getStatusLine(); * @param clazz
} * @param <T>
* @return
@Override */
public void setStatusLine(StatusLine statusLine) { public <T> List<T> getEntityArray(Class<T> clazz) {
return JSON.parseArray(this.getEntityString(), clazz);
} }
@Override @Override
public void setStatusLine(ProtocolVersion protocolVersion, int i) { public StatusLine getStatusLine() {
return this.response.getStatusLine();
} }
@Override @Override
public void setStatusLine(ProtocolVersion protocolVersion, int i, String s) { public void setStatusLine(StatusLine statusLine) {
} }
@Override @Override
public void setStatusCode(int i) throws IllegalStateException { public void setStatusLine(ProtocolVersion protocolVersion, int i) {
} }
@Override @Override
public void setReasonPhrase(String s) throws IllegalStateException { public void setStatusLine(ProtocolVersion protocolVersion, int i, String s) {
} }
@Override @Override
public HttpEntity getEntity() { public void setStatusCode(int i) throws IllegalStateException {
return null;
} }
@Override @Override
public void setEntity(HttpEntity httpEntity) { public void setReasonPhrase(String s) throws IllegalStateException {
} }
public Locale getLocale() { @Override
return locale; public HttpEntity getEntity() {
} return null;
}
public void setLocale(Locale locale) {
this.locale = locale; @Override
} public void setEntity(HttpEntity httpEntity) {
@Override }
public ProtocolVersion getProtocolVersion() {
return this.response.getProtocolVersion(); public Locale getLocale() {
} return locale;
}
@Override
public boolean containsHeader(String s) { public void setLocale(Locale locale) {
return response.containsHeader(s); this.locale = locale;
} }
@Override @Override
public Header[] getHeaders(String s) { public ProtocolVersion getProtocolVersion() {
return response.getHeaders(s); return this.response.getProtocolVersion();
} }
@Override @Override
public Header getFirstHeader(String s) { public boolean containsHeader(String s) {
return response.getFirstHeader(s); return response.containsHeader(s);
} }
@Override @Override
public Header getLastHeader(String s) { public Header[] getHeaders(String s) {
return response.getLastHeader(s); return response.getHeaders(s);
} }
public Header[] getAllHeaders() { @Override
return response.getAllHeaders(); public Header getFirstHeader(String s) {
} return response.getFirstHeader(s);
}
@Override
public void addHeader(Header header) { @Override
public Header getLastHeader(String s) {
} return response.getLastHeader(s);
}
@Override
public void addHeader(String s, String s1) { public Header[] getAllHeaders() {
return response.getAllHeaders();
} }
@Override @Override
public void setHeader(Header header) { public void addHeader(Header header) {
} }
@Override @Override
public void setHeader(String s, String s1) { public void addHeader(String s, String s1) {
} }
@Override @Override
public void setHeaders(Header[] headers) { public void setHeader(Header header) {
} }
@Override @Override
public void removeHeader(Header header) { public void setHeader(String s, String s1) {
} }
@Override @Override
public void removeHeaders(String s) { public void setHeaders(Header[] headers) {
} }
@Override @Override
public HeaderIterator headerIterator() { public void removeHeader(Header header) {
return response.headerIterator();
} }
@Override @Override
public HeaderIterator headerIterator(String s) { public void removeHeaders(String s) {
return response.headerIterator(s);
} }
@Override @Override
@Deprecated public HeaderIterator headerIterator() {
public HttpParams getParams() { return response.headerIterator();
return response.getParams(); }
}
@Override
@Override public HeaderIterator headerIterator(String s) {
public void setParams(HttpParams httpParams) { return response.headerIterator(s);
}
}
@Override
@Deprecated
public HttpParams getParams() {
return response.getParams();
}
@Override
public void setParams(HttpParams httpParams) {
}
} }

View File

@ -55,11 +55,24 @@ public class HttpUtils {
private final PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter(); private final PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
// 默认编码 // 默认编码
private String DEFAULT_ENCODING = "UTF-8"; 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 * basic
*/ */
private CredentialsProvider credentialsProvider = null; private CredentialsProvider credentialsProvider = null;
{ {
// private final ExecutorService executorService = Executors.newFixedThreadPool(3); // private final ExecutorService executorService = Executors.newFixedThreadPool(3);
ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
@ -72,19 +85,19 @@ public class HttpUtils {
String[] excludeProperties = {"locale", "contentByteArr", "response"}; String[] excludeProperties = {"locale", "contentByteArr", "response"};
excludefilter.addExcludes(excludeProperties); excludefilter.addExcludes(excludeProperties);
} }
public HttpUtils() { public HttpUtils() {
} }
public HttpUtils(CredentialsProvider credentialsProvider) { public HttpUtils(CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider; this.credentialsProvider = credentialsProvider;
} }
public HttpUtils(String DEFAULT_ENCODING) { public HttpUtils(String DEFAULT_ENCODING) {
this.DEFAULT_ENCODING = DEFAULT_ENCODING; this.DEFAULT_ENCODING = DEFAULT_ENCODING;
} }
public static String urlHandle(String url, Map<String, Object> params) { public static String urlHandle(String url, Map<String, Object> params) {
if (params == null || params.size() <= 0) { if (params == null || params.size() <= 0) {
return url; return url;
@ -106,7 +119,7 @@ public class HttpUtils {
} }
return getUrl; return getUrl;
} }
private static String serializeParams(Map<String, Object> params) { private static String serializeParams(Map<String, Object> params) {
if (params != null && params.size() > 0) { if (params != null && params.size() > 0) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
@ -120,7 +133,7 @@ public class HttpUtils {
} }
return ""; return "";
} }
private static String removeSeparator(StringBuilder sqlBuilder) { private static String removeSeparator(StringBuilder sqlBuilder) {
String str = sqlBuilder.toString().trim(); String str = sqlBuilder.toString().trim();
String removeSeparator = "&"; String removeSeparator = "&";
@ -134,41 +147,56 @@ public class HttpUtils {
} }
return str; return str;
} }
public void setCredentialsProvider(CredentialsProvider credentialsProvider) { public void setCredentialsProvider(CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider; this.credentialsProvider = credentialsProvider;
} }
public GlobalCache getGlobalCache() { public GlobalCache getGlobalCache() {
return globalCache; return globalCache;
} }
public void setDEFAULT_ENCODING() { public void setDEFAULT_ENCODING() {
this.DEFAULT_ENCODING = DEFAULT_ENCODING; this.DEFAULT_ENCODING = DEFAULT_ENCODING;
} }
public HttpPost getHttpPost(String url) { public HttpPost getHttpPost(String url) {
HttpPost httpPost = new HttpPost(url); HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom() RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000) .setConnectTimeout(10000)
.setConnectionRequestTimeout(10000) .setConnectionRequestTimeout(10000)
.setRedirectsEnabled(true) .setRedirectsEnabled(true)
.build(); .build();
httpPost.setConfig(requestConfig); httpPost.setConfig(requestConfig);
return httpPost; return httpPost;
} }
public HttpGet getHttpGet(String url) { public HttpGet getHttpGet(String url) {
HttpGet httpGet = new HttpGet(url); HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom() RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000) .setConnectTimeout(10000)
.setConnectionRequestTimeout(10000) .setConnectionRequestTimeout(10000)
.setRedirectsEnabled(true) .setRedirectsEnabled(true)
.build(); .build();
httpGet.setConfig(requestConfig); httpGet.setConfig(requestConfig);
return httpGet; 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 * get
* *
@ -177,7 +205,7 @@ public class HttpUtils {
* @throws IOException io * @throws IOException io
*/ */
public ResponeVo apiGet(String url) throws IOException { public ResponeVo apiGet(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> params = paramsHandle(null); Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params); String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null); Map<String, String> headers = headersHandle(null);
@ -193,11 +221,11 @@ public class HttpUtils {
httpUtilParamInfo.setParams(params); httpUtilParamInfo.setParams(params);
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) { } catch (Exception ignore) {
} }
return baseRequest(httpConnection, httpGet); return baseRequest(httpConnection, httpGet);
} }
/** /**
* delete * delete
* *
@ -206,7 +234,7 @@ public class HttpUtils {
* @throws IOException io * @throws IOException io
*/ */
public ResponeVo apiDelete(String url) throws IOException { public ResponeVo apiDelete(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> params = paramsHandle(null); Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params); String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null); Map<String, String> headers = headersHandle(null);
@ -222,11 +250,11 @@ public class HttpUtils {
httpUtilParamInfo.setUrl(getUrl.trim()); httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) { } catch (Exception ignore) {
} }
return baseRequest(httpConnection, httpDelete); return baseRequest(httpConnection, httpDelete);
} }
/** /**
* get * get
* *
@ -236,7 +264,7 @@ public class HttpUtils {
* @throws IOException io * @throws IOException io
*/ */
public ResponeVo apiGet(String url, Map<String, String> headers) throws IOException { public ResponeVo apiGet(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> params = paramsHandle(null); Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params); String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
@ -252,13 +280,13 @@ public class HttpUtils {
httpUtilParamInfo.setUrl(getUrl.trim()); httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) { } catch (Exception ignore) {
} }
return baseRequest(httpConnection, httpGet); return baseRequest(httpConnection, httpGet);
} }
public ResponeVo apiDelete(String url, Map<String, String> headers) throws IOException { public ResponeVo apiDelete(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> params = paramsHandle(null); Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params); String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
@ -274,16 +302,16 @@ public class HttpUtils {
httpUtilParamInfo.setUrl(getUrl.trim()); httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) { } catch (Exception ignore) {
} }
return baseRequest(httpConnection, httpDelete); return baseRequest(httpConnection, httpDelete);
} }
public ResponeVo apiGet(String url, Map<String, Object> params, Map<String, String> headers) throws IOException { public ResponeVo apiGet(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
HttpGet httpGet = new HttpGet(getUrl.trim()); HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) { for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue()); httpGet.setHeader(entry.getKey(), entry.getValue());
@ -296,16 +324,16 @@ public class HttpUtils {
httpUtilParamInfo.setUrl(getUrl.trim()); httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) { } catch (Exception ignore) {
} }
return baseRequest(httpConnection, httpGet); return baseRequest(httpConnection, httpGet);
} }
public ResponeVo apiDelete(String url, Map<String, Object> params, Map<String, String> headers) throws IOException { public ResponeVo apiDelete(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim()); HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) { for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue()); httpDelete.setHeader(entry.getKey(), entry.getValue());
@ -318,11 +346,11 @@ public class HttpUtils {
httpUtilParamInfo.setUrl(getUrl.trim()); httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) { } catch (Exception ignore) {
} }
return baseRequest(httpConnection, httpDelete); return baseRequest(httpConnection, httpDelete);
} }
/** /**
* *
* *
@ -336,7 +364,7 @@ public class HttpUtils {
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
HttpGet httpGet = new HttpGet(getUrl.trim()); HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) { for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue()); httpGet.setHeader(entry.getKey(), entry.getValue());
@ -349,11 +377,11 @@ public class HttpUtils {
httpUtilParamInfo.setUrl(getUrl.trim()); httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) { } catch (Exception ignore) {
} }
callBackRequest(httpConnection, httpGet, consumer); callBackRequest(httpConnection, httpGet, consumer);
} }
/** /**
* *
* *
@ -367,7 +395,7 @@ public class HttpUtils {
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim()); HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) { for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue()); httpDelete.setHeader(entry.getKey(), entry.getValue());
@ -380,57 +408,57 @@ public class HttpUtils {
httpUtilParamInfo.setUrl(getUrl.trim()); httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) { } catch (Exception ignore) {
} }
callBackRequest(httpConnection, httpDelete, consumer); callBackRequest(httpConnection, httpDelete, consumer);
} }
public ResponeVo apiPost(String url, Map<String, Object> params) throws IOException { public ResponeVo apiPost(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null); Map<String, String> headerMap = headersHandle(null);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPost); return baseRequest(httpConnection, httpPost);
} }
public ResponeVo apiPut(String url, Map<String, Object> params) throws IOException { public ResponeVo apiPut(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null); Map<String, String> headerMap = headersHandle(null);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPut); return baseRequest(httpConnection, httpPut);
} }
public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException { public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPost); return baseRequest(httpConnection, httpPost);
} }
public ResponeVo apiPost(String url, List<Object> params, Map<String, String> headers) throws IOException { public ResponeVo apiPost(String url, List<Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, params); HttpPost httpPost = handleHttpPost(url, headerMap, params);
return baseRequest(httpConnection, httpPost); return baseRequest(httpConnection, httpPost);
} }
public ResponeVo apiPostObject(String url, Object params, Map<String, String> headers) throws IOException { public ResponeVo apiPostObject(String url, Object params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPostObject(url, headerMap, params); HttpPost httpPost = handleHttpPostObject(url, headerMap, params);
return baseRequest(httpConnection, httpPost); return baseRequest(httpConnection, httpPost);
} }
public ResponeVo apiPut(String url, Map<String, Object> params, Map<String, String> headers) throws IOException { public ResponeVo apiPut(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPut); return baseRequest(httpConnection, httpPut);
} }
/** /**
* <h2></h2> * <h2></h2>
* *
@ -443,10 +471,10 @@ public class HttpUtils {
* @return * @return
* @throws IOException IO * @throws IOException IO
*/ */
public ResponeVo apiUploadFile(String url, InputStream inputStream, String fileKey, String fileName, public ResponeVo apiUploadFile(String url, InputStream inputStream, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException { Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpMultipartFile multipartFile = new HttpMultipartFile(); HttpMultipartFile multipartFile = new HttpMultipartFile();
@ -457,8 +485,8 @@ public class HttpUtils {
HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap);
return baseRequest(httpConnection, httpPost); return baseRequest(httpConnection, httpPost);
} }
/** /**
* <h2></h2> * <h2></h2>
* *
@ -471,14 +499,14 @@ public class HttpUtils {
*/ */
public ResponeVo apiUploadFiles(String url, List<HttpMultipartFile> multipartFileList, Map<String, Object> params, public ResponeVo apiUploadFiles(String url, List<HttpMultipartFile> multipartFileList, Map<String, Object> params,
Map<String, String> headers) throws IOException { Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url, multipartFileList, paramsMap, headerMap); HttpPost httpPost = uploadFileByInputStream(url, multipartFileList, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost); return baseRequest(httpConnection, httpPost);
} }
/** /**
* <h2></h2> * <h2></h2>
* *
@ -491,13 +519,13 @@ public class HttpUtils {
*/ */
public ResponeVo apiPutUploadFiles(String url, List<HttpMultipartFile> multipartFileList, Map<String, Object> params, public ResponeVo apiPutUploadFiles(String url, List<HttpMultipartFile> multipartFileList, Map<String, Object> params,
Map<String, String> headers) throws IOException { Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = uploadFileByInputStreamPut(url, multipartFileList, paramsMap, headerMap); HttpPut httpPut = uploadFileByInputStreamPut(url, multipartFileList, paramsMap, headerMap);
return baseRequest(httpConnection, httpPut); return baseRequest(httpConnection, httpPut);
} }
/** /**
* <h2></h2> * <h2></h2>
* *
@ -512,7 +540,7 @@ public class HttpUtils {
*/ */
public Future<ResponeVo> apiUploadFileAsync(String url, InputStream inputStream, String fileKey, String fileName, public Future<ResponeVo> apiUploadFileAsync(String url, InputStream inputStream, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException { Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpMultipartFile multipartFile = new HttpMultipartFile(); HttpMultipartFile multipartFile = new HttpMultipartFile();
@ -523,7 +551,7 @@ public class HttpUtils {
HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
} }
/** /**
* <h2></h2> * <h2></h2>
* *
@ -538,13 +566,13 @@ public class HttpUtils {
*/ */
public ResponeVo apiUploadFile(String url, File file, String fileKey, String fileName, public ResponeVo apiUploadFile(String url, File file, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException { Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url, file, fileKey, fileName, paramsMap, headerMap); HttpPost httpPost = uploadFileByInputStream(url, file, fileKey, fileName, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost); return baseRequest(httpConnection, httpPost);
} }
/** /**
* <h2>ImageFileId</h2> * <h2>ImageFileId</h2>
* *
@ -557,10 +585,10 @@ public class HttpUtils {
* @return * @return
* @throws IOException IO * @throws IOException IO
*/ */
public ResponeVo apiUploadFileById(String url, int id, String fileKey, String fileName, public ResponeVo apiUploadFileById(String url, int id, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException { Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
InputStream inputStream = ImageFileManager.getInputStreamById(id); InputStream inputStream = ImageFileManager.getInputStreamById(id);
@ -572,7 +600,7 @@ public class HttpUtils {
HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap);
return baseRequest(httpConnection, httpPost); return baseRequest(httpConnection, httpPost);
} }
/** /**
* @param url * @param url
* @param params * @param params
@ -581,29 +609,29 @@ public class HttpUtils {
* @throws IOException io * @throws IOException io
*/ */
public void apiPost(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException { public void apiPost(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
callBackRequest(httpConnection, httpPost, consumer); callBackRequest(httpConnection, httpPost, consumer);
} }
public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers, Function<CloseableHttpResponse, ResponeVo> consumer) throws IOException { public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers, Function<CloseableHttpResponse, ResponeVo> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return callBackRequest(httpConnection, httpPost, consumer); return callBackRequest(httpConnection, httpPost, consumer);
} }
public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers, BiFunction<Map<String, Object>, CloseableHttpResponse, ResponeVo> consumer) throws IOException { public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers, BiFunction<Map<String, Object>, CloseableHttpResponse, ResponeVo> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return callBackRequest(paramsMap, httpConnection, httpPost, consumer); return callBackRequest(paramsMap, httpConnection, httpPost, consumer);
} }
/** /**
* @param url * @param url
* @param params * @param params
@ -612,13 +640,13 @@ public class HttpUtils {
* @throws IOException io * @throws IOException io
*/ */
public void apiPut(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException { public void apiPut(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
callBackRequest(httpConnection, httpPut, consumer); callBackRequest(httpConnection, httpPut, consumer);
} }
private void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer<CloseableHttpResponse> consumer) throws IOException { private void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
@ -633,7 +661,7 @@ public class HttpUtils {
ExtendedIOUtils.closeQuietly(response); ExtendedIOUtils.closeQuietly(response);
} }
} }
private ResponeVo callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Function<CloseableHttpResponse, ResponeVo> consumer) throws IOException { private ResponeVo callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Function<CloseableHttpResponse, ResponeVo> consumer) throws IOException {
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
ResponeVo apply = null; ResponeVo apply = null;
@ -662,7 +690,7 @@ public class HttpUtils {
SerializerFeature.PrettyFormat, SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat))); SerializerFeature.WriteDateUseDateFormat)));
} catch (Exception ignore) { } catch (Exception ignore) {
} }
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove();
ExtendedIOUtils.closeQuietly(httpClient); ExtendedIOUtils.closeQuietly(httpClient);
@ -670,7 +698,7 @@ public class HttpUtils {
} }
return apply; return apply;
} }
private ResponeVo callBackRequest(Map<String, Object> requestParam, CloseableHttpClient httpClient, HttpUriRequest request, BiFunction<Map<String, Object>, CloseableHttpResponse, ResponeVo> consumer) throws IOException { private ResponeVo callBackRequest(Map<String, Object> requestParam, CloseableHttpClient httpClient, HttpUriRequest request, BiFunction<Map<String, Object>, CloseableHttpResponse, ResponeVo> consumer) throws IOException {
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
ResponeVo apply = null; ResponeVo apply = null;
@ -700,14 +728,14 @@ public class HttpUtils {
SerializerFeature.PrettyFormat, SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat))); SerializerFeature.WriteDateUseDateFormat)));
} catch (Exception ignore) { } catch (Exception ignore) {
} }
ExtendedIOUtils.closeQuietly(httpClient); ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response); ExtendedIOUtils.closeQuietly(response);
} }
return apply; return apply;
} }
public ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException { public ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
ResponeVo responeVo = new ResponeVo(); ResponeVo responeVo = new ResponeVo();
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
@ -738,7 +766,7 @@ public class HttpUtils {
SerializerFeature.PrettyFormat, SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat))); SerializerFeature.WriteDateUseDateFormat)));
} catch (Exception ignore) { } catch (Exception ignore) {
} }
} catch (Exception e) { } catch (Exception e) {
toolUtil.writeErrorLog(" http调用失败:" + Util.getErrString(e)); toolUtil.writeErrorLog(" http调用失败:" + Util.getErrString(e));
@ -750,7 +778,7 @@ public class HttpUtils {
SerializerFeature.PrettyFormat, SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat))); SerializerFeature.WriteDateUseDateFormat)));
} catch (Exception ignore) { } catch (Exception ignore) {
} }
throw e; throw e;
} finally { } finally {
@ -759,7 +787,7 @@ public class HttpUtils {
} }
return responeVo; return responeVo;
} }
/** /**
* get * get
* *
@ -768,7 +796,7 @@ public class HttpUtils {
* @throws IOException io * @throws IOException io
*/ */
public Future<ResponeVo> asyncApiGet(String url) throws IOException { public Future<ResponeVo> asyncApiGet(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> params = paramsHandle(null); Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params); String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null); Map<String, String> headers = headersHandle(null);
@ -778,7 +806,7 @@ public class HttpUtils {
} }
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
} }
/** /**
* delete * delete
* *
@ -787,7 +815,7 @@ public class HttpUtils {
* @throws IOException io * @throws IOException io
*/ */
public Future<ResponeVo> asyncApiDelete(String url) throws IOException { public Future<ResponeVo> asyncApiDelete(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> params = paramsHandle(null); Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params); String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null); Map<String, String> headers = headersHandle(null);
@ -797,7 +825,7 @@ public class HttpUtils {
} }
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
} }
/** /**
* get * get
* *
@ -807,7 +835,7 @@ public class HttpUtils {
* @throws IOException io * @throws IOException io
*/ */
public Future<ResponeVo> asyncApiGet(String url, Map<String, String> headers) throws IOException { public Future<ResponeVo> asyncApiGet(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> params = paramsHandle(null); Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params); String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
@ -817,9 +845,9 @@ public class HttpUtils {
} }
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
} }
public Future<ResponeVo> asyncApiDelete(String url, Map<String, String> headers) throws IOException { public Future<ResponeVo> asyncApiDelete(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> params = paramsHandle(null); Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params); String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
@ -829,31 +857,31 @@ public class HttpUtils {
} }
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
} }
public Future<ResponeVo> asyncApiGet(String url, Map<String, Object> params, Map<String, String> headers) throws IOException { public Future<ResponeVo> asyncApiGet(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
HttpGet httpGet = new HttpGet(getUrl.trim()); HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) { for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue()); httpGet.setHeader(entry.getKey(), entry.getValue());
} }
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
} }
public Future<ResponeVo> asyncApiDelete(String url, Map<String, Object> params, Map<String, String> headers) throws IOException { public Future<ResponeVo> asyncApiDelete(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim()); HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) { for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue()); httpDelete.setHeader(entry.getKey(), entry.getValue());
} }
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
} }
/** /**
* *
* *
@ -867,7 +895,7 @@ public class HttpUtils {
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
HttpGet httpGet = new HttpGet(getUrl.trim()); HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) { for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue()); httpGet.setHeader(entry.getKey(), entry.getValue());
@ -881,7 +909,7 @@ public class HttpUtils {
command.setHttpUtilParamInfo(httpUtilParamInfo); command.setHttpUtilParamInfo(httpUtilParamInfo);
executorService.execute(command); executorService.execute(command);
} }
/** /**
* @param url * @param url
* @param params * @param params
@ -893,7 +921,7 @@ public class HttpUtils {
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim()); HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) { for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue()); httpDelete.setHeader(entry.getKey(), entry.getValue());
@ -907,39 +935,39 @@ public class HttpUtils {
command.setHttpUtilParamInfo(httpUtilParamInfo); command.setHttpUtilParamInfo(httpUtilParamInfo);
executorService.execute(command); executorService.execute(command);
} }
public Future<ResponeVo> asyncApiPost(String url, Map<String, Object> params) throws IOException { public Future<ResponeVo> asyncApiPost(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null); Map<String, String> headerMap = headersHandle(null);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
} }
public Future<ResponeVo> asyncApiPut(String url, Map<String, Object> params) throws IOException { public Future<ResponeVo> asyncApiPut(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null); Map<String, String> headerMap = headersHandle(null);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING));
} }
public Future<ResponeVo> asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException { public Future<ResponeVo> asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
} }
public Future<ResponeVo> asyncApiPut(String url, Map<String, Object> params, Map<String, String> headers) throws IOException { public Future<ResponeVo> asyncApiPut(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING));
} }
/** /**
* @param url * @param url
* @param params * @param params
@ -948,7 +976,7 @@ public class HttpUtils {
* @throws IOException io * @throws IOException io
*/ */
public void asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException { public void asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
@ -961,7 +989,7 @@ public class HttpUtils {
command.setHttpUtilParamInfo(httpUtilParamInfo); command.setHttpUtilParamInfo(httpUtilParamInfo);
executorService.execute(command); executorService.execute(command);
} }
/** /**
* @param url * @param url
* @param params * @param params
@ -970,7 +998,7 @@ public class HttpUtils {
* @throws IOException io * @throws IOException io
*/ */
public void asyncApiPut(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException { public void asyncApiPut(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = getHttpClient(url);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
@ -983,7 +1011,7 @@ public class HttpUtils {
command.setHttpUtilParamInfo(httpUtilParamInfo); command.setHttpUtilParamInfo(httpUtilParamInfo);
executorService.execute(command); executorService.execute(command);
} }
private HttpPost handleHttpPostObject(String url, Map<String, String> headerMap, Object paramsMap) throws UnsupportedEncodingException { private HttpPost handleHttpPostObject(String url, Map<String, String> headerMap, Object paramsMap) throws UnsupportedEncodingException {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(paramsMap); httpUtilParamInfo.setParams(paramsMap);
@ -1010,9 +1038,9 @@ public class HttpUtils {
if (Strings.isNullOrEmpty(contentType)) { if (Strings.isNullOrEmpty(contentType)) {
List<NameValuePair> nvps = new ArrayList<>(); List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : params.entrySet()) { for (Map.Entry<String, Object> entry : params.entrySet()) {
//nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//修复请求form表单提交时参数值被双引号括了起来 // 修复请求form表单提交时参数值被双引号括了起来
nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue())));
} }
httpPost.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE); 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())) { } else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) {
List<NameValuePair> nvps = new ArrayList<>(); List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : params.entrySet()) { for (Map.Entry<String, Object> entry : params.entrySet()) {
//nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//修复请求form表单提交时参数值被双引号括了起来 // 修复请求form表单提交时参数值被双引号括了起来
nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue())));
} }
httpPost.setEntity(new UrlEncodedFormEntity(nvps)); httpPost.setEntity(new UrlEncodedFormEntity(nvps));
@ -1039,15 +1067,15 @@ public class HttpUtils {
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
return httpPost; return httpPost;
} }
private HttpPost handleHttpPost(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException { private HttpPost handleHttpPost(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException {
return handleHttpPostObject(url, headerMap, paramsMap); return handleHttpPostObject(url, headerMap, paramsMap);
} }
private HttpPost handleHttpPost(String url, Map<String, String> headerMap, List<Object> params) throws UnsupportedEncodingException { private HttpPost handleHttpPost(String url, Map<String, String> headerMap, List<Object> params) throws UnsupportedEncodingException {
return handleHttpPostObject(url, headerMap, params); return handleHttpPostObject(url, headerMap, params);
} }
/** /**
* <h2></h2> * <h2></h2>
* *
@ -1059,7 +1087,7 @@ public class HttpUtils {
*/ */
private HttpPost uploadFileByInputStream(String url, List<HttpMultipartFile> multipartFileList, private HttpPost uploadFileByInputStream(String url, List<HttpMultipartFile> multipartFileList,
Map<String, Object> params, Map<String, String> headers) { Map<String, Object> params, Map<String, String> 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, // excludefilter,
// SerializerFeature.PrettyFormat, // SerializerFeature.PrettyFormat,
// SerializerFeature.WriteDateUseDateFormat), // SerializerFeature.WriteDateUseDateFormat),
@ -1090,7 +1118,7 @@ public class HttpUtils {
builder.addPart(param.getKey(), stringBody); builder.addPart(param.getKey(), stringBody);
} }
HttpPost httpPost = new HttpPost(url.trim()); HttpPost httpPost = new HttpPost(url.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) { for (Map.Entry<String, String> entry : headers.entrySet()) {
if ("Content-Type".equalsIgnoreCase(entry.getKey())) { if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
continue; continue;
@ -1101,8 +1129,8 @@ public class HttpUtils {
httpPost.setEntity(entity); httpPost.setEntity(entity);
return httpPost; return httpPost;
} }
/** /**
* <h2></h2> * <h2></h2>
* *
@ -1145,7 +1173,7 @@ public class HttpUtils {
builder.addPart(param.getKey(), stringBody); builder.addPart(param.getKey(), stringBody);
} }
HttpPut httpPut = new HttpPut(url.trim()); HttpPut httpPut = new HttpPut(url.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) { for (Map.Entry<String, String> entry : headers.entrySet()) {
if ("Content-Type".equalsIgnoreCase(entry.getKey())) { if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
continue; continue;
@ -1156,11 +1184,11 @@ public class HttpUtils {
httpPut.setEntity(entity); httpPut.setEntity(entity);
return httpPut; return httpPut;
} }
private HttpPost uploadFileByInputStream(String url, File file, String fileKey, String fileName, private HttpPost uploadFileByInputStream(String url, File file, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) { Map<String, Object> params, Map<String, String> headers) {
log.info(Util.logStr("start request : url is [{}], params is [{}], header is [{}]; fileKey is [{}], fileName is [{}]" + 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 httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(params); httpUtilParamInfo.setParams(params);
httpUtilParamInfo.setUrl(url); httpUtilParamInfo.setUrl(url);
@ -1175,7 +1203,7 @@ public class HttpUtils {
builder.addPart(param.getKey(), stringBody); builder.addPart(param.getKey(), stringBody);
} }
HttpPost httpPost = new HttpPost(url.trim()); HttpPost httpPost = new HttpPost(url.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) { for (Map.Entry<String, String> entry : headers.entrySet()) {
if ("Content-Type".equalsIgnoreCase(entry.getKey())) { if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
continue; continue;
@ -1186,7 +1214,7 @@ public class HttpUtils {
httpPost.setEntity(entity); httpPost.setEntity(entity);
return httpPost; return httpPost;
} }
private HttpPut handleHttpPut(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException { private HttpPut handleHttpPut(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(paramsMap); httpUtilParamInfo.setParams(paramsMap);
@ -1204,8 +1232,8 @@ public class HttpUtils {
if (Strings.isNullOrEmpty(contentType)) { if (Strings.isNullOrEmpty(contentType)) {
List<NameValuePair> nvps = new ArrayList<>(); List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) { for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
//nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//修复请求form表单提交时参数值被双引号括了起来 // 修复请求form表单提交时参数值被双引号括了起来
nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue())));
} }
httpPut.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE); 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())) { } else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) {
List<NameValuePair> nvps = new ArrayList<>(); List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) { for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
//nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//修复请求form表单提交时参数值被双引号括了起来 // 修复请求form表单提交时参数值被双引号括了起来
nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue())));
} }
httpPut.setEntity(new UrlEncodedFormEntity(nvps)); httpPut.setEntity(new UrlEncodedFormEntity(nvps));
@ -1225,7 +1253,7 @@ public class HttpUtils {
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
return httpPut; return httpPut;
} }
private String inputStreamToString(InputStream is) { private String inputStreamToString(InputStream is) {
String line = ""; String line = "";
StringBuilder total = new StringBuilder(); StringBuilder total = new StringBuilder();
@ -1239,7 +1267,7 @@ public class HttpUtils {
} }
return total.toString(); return total.toString();
} }
public Map<String, String> headersHandle(Map<String, String> headers) { public Map<String, String> headersHandle(Map<String, String> headers) {
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
if (headers != null && headers.size() > 0) { if (headers != null && headers.size() > 0) {
@ -1252,7 +1280,7 @@ public class HttpUtils {
} }
return map; return map;
} }
public Map<String, Object> paramsHandle(Map<String, Object> params) { public Map<String, Object> paramsHandle(Map<String, Object> params) {
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
if (params != null && params.size() > 0) { if (params != null && params.size() > 0) {

View File

@ -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);
}
}
/**
* <br>
* ASCII使
*
* @param c
* @return
*/
public static String toString(char c) {
return c < ASCII_LENGTH ? CACHE[c] : String.valueOf(c);
}
}

View File

@ -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 <T> 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> 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> T notNull(T object) throws IllegalArgumentException {
return notNull(object, "[Assertion failed] - this argument is required; it must not be null");
}
public static <T extends CharSequence> 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 extends CharSequence> 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 extends CharSequence> 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 extends CharSequence> 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> 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 <T> 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 <T> boolean isNotEmpty(T[] array) {
return array != null && array.length != 0;
}
public static <T> T[] noNullElements(T[] array) throws IllegalArgumentException {
return noNullElements(array, "[Assertion failed] - this array must not contain any null elements");
}
public static <T> Collection<T> notEmpty(Collection<T> collection, String errorMsgTemplate, Object... params) throws IllegalArgumentException {
if (collection == null || collection.isEmpty()) {
throw new IllegalArgumentException(StrFormatter.format(errorMsgTemplate, params));
} else {
return collection;
}
}
public static <T> Collection<T> notEmpty(Collection<T> collection) throws IllegalArgumentException {
return notEmpty(collection, "[Assertion failed] - this collection must not be empty: it must contain at least 1 element");
}
public static <K, V> Map<K, V> notEmpty(Map<K, V> 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 <K, V> Map<K, V> notEmpty(Map<K, V> map) throws IllegalArgumentException {
return notEmpty(map, "[Assertion failed] - this map must not be empty; it must contain at least one entry");
}
public static <T> T isInstanceOf(Class<?> type, T obj) {
return isInstanceOf(type, obj, "Object [{}] is not instanceof [{}]", obj, type);
}
public static <T> 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);
}
}
}

View File

@ -0,0 +1,336 @@
package aiyh.utils.tool;
import cn.hutool.core.text.ASCIIStrCache;
/**
* <br>
* 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 = '&';
/**
* ASCIIASCII0~127
*
* <pre>
* CharUtil.isAscii('a') = true
* CharUtil.isAscii('A') = true
* CharUtil.isAscii('3') = true
* CharUtil.isAscii('-') = true
* CharUtil.isAscii('\n') = true
* CharUtil.isAscii('&copy;') = false
* </pre>
*
* @param ch
* @return trueASCIIASCII0~127
*/
public static boolean isAscii(char ch) {
return ch < 128;
}
/**
* ASCII32~126
*
* <pre>
* CharUtil.isAsciiPrintable('a') = true
* CharUtil.isAsciiPrintable('A') = true
* CharUtil.isAsciiPrintable('3') = true
* CharUtil.isAsciiPrintable('-') = true
* CharUtil.isAsciiPrintable('\n') = false
* CharUtil.isAsciiPrintable('&copy;') = false
* </pre>
*
* @param ch
* @return trueASCII32~126
*/
public static boolean isAsciiPrintable(char ch) {
return ch >= 32 && ch < 127;
}
/**
* ASCII0~31127
*
* <pre>
* CharUtil.isAsciiControl('a') = false
* CharUtil.isAsciiControl('A') = false
* CharUtil.isAsciiControl('3') = false
* CharUtil.isAsciiControl('-') = false
* CharUtil.isAsciiControl('\n') = true
* CharUtil.isAsciiControl('&copy;') = false
* </pre>
*
* @param ch
* @return true0~31127
*/
public static boolean isAsciiControl(final char ch) {
return ch < 32 || ch == 127;
}
/**
* <br>
* A~Za~z
*
* <pre>
* CharUtil.isLetter('a') = true
* CharUtil.isLetter('A') = true
* CharUtil.isLetter('3') = false
* CharUtil.isLetter('-') = false
* CharUtil.isLetter('\n') = false
* CharUtil.isLetter('&copy;') = false
* </pre>
*
* @param ch
* @return trueA~Za~z
*/
public static boolean isLetter(char ch) {
return isLetterUpper(ch) || isLetterLower(ch);
}
/**
* <p>
* A~Z
* </p>
*
* <pre>
* CharUtil.isLetterUpper('a') = false
* CharUtil.isLetterUpper('A') = true
* CharUtil.isLetterUpper('3') = false
* CharUtil.isLetterUpper('-') = false
* CharUtil.isLetterUpper('\n') = false
* CharUtil.isLetterUpper('&copy;') = false
* </pre>
*
* @param ch
* @return trueA~Z
*/
public static boolean isLetterUpper(final char ch) {
return ch >= 'A' && ch <= 'Z';
}
/**
* <p>
* a~z
* </p>
*
* <pre>
* CharUtil.isLetterLower('a') = true
* CharUtil.isLetterLower('A') = false
* CharUtil.isLetterLower('3') = false
* CharUtil.isLetterLower('-') = false
* CharUtil.isLetterLower('\n') = false
* CharUtil.isLetterLower('&copy;') = false
* </pre>
*
* @param ch
* @return truea~z
*/
public static boolean isLetterLower(final char ch) {
return ch >= 'a' && ch <= 'z';
}
/**
* <p>
* 0~9
* </p>
*
* <pre>
* CharUtil.isNumber('a') = false
* CharUtil.isNumber('A') = false
* CharUtil.isNumber('3') = true
* CharUtil.isNumber('-') = false
* CharUtil.isNumber('\n') = false
* CharUtil.isNumber('&copy;') = false
* </pre>
*
* @param ch
* @return true0~9
*/
public static boolean isNumber(char ch) {
return ch >= '0' && ch <= '9';
}
/**
* 16
* <pre>
* 1. 0~9
* 2. a~f
* 4. A~F
* </pre>
*
* @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~Za~z0~9
*
* <pre>
* CharUtil.isLetterOrNumber('a') = true
* CharUtil.isLetterOrNumber('A') = true
* CharUtil.isLetterOrNumber('3') = true
* CharUtil.isLetterOrNumber('-') = false
* CharUtil.isLetterOrNumber('\n') = false
* CharUtil.isLetterOrNumber('&copy;') = false
* </pre>
*
* @param ch
* @return trueA~Za~z0~9
*/
public static boolean isLetterOrNumber(final char ch) {
return isLetter(ch) || isNumber(ch);
}
/**
* <br>
* ASCII使
*
* @param c
* @return
* @see ASCIIStrCache#toString(char)
*/
public static String toString(char c) {
return ASCIIStrCache.toString(c);
}
/**
*
*
* <pre>
* Character.class
* char.class
* </pre>
*
* @param clazz
* @return true
*/
public static boolean isCharClass(Class<?> clazz) {
return clazz == Character.class || clazz == char.class;
}
/**
*
*
* <pre>
* Character.class
* char.class
* </pre>
*
* @param value
* @return true
*/
public static boolean isChar(Object value) {
// noinspection ConstantConditions
return value instanceof Character || value.getClass() == char.class;
}
/**
* <br>
* <br>
*
* @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);
}
/**
* <br>
* <br>
*
* @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<br>
*
* @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)));
}
/**
* WindowsLinuxUnix<br>
* Windows\LinuxUnix/
*
* @param c
* @return WindowsLinuxUnix
* @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);
}
}

View File

@ -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 = "&nbsp;";
public static final String HTML_AMP = "&amp;";
public static final String HTML_QUOTE = "&quot;";
public static final String HTML_APOS = "&apos;";
public static final String HTML_LT = "&lt;";
public static final String HTML_GT = "&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';
}
/**
* <br>
* {} <br>
* {} 使 \\ { {} \ 使 \\\\ <br>
* <br>
* 使format("this is {} for {}", "a", "b") = this is a for b<br>
* {} format("this is \\{} for {}", "a", "b") = this is \{} for a<br>
* \ format("this is \\\\{} for {}", "a", "b") = this is \a for b<br>
*
* @param strPattern
* @param argArray
* @return
*/
public static String format(String strPattern, Object... argArray) {
return formatWith(strPattern, EMPTY_JSON, argArray);
}
public static <T> boolean isEmpty(T[] array) {
return array == null || array.length == 0;
}
/**
* <br>
* <br>
* 使 \\ \ 使 \\\\ <br>
* <br>
* 使format("this is {} for {}", "{}", "a", "b") = this is a for b<br>
* {} format("this is \\{} for {}", "{}", "a", "b") = this is {} for a<br>
* \ format("this is \\\\{} for {}", "{}", "a", "b") = this is \a for b<br>
*
* @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} <br>
* 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();
}
}

View File

@ -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;
/**
* <h1></h1>
*
* <p>create: 2023/2/14 11:58</p>
*
* @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!");
}
}
}

View File

@ -0,0 +1,32 @@
package com.api.youhong.ai.pcn.racetrack.dto;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* <h1></h1>
*
* <p>create: 2023/2/14 17:19</p>
*
* @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;
}

View File

@ -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;
/**
* <h1></h1>
*
* <p>create: 2023/2/14 15:07</p>
*
* @author youHong.ai
*/
@SqlMapper
public interface RacetrackMapper {
/**
* <h2></h2>
*
* @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<RaceTrackEvent> selectEventList(@ParamMapper("raceTrackEventListTable") String raceTrackEventListTable,
@ParamMapper("raceTrackEventListDateField") String raceTrackEventListDateField,
@ParamMapper("raceTrackEventListTitleField") String raceTrackEventListTitleField,
@ParamMapper("raceTrackEventListSubtitleField") String raceTrackEventListSubtitleField);
/**
* <h2></h2>
*
* @param userId ID
* @return
* @author youhong.ai
*/
@Select("select companyworkyear from hrmresource where id = #{userId}")
String selectLengthOfEntryTime(@ParamMapper("userId") Integer userId);
}

View File

@ -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;
/**
* <h1></h1>
*
* <p>create: 2023/2/14 12:13</p>
*
* @author youHong.ai
*/
public class RaceTrackService {
private final RacetrackMapper mapper = Util.getMapper(RacetrackMapper.class);
/**
* <h2></h2>
*
* @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<RaceTrackEvent> 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();
}
}

View File

@ -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;
/**
* <h1></h1>
*
* <p>create: 2023/2/14 15:08</p>
*
* @author youHong.ai
*/
@Setter
@Getter
@ToString
public class RaceTrackVo {
/** 事件列表 */
List<RaceTrackEvent> eventList;
/** 入职时长 */
private String lengthOfEntryTime;
}

View File

@ -3,6 +3,7 @@ package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper;
import aiyh.utils.annotation.recordset.ParamMapper; import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select; import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper; import aiyh.utils.annotation.recordset.SqlMapper;
import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.vo.ApaDataBtnShowVo;
/** /**
* <h1></h1> * <h1></h1>
@ -28,8 +29,9 @@ public interface ApaLevelByScoreMapper {
Integer selectLevelByScore(Double score); Integer selectLevelByScore(Double score);
@Select("select id from $t{tableName} where $t{userField} = #{uId}") @Select("select id, $t{statusField} status from $t{tableName} where $t{userField} = #{uId} order by id desc limit 1")
Integer selectLevelByUserId(@ParamMapper("uId") int uid, ApaDataBtnShowVo selectLevelByUserId(@ParamMapper("uId") int uid,
@ParamMapper("tableName") String tableName, @ParamMapper("tableName") String tableName,
@ParamMapper("userField") String userField); @ParamMapper("statusField") String statusField,
@ParamMapper("userField") String userField);
} }

View File

@ -4,6 +4,7 @@ import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException; import aiyh.utils.excention.CustomerException;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper.ApaLevelByScoreMapper; import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper.ApaLevelByScoreMapper;
import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.vo.ApaDataBtnShowVo;
import weaver.hrm.User; import weaver.hrm.User;
/** /**
@ -34,11 +35,13 @@ public class ApaLevelByScoreService {
return level; return level;
} }
public Integer getApaLastDateId(User user) { public ApaDataBtnShowVo getApaLastDateId(User user) {
String apaLastIdTableName = Util.getCusConfigValue("APA_LAST_ID_TABLE_NAME"); String apaLastIdTableName = Util.getCusConfigValue("APA_LAST_ID_TABLE_NAME");
String apaLastIdUserField = Util.getCusConfigValue("APA_LAST_ID_USER_FIELD"); 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(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!"); 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);
} }
} }

View File

@ -0,0 +1,22 @@
package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.vo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* <h1>apaVo</h1>
*
* <p>create: 2023/2/13 16:39</p>
*
* @author youHong.ai
*/
@Getter
@Setter
@ToString
public class ApaDataBtnShowVo {
private Integer id;
private Integer status;
}

View File

@ -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;
/**
* <h1>ca</h1>
*
* <p>create: 2023/2/16 15:22</p>
*
* @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<String, Object> requestParam = dealWithMapping.getRequestParam(super.getObjMainTableValue(requestInfo), requestMappingConfig);
ResponeVo responeVo = httpUtils.apiPost(requestUrl, requestParam);
Map<String, Object> 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, "电子签自动提交流程");
}
}

View File

@ -2,13 +2,10 @@ package weaver.youhong.ai.pcn.actioin.sendemail;
import aiyh.utils.Util; import aiyh.utils.Util;
import aiyh.utils.action.SafeCusBaseAction; import aiyh.utils.action.SafeCusBaseAction;
import aiyh.utils.annotation.ActionDesc; import aiyh.utils.annotation.*;
import aiyh.utils.annotation.ActionOptionalParam;
import aiyh.utils.annotation.PrintParamMark;
import aiyh.utils.annotation.RequiredMark;
import aiyh.utils.entity.DocImageInfo; import aiyh.utils.entity.DocImageInfo;
import aiyh.utils.excention.CustomerException; import aiyh.utils.excention.CustomerException;
import cn.hutool.core.lang.Assert; import aiyh.utils.tool.Assert;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
@ -34,86 +31,90 @@ import java.util.stream.Collectors;
@ToString @ToString
@ActionDesc(value = "发送邮件到外部人员邮箱", author = "youhong.ai") @ActionDesc(value = "发送邮件到外部人员邮箱", author = "youhong.ai")
public class SendEmailToExternalPersonnelAction extends SafeCusBaseAction { public class SendEmailToExternalPersonnelAction extends SafeCusBaseAction {
@PrintParamMark @PrintParamMark
@ActionOptionalParam(value = "false", desc = "是否自动提交流程") @ActionOptionalParam(value = "false", desc = "是否自动提交流程")
private String submitAction = "false"; private String submitAction = "false";
@PrintParamMark @PrintParamMark
@ActionOptionalParam(value = "true", desc = "是否失败后阻断流程") @ActionOptionalParam(value = "true", desc = "是否失败后阻断流程")
private String block = "true"; private String block = "true";
@PrintParamMark @PrintParamMark
@RequiredMark("用户邮箱对应表单字段") @RequiredMark("用户邮箱对应表单字段")
private String emailField; @ActionDefaultTestValue("yx")
private String emailField;
@PrintParamMark
@ActionOptionalParam(value = "", desc = "发送邮箱内容自定义表单表单字段不填则默认使用开发参数配置表uf_cus_dev_config中唯一标识为" + @PrintParamMark
"`SendEmailToExternalPersonnelEmail`的值的邮件内容") @ActionOptionalParam(value = "", desc = "发送邮箱内容自定义表单表单字段不填则默认使用开发参数配置表uf_cus_dev_config中唯一标识为" +
private String customerContentField; "`SendEmailToExternalPersonnelEmail`的值的邮件内容")
@ActionDefaultTestValue("nr")
@PrintParamMark private String customerContentField;
@ActionOptionalParam(value = "", desc = "邮箱携带附件字段,不填则没有附件")
private String emailFileField; @PrintParamMark
@ActionOptionalParam(value = "", desc = "邮箱携带附件字段,不填则没有附件")
@PrintParamMark @ActionDefaultTestValue("fj")
@ActionOptionalParam(value = "", desc = "邮件标题字段,不填写则默认使用`defaultEmailSubject`的参数值") private String emailFileField;
private String emailSubjectField;
@PrintParamMark
@PrintParamMark @ActionOptionalParam(value = "", desc = "邮件标题字段,不填写则默认使用`defaultEmailSubject`的参数值")
@ActionOptionalParam(value = "", desc = "邮件标题默认") @ActionDefaultTestValue("bt")
private String defaultEmailSubject = ""; private String emailSubjectField;
@PrintParamMark
@Override @ActionOptionalParam(value = "", desc = "邮件标题默认")
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { private String defaultEmailSubject = "";
try {
Map<String, String> mainTableValue = super.getMainTableValue(requestInfo); @Override
String content = ""; public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) {
String email = mainTableValue.get(emailField); try {
String emailSubject = StringUtils.isNullOrEmpty(emailSubjectField) ? defaultEmailSubject : mainTableValue.get(emailSubjectField);
if (StringUtils.isNullOrEmpty(customerContentField)) { Map<String, String> mainTableValue = super.getMainTableValue(requestInfo);
content = Util.getCusConfigDefaultValue("SendEmailToExternalPersonnelEmail", ""); String content = "";
} else { String email = mainTableValue.get(emailField);
content = mainTableValue.get(customerContentField); String emailSubject = StringUtils.isNullOrEmpty(emailSubjectField) ? defaultEmailSubject : mainTableValue.get(emailSubjectField);
} if (StringUtils.isNullOrEmpty(customerContentField)) {
if (StringUtils.isNullOrEmpty(emailFileField)) { content = Util.getCusConfigDefaultValue("SendEmailToExternalPersonnelEmail", "");
EmailWorkRunnable.threadModeReminder(email, emailSubject, content); } else {
if (Boolean.parseBoolean(submitAction)) { content = mainTableValue.get(customerContentField);
this.submitWorkflow(requestId, user.getUID()); }
} if (StringUtils.isNullOrEmpty(emailFileField)) {
return; EmailWorkRunnable.threadModeReminder(email, emailSubject, content);
} if (Boolean.parseBoolean(submitAction)) {
String docIds = mainTableValue.get(emailFileField); this.submitWorkflow(requestId, user.getUID());
if (StringUtils.isNullOrEmpty(docIds)) { }
EmailWorkRunnable.threadModeReminder(email, emailSubject, content); return;
if (Boolean.parseBoolean(submitAction)) { }
this.submitWorkflow(requestId, user.getUID()); String docIds = mainTableValue.get(emailFileField);
} if (StringUtils.isNullOrEmpty(docIds)) {
return; EmailWorkRunnable.threadModeReminder(email, emailSubject, content);
} if (Boolean.parseBoolean(submitAction)) {
List<DocImageInfo> docImageInfos = Util.selectImageInfoByDocIds(docIds); this.submitWorkflow(requestId, user.getUID());
Assert.notEmpty(docImageInfos, "can not query docImageInfo by Util.selectImageInfoByDocIds method, param is [{}]", docIds); }
List<Integer> imageIdList = docImageInfos.stream().map(DocImageInfo::getImageFileId).collect(Collectors.toList()); return;
EmailWorkRunnable.threadModeReminder(email, "", "", }
emailSubject, content, Util.intJoin(imageIdList, ",")); List<DocImageInfo> docImageInfos = Util.selectImageInfoByDocIds(docIds);
if (Boolean.parseBoolean(submitAction)) { Assert.notEmpty(docImageInfos, "can not query docImageInfo by Util.selectImageInfoByDocIds method, param is [{}]", docIds);
this.submitWorkflow(requestId, user.getUID()); List<Integer> imageIdList = docImageInfos.stream().map(DocImageInfo::getImageFileId).collect(Collectors.toList());
} EmailWorkRunnable.threadModeReminder(email, "", "",
} catch (Exception e) { emailSubject, content, Util.intJoin(imageIdList, ","));
if (Boolean.parseBoolean(block)) { if (Boolean.parseBoolean(submitAction)) {
throw new CustomerException(e.getMessage(), e); 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, "批量签署自动提交流程!");
}
public void submitWorkflow(String requestId, Integer userId) {
Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "邮件发送附件提交流程!");
}
} }

View File

@ -77,7 +77,7 @@ getQueryString = (name) => {
**5.通过js获取react组件操作组件内部数据** **5.通过js获取react组件操作组件内部数据**
```javascript ```javascript
function FindReact(dom, traverseUp = 0) { function findReact(dom, traverseUp = 0) {
const key = Object.keys(dom).find(key => { const key = Object.keys(dom).find(key => {
return key.startsWith("__reactFiber$") // react 17+ return key.startsWith("__reactFiber$") // react 17+
|| key.startsWith("__reactInternalInstance$"); // react <17 || key.startsWith("__reactInternalInstance$"); // react <17
@ -502,10 +502,10 @@ from workflow_nodebase nb
```java ```java
//@Context HttpServletRequest request, @Context HttpServletResponse response //@Context HttpServletRequest request, @Context HttpServletResponse response
User logInUser=HrmUserVarify.getUser(request,response); User logInUser=HrmUserVarify.getUser(request,response);
// 传入id会将此人员信息带出 // 传入id会将此人员信息带出
User user=new User(id); User user=new User(id);
// 获取人员id // 获取人员id
user.getUID(); user.getUID();
``` ```
**2.发送邮件** **2.发送邮件**
@ -548,8 +548,8 @@ EmailWorkRunnable.threadModeReminder(sendTo,sendCc,sendBcc,subject,content,image
@param imageFileIds 附件id @param imageFileIds 附件id
*/ */
EmailWorkRunnable emailWorkRunable=new EmailWorkRunnable(sendTo,sendCc,sendBcc,subject,content); EmailWorkRunnable emailWorkRunable=new EmailWorkRunnable(sendTo,sendCc,sendBcc,subject,content);
emailWorkRunable.setImagefileids(imageFileIds); emailWorkRunable.setImagefileids(imageFileIds);
MailCommonUtils.executeThreadPool(EmailPoolSubTypeEnum.EMAIL_SYS_ALTER.toString(),emailWorkRunable); MailCommonUtils.executeThreadPool(EmailPoolSubTypeEnum.EMAIL_SYS_ALTER.toString(),emailWorkRunable);
``` ```
**3.短信服务** **3.短信服务**
@ -557,11 +557,11 @@ EmailWorkRunnable emailWorkRunable=new EmailWorkRunnable(sendTo,sendCc,sendBcc,s
```java ```java
public class SendSms implements SmsService { public class SendSms implements SmsService {
@Override @Override
public boolean sendSMS(String smsId, String number, String msg) { public boolean sendSMS(String smsId, String number, String msg) {
//执行短信调用接口逻辑 //执行短信调用接口逻辑
return SMSUtil.sendSms(number, msg, url, sn, pwd); return SMSUtil.sendSms(number, msg, url, sn, pwd);
} }
} }
``` ```
@ -571,9 +571,9 @@ public class SendSms implements SmsService {
```java ```java
//wps转PDF //wps转PDF
DocImagefileToPdfUseWps toPdfUseWps=new DocImagefileToPdfUseWps(); DocImagefileToPdfUseWps toPdfUseWps=new DocImagefileToPdfUseWps();
newimagefileid=toPdfUseWps.officeDocumetnToPdfByImagefileid(docimagefileid); newimagefileid=toPdfUseWps.officeDocumetnToPdfByImagefileid(docimagefileid);
//永中转PDF //永中转PDF
DocImagefileToPdf yozoToPdf=new DocImagefileToPdf(); DocImagefileToPdf yozoToPdf=new DocImagefileToPdf();
newimagefileid=yozoToPdf.officeDocumetnToPdfByImagefileid(docimagefileid); newimagefileid=yozoToPdf.officeDocumetnToPdfByImagefileid(docimagefileid);
``` ```