diff --git a/javascript/youhong.ai/taibao/建模打包带数据到指定明细.js b/javascript/youhong.ai/taibao/建模打包带数据到指定明细.js index 75e2a2c..2467d65 100644 --- a/javascript/youhong.ai/taibao/建模打包带数据到指定明细.js +++ b/javascript/youhong.ai/taibao/建模打包带数据到指定明细.js @@ -106,4 +106,122 @@ $(() => { }) -/* ******************* youhong.ai 流程部分 end ******************* */ \ No newline at end of file +/* ******************* youhong.ai 流程部分 end ******************* */ + + +/* ******************* youhong.ai 编号验证是否存在 start ******************* */ +$(() => { + const config = { + ecId: '', + tableName: '', + field: 'fwbh', + } + + /** + * @author youhong.ai + * @desc 发起请求 + */ + function api(requestOptions = { + url: "", + type: "GET", + data: "", + isAsync: true, + success: () => { + }, + error: () => { + }, + complete: () => { + }, + contentType: 'application/json', + beforeSend: () => { + } + }) { + let options = Object.assign({ + url: "", + type: "GET", + data: "", + isAsync: true, + success: () => { + }, + error: () => { + }, + complete: () => { + }, + contentType: 'application/json', + beforeSend: () => { + } + }, requestOptions) + return $.ajax(options) + } + + function findReact(dom, traverseUp = 0) { + const key = Object.keys(dom).find(key => { + return key.startsWith("__reactFiber$") // react 17+ + || key.startsWith("__reactInternalInstance$") + || key.startsWith("__reactEventHandlers$"); // react <17 + }); + const domFiber = dom[key]; + if (domFiber == null) return null; + // react <16 + if (domFiber._currentElement) { + let compFiber = domFiber._currentElement._owner; + for (let i = 0; i < traverseUp; i++) { + compFiber = compFiber._currentElement._owner; + } + return compFiber._instance; + } + // react 16+ + const GetCompFiber = fiber => { + let parentFiber = fiber.return; + while (typeof parentFiber.type == "string") { + parentFiber = parentFiber.return; + } + return parentFiber; + }; + let compFiber = GetCompFiber(domFiber); + for (let i = 0; i < traverseUp; i++) { + compFiber = GetCompFiber(compFiber); + } + return compFiber.stateNode; + } + + function runJs() { + let node = findReact($(`button[ecid='${config.ecId}']`)[0]) + let baseInfo = WfForm.getBaseInfo(); + baseInfo.workflowid + if (baseInfo.requestid == -1) { + return + } + if (node) { + let click = node.props.onClick; + node.props.onClick = (e) => { + api({ + url: `/api/aiyh/taibao/bh/check-number?tableName=${config.tableName}&field=${config.field}&requestId=${baseInfo.requestid}`, + success(res) { + if (res && res.code == 200) { + if (res.data) { + // 存在编号,提示是否需要编号 + WfForm.showConfirm("编号一存在,是否重新编号?", function () { + click(e) + }, function () { + // 不重新编号,刷新 + window.location.reload() + }, { + title: "编号确认", //弹确认框的title,仅PC端有效 + okText: "确认", //自定义确认按钮名称 + cancelText: "取消" //自定义取消按钮名称 + }); + } else { + click(e) + } + } + } + }) + }; + } + + } + + runJs() +}) +/* ******************* youhong.ai 编号验证是否存在 end ******************* */ diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index 72856e1..357e947 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -244,7 +244,7 @@ public class Util extends weaver.general.Util { str = str.substring(0, str.length() - 1); } if (str.trim().startsWith(removeSeparator)) { - str = str.substring(1); + str = str.substring(removeSeparator.length()); } return str; } diff --git a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java index 77ea7c8..3f76b9f 100644 --- a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java +++ b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java @@ -121,7 +121,7 @@ public class HttpUtils { return getUrl; } - private static String serializeParams(Map params) { + public static String serializeParams(Map params) { if (params != null && params.size() > 0) { StringBuilder builder = new StringBuilder(); for (Map.Entry entry : params.entrySet()) { @@ -1113,6 +1113,9 @@ public class HttpUtils { } private boolean isBean(Object o) { + if (Objects.isNull(o)) { + return false; + } if (o instanceof Number) { return false; } @@ -1122,9 +1125,6 @@ public class HttpUtils { if (o instanceof Boolean) { return false; } - if (Objects.isNull(o)) { - return false; - } return !o.getClass().isPrimitive(); } diff --git a/src/main/java/aiyh/utils/recordset/ResultMapper.java b/src/main/java/aiyh/utils/recordset/ResultMapper.java index c5305cf..5b7ca54 100644 --- a/src/main/java/aiyh/utils/recordset/ResultMapper.java +++ b/src/main/java/aiyh/utils/recordset/ResultMapper.java @@ -336,18 +336,18 @@ public class ResultMapper { if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { if (Objects.nonNull(toLowerCase)) { - ((Map) o).put(columnName[i].toLowerCase(), rs.getFloat(i + 1)); + ((Map) o).put(columnName[i].toLowerCase(), rs.getString(i + 1)); } else { if (enable) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1)); + ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1)); continue; } if (DBConstant.DB_TYPE_ORACLE.equals(rs.getDBType())) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1)); + ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1)); } - ((Map) o).put(columnName[i].toLowerCase(), rs.getFloat(i + 1)); - ((Map) o).put(columnName[i].toUpperCase(), rs.getFloat(i + 1)); - ((Map) o).put(columnName[i], rs.getFloat(i + 1)); + ((Map) o).put(columnName[i].toLowerCase(), rs.getString(i + 1)); + ((Map) o).put(columnName[i].toUpperCase(), rs.getString(i + 1)); + ((Map) o).put(columnName[i], rs.getString(i + 1)); } continue; } @@ -475,39 +475,58 @@ public class ResultMapper { } else { columnType = columnTypeName[i]; } + String value = rs.getString(i + 1); + String valueCloumn = rs.getString(columnName[i]); if ("int".equalsIgnoreCase(columnType) || "long".equalsIgnoreCase(columnType) || "number".equalsIgnoreCase(columnType) || "MEDIUMINT".equalsIgnoreCase(columnType) || "TINYINT".equalsIgnoreCase(columnType) || "SMALLINT".equalsIgnoreCase(columnType) || "BIGINT".equalsIgnoreCase(columnType) || "INTEGER".equalsIgnoreCase(columnType)) { - if (Objects.nonNull(toLowerCase)) { - ((Map) o).put(columnName[i].toLowerCase(), rs.getInt(i + 1)); + try { + ((Map) o).put(columnName[i].toLowerCase(), Integer.parseInt(value)); + } catch (Exception e) { + ((Map) o).put(columnName[i].toLowerCase(), value); + } } else { if (enable) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getInt(columnName[i])); + try { + ((Map) o).put(Util.toCamelCase(columnName[i]), Integer.parseInt(valueCloumn)); + } catch (Exception e) { + ((Map) o).put(Util.toCamelCase(columnName[i]), valueCloumn); + } continue; } if (DBConstant.DB_TYPE_ORACLE.equals(rs.getDBType())) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getInt(i + 1)); + try { + ((Map) o).put(Util.toCamelCase(columnName[i]), Integer.parseInt(value)); + } catch (Exception e) { + ((Map) o).put(Util.toCamelCase(columnName[i]), value); + } + } + try { + ((Map) o).put(columnName[i].toLowerCase(), Integer.parseInt(value)); + ((Map) o).put(columnName[i].toUpperCase(), Integer.parseInt(value)); + ((Map) o).put(columnName[i], Integer.parseInt(value)); + } catch (Exception e) { + ((Map) o).put(columnName[i].toLowerCase(), value); + ((Map) o).put(columnName[i].toUpperCase(), value); + ((Map) o).put(columnName[i], value); } - ((Map) o).put(columnName[i].toLowerCase(), rs.getInt(i + 1)); - ((Map) o).put(columnName[i].toUpperCase(), rs.getInt(i + 1)); - ((Map) o).put(columnName[i], rs.getInt(i + 1)); } continue; } if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { if (Objects.nonNull(toLowerCase)) { - ((Map) o).put(columnName[i].toLowerCase(), rs.getString(i + 1)); + ((Map) o).put(columnName[i].toLowerCase(), value); } else { if (enable) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getString(columnName[i])); + ((Map) o).put(Util.toCamelCase(columnName[i]), valueCloumn); continue; } if (DBConstant.DB_TYPE_ORACLE.equals(rs.getDBType())) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getString(columnName[i])); + ((Map) o).put(Util.toCamelCase(columnName[i]), valueCloumn); } - ((Map) o).put(columnName[i].toLowerCase(), rs.getString(i + 1)); - ((Map) o).put(columnName[i].toUpperCase(), rs.getString(i + 1)); - ((Map) o).put(columnName[i], rs.getString(i + 1)); + ((Map) o).put(columnName[i].toLowerCase(), value); + ((Map) o).put(columnName[i].toUpperCase(), value); + ((Map) o).put(columnName[i], value); } continue; } @@ -535,18 +554,18 @@ public class ResultMapper { } if (Objects.nonNull(toLowerCase)) { - ((Map) o).put(columnName[i].toLowerCase(), rs.getString(i + 1)); + ((Map) o).put(columnName[i].toLowerCase(), value); } else { if (enable) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getString(columnName[i])); + ((Map) o).put(Util.toCamelCase(columnName[i]), valueCloumn); continue; } if (DBConstant.DB_TYPE_ORACLE.equals(rs.getDBType())) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1)); + ((Map) o).put(Util.toCamelCase(columnName[i]), value); } - ((Map) o).put(columnName[i].toLowerCase(), rs.getString(i + 1)); - ((Map) o).put(columnName[i].toUpperCase(), rs.getString(i + 1)); - ((Map) o).put(columnName[i], rs.getString(i + 1)); + ((Map) o).put(columnName[i].toLowerCase(), value); + ((Map) o).put(columnName[i].toUpperCase(), value); + ((Map) o).put(columnName[i], value); } diff --git a/src/main/java/com/api/xuanran/wang/shyl/service/BatchCreateWorkflowService.java b/src/main/java/com/api/xuanran/wang/shyl/service/BatchCreateWorkflowService.java index 998cd6e..f04e37a 100644 --- a/src/main/java/com/api/xuanran/wang/shyl/service/BatchCreateWorkflowService.java +++ b/src/main/java/com/api/xuanran/wang/shyl/service/BatchCreateWorkflowService.java @@ -17,8 +17,13 @@ import weaver.hrm.User; import weaver.workflow.webservices.WorkflowRequestTableField; import weaver.xuanran.wang.common.util.CommonUtil; -import java.util.*; -import java.util.concurrent.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Future; import java.util.stream.Collectors; @@ -29,165 +34,170 @@ import java.util.stream.Collectors; * @date 2023/2/22 13:58 */ public class BatchCreateWorkflowService { - - // 表名 : requestId 本次需要删除的数据 - private final ConcurrentHashMap> delWorkflowTableRequestId = new ConcurrentHashMap<>(); - // workflowId : tableName - private static final HashMap workflowTable = new HashMap<>(); - private final Logger log = Util.getLogger(); - - private static final String CUSTOM_ID = "customId"; -// private final MeetingMapper meetingTransMapper = Util.getTransMapper(MeetingMapper.class); - private final MeetingService meetingService = new MeetingService(); - /** - *

取消会议 支持多个

- * @author xuanran.wang - * @dateTime 2023/2/24 10:21 - * @param ids 会议id - **/ - public void cancelMeeting(String ids){ - meetingService.cancelMeeting(ids); - } - - /** - *

批量创建流程

- * @author xuanran.wang - * @dateTime 2023/2/22 17:10 - * @param array 流程数据数组 - * @return 创建流程结果 - **/ - public List batchCreateWorkflow(User user, JSONArray array) { - List> list = new ArrayList<>(); - List errors = new ArrayList<>(); - ArrayList res = new ArrayList<>(); - try { - List reqOperateRequestEntities = checkParams(array); - // 结果集 - for (int i = 0; i < reqOperateRequestEntities.size(); i++) { - int temp = i; - // 创建流程 - Callable callable = () -> this.createWorkflow(user,reqOperateRequestEntities.get(temp), temp); - list.add(Util.threadPool.submit(callable)); - } - for (Future future : list) { - CusCreateWfInfo cusCreateWfInfo = future.get(); - PAResponseEntity entity = cusCreateWfInfo.getPaResponseEntity(); - String tableName = workflowTable.get(cusCreateWfInfo.getWorkflowId()); - if(PAResponseCode.SUCCESS != entity.getCode()){ - errors.add(cusCreateWfInfo); - continue; - } - // 将生成的requestId存到vo中返回 - Map data = (Map) entity.getData(); - String requestId = Util.null2DefaultStr(data.get("requestid"),""); - CreateWfVO vo = new CreateWfVO(); - vo.setRequestId(requestId); - vo.setCustomId(cusCreateWfInfo.getCustomId()); - res.add(vo); - - // 将表名 requestId 存到成员变量中 - if (!delWorkflowTableRequestId.containsKey(tableName)) { - ArrayList requestIds = new ArrayList<>(); - requestIds.add(requestId); - delWorkflowTableRequestId.put(tableName, requestIds); - }else { - delWorkflowTableRequestId.get(tableName).add(requestId); - } - } - if(errors.size() > 0){ - throw new CustomerException(JSONObject.toJSONString(errors)); - } - return res; - }catch (Exception e){ - if(MapUtils.isNotEmpty(delWorkflowTableRequestId)){ - log.info("删除流程数据map : " + JSONObject.toJSONString(delWorkflowTableRequestId)); - for (Map.Entry> entry : delWorkflowTableRequestId.entrySet()) { - String tableName = entry.getKey(); - List requestIds = entry.getValue(); - if (!CommonUtil.deleteWorkflowDataByRequestIds(tableName, requestIds)) { - log.error(Util.logStr("删除流程数据失败!表名:{}, 待删除流程集合: {} ", tableName,JSONObject.toJSONString(requestIds))); - } - if (!CommonUtil.deleteWorkflowDataByRequestIds("workflow_requestbase", requestIds)) { - log.error(Util.logStr("删除流程数据失败!表名:{}, 待删除流程集合: {} ", "workflow_requestbase", JSONObject.toJSONString(requestIds))); - } - if (!CommonUtil.deleteWorkflowDataByRequestIds("Bill_Meeting", requestIds)) { - log.error(Util.logStr("删除流程数据失败!表名:{}, 待删除流程集合: {} ", "Bill_Meeting", JSONObject.toJSONString(requestIds))); - } - } - } - throw new CustomerException(e.getMessage()); - } - } - - /** - *

创建流程

- * @author xuanran.wang - * @dateTime 2023/2/24 14:33 - * @param user 用户 - * @param requestEntity 流程请求体 - * @param index 流程集合下标 - * @return 流程创建成功相关数据 - **/ - public CusCreateWfInfo createWorkflow(User user, - ReqOperateRequestEntity requestEntity, - int index){ - // 创建流程 - PAResponseEntity responseEntity = BatchCreateWorkFlowController.WRO.doCreateRequest(user, requestEntity); - CusCreateWfInfo cusCreateWfInfo = new CusCreateWfInfo(); - cusCreateWfInfo.setIndex(index); - cusCreateWfInfo.setPaResponseEntity(responseEntity); - int workflowId = requestEntity.getWorkflowId(); - String tableName = workflowTable.get(workflowId); - if(StringUtils.isBlank(tableName)){ - tableName = CommonUtil.getTableNameByWorkflowId(workflowId); - workflowTable.put(workflowId, tableName); - } - // 获取主表的customId - List collect = requestEntity.getMainData() - .stream() - .filter(item -> CUSTOM_ID.equals(item.getFieldName())) - .collect(Collectors.toList()); - String customIdVal = collect.get(0).getFieldValue(); - cusCreateWfInfo.setCustomId(customIdVal); - cusCreateWfInfo.setWorkflowId(workflowId); - return cusCreateWfInfo; - } - - /** - *

参数校验并将json转成ReqOperateRequestEntity

- * @author xuanran.wang - * @dateTime 2023/2/24 13:36 - * @param array json数组 - * @return 解析后的集合 - **/ - public List checkParams(JSONArray array){ - ArrayList res = new ArrayList<>(); - try { - for (Object obj : array) { - ReqOperateRequestEntity entity; - JSONObject jsonObject; - // 将json转成内部流程对象 - try { - jsonObject = JSONObject.parseObject(obj.toString()); - entity = JSONObject.parseObject(jsonObject.toString(), ReqOperateRequestEntity.class); - }catch (Exception e){ - throw new CustomerException(Util.logStr("json反序列化失败!当前对象:{}, 错误信息: {}" ,obj,e.getMessage())); - } - if(Util.getIntValue(String.valueOf(entity.getWorkflowId()),-1) < 0){ - throw new CustomerException(Util.logStr("该对象workflowId为空!", obj)); - } - List collect = entity.getMainData() - .stream() - .filter(item -> CUSTOM_ID.equals(item.getFieldName())) - .collect(Collectors.toList()); - if(collect.size() == 0){ - throw new CustomerException(Util.logStr("该对象mainData中未找到customId!:{}", obj)); - } - res.add(entity); - } - }catch (Exception e){ - throw new CustomerException(Util.logStr("JSON参数校验失败!请检查json是否正确!错误信息: {}",e.getMessage())); - } - return res; - } + + // 表名 : requestId 本次需要删除的数据 + private final ConcurrentHashMap> delWorkflowTableRequestId = new ConcurrentHashMap<>(); + // workflowId : tableName + private static final HashMap workflowTable = new HashMap<>(); + private final Logger log = Util.getLogger(); + + private static final String CUSTOM_ID = "customId"; + // private final MeetingMapper meetingTransMapper = Util.getTransMapper(MeetingMapper.class); + private final MeetingService meetingService = new MeetingService(); + + /** + *

取消会议 支持多个

+ * + * @param ids 会议id + * @author xuanran.wang + * @dateTime 2023/2/24 10:21 + **/ + public void cancelMeeting(String ids) { + meetingService.cancelMeeting(ids); + } + + /** + *

批量创建流程

+ * + * @param array 流程数据数组 + * @return 创建流程结果 + * @author xuanran.wang + * @dateTime 2023/2/22 17:10 + **/ + public List batchCreateWorkflow(User user, JSONArray array) { + List> list = new ArrayList<>(); + List errors = new ArrayList<>(); + ArrayList res = new ArrayList<>(); + try { + List reqOperateRequestEntities = checkParams(array); + // 结果集 + for (int i = 0; i < reqOperateRequestEntities.size(); i++) { + int temp = i; + // 创建流程 + Callable callable = () -> this.createWorkflow(user, reqOperateRequestEntities.get(temp), temp); + list.add(Util.threadPool.submit(callable)); + } + for (Future future : list) { + CusCreateWfInfo cusCreateWfInfo = future.get(); + PAResponseEntity entity = cusCreateWfInfo.getPaResponseEntity(); + String tableName = workflowTable.get(cusCreateWfInfo.getWorkflowId()); + if (PAResponseCode.SUCCESS != entity.getCode()) { + errors.add(cusCreateWfInfo); + continue; + } + // 将生成的requestId存到vo中返回 + Map data = (Map) entity.getData(); + String requestId = Util.null2DefaultStr(data.get("requestid"), ""); + CreateWfVO vo = new CreateWfVO(); + vo.setRequestId(requestId); + vo.setCustomId(cusCreateWfInfo.getCustomId()); + res.add(vo); + + // 将表名 requestId 存到成员变量中 + if (!delWorkflowTableRequestId.containsKey(tableName)) { + ArrayList requestIds = new ArrayList<>(); + requestIds.add(requestId); + delWorkflowTableRequestId.put(tableName, requestIds); + } else { + delWorkflowTableRequestId.get(tableName).add(requestId); + } + } + if (errors.size() > 0) { + throw new CustomerException(JSONObject.toJSONString(errors)); + } + return res; + } catch (Exception e) { + if (MapUtils.isNotEmpty(delWorkflowTableRequestId)) { + log.info("删除流程数据map : " + JSONObject.toJSONString(delWorkflowTableRequestId)); + for (Map.Entry> entry : delWorkflowTableRequestId.entrySet()) { + String tableName = entry.getKey(); + List requestIds = entry.getValue(); + if (!CommonUtil.deleteWorkflowDataByRequestIds(tableName, requestIds)) { + log.error(Util.logStr("删除流程数据失败!表名:{}, 待删除流程集合: {} ", tableName, JSONObject.toJSONString(requestIds))); + } + if (!CommonUtil.deleteWorkflowDataByRequestIds("workflow_requestbase", requestIds)) { + log.error(Util.logStr("删除流程数据失败!表名:{}, 待删除流程集合: {} ", "workflow_requestbase", JSONObject.toJSONString(requestIds))); + } + if (!CommonUtil.deleteWorkflowDataByRequestIds("Bill_Meeting", requestIds)) { + log.error(Util.logStr("删除流程数据失败!表名:{}, 待删除流程集合: {} ", "Bill_Meeting", JSONObject.toJSONString(requestIds))); + } + } + } + throw new CustomerException(e.getMessage()); + } + } + + /** + *

创建流程

+ * + * @param user 用户 + * @param requestEntity 流程请求体 + * @param index 流程集合下标 + * @return 流程创建成功相关数据 + * @author xuanran.wang + * @dateTime 2023/2/24 14:33 + **/ + public CusCreateWfInfo createWorkflow(User user, + ReqOperateRequestEntity requestEntity, + int index) { + // 创建流程 + PAResponseEntity responseEntity = BatchCreateWorkFlowController.WRO.doCreateRequest(user, requestEntity); + CusCreateWfInfo cusCreateWfInfo = new CusCreateWfInfo(); + cusCreateWfInfo.setIndex(index); + cusCreateWfInfo.setPaResponseEntity(responseEntity); + int workflowId = requestEntity.getWorkflowId(); + String tableName = workflowTable.get(workflowId); + if (StringUtils.isBlank(tableName)) { + tableName = CommonUtil.getTableNameByWorkflowId(workflowId); + workflowTable.put(workflowId, tableName); + } + // 获取主表的customId + List collect = requestEntity.getMainData() + .stream() + .filter(item -> CUSTOM_ID.equals(item.getFieldName())) + .collect(Collectors.toList()); + String customIdVal = collect.get(0).getFieldValue(); + cusCreateWfInfo.setCustomId(customIdVal); + cusCreateWfInfo.setWorkflowId(workflowId); + return cusCreateWfInfo; + } + + /** + *

参数校验并将json转成ReqOperateRequestEntity

+ * + * @param array json数组 + * @return 解析后的集合 + * @author xuanran.wang + * @dateTime 2023/2/24 13:36 + **/ + public List checkParams(JSONArray array) { + ArrayList res = new ArrayList<>(); + try { + for (Object obj : array) { + ReqOperateRequestEntity entity; + JSONObject jsonObject; + // 将json转成内部流程对象 + try { + jsonObject = JSONObject.parseObject(obj.toString()); + entity = JSONObject.parseObject(jsonObject.toString(), ReqOperateRequestEntity.class); + } catch (Exception e) { + throw new CustomerException(Util.logStr("json反序列化失败!当前对象:{}, 错误信息: {}", obj, e.getMessage())); + } + if (Util.getIntValue(String.valueOf(entity.getWorkflowId()), -1) < 0) { + throw new CustomerException(Util.logStr("该对象workflowId为空!", obj)); + } + List collect = entity.getMainData() + .stream() + .filter(item -> CUSTOM_ID.equals(item.getFieldName())) + .collect(Collectors.toList()); + if (collect.size() == 0) { + throw new CustomerException(Util.logStr("该对象mainData中未找到customId!:{}", obj)); + } + res.add(entity); + } + } catch (Exception e) { + throw new CustomerException(Util.logStr("JSON参数校验失败!请检查json是否正确!错误信息: {}", e.getMessage())); + } + return res; + } } diff --git a/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/contoller/TaskElementController.java b/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/contoller/TaskElementController.java index 6070c98..e1ab629 100644 --- a/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/contoller/TaskElementController.java +++ b/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/contoller/TaskElementController.java @@ -143,4 +143,5 @@ public class TaskElementController { return ApiResult.error("system error!"); } } + } diff --git a/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/mapper/TaskElementMapper.java b/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/mapper/TaskElementMapper.java index 9278b84..74407f1 100644 --- a/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/mapper/TaskElementMapper.java +++ b/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/mapper/TaskElementMapper.java @@ -168,4 +168,22 @@ public interface TaskElementMapper { */ @Update("update uf_rwtzeq_dt1 set zjwczt = 0 where zjr = #{userId} and mainid = #{mainId}") boolean updateTaskHandoverStatus(@ParamMapper("userId") String userId, @ParamMapper("mainId") String mainId); + + /** + *

查询相似名称的人员信息

+ * + * @param nameLike 姓名like + * @return 姓名like的id + */ + @Select("select id from hrmresource where lastname like #{nameLike}") + List selectUserNameLike(String nameLike); + + /** + *

查询相似名称的人员信息

+ * + * @param value 姓名 + * @return 姓名的id + */ + @Select("select id from hrmresource where lastname = #{nameLike}") + Integer selectUserName(String value); } diff --git a/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/service/TaskElementService.java b/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/service/TaskElementService.java index 9fbb345..464ff4a 100644 --- a/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/service/TaskElementService.java +++ b/src/main/java/com/api/youhong/ai/ihgzhouji/taskele/service/TaskElementService.java @@ -106,7 +106,10 @@ public class TaskElementService { for (Map item : authorityList) { if ("0".equals(dataSource)) { // 自定义sql - customerValue += " " + whereStr; + // customerValue += " " + whereStr; + if (StrUtil.isNotBlank(whereStr)) { + customerValue = "select * from (" + customerValue + ") temp where " + whereStr; + } List> list = mapper.selectWorkList(customerValue, item, user, whereMap, currentMap); if (CollectionUtil.isNotEmpty(list)) { result.addAll(list); @@ -179,8 +182,10 @@ public class TaskElementService { Map map = new HashMap<>(8); map.put("currentDate", Util.getTime("yyyy-MM-dd")); map.put("currentTime", Util.getTime("HH:mm:ss")); + Map searchParam = (Map) params.get("searchParam"); + Map allSearch = (Map) params.get("allSearch"); StringBuilder builder = new StringBuilder(); - for (Map.Entry entry : params.entrySet()) { + for (Map.Entry entry : searchParam.entrySet()) { Map valueMap = (Map) entry.getValue(); String key = Util.null2String(valueMap.get("key")); String value = Util.null2String(valueMap.get("value")); @@ -196,6 +201,49 @@ public class TaskElementService { } } String whereStr = builder.toString(); + if (StrUtil.isNotBlank(whereStr)) { + String trim = whereStr.trim(); + if (trim.startsWith("and")) { + whereStr = trim.substring(3); + } + } + if (CollectionUtil.isNotEmpty(allSearch)) { + StringBuilder orWhere = new StringBuilder(); + String value = Util.null2String(allSearch.get("value")); + if (StrUtil.isNotBlank(value)) { + List> fields = (List>) allSearch.get("fields"); + for (Map field : fields) { + String key = Util.null2String(field.get("key")); + String type = Util.null2String(field.get("type")); + if ("like".equalsIgnoreCase(type)) { + orWhere.append(" or ").append(key).append(" like ").append("concat('%',#{where._allValue},'%')"); + } else if ("hrm like".equalsIgnoreCase(type)) { + List hrmList = mapper.selectUserNameLike("%" + value + "%"); + orWhere.append(" or ").append(key).append(" in ( ").append(Util.intJoin(hrmList, ",")).append(") "); + } else if ("hrm".equalsIgnoreCase(type)) { + Integer hrmId = mapper.selectUserName(value); + orWhere.append(" or ").append(key).append(" = ").append(hrmId); + } else { + orWhere.append(" or ").append(key).append(" = ").append("#{where._allValue}"); + } + } + map.put("_allValue", value); + String orWhereStr = orWhere.toString(); + if (StrUtil.isNotBlank(orWhereStr)) { + String trim = orWhereStr.trim(); + if (trim.startsWith("or")) { + orWhereStr = trim.substring(2); + } + if (StrUtil.isNotBlank(whereStr)) { + whereStr = whereStr + " or ( " + orWhereStr + " )"; + } else { + whereStr = orWhereStr; + } + } + } + + } + // 查询可查看权限并进行过滤 String viewAuthoritySql = ihgTaskElementConfItem.getViewAuthority(); List> authorityList = mapper.selectAuthority(viewAuthoritySql, user, map); diff --git a/src/main/java/com/api/youhong/ai/pcn/download/controller/DownloadFileController.java b/src/main/java/com/api/youhong/ai/pcn/download/controller/DownloadFileController.java new file mode 100644 index 0000000..1527417 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/download/controller/DownloadFileController.java @@ -0,0 +1,40 @@ +package com.api.youhong.ai.pcn.download.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.youhong.ai.pcn.download.service.DownloadFileService; +import org.apache.log4j.Logger; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +/** + *

下载文件

+ * + *

create: 2023/6/26 23:30

+ * + * @author youHong.ai + */ +@Path("aiyh/download-file") +public class DownloadFileController { + + private final Logger log = Util.getLogger(); + + private final DownloadFileService service = new DownloadFileService(); + + @GET + @Path("download") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response downloadFile(@QueryParam("fieldId") String fieldId) { + try { + return service.downloadFile(fieldId); + } catch (Exception e) { + log.error("下载文件出错:" + Util.getErrString(e)); + return Response.ok(ApiResult.error("system error!"), MediaType.APPLICATION_JSON).build(); + } + } +} diff --git a/src/main/java/com/api/youhong/ai/pcn/download/service/DownloadFileService.java b/src/main/java/com/api/youhong/ai/pcn/download/service/DownloadFileService.java new file mode 100644 index 0000000..6585426 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/download/service/DownloadFileService.java @@ -0,0 +1,67 @@ +package com.api.youhong.ai.pcn.download.service; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import aiyh.utils.entity.DocImageInfo; +import aiyh.utils.excention.CustomerException; +import aiyh.utils.tool.cn.hutool.core.util.StrUtil; +import weaver.file.ImageFileManager; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import java.io.InputStream; +import java.net.URLDecoder; + +/** + *

+ * + *

create: 2023/6/26 23:33

+ * + * @author youHong.ai + */ + +public class DownloadFileService { + + + public static final String SUFFIX = "=="; + + /** + *

下载文件

+ * + * @param encryptionFileId 加密后的文件id docid + * @return 文件流 + */ + public Response downloadFile(String encryptionFileId) { + if (StrUtil.isBlank(encryptionFileId)) { + return Response.ok(ApiResult.error("fileId is blank!"), MediaType.APPLICATION_JSON).build(); + } + String fieldId = null; + try { + String decode = URLDecoder.decode(encryptionFileId, "UTF-8"); + if (encryptionFileId.endsWith(SUFFIX)) { + decode = encryptionFileId; + } + fieldId = EncryptionFileIdUtil.decrypt(decode); + } catch (Exception e) { + throw new CustomerException("解密附件id失败!", e); + } + DocImageInfo docImageInfo = Util.selectImageInfoByDocId(fieldId); + StreamingOutput stream = outputStream -> { + Integer imageFileId = docImageInfo.getImageFileId(); + InputStream inputStreamById = ImageFileManager.getInputStreamById(imageFileId); + byte[] buffer = new byte[4096]; + int bytesRead; + while ((bytesRead = inputStreamById.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + }; + String imageFileName = docImageInfo.getImageFileName(); + return Response + .ok(stream) + .header("Content-Disposition", "attachment; filename=\"" + imageFileName + "\"") + .build(); + } + + +} diff --git a/src/main/java/com/api/youhong/ai/pcn/download/service/EncryptionFileIdUtil.java b/src/main/java/com/api/youhong/ai/pcn/download/service/EncryptionFileIdUtil.java new file mode 100644 index 0000000..aecf9f5 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/download/service/EncryptionFileIdUtil.java @@ -0,0 +1,70 @@ +package com.api.youhong.ai.pcn.download.service; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; + +/** + *

加密工具

+ * + *

create: 2023/6/26 23:43

+ * + * @author youHong.ai + */ +public class EncryptionFileIdUtil { + private static final String PASSWORD = "H6f9T4x2jL8E3K7Y"; + + + /** + * 将密码补齐到合法长度 + * + * @param password 密码 + * @return 合法长度的密码 + */ + public static String padPassword(String password) { + byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8); + // AES-128 + int validKeyLength = 16; + if (passwordBytes.length < validKeyLength) { + byte[] paddedBytes = Arrays.copyOf(passwordBytes, validKeyLength); + return new String(paddedBytes, StandardCharsets.UTF_8); + } else if (passwordBytes.length > validKeyLength) { + return new String(Arrays.copyOf(passwordBytes, validKeyLength), StandardCharsets.UTF_8); + } + return password; + } + + /** + *

使用AES对称加密算法和Base64编码进行加密

+ * + * @param plaintext 待加密字符串 + * @return 加密后的字符串 + * @throws Exception 产生的异常信息 + */ + public static String encrypt(String plaintext) throws Exception { + String password = padPassword(PASSWORD); + SecretKeySpec secretKey = new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), "AES"); + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, secretKey); + byte[] encryptedData = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); + return Base64.getEncoder().encodeToString(encryptedData); + } + + /** + *

使用AES对称加密算法和Base64编码进行解密

+ * + * @param encryptedText 加密后的字符串 + * @return 解密后的字符串 + * @throws Exception 异常信息 + */ + public static String decrypt(String encryptedText) throws Exception { + String password = padPassword(PASSWORD); + SecretKeySpec secretKey = new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), "AES"); + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, secretKey); + byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); + return new String(decryptedData, StandardCharsets.UTF_8); + } +} diff --git a/src/main/java/com/api/youhong/ai/taibao/checknumber/controller/CheckNumberController.java b/src/main/java/com/api/youhong/ai/taibao/checknumber/controller/CheckNumberController.java new file mode 100644 index 0000000..df99bdd --- /dev/null +++ b/src/main/java/com/api/youhong/ai/taibao/checknumber/controller/CheckNumberController.java @@ -0,0 +1,41 @@ +package com.api.youhong.ai.taibao.checknumber.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.youhong.ai.taibao.checknumber.service.CheckNumberService; +import org.apache.log4j.Logger; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + +/** + *

检查是否存在编号

+ * + *

create: 2023/6/26 11:03

+ * + * @author youHong.ai + */ +@Path("/aiyh/taibao/bh") +public class CheckNumberController { + + private final Logger log = Util.getLogger(); + + private final CheckNumberService service = new CheckNumberService(); + + @Path("check-number") + @GET + @Produces(MediaType.APPLICATION_JSON) + public String checkNumber(@QueryParam("tableName") String tableName, + @QueryParam("field") String field, + @QueryParam("requestId") String requestId) { + try { + return ApiResult.success(service.checkNumber(tableName, field, requestId)); + } catch (Exception e) { + log.error("检查是否存在编号出错:" + Util.getErrString(e)); + return ApiResult.error("system error!"); + } + } +} diff --git a/src/main/java/com/api/youhong/ai/taibao/checknumber/mapper/CheckNumberMapper.java b/src/main/java/com/api/youhong/ai/taibao/checknumber/mapper/CheckNumberMapper.java new file mode 100644 index 0000000..791a356 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/taibao/checknumber/mapper/CheckNumberMapper.java @@ -0,0 +1,29 @@ +package com.api.youhong.ai.taibao.checknumber.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +/** + *

+ * + *

create: 2023/6/26 11:08

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

查询编号是否存在

+ * + * @param field 编号字段 + * @param tableName 表名称 + * @param requestId 流程id + * @return 编号 + */ + @Select("select $t{field} from $t{tableName} where requestid = #{requestId}") + String selectNumber(@ParamMapper("field") String field, + @ParamMapper("tableName") String tableName, + @ParamMapper("requestId") String requestId); +} diff --git a/src/main/java/com/api/youhong/ai/taibao/checknumber/service/CheckNumberService.java b/src/main/java/com/api/youhong/ai/taibao/checknumber/service/CheckNumberService.java new file mode 100644 index 0000000..2daef06 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/taibao/checknumber/service/CheckNumberService.java @@ -0,0 +1,31 @@ +package com.api.youhong.ai.taibao.checknumber.service; + +import aiyh.utils.Util; +import aiyh.utils.tool.cn.hutool.core.util.StrUtil; +import com.api.youhong.ai.taibao.checknumber.mapper.CheckNumberMapper; + +/** + *

+ * + *

create: 2023/6/26 11:06

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

检查是否存在编号

+ * + * @param tableName 表名称 + * @param field 字段 + * @param requestId 流程id + * @return 是否存在编号 + */ + public boolean checkNumber(String tableName, String field, String requestId) { + String number = mapper.selectNumber(field, tableName, requestId); + return StrUtil.isNotBlank(number); + } + +} diff --git a/src/main/java/com/customization/youhong/pcn/createrworkflow/impl/CheckWorkflowRequestParamsImpl.java b/src/main/java/com/customization/youhong/pcn/createrworkflow/impl/CheckWorkflowRequestParamsImpl.java index 6e8f413..46c87cd 100644 --- a/src/main/java/com/customization/youhong/pcn/createrworkflow/impl/CheckWorkflowRequestParamsImpl.java +++ b/src/main/java/com/customization/youhong/pcn/createrworkflow/impl/CheckWorkflowRequestParamsImpl.java @@ -2,7 +2,6 @@ package com.customization.youhong.pcn.createrworkflow.impl; import aiyh.utils.Util; import com.customization.youhong.pcn.createrworkflow.CreateRequestException; -import com.customization.youhong.pcn.createrworkflow.mapper.CheckWorkflowRequestParamsMapper; import com.customization.youhong.pcn.createrworkflow.util.CheckWorkflowRequestParamsUtil; import com.engine.core.cfg.annotation.ServiceDynamicProxy; import com.engine.core.cfg.annotation.ServiceMethodDynamicProxy; @@ -31,7 +30,6 @@ public class CheckWorkflowRequestParamsImpl extends AbstractServiceProxy impleme private final Logger log = Util.getLogger("workflow"); - private final CheckWorkflowRequestParamsMapper mapper = Util.getMapper(CheckWorkflowRequestParamsMapper.class); private final CheckWorkflowRequestParamsUtil checkUtil = new CheckWorkflowRequestParamsUtil(); diff --git a/src/main/java/com/customization/youhong/pcn/createrworkflow/util/CheckWorkflowRequestParamsUtil.java b/src/main/java/com/customization/youhong/pcn/createrworkflow/util/CheckWorkflowRequestParamsUtil.java index a710693..c133eb0 100644 --- a/src/main/java/com/customization/youhong/pcn/createrworkflow/util/CheckWorkflowRequestParamsUtil.java +++ b/src/main/java/com/customization/youhong/pcn/createrworkflow/util/CheckWorkflowRequestParamsUtil.java @@ -2,6 +2,7 @@ package com.customization.youhong.pcn.createrworkflow.util; import aiyh.utils.Util; import aiyh.utils.tool.cn.hutool.core.collection.CollectionUtil; +import com.alibaba.fastjson.JSON; import com.customization.youhong.pcn.createrworkflow.CreateRequestException; import com.customization.youhong.pcn.createrworkflow.mapper.CheckWorkflowRequestParamsMapper; import com.customization.youhong.pcn.createrworkflow.pojo.CheckConditionItem; @@ -51,6 +52,8 @@ public class CheckWorkflowRequestParamsUtil { if (CollectionUtil.isEmpty(detailList)) { return; } + log.info("checkCreateConfig: " + JSON.toJSONString(checkCreateConfig)); + log.info("detailList: " + JSON.toJSONString(detailList)); Map checkConditionItemMap; List conditionGroupItems = checkCreateConfig.getConditionGroupItems(); if (CollectionUtil.isNotEmpty(conditionGroupItems)) { diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/todwfworkflow/cusgetdata/FileLinkListGetImpl.java b/src/main/java/weaver/youhong/ai/pcn/actioin/todwfworkflow/cusgetdata/FileLinkListGetImpl.java new file mode 100644 index 0000000..3fcdd09 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/todwfworkflow/cusgetdata/FileLinkListGetImpl.java @@ -0,0 +1,46 @@ +package weaver.youhong.ai.pcn.actioin.todwfworkflow.cusgetdata; + +import aiyh.utils.Util; +import aiyh.utils.entity.DocImageInfo; +import aiyh.utils.excention.CustomerException; +import aiyh.utils.tool.cn.hutool.core.util.StrUtil; +import com.api.youhong.ai.pcn.download.service.EncryptionFileIdUtil; +import weaver.xiao.commons.config.interfacies.CusInterfaceGetValue; + +import java.net.URLEncoder; +import java.util.*; + +/** + *

自定义附件数组获取值

+ * + *

create: 2023/6/26 23:57

+ * + * @author youHong.ai + */ +public class FileLinkListGetImpl implements CusInterfaceGetValue { + @Override + public Object execute(Map mainMap, Map detailMap, String currentValue, Map pathParam) { + if (StrUtil.isBlank(currentValue)) { + return Collections.emptyList(); + } + String downloadFileHost = Util.getCusConfigValue("downloadFileHost"); + List docImageInfos = Util.selectImageInfoByDocIds(currentValue); + List> list = new ArrayList<>(); + for (DocImageInfo docImageInfo : docImageInfos) { + String encode = null; + try { + String encrypt = EncryptionFileIdUtil.encrypt(docImageInfo.getDocId() + ""); + encode = URLEncoder.encode(encrypt, "UTF-8"); + } catch (Exception e) { + throw new CustomerException("加密附件id出错!", e); + } + String url = downloadFileHost + "/api/aiyh/download-file/download?fieldId=" + encode; + Map map = new HashMap<>(8); + map.put("fileName", docImageInfo.getImageFileName()); + map.put("fileId", docImageInfo.getImageFileId()); + map.put("fileUrl", url); + list.add(map); + } + return list; + } +} diff --git a/src/test/java/youhong/ai/pcn/Test01.java b/src/test/java/youhong/ai/pcn/Test01.java index 556eece..fd04386 100644 --- a/src/test/java/youhong/ai/pcn/Test01.java +++ b/src/test/java/youhong/ai/pcn/Test01.java @@ -1,10 +1,14 @@ package youhong.ai.pcn; import basetest.BaseTest; +import com.api.youhong.ai.pcn.download.service.EncryptionFileIdUtil; import com.api.youhong.ai.pcn.ssoyunzhao.service.SsoYunZhaoService; import org.junit.Test; import weaver.hrm.User; +import java.net.URLDecoder; +import java.net.URLEncoder; + /** *

test

* @@ -23,4 +27,13 @@ public class Test01 extends BaseTest { System.out.println(service.rsaDecryptUserInfo("EpPlcAYvNOFfJWHBuvLkWzkTOoEk3NoO95FoRlEJTGlblyBEYV0CQWnCDd4yXDCgcR1yhaig/5NrIZ5dGTTgwZ6f0fOfVDdnFPr5/GUUzxxsW8qpdHLIswFT1O4E57ny1Df6uxPaE5Hqp3QHvGkfUo4ak2mI0D11V7XzxGmVsSqoofdrCVXJIRrTkUHJ3OSxtQtkuxHcc0ivSAtJkWtdgnxRbmCvMMuPKELAq/cxqPfRSAf/sL/SI374DqlYnZDn/BCVA9Ab9TC/9g08QHSlGP+XV/CySecV5Z8bILCTV8bzcgMUznQSTuyIastzMHWLtcJ2zr4gE8jR393vRtAI9A==")); } + + @Test + public void testEnDocid() throws Exception { + String encrypt = EncryptionFileIdUtil.encrypt("76"); + String encode = URLEncoder.encode(encrypt, "UTF-8"); + System.out.println(encode); + String decode = URLDecoder.decode(encode, "UTF-8"); + System.out.println(EncryptionFileIdUtil.decrypt(decode)); + } } diff --git a/src/test/java/youhong/ai/utiltest/OtherTest.java b/src/test/java/youhong/ai/utiltest/OtherTest.java new file mode 100644 index 0000000..4be3735 --- /dev/null +++ b/src/test/java/youhong/ai/utiltest/OtherTest.java @@ -0,0 +1,22 @@ +package youhong.ai.utiltest; + +import org.junit.Test; + +/** + *

其他测试

+ * + *

create: 2023/6/28 10:59

+ * + * @author youHong.ai + */ +public class OtherTest { + + + @Test + public void test() { + String str = "and alsdjf jsi3jtj"; + System.out.println(str.substring(3)); + } + + +} \ No newline at end of file diff --git a/src/test/java/youhong/ai/utiltest/ShortEncryptionExample.java b/src/test/java/youhong/ai/utiltest/ShortEncryptionExample.java new file mode 100644 index 0000000..64f90c9 --- /dev/null +++ b/src/test/java/youhong/ai/utiltest/ShortEncryptionExample.java @@ -0,0 +1,63 @@ +package youhong.ai.utiltest; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; + +public class ShortEncryptionExample { + + public static void main(String[] args) { + try { + String plaintext = "9384819"; + String password = "SecretPassword"; + + // 补齐密码到合法长度 + password = padPassword(password); + + // 加密 + String encryptedText = encrypt(plaintext, password); + + // 解密 + String decryptedText = decrypt(encryptedText, password); + + System.out.println("原文: " + plaintext); + System.out.println("加密后: " + encryptedText); + System.out.println("解密后: " + decryptedText); + } catch (Exception e) { + e.printStackTrace(); + } + } + + // 将密码补齐到合法长度 + public static String padPassword(String password) { + byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8); + int validKeyLength = 16; // AES-128 + if (passwordBytes.length < validKeyLength) { + byte[] paddedBytes = Arrays.copyOf(passwordBytes, validKeyLength); + return new String(paddedBytes, StandardCharsets.UTF_8); + } else if (passwordBytes.length > validKeyLength) { + return new String(Arrays.copyOf(passwordBytes, validKeyLength), StandardCharsets.UTF_8); + } + return password; + } + + // 使用AES对称加密算法和Base64编码进行加密 + public static String encrypt(String plaintext, String password) throws Exception { + SecretKeySpec secretKey = new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), "AES"); + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, secretKey); + byte[] encryptedData = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); + return Base64.getEncoder().encodeToString(encryptedData); + } + + // 使用AES对称加密算法和Base64编码进行解密 + public static String decrypt(String encryptedText, String password) throws Exception { + SecretKeySpec secretKey = new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), "AES"); + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, secretKey); + byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); + return new String(decryptedData, StandardCharsets.UTF_8); + } +}