diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index 59bbd3f..9618e72 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -447,7 +447,7 @@ $(() => { $(() => { const config = { table: 'detail_1', - field: ['fj'] + field: ['qswj'] } function check() { @@ -456,7 +456,7 @@ $(() => { try { rowIndexArr.forEach(item => { config.field.forEach(field => { - let value = WfForm.getFieldValue(WfForm.convertFieldNameToId(field,
) + "_" + item) + let value = WfForm.getFieldValue(WfForm.convertFieldNameToId(field, config.table) + "_" + item) if (value == '' || value == null) { throw field + " is can not be null!"; } diff --git a/src/main/java/aiyh/utils/GenerateFileUtil.java b/src/main/java/aiyh/utils/GenerateFileUtil.java index 54b3cda..7b8631b 100644 --- a/src/main/java/aiyh/utils/GenerateFileUtil.java +++ b/src/main/java/aiyh/utils/GenerateFileUtil.java @@ -29,196 +29,195 @@ import java.util.Map; */ public class GenerateFileUtil { - - private static final Logger log = Util.getLogger(); - - - /** - *

根据Action类生成Action配置文档

- * - * @param tClass Action类 - * @param Action接口 - */ - @SafeVarargs - public static void createActionDocument(Class... tClass) { - for (Class aClass : tClass) { - createDocument(aClass, 1); - } - } - - - /** - *

根据定时任务类生成定时任务配置文档

- * - * @param tClass 定时任务类 - * @param Action接口 - */ - @SafeVarargs - public static void createCronJobDocument(Class... tClass) { - for (Class aClass : tClass) { - createDocument(aClass, 2); - } - } - - /** - *

根据类生成配置文档

- * - * @param tClass 类 - * @param 接口 - */ - private static void createDocument(Class tClass, Integer type) { - if (tClass == null) { - return; - } - if (!tClass.isAnnotationPresent(ActionDesc.class)) { - log.info(Util.logStr("[{}] has not ActionDesc annotation!", tClass.getName())); - return; - } - ActionDesc actionDesc = tClass.getAnnotation(ActionDesc.class); - String author = actionDesc.author(); - String actionDescValue = actionDesc.value(); - String actionName = tClass.getSimpleName(); - String actionAllPathName = tClass.getName(); - List> paramList = new ArrayList<>(); - for (Field declaredField : tClass.getDeclaredFields()) { - boolean hasRequired = declaredField.isAnnotationPresent(RequiredMark.class); - String name = declaredField.getName(); - if (hasRequired) { + + private static final Logger log = Util.getLogger(); + + + /** + *

根据Action类生成Action配置文档

+ * + * @param tClass Action类 + * @param Action接口 + */ + @SafeVarargs + public static void createActionDocument(Class... tClass) { + for (Class aClass : tClass) { + createDocument(aClass, 1); + } + } + + + /** + *

根据定时任务类生成定时任务配置文档

+ * + * @param tClass 定时任务类 + * @param Action接口 + */ + @SafeVarargs + public static void createCronJobDocument(Class... tClass) { + for (Class aClass : tClass) { + createDocument(aClass, 2); + } + } + + /** + *

根据类生成配置文档

+ * + * @param tClass 类 + * @param 接口 + */ + private static void createDocument(Class tClass, Integer type) { + if (tClass == null) { + return; + } + if (!tClass.isAnnotationPresent(ActionDesc.class)) { + throw new CustomerException(Util.logStr("[{}] has not ActionDesc annotation!", tClass.getName())); + } + ActionDesc actionDesc = tClass.getAnnotation(ActionDesc.class); + String author = actionDesc.author(); + String actionDescValue = actionDesc.value(); + String actionName = tClass.getSimpleName(); + String actionAllPathName = tClass.getName(); + List> paramList = new ArrayList<>(); + for (Field declaredField : tClass.getDeclaredFields()) { + boolean hasRequired = declaredField.isAnnotationPresent(RequiredMark.class); + String name = declaredField.getName(); + if (hasRequired) { // 必填参数 - RequiredMark requiredMark = declaredField.getAnnotation(RequiredMark.class); - String fieldDesc = requiredMark.value(); - Map param = new HashMap<>(); - param.put("name", name); - param.put("desc", fieldDesc); - param.put("isRequired", "是"); - boolean hasDefaultTestValue = declaredField.isAnnotationPresent(ActionDefaultTestValue.class); - if (hasDefaultTestValue) { + RequiredMark requiredMark = declaredField.getAnnotation(RequiredMark.class); + String fieldDesc = requiredMark.value(); + Map param = new HashMap<>(); + param.put("name", name); + param.put("desc", fieldDesc); + param.put("isRequired", "是"); + boolean hasDefaultTestValue = declaredField.isAnnotationPresent(ActionDefaultTestValue.class); + if (hasDefaultTestValue) { // 示例值 - ActionDefaultTestValue defaultTestValue = declaredField.getAnnotation(ActionDefaultTestValue.class); - param.put("example", defaultTestValue.value()); - } - paramList.add(param); - } else { + ActionDefaultTestValue defaultTestValue = declaredField.getAnnotation(ActionDefaultTestValue.class); + param.put("example", defaultTestValue.value()); + } + paramList.add(param); + } else { // 非必填参数 - boolean hasActionOptional = declaredField.isAnnotationPresent(ActionOptionalParam.class); - if (hasActionOptional) { + boolean hasActionOptional = declaredField.isAnnotationPresent(ActionOptionalParam.class); + if (hasActionOptional) { // 可选参数 - ActionOptionalParam actionOptionalParam = declaredField.getAnnotation(ActionOptionalParam.class); - String fieldDesc = actionOptionalParam.desc(); - String defaultValue = actionOptionalParam.value(); - Map param = new HashMap<>(); - param.put("name", name); - param.put("desc", fieldDesc); - param.put("isRequired", "否"); - param.put("defaultValue", defaultValue); - paramList.add(param); - } - } - } - Map vmParam = new HashMap<>(); - vmParam.put("author", author); - vmParam.put("actionDesc", actionDescValue); - vmParam.put("actionName", actionName); - vmParam.put("actionAllPathName", actionAllPathName); - vmParam.put("paramList", paramList); - vmParam.put("type", type); - vmParam.put("createTime", Util.getTime("yyyy-MM-dd HH:mm:ss")); - VelocityEngine ve = new VelocityEngine(); - ve.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8"); - String path = weaver.general.GCONST.getPropertyPath().replace("prop", "vm"); - ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path); + ActionOptionalParam actionOptionalParam = declaredField.getAnnotation(ActionOptionalParam.class); + String fieldDesc = actionOptionalParam.desc(); + String defaultValue = actionOptionalParam.value(); + Map param = new HashMap<>(); + param.put("name", name); + param.put("desc", fieldDesc); + param.put("isRequired", "否"); + param.put("defaultValue", defaultValue); + paramList.add(param); + } + } + } + Map vmParam = new HashMap<>(); + vmParam.put("author", author); + vmParam.put("actionDesc", actionDescValue); + vmParam.put("actionName", actionName); + vmParam.put("actionAllPathName", actionAllPathName); + vmParam.put("paramList", paramList); + vmParam.put("type", type); + vmParam.put("createTime", Util.getTime("yyyy-MM-dd HH:mm:ss")); + VelocityEngine ve = new VelocityEngine(); + ve.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8"); + String path = weaver.general.GCONST.getPropertyPath().replace("prop", "vm"); + ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path); /* ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath") ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());*/ - try { - ve.init(); - } catch (Exception e) { - e.printStackTrace(); - } - // 获取模板文件 - try { - Template template = ve.getTemplate("ActionConfigTemplate.md.vm", "UTF-8"); - String prefix = type == 1 ? "Action" : "定时任务"; - String fileName = prefix + "部署配置文档-" + actionName + "-" + author + "-" + Util.getTime("yyyyMMddHHmmss") + ".md"; - File saveFile = new File(path + "outFile" + File.separator + fileName); - if (!saveFile.getParentFile().exists()) { - saveFile.getParentFile().mkdirs(); - } - // 创建文件输出流 - FileOutputStream outStream = new FileOutputStream(saveFile); - // 因为模板整合的时候,需要提供一个Writer,所以创建一个Writer - OutputStreamWriter writer = new OutputStreamWriter(outStream); - // 创建一个缓冲流 - BufferedWriter bufferWriter = new BufferedWriter(writer); - - VelocityContext ctx = new VelocityContext(vmParam); - // 5 合并模板和数据并输出 - template.merge(ctx, bufferWriter); - // 强制刷新 - bufferWriter.flush(); - outStream.close(); - bufferWriter.close(); - System.out.println("\n\t文件生成成功:" + path + "outFile" + File.separator + fileName + "\n"); - } catch (Exception e) { - throw new CustomerException("创建模版文件失败!", e); - } - } - - - /** - *

生成Action模版代码

- * - * @param actionTemplate action模版必要参数 - */ - public static void createActionTemplate(ActionTemplate actionTemplate) { - File directory = new File(""); - String courseFile = null; - try { - courseFile = directory.getCanonicalPath(); - } catch (IOException e) { - throw new CustomerException("无法获取当前项目的路径所在位置!"); - } - String targetPath = courseFile + File.separator + - actionTemplate.getSrcDirectory().replaceAll("\\.", File.separator); - targetPath = targetPath + File.separator + actionTemplate.getPackageName().replaceAll("\\.", File.separator); - String fileName = targetPath + File.separator + actionTemplate.getActionName() + ".java"; - - Map vmParam = new HashMap<>(); - vmParam.put("author", actionTemplate.getAuthor()); - vmParam.put("actionDesc", actionTemplate.getActionDesc()); - vmParam.put("fileName", actionTemplate.getActionName()); - vmParam.put("package", actionTemplate.getPackageName()); - vmParam.put("createTime", Util.getTime("yyyy-MM-dd HH:mm:ss")); - VelocityEngine ve = new VelocityEngine(); - try { - ve.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8"); - String path = weaver.general.GCONST.getPropertyPath().replace("prop", "vm"); - ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path); - ve.init(); - } catch (Exception e) { - e.printStackTrace(); - } - // 获取模板文件 - try { - Template template = ve.getTemplate("ActionJavaFileTemplate.java.vm", "UTF-8"); - File saveFile = new File(fileName); - if (!saveFile.getParentFile().exists()) { - saveFile.getParentFile().mkdirs(); - } - if (saveFile.exists()) { - throw new CustomerException("文件:" + fileName + " is exists;"); - } - FileOutputStream outStream = new FileOutputStream(saveFile); - OutputStreamWriter writer = new OutputStreamWriter(outStream); - BufferedWriter bufferWriter = new BufferedWriter(writer); - VelocityContext ctx = new VelocityContext(vmParam); - template.merge(ctx, bufferWriter); - bufferWriter.flush(); - outStream.close(); - bufferWriter.close(); - System.out.println("\n\t文件生成成功:" + fileName + "\n"); - } catch (Exception e) { - throw new CustomerException("创建模版文件失败!", e); - } - } + try { + ve.init(); + } catch (Exception e) { + e.printStackTrace(); + } + // 获取模板文件 + try { + Template template = ve.getTemplate("ActionConfigTemplate.md.vm", "UTF-8"); + String prefix = type == 1 ? "Action" : "定时任务"; + String fileName = prefix + "部署配置文档-" + actionName + "-" + author + "-" + Util.getTime("yyyyMMddHHmmss") + ".md"; + File saveFile = new File(path + "outFile" + File.separator + fileName); + if (!saveFile.getParentFile().exists()) { + saveFile.getParentFile().mkdirs(); + } + // 创建文件输出流 + FileOutputStream outStream = new FileOutputStream(saveFile); + // 因为模板整合的时候,需要提供一个Writer,所以创建一个Writer + OutputStreamWriter writer = new OutputStreamWriter(outStream); + // 创建一个缓冲流 + BufferedWriter bufferWriter = new BufferedWriter(writer); + + VelocityContext ctx = new VelocityContext(vmParam); + // 5 合并模板和数据并输出 + template.merge(ctx, bufferWriter); + // 强制刷新 + bufferWriter.flush(); + outStream.close(); + bufferWriter.close(); + System.out.println("\n\t文件生成成功:" + path + "outFile" + File.separator + fileName + "\n"); + } catch (Exception e) { + throw new CustomerException("创建模版文件失败!", e); + } + } + + + /** + *

生成Action模版代码

+ * + * @param actionTemplate action模版必要参数 + */ + public static void createActionTemplate(ActionTemplate actionTemplate) { + File directory = new File(""); + String courseFile = null; + try { + courseFile = directory.getCanonicalPath(); + } catch (IOException e) { + throw new CustomerException("无法获取当前项目的路径所在位置!"); + } + String targetPath = courseFile + File.separator + + actionTemplate.getSrcDirectory().replaceAll("\\.", File.separator); + targetPath = targetPath + File.separator + actionTemplate.getPackageName().replaceAll("\\.", File.separator); + String fileName = targetPath + File.separator + actionTemplate.getActionName() + ".java"; + + Map vmParam = new HashMap<>(); + vmParam.put("author", actionTemplate.getAuthor()); + vmParam.put("actionDesc", actionTemplate.getActionDesc()); + vmParam.put("fileName", actionTemplate.getActionName()); + vmParam.put("package", actionTemplate.getPackageName()); + vmParam.put("createTime", Util.getTime("yyyy-MM-dd HH:mm:ss")); + VelocityEngine ve = new VelocityEngine(); + try { + ve.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8"); + String path = weaver.general.GCONST.getPropertyPath().replace("prop", "vm"); + ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path); + ve.init(); + } catch (Exception e) { + e.printStackTrace(); + } + // 获取模板文件 + try { + Template template = ve.getTemplate("ActionJavaFileTemplate.java.vm", "UTF-8"); + File saveFile = new File(fileName); + if (!saveFile.getParentFile().exists()) { + saveFile.getParentFile().mkdirs(); + } + if (saveFile.exists()) { + throw new CustomerException("文件:" + fileName + " is exists;"); + } + FileOutputStream outStream = new FileOutputStream(saveFile); + OutputStreamWriter writer = new OutputStreamWriter(outStream); + BufferedWriter bufferWriter = new BufferedWriter(writer); + VelocityContext ctx = new VelocityContext(vmParam); + template.merge(ctx, bufferWriter); + bufferWriter.flush(); + outStream.close(); + bufferWriter.close(); + System.out.println("\n\t文件生成成功:" + fileName + "\n"); + } catch (Exception e) { + throw new CustomerException("创建模版文件失败!", e); + } + } } diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index 52a3cec..4ab3b95 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -3345,63 +3345,63 @@ public class Util extends weaver.general.Util { } try { action = cronJobClass.newInstance(); - for (Field declaredField : declaredFields) { + for (Field declaredField : declaredFields) { // 必填参数验证 - boolean hasRequiredMark = declaredField.isAnnotationPresent(RequiredMark.class); - String name = declaredField.getName(); - String setMethodName = getSetMethodName(name); - String value = params.get(name); - boolean hasDefaultValue = declaredField.isAnnotationPresent(ActionDefaultTestValue.class); - RequiredMark requiredMark = declaredField.getAnnotation(RequiredMark.class); - ActionDefaultTestValue defaultTestValue = declaredField.getAnnotation(ActionDefaultTestValue.class); - boolean hasOptional = declaredField.isAnnotationPresent(ActionOptionalParam.class); + boolean hasRequiredMark = declaredField.isAnnotationPresent(RequiredMark.class); + String name = declaredField.getName(); + String setMethodName = getSetMethodName(name); + String value = params.get(name); + boolean hasDefaultValue = declaredField.isAnnotationPresent(ActionDefaultTestValue.class); + RequiredMark requiredMark = declaredField.getAnnotation(RequiredMark.class); + ActionDefaultTestValue defaultTestValue = declaredField.getAnnotation(ActionDefaultTestValue.class); + boolean hasOptional = declaredField.isAnnotationPresent(ActionOptionalParam.class); // 如果存在默认值,并且是必填参数 - if (hasDefaultValue && hasRequiredMark) { + if (hasDefaultValue && hasRequiredMark) { // 如果参数map中没有则赋值为默认值 - if (null == value) { + if (null == value) { // 获取默认值赋值 - String defaultValue = defaultTestValue.value(); - if (defaultValue == null) { - throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); - } - value = defaultValue; - } + String defaultValue = defaultTestValue.value(); + if (defaultValue == null) { + throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); + } + value = defaultValue; + } // 如果没有默认值,并且是必填参数 - } else if (!hasDefaultValue && hasRequiredMark) { + } else if (!hasDefaultValue && hasRequiredMark) { // 如果没有从param中获取到,则抛出异常 - if (Util.isNullOrEmpty(value)) { - throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); - } + if (Util.isNullOrEmpty(value)) { + throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); + } // 如果有默认值,并且没有从params中获得,则赋值 - } else if (hasDefaultValue) { - if (null == value) { - value = defaultTestValue.value(); - } - } else if (hasOptional) { + } else if (hasDefaultValue) { + if (null == value) { + value = defaultTestValue.value(); + } + } else if (hasOptional) { // 如果存在可选值 - ActionOptionalParam optionalParam = declaredField.getAnnotation(ActionOptionalParam.class); - String defaultValue = optionalParam.value(); + ActionOptionalParam optionalParam = declaredField.getAnnotation(ActionOptionalParam.class); + String defaultValue = optionalParam.value(); // 可选值没有在param中存在 - if (null == value) { - value = defaultValue; - } - } else { + if (null == value) { + value = defaultValue; + } + } else { // 都不符合必填和默认值的参数,判断params中是否存在,如果不存在则直接跳过 - if (null == value) { - continue; - } - value = params.get(name); - } - Method method = cronJobClass.getMethod(setMethodName, String.class); - method.invoke(action, value); - } - action.execute(); + if (null == value) { + continue; + } + value = params.get(name); + } + Method method = cronJobClass.getMethod(setMethodName, String.class); + method.invoke(action, value); + } + action.execute(); } catch (Exception e) { throw new CustomerException("计划任务执行异常!异常信息:\n" + Util.getErrString(e)); } - getLogger().info(Util.logStr("\n\t计划任务 [{}] getDataId success!\n", cronJobClass.getName())); + getLogger().info(Util.logStr("\n\t计划任务 [{}] execute success!\n", cronJobClass.getName())); } @@ -3424,45 +3424,46 @@ public class Util extends weaver.general.Util { } try { action = actionClass.newInstance(); - for (Field declaredField : declaredFields) { + for (Field declaredField : declaredFields) { // 必填参数验证 - boolean hasRequiredMark = declaredField.isAnnotationPresent(RequiredMark.class); - String name = declaredField.getName(); - String setMethodName = getSetMethodName(name); - String value = params.get(name); - boolean hasDefaultValue = declaredField.isAnnotationPresent(ActionDefaultTestValue.class); - RequiredMark requiredMark = declaredField.getAnnotation(RequiredMark.class); - ActionDefaultTestValue defaultTestValue = declaredField.getAnnotation(ActionDefaultTestValue.class); - if (hasDefaultValue && hasRequiredMark) { - if (value == null) { - String defaultValue = defaultTestValue.value(); - if (defaultValue == null) { - throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); - } - value = defaultValue; - } - } else if (!hasDefaultValue && hasRequiredMark) { - if (value == null) { - throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); - } - } else if (hasDefaultValue) { - value = defaultTestValue.value(); - } - if (!params.containsKey(name) && Util.isNullOrEmpty(value)) { - continue; - } - if (params.containsKey(name)) { - value = params.get(name); - } - Method method = actionClass.getMethod(setMethodName, String.class); - method.invoke(action, value); - } - RequestService requestService = new RequestService(); + boolean hasRequiredMark = declaredField.isAnnotationPresent(RequiredMark.class); + String name = declaredField.getName(); + String setMethodName = getSetMethodName(name); + String value = params.get(name); + boolean hasDefaultValue = declaredField.isAnnotationPresent(ActionDefaultTestValue.class); + RequiredMark requiredMark = declaredField.getAnnotation(RequiredMark.class); + ActionDefaultTestValue defaultTestValue = declaredField.getAnnotation(ActionDefaultTestValue.class); + if (hasDefaultValue && hasRequiredMark) { + if (value == null) { + String defaultValue = defaultTestValue.value(); + if (defaultValue == null) { + throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); + } + value = defaultValue; + } + } else if (!hasDefaultValue && hasRequiredMark) { + if (value == null) { + throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); + } + } else if (hasDefaultValue) { + value = defaultTestValue.value(); + } + if (!params.containsKey(name) && Util.isNullOrEmpty(value)) { + continue; + } + if (params.containsKey(name)) { + value = params.get(name); + } + Method method = actionClass.getMethod(setMethodName, String.class); + method.invoke(action, value); + } + RequestService requestService = new RequestService(); requestInfo = requestService.getRequest(requestId); if (null == requestInfo) { throw new CustomerException("没有查找到对应的请求requestId : " + requestId); } requestInfo.getRequestManager().setSrc(runType); + requestInfo.getRequestManager().setUser(new User(1)); execute = action.execute(requestInfo); } catch (Exception e) { throw new CustomerException("action执行异常!异常信息:\n" + Util.getErrString(e)); @@ -3470,7 +3471,7 @@ public class Util extends weaver.general.Util { if (Action.FAILURE_AND_CONTINUE.equals(execute)) { throw new CustomerException("action执行失败,失败原因:\n" + requestInfo.getRequestManager().getMessagecontent()); } - getLogger().info(Util.logStr("\n\n\tAction [{}] getDataId success!\n", actionClass.getName())); + getLogger().info(Util.logStr("\n\n\tAction [{}] execute success!\n", actionClass.getName())); } public static String getSetMethodName(String fieldName) { @@ -3638,12 +3639,52 @@ public class Util extends weaver.general.Util { return o.execute(pathParam, requestId, billTable, workflowId, user, requestInfo); } - + /** + *

通过表fromid查询表名

+ * + * @param fromId fromid + * @return 表名 + */ public static String selectBillTableByFromId(String fromId) { return mapper.selectBillTableByFromId(fromId); } + /** + *

删除表数据

+ * + * @param tableName 表 + * @param dataId 数据id + */ public static void deleteModeId(String tableName, Integer dataId) { mapper.deleteModeId(tableName, dataId); } + + /** + *

首字母大写

+ * + * @param str 字符串 + * @return 转换后字符串 + */ + public static String firstUpperCase(String str) { + if (Strings.isNullOrEmpty(str)) { + return str; + } + return str.substring(0, 1).toUpperCase() + str.substring(1); + } + + /** + *

通过fieldViewInfo对象获取map的值

+ * + * @param fieldInfo 字段信息对象 + * @param workflowData 流程值 + * @return 值 + */ + public static Object getValueByFieldViwInfo(FieldViewInfo fieldInfo, Map workflowData) { + String tableName = fieldInfo.getTableName(); + String[] dts = tableName.split("_dt"); + if (dts.length == 2) { + return Util.getValueByKeyStr("detail_" + dts[1] + "." + fieldInfo.getFieldName(), workflowData); + } + return Util.getValueByKeyStr("main." + fieldInfo.getFieldName(), workflowData); + } } diff --git a/src/main/java/aiyh/utils/action/CusBaseAction.java b/src/main/java/aiyh/utils/action/CusBaseAction.java index 91a2f07..8da80ad 100644 --- a/src/main/java/aiyh/utils/action/CusBaseAction.java +++ b/src/main/java/aiyh/utils/action/CusBaseAction.java @@ -21,317 +21,317 @@ import java.util.*; */ @Deprecated public abstract class CusBaseAction implements Action { - - /** - * 全局日志对象 - */ - protected final Logger log = Util.getLogger(); - private final Map actionHandleMethod = new HashMap<>(); - /** - * 全局requestInfo对象 - */ - protected RequestInfo globalRequestInfo; - /** - *

线程局部变量

- **/ - protected static ThreadLocal requestInfoThreadLocal = new ThreadLocal<>(); - - /** - *

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

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

程序执行异常回调

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

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

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

action 提交流程业务处理方法

- *

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

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

action 退回流程业务处理方法

- *

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

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

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

- *

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

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

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

- *

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

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

获取流程主表数据

- * - * @return 流程主表数据 - */ - @Deprecated - protected Map getMainTableValue() { - // 获取主表数据 - Property[] propertyArr = globalRequestInfo.getMainTableInfo().getProperty(); - return getStringMap(propertyArr); - } - - /** - *

获取流程主表数据

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

获取所有明细数据

- * - * @return 以明细表需要为键,以明细表数据为值的键值对明细数据信息 - */ - @Deprecated - protected Map>> getDetailTableValue() { - DetailTable[] detailTableArr = globalRequestInfo.getDetailTableInfo().getDetailTable(); - return getListMap(detailTableArr); - } - - /** - *

获取所有明细数据

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

获取指定明细表的表数据

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

获取指定明细表的表数据

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

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

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

线程局部变量

+ **/ + protected static ThreadLocal requestInfoThreadLocal = new ThreadLocal<>(); + + /** + *

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

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

程序执行异常回调

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

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

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

action 提交流程业务处理方法

+ *

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

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

action 退回流程业务处理方法

+ *

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

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

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

+ *

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

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

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

+ *

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

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

获取流程主表数据

+ * + * @return 流程主表数据 + */ + @Deprecated + protected Map getMainTableValue() { + // 获取主表数据 + Property[] propertyArr = globalRequestInfo.getMainTableInfo().getProperty(); + return getStringMap(propertyArr); + } + + /** + *

获取流程主表数据

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

获取所有明细数据

+ * + * @return 以明细表需要为键,以明细表数据为值的键值对明细数据信息 + */ + @Deprecated + protected Map>> getDetailTableValue() { + DetailTable[] detailTableArr = globalRequestInfo.getDetailTableInfo().getDetailTable(); + return getListMap(detailTableArr); + } + + /** + *

获取所有明细数据

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

获取指定明细表的表数据

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

获取指定明细表的表数据

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

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

+ * + * @param detailTable 明细表对象 + * @return 明细表数据 + */ + @NotNull + private List> getDetailValue(DetailTable detailTable) { + Row[] rowArr = detailTable.getRow(); + List> detailData = new ArrayList<>(rowArr.length); + for (Row row : rowArr) { + Cell[] cellArr = row.getCell(); + Map rowData = new HashMap<>((int) Math.ceil(cellArr.length * (1 + 0.4))); + rowData.put("id", row.getId()); + for (Cell cell : cellArr) { + String fieldName = cell.getName(); + String value = cell.getValue(); + rowData.put(fieldName, value); + } + detailData.add(rowData); + } + return detailData; + } + + + public static final class ActionRunType { + /** + * 退回 + */ + public static final String REJECT = "reject"; + /** + * 撤回 + */ + public static final String WITHDRAW = "withdraw"; + /** + * 强制收回 + */ + public static final String DRAW_BACK = "drawBack"; + /** + * 提交 + */ + public static final String SUBMIT = "submit"; + } + } diff --git a/src/main/java/aiyh/utils/action/SafeCusBaseAction.java b/src/main/java/aiyh/utils/action/SafeCusBaseAction.java index c1e81df..4812e87 100644 --- a/src/main/java/aiyh/utils/action/SafeCusBaseAction.java +++ b/src/main/java/aiyh/utils/action/SafeCusBaseAction.java @@ -13,6 +13,7 @@ import weaver.workflow.workflow.WorkflowBillComInfo; import weaver.workflow.workflow.WorkflowComInfo; import java.util.*; +import java.util.stream.Collectors; /** *

基础的action,实现一些基础的参数

@@ -228,6 +229,23 @@ public abstract class SafeCusBaseAction implements Action { return getListMap(detailTableArr); } + /** + *

获取所有明细数据

+ * + * @return 以明细表需要为键,以明细表数据为值的键值对明细数据信息 + */ + protected Map>> getDetailTableObjValue(RequestInfo requestInfo) { + DetailTable[] detailTableArr = requestInfo.getDetailTableInfo().getDetailTable(); + Map>> listMap = getListMap(detailTableArr); + Map>> result = new HashMap<>(listMap.size()); + for (Map.Entry>> entry : listMap.entrySet()) { + List> list = entry.getValue(); + List> collect = list.stream().map(item -> new HashMap(item)).collect(Collectors.toList()); + result.put(entry.getKey(), collect); + } + return result; + } + @NotNull private Map>> getListMap(DetailTable[] detailTableArr) { @@ -251,6 +269,18 @@ public abstract class SafeCusBaseAction implements Action { return getDetailValue(detailTable); } + /** + *

获取指定明细表的表数据

+ * + * @param detailNo 明细表编号 + * @return 明细数据 + */ + protected List> getDetailTableObjValueByDetailNo(int detailNo, RequestInfo requestInfo) { + DetailTable detailTable = requestInfo.getDetailTableInfo().getDetailTable(detailNo); + List> detailValue = getDetailValue(detailTable); + return detailValue.stream().map(item -> new HashMap(item)).collect(Collectors.toList()); + } + /** *

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

* diff --git a/src/main/java/aiyh/utils/annotation/MethodRuleNo.java b/src/main/java/aiyh/utils/annotation/MethodRuleNo.java new file mode 100644 index 0000000..54840f9 --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/MethodRuleNo.java @@ -0,0 +1,19 @@ +package aiyh.utils.annotation; + +import java.lang.annotation.*; + +/** + *

方法编号

+ * + *

create: 2023/2/19 23:24

+ * + * @author youHong.ai + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface MethodRuleNo { + int value(); + + String desc(); +} diff --git a/src/main/java/aiyh/utils/annotation/recordset/Association.java b/src/main/java/aiyh/utils/annotation/recordset/Association.java new file mode 100644 index 0000000..cbe017b --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/Association.java @@ -0,0 +1,25 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

association注解

+ * + *

create: 2023/2/19 13:49

+ * + * @author youHong.ai + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.ANNOTATION_TYPE) +@Documented +public @interface Association { + + String property(); + + String column(); + + String select(); + + Id id(); + +} diff --git a/src/main/java/aiyh/utils/annotation/recordset/AssociationMethod.java b/src/main/java/aiyh/utils/annotation/recordset/AssociationMethod.java new file mode 100644 index 0000000..70d6607 --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/AssociationMethod.java @@ -0,0 +1,17 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

association方法

+ * + *

create: 2023/2/20 11:55

+ * + * @author youHong.ai + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@Documented +public @interface AssociationMethod { + int value(); +} diff --git a/src/main/java/aiyh/utils/annotation/recordset/Associations.java b/src/main/java/aiyh/utils/annotation/recordset/Associations.java new file mode 100644 index 0000000..cf1120b --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/Associations.java @@ -0,0 +1,17 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

实体映射注解

+ * + *

create: 2023/2/19 21:50

+ * + * @author youHong.ai + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@Documented +public @interface Associations { + Association[] value(); +} diff --git a/src/main/java/aiyh/utils/annotation/recordset/CollectionMapping.java b/src/main/java/aiyh/utils/annotation/recordset/CollectionMapping.java new file mode 100644 index 0000000..f3ba58a --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/CollectionMapping.java @@ -0,0 +1,27 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

association注解

+ * + *

create: 2023/2/19 13:49

+ * + * @author youHong.ai + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.ANNOTATION_TYPE) +@Documented +public @interface CollectionMapping { + /** 实体字段名 */ + String property(); + + /** 数据库字段名 */ + String column(); + + /** 查询方法全限定类名 */ + String select() default ""; + + /** collection查询的id信息 */ + Id id(); +} diff --git a/src/main/java/aiyh/utils/annotation/recordset/CollectionMappings.java b/src/main/java/aiyh/utils/annotation/recordset/CollectionMappings.java new file mode 100644 index 0000000..6362bb2 --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/CollectionMappings.java @@ -0,0 +1,17 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

映射

+ * + *

create: 2023/2/19 15:39

+ * + * @author youHong.ai + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@Documented +public @interface CollectionMappings { + CollectionMapping[] value(); +} diff --git a/src/main/java/aiyh/utils/annotation/recordset/CollectionMethod.java b/src/main/java/aiyh/utils/annotation/recordset/CollectionMethod.java new file mode 100644 index 0000000..d767632 --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/CollectionMethod.java @@ -0,0 +1,17 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

association方法

+ * + *

create: 2023/2/20 11:55

+ * + * @author youHong.ai + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@Documented +public @interface CollectionMethod { + int value(); +} diff --git a/src/main/java/aiyh/utils/annotation/recordset/Id.java b/src/main/java/aiyh/utils/annotation/recordset/Id.java new file mode 100644 index 0000000..1388b6f --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/Id.java @@ -0,0 +1,21 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

association和collection对应id

+ * + *

create: 2023/2/19 14:41

+ * + * @author youHong.ai + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.ANNOTATION_TYPE) +@Documented +public @interface Id { + /** 查询方法名的唯一键的Java类型 */ + Class value(); + + /** 方法id */ + int methodId() default -1; +} diff --git a/src/main/java/aiyh/utils/entity/FieldViewInfo.java b/src/main/java/aiyh/utils/entity/FieldViewInfo.java new file mode 100644 index 0000000..e337135 --- /dev/null +++ b/src/main/java/aiyh/utils/entity/FieldViewInfo.java @@ -0,0 +1,36 @@ +package aiyh.utils.entity; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + *

+ * + *

create: 2023/2/20 11:01

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +public class FieldViewInfo { + + /** 字段id */ + private Integer id; + + /** 字段名 */ + private String fieldName; + + /** 字段表名 */ + private String tableName; + + /** 表id */ + private Integer billId; + + /** 字段类型 */ + private Integer fieldType; + + /** 字段类型名称 */ + private String fieldHtmlType; +} diff --git a/src/main/java/aiyh/utils/excention/CustomerException.java b/src/main/java/aiyh/utils/excention/CustomerException.java index e2292c9..0d939bc 100644 --- a/src/main/java/aiyh/utils/excention/CustomerException.java +++ b/src/main/java/aiyh/utils/excention/CustomerException.java @@ -16,6 +16,11 @@ public class CustomerException extends RuntimeException { private Throwable throwable; private Integer code = -1; + public CustomerException(Throwable throwable) { + super(throwable); + this.msg = throwable.getMessage(); + } + public CustomerException(String msg) { super(msg); this.msg = msg; diff --git a/src/main/java/aiyh/utils/excention/monad/Try.java b/src/main/java/aiyh/utils/excention/monad/Try.java index 6791a08..da48fb4 100644 --- a/src/main/java/aiyh/utils/excention/monad/Try.java +++ b/src/main/java/aiyh/utils/excention/monad/Try.java @@ -19,351 +19,357 @@ import java.util.function.Supplier; */ public abstract class Try { - - protected Try() { - } - - public static Try ofFailable(TrySupplier f) { - Objects.requireNonNull(f); - - try { - return Try.successful(f.get()); - } catch (Throwable t) { - return Try.failure(t); - } - } - - /** - * Transform success or pass on failure. - * Takes an optional type parameter of the new type. - * You need to be specific about the new type if changing type - * - * Try.ofFailable(() -> "1").<Integer>map((x) -> Integer.valueOf(x)) - * - * @param f function to apply to successful value. - * @param new type (optional) - * @return Success<U> or Failure<U> - */ - - public abstract Try map(TryMapFunction f); - - /** - * Transform success or pass on failure, taking a Try<U> as the result. - * Takes an optional type parameter of the new type. - * You need to be specific about the new type if changing type. - * - * Try.ofFailable(() -> "1").<Integer>flatMap((x) -> Try.ofFailable(() -> Integer.valueOf(x))) - * returns Integer(1) - * - * @param f function to apply to successful value. - * @param new type (optional) - * @return new composed Try - */ - public abstract Try flatMap(TryMapFunction> f); - - /** - * Specifies a result to use in case of failure. - * Gives access to the exception which can be pattern matched on. - * - * Try.ofFailable(() -> "not a number") - * .<Integer>flatMap((x) -> Try.ofFailable(() ->Integer.valueOf(x))) - * .recover((t) -> 1) - * returns Integer(1) - * - * @param f function to getDataId on successful result. - * @return new composed Try - */ - - public abstract T recover(Function f); - - /** - * Try applying f(t) on the case of failure. - * @param f function that takes throwable and returns result - * @return a new Try in the case of failure, or the current Success. - */ - public abstract Try recoverWith(TryMapFunction> f); - - /** - * Return a value in the case of a failure. - * This is similar to recover but does not expose the exception type. - * - * @param value return the try's value or else the value specified. - * @return new composed Try - */ - public abstract T orElse(T value); - - /** - * Return another try in the case of failure. - * Like recoverWith but without exposing the exception. - * - * @param f return the value or the value from the new try. - * @return new composed Try - */ - public abstract Try orElseTry(TrySupplier f); - - /** - * Gets the value T on Success or throws the cause of the failure. - * - * @return T - * @throws Throwable produced by the supplier function argument - */ - - public abstract T orElseThrow(Supplier exceptionSupplier) throws X; - - /** - * Gets the value T on Success or throws the cause of the failure. - * - * @return T - * @throws Throwable - */ - public abstract T get() throws Throwable; - - /** - * Gets the value T on Success or throws the cause of the failure wrapped into a RuntimeException - * @return T - * @throws RuntimeException - */ - public abstract T getUnchecked(); - - public abstract boolean isSuccess(); - - /** - * Performs the provided action, when successful - * @param action action to run - * @return new composed Try - * @throws E if the action throws an exception - */ - public abstract Try onSuccess(TryConsumer action) throws E; - - /** - * Performs the provided action, when failed - * @param action action to run - * @return new composed Try - * @throws E if the action throws an exception - */ - public abstract Try onFailure(TryConsumer action) throws E; - - /** - * If a Try is a Success and the predicate holds true, the Success is passed further. - * Otherwise (Failure or predicate doesn't hold), pass Failure. - * @param pred predicate applied to the value held by Try - * @return For Success, the same success if predicate holds true, otherwise Failure - */ - public abstract Try filter(Predicate pred); - - /** - * Try contents wrapped in Optional. - * @return Optional of T, if Success, Empty if Failure or null value - */ - public abstract Optional toOptional(); - - /** - * Factory method for failure. - * - * @param e throwable to create the failed Try with - * @param Type - * @return a new Failure - */ - - public static Try failure(Throwable e) { - return new Failure<>(e); - } - - /** - * Factory method for success. - * - * @param x value to create the successful Try with - * @param Type - * @return a new Success - */ - public static Try successful(U x) { - return new Success<>(x); - } + + protected Try() { + } + + public static Try ofFailable(TrySupplier f) { + Objects.requireNonNull(f); + + try { + return Try.successful(f.get()); + } catch (Throwable t) { + return Try.failure(t); + } + } + + /** + * Transform success or pass on failure. + * Takes an optional type parameter of the new type. + * You need to be specific about the new type if changing type + *

+ * Try.ofFailable(() -> "1").<Integer>map((x) -> Integer.valueOf(x)) + * + * @param f function to apply to successful value. + * @param new type (optional) + * @return Success<U> or Failure<U> + */ + + public abstract Try map(TryMapFunction f); + + /** + * Transform success or pass on failure, taking a Try<U> as the result. + * Takes an optional type parameter of the new type. + * You need to be specific about the new type if changing type. + *

+ * Try.ofFailable(() -> "1").<Integer>flatMap((x) -> Try.ofFailable(() -> Integer.valueOf(x))) + * returns Integer(1) + * + * @param f function to apply to successful value. + * @param new type (optional) + * @return new composed Try + */ + public abstract Try flatMap(TryMapFunction> f); + + /** + * Specifies a result to use in case of failure. + * Gives access to the exception which can be pattern matched on. + *

+ * Try.ofFailable(() -> "not a number") + * .<Integer>flatMap((x) -> Try.ofFailable(() ->Integer.valueOf(x))) + * .recover((t) -> 1) + * returns Integer(1) + * + * @param f function to execute on successful result. + * @return new composed Try + */ + + public abstract T recover(Function f); + + /** + * Try applying f(t) on the case of failure. + * + * @param f function that takes throwable and returns result + * @return a new Try in the case of failure, or the current Success. + */ + public abstract Try recoverWith(TryMapFunction> f); + + /** + * Return a value in the case of a failure. + * This is similar to recover but does not expose the exception type. + * + * @param value return the try's value or else the value specified. + * @return new composed Try + */ + public abstract T orElse(T value); + + /** + * Return another try in the case of failure. + * Like recoverWith but without exposing the exception. + * + * @param f return the value or the value from the new try. + * @return new composed Try + */ + public abstract Try orElseTry(TrySupplier f); + + /** + * Gets the value T on Success or throws the cause of the failure. + * + * @return T + * @throws Throwable produced by the supplier function argument + */ + + public abstract T orElseThrow(Supplier exceptionSupplier) throws X; + + /** + * Gets the value T on Success or throws the cause of the failure. + * + * @return T + * @throws Throwable + */ + public abstract T get() throws Throwable; + + /** + * Gets the value T on Success or throws the cause of the failure wrapped into a RuntimeException + * + * @return T + * @throws RuntimeException + */ + public abstract T getUnchecked(); + + public abstract boolean isSuccess(); + + /** + * Performs the provided action, when successful + * + * @param action action to run + * @return new composed Try + * @throws E if the action throws an exception + */ + public abstract Try onSuccess(TryConsumer action) throws E; + + /** + * Performs the provided action, when failed + * + * @param action action to run + * @return new composed Try + * @throws E if the action throws an exception + */ + public abstract Try onFailure(TryConsumer action) throws E; + + /** + * If a Try is a Success and the predicate holds true, the Success is passed further. + * Otherwise (Failure or predicate doesn't hold), pass Failure. + * + * @param pred predicate applied to the value held by Try + * @return For Success, the same success if predicate holds true, otherwise Failure + */ + public abstract Try filter(Predicate pred); + + /** + * Try contents wrapped in Optional. + * + * @return Optional of T, if Success, Empty if Failure or null value + */ + public abstract Optional toOptional(); + + /** + * Factory method for failure. + * + * @param e throwable to create the failed Try with + * @param Type + * @return a new Failure + */ + + public static Try failure(Throwable e) { + return new Failure<>(e); + } + + /** + * Factory method for success. + * + * @param x value to create the successful Try with + * @param Type + * @return a new Success + */ + public static Try successful(U x) { + return new Success<>(x); + } } class Success extends Try { - private final T value; - - public Success(T value) { - this.value = value; - } - - @Override - public Try flatMap(TryMapFunction> f) { - Objects.requireNonNull(f); - try { - return f.apply(value); - } catch (Throwable t) { - return Try.failure(t); - } - } - - @Override - public T recover(Function f) { - Objects.requireNonNull(f); - return value; - } - - @Override - public Try recoverWith(TryMapFunction> f) { - Objects.requireNonNull(f); - return this; - } - - @Override - public T orElse(T value) { - return this.value; - } - - @Override - public Try orElseTry(TrySupplier f) { - Objects.requireNonNull(f); - return this; - } - - @Override - public T orElseThrow(Supplier exceptionSupplier) throws X { - return value; - } - - @Override - public T get() throws Throwable { - return value; - } - - @Override - public T getUnchecked() { - return value; - } - - @Override - public Try map(TryMapFunction f) { - Objects.requireNonNull(f); - try { - return new Success<>(f.apply(value)); - } catch (Throwable t) { - return Try.failure(t); - } - } - - @Override - public boolean isSuccess() { - return true; - } - - @Override - public Try onSuccess(TryConsumer action) throws E { - action.accept(value); - return this; - } - - @Override - public Try filter(Predicate p) { - Objects.requireNonNull(p); - - if (p.test(value)) { - return this; - } else { - return Try.failure(new NoSuchElementException("Predicate does not match for " + value)); - } - } - - @Override - public Optional toOptional() { - return Optional.ofNullable(value); - } - - @Override - public Try onFailure(TryConsumer action) { - return this; - } + private final T value; + + public Success(T value) { + this.value = value; + } + + @Override + public Try flatMap(TryMapFunction> f) { + Objects.requireNonNull(f); + try { + return f.apply(value); + } catch (Throwable t) { + return Try.failure(t); + } + } + + @Override + public T recover(Function f) { + Objects.requireNonNull(f); + return value; + } + + @Override + public Try recoverWith(TryMapFunction> f) { + Objects.requireNonNull(f); + return this; + } + + @Override + public T orElse(T value) { + return this.value; + } + + @Override + public Try orElseTry(TrySupplier f) { + Objects.requireNonNull(f); + return this; + } + + @Override + public T orElseThrow(Supplier exceptionSupplier) throws X { + return value; + } + + @Override + public T get() throws Throwable { + return value; + } + + @Override + public T getUnchecked() { + return value; + } + + @Override + public Try map(TryMapFunction f) { + Objects.requireNonNull(f); + try { + return new Success<>(f.apply(value)); + } catch (Throwable t) { + return Try.failure(t); + } + } + + @Override + public boolean isSuccess() { + return true; + } + + @Override + public Try onSuccess(TryConsumer action) throws E { + action.accept(value); + return this; + } + + @Override + public Try filter(Predicate p) { + Objects.requireNonNull(p); + + if (p.test(value)) { + return this; + } else { + return Try.failure(new NoSuchElementException("Predicate does not match for " + value)); + } + } + + @Override + public Optional toOptional() { + return Optional.ofNullable(value); + } + + @Override + public Try onFailure(TryConsumer action) { + return this; + } } class Failure extends Try { - private final Throwable e; - - Failure(Throwable e) { - this.e = e; - } - - @Override - public Try map(TryMapFunction f) { - Objects.requireNonNull(f); - return Try.failure(e); - } - - @Override - public Try flatMap(TryMapFunction> f) { - Objects.requireNonNull(f); - return Try.failure(e); - } - - @Override - public T recover(Function f) { - Objects.requireNonNull(f); - return f.apply(e); - } - - @Override - public Try recoverWith(TryMapFunction> f) { - Objects.requireNonNull(f); - try{ - return f.apply(e); - }catch(Throwable t){ - return Try.failure(t); - } - } - - @Override - public T orElse(T value) { - return value; - } - - @Override - public Try orElseTry(TrySupplier f) { - Objects.requireNonNull(f); - return Try.ofFailable(f); - } - - @Override - public T orElseThrow(Supplier exceptionSupplier) throws X { - throw exceptionSupplier.get(); - } - - @Override - public T get() throws Throwable { - throw e; - } - - @Override - public T getUnchecked() { - throw new RuntimeException(e); - } - - @Override - public boolean isSuccess() { - return false; - } - - @Override - public Try onSuccess(TryConsumer action) { - return this; - } - - @Override - public Try filter(Predicate pred) { - return this; - } - - @Override - public Optional toOptional() { - return Optional.empty(); - } - - @Override - public Try onFailure(TryConsumer action) throws E { - action.accept(e); - return this; - } + private final Throwable e; + + Failure(Throwable e) { + this.e = e; + } + + @Override + public Try map(TryMapFunction f) { + Objects.requireNonNull(f); + return Try.failure(e); + } + + @Override + public Try flatMap(TryMapFunction> f) { + Objects.requireNonNull(f); + return Try.failure(e); + } + + @Override + public T recover(Function f) { + Objects.requireNonNull(f); + return f.apply(e); + } + + @Override + public Try recoverWith(TryMapFunction> f) { + Objects.requireNonNull(f); + try { + return f.apply(e); + } catch (Throwable t) { + return Try.failure(t); + } + } + + @Override + public T orElse(T value) { + return value; + } + + @Override + public Try orElseTry(TrySupplier f) { + Objects.requireNonNull(f); + return Try.ofFailable(f); + } + + @Override + public T orElseThrow(Supplier exceptionSupplier) throws X { + throw exceptionSupplier.get(); + } + + @Override + public T get() throws Throwable { + throw e; + } + + @Override + public T getUnchecked() { + throw new RuntimeException(e); + } + + @Override + public boolean isSuccess() { + return false; + } + + @Override + public Try onSuccess(TryConsumer action) { + return this; + } + + @Override + public Try filter(Predicate pred) { + return this; + } + + @Override + public Optional toOptional() { + return Optional.empty(); + } + + @Override + public Try onFailure(TryConsumer action) throws E { + action.accept(e); + return this; + } } \ No newline at end of file diff --git a/src/main/java/aiyh/utils/httpUtil/HttpManager.java b/src/main/java/aiyh/utils/httpUtil/HttpManager.java index d01fffc..41a7222 100644 --- a/src/main/java/aiyh/utils/httpUtil/HttpManager.java +++ b/src/main/java/aiyh/utils/httpUtil/HttpManager.java @@ -75,10 +75,11 @@ public class HttpManager { return true; }).build(); HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; - sslsf = new SSLConnectionSocketFactory(sslContext, - new String[]{"TLSv1"}, - null, - hostnameVerifier); + sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); + // sslsf = new SSLConnectionSocketFactory(sslContext, + // new String[]{"TLSv1"}, + // null, + // hostnameVerifier); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new RuntimeException(e); } diff --git a/src/main/java/aiyh/utils/mapper/UtilMapper.java b/src/main/java/aiyh/utils/mapper/UtilMapper.java index e9f3960..07170c3 100644 --- a/src/main/java/aiyh/utils/mapper/UtilMapper.java +++ b/src/main/java/aiyh/utils/mapper/UtilMapper.java @@ -2,6 +2,7 @@ package aiyh.utils.mapper; import aiyh.utils.annotation.recordset.*; import aiyh.utils.entity.DocImageInfo; +import aiyh.utils.entity.FieldViewInfo; import aiyh.utils.entity.SelectValueEntity; import aiyh.utils.entity.WorkflowNodeConfig; @@ -17,139 +18,158 @@ import java.util.Map; @SqlMapper public interface UtilMapper { - - /** - * 查询日志级别是否开启Debug模式 - * - * @return 是否开启Debug模式 - */ - @Select("select param_value from $t{configTableName} where only_mark = 'enableDebugLog'") - public Boolean selectLogLevel(@ParamMapper("configTableName") String configTableName); - - - /** - * 根据唯一标识查询参数值 - * - * @param onlyMark 唯一标识 - * @return 参数值 - */ - @Select("select param_value from $t{configTableName} where only_mark = #{onlyMark} and enable_param = 1") - public String selectCusConfigParam(@ParamMapper("onlyMark") String onlyMark, - @ParamMapper("configTableName") String cusConfigTableName); - - - /** - * 查询文件名 - * - * @param imageFileId 查询文件名 - * @return 文件名 - */ - @Select("select imagefilename from imagefile where imagefileid = #{imageFileId}") - String selectFileNameByImageFileId(@ParamMapper("imageFileId") int imageFileId); - - /** - * 查询流程主表 - * - * @param workflowId 流程id - * @return 流程表名 - */ - @Select("select bill.tablename from workflow_bill bill join workflow_base base on base.formid = bill.id where base.id = #{workflowId}") - String selectWorkfowMainTable(@ParamMapper("workflowId") String workflowId); - - - @Select("select id,docid doc_id,imagefileid image_file_id,imagefilename image_file_name from docimagefile where docid = #{docId}") - DocImageInfo selectDocImageInfo(@ParamMapper("docId") String docId); - - @Select("select id,docid doc_id,imagefileid image_file_id,imagefilename image_file_name from docimagefile where docid in ($t{docIds})") - List selectDocImageInfos(@ParamMapper("docIds") String docIds); - - @Select("select id,docid doc_id,imagefileid image_file_id,imagefilename image_file_name from docimagefile where docid in (${docIds})") - List selectDocImageInfos(@ParamMapper("docIds") String[] docIds); - - - @Select("select id,workflow_type,mark_only,workflow_nodes,enable_nodes from uf_node_config where enable_nodes = 1 and workflow_type in ($t{allVersion}) and mark_only = #{markOnly}") - WorkflowNodeConfig selectNodeConfig(@ParamMapper("allVersion") String allVersion, @ParamMapper("markOnly") String markOnly); - - /** - * 查询下拉框值 - * - * @param tableName 表明 - * @param fileName 字段名 - * @return 下拉框 - */ - @Select("select wbf.id,wbf.fieldname,wbf.fieldlabel,wb.tablename, ws.selectname,ws.selectvalue " + - "from workflow_billfield wbf left join workflow_bill wb on wbf.billid = wb.id " + - "left join workflow_selectitem ws on ws.fieldid = wbf.id where wb.tablename = #{tableName} and fieldname = #{fileName}") - List selectSelectFieldValue(@ParamMapper("tableName") String tableName, @ParamMapper("fileName") String fileName); - - @Select("select ws.selectname " + - "from workflow_billfield wbf left join workflow_bill wb on wbf.billid = wb.id " + - "left join workflow_selectitem ws on ws.fieldid = wbf.id where wb.tablename = #{tableName} and fieldname = #{fileName} and selectvalue = #{value}") - String selectSelectFieldValueByValue(@ParamMapper("tableName") String tableName, @ParamMapper("fileName") String fileName, - @ParamMapper("value") String value); - - /** - * 查询文件信息 - * - * @param imageFileId 查询文件名 - * @return 文件名 - */ - @Select("select * from imagefile where imagefileid = #{imageFileId}") - Map selectFileInfoByImageFileId(@ParamMapper("imageFileId") int imageFileId); - - /** - * 删除文件信息 - * - * @param imageFileId 文件ID - * @return 是否删除成功 - */ - @Delete("delete from imagefile where imagefileid = #{imageFileId}") - boolean deleteImageFileInfo(@ParamMapper("imageFileId") Integer imageFileId); - - /** - *

插入自定义配置数据

- * - * @param onlyMark 唯一标识 - * @param value 参数值 - * @param desc 描述 - * @return 是否插入成功 - */ - @Update("update $t{configTableName} set only_mark = #{onlyMark},param_value = #{paramValue}, \n" + - "param_desc = #{paramDesc} where id = #{id}") - boolean updateConfigValueById(@ParamMapper("onlyMark") String onlyMark, - @ParamMapper("paramValue") String value, - @ParamMapper("paramDesc") String desc, - @ParamMapper("id") String id, - @ParamMapper("configTableName") String configTableName); - - /** - *

修改自定义配置数据

- * - * @param onlyMark 唯一标识 - * @param value 值 - * @param desc 描述 - * @return 是否更新成功 - */ - @Update("update $t{configTableName} set param_value = #{paramValue}, \n" + - "param_desc = #{paramDesc} where only_mark = #{onlyMark}") - boolean updateConfigValueByOnlyMark(@ParamMapper("onlyMark") String onlyMark, - @ParamMapper("paramValue") String value, - @ParamMapper("paramDesc") String desc, - @ParamMapper("configTableName") String configTableName); - - /** - *

selectBillTableByFromId 根据fromId查询billTable表明

- * 2023/2/6 13:40 - * ************************************************************ - * - * @param fromId fromId - * @return String 表名 - * @author youHong.ai - * ****************************************** - */ - @Select("select * from workflow_bill where id = #{fromId}") - String selectBillTableByFromId(@ParamMapper("fromId") String fromId); - - @Delete("delete from $t{tableName} where id = #{dataId}") - void deleteModeId(@ParamMapper("tableName") String tableName, @ParamMapper("dataId") Integer dataId); + + /** + * 查询日志级别是否开启Debug模式 + * + * @return 是否开启Debug模式 + */ + @Select("select param_value from $t{configTableName} where only_mark = 'enableDebugLog'") + Boolean selectLogLevel(@ParamMapper("configTableName") String configTableName); + + + /** + * 根据唯一标识查询参数值 + * + * @param onlyMark 唯一标识 + * @return 参数值 + */ + @Select("select param_value from $t{configTableName} where only_mark = #{onlyMark} and enable_param = 1") + String selectCusConfigParam(@ParamMapper("onlyMark") String onlyMark, + @ParamMapper("configTableName") String cusConfigTableName); + + + /** + * 查询文件名 + * + * @param imageFileId 查询文件名 + * @return 文件名 + */ + @Select("select imagefilename from imagefile where imagefileid = #{imageFileId}") + String selectFileNameByImageFileId(@ParamMapper("imageFileId") int imageFileId); + + /** + * 查询流程主表 + * + * @param workflowId 流程id + * @return 流程表名 + */ + @Select("select bill.tablename from workflow_bill bill join workflow_base base on base.formid = bill.id where base.id = #{workflowId}") + String selectWorkfowMainTable(@ParamMapper("workflowId") String workflowId); + + + @Select("select id,docid doc_id,imagefileid image_file_id,imagefilename image_file_name from docimagefile where docid = #{docId}") + DocImageInfo selectDocImageInfo(@ParamMapper("docId") String docId); + + @Select("select id,docid doc_id,imagefileid image_file_id,imagefilename image_file_name from docimagefile where docid in ($t{docIds})") + List selectDocImageInfos(@ParamMapper("docIds") String docIds); + + @Select("select id,docid doc_id,imagefileid image_file_id,imagefilename image_file_name from docimagefile where docid in (${docIds})") + List selectDocImageInfos(@ParamMapper("docIds") String[] docIds); + + + @Select("select id,workflow_type,mark_only,workflow_nodes,enable_nodes from uf_node_config where enable_nodes = 1 and workflow_type in ($t{allVersion}) and mark_only = #{markOnly}") + WorkflowNodeConfig selectNodeConfig(@ParamMapper("allVersion") String allVersion, @ParamMapper("markOnly") String markOnly); + + /** + * 查询下拉框值 + * + * @param tableName 表明 + * @param fileName 字段名 + * @return 下拉框 + */ + @Select("select wbf.id,wbf.fieldname,wbf.fieldlabel,wb.tablename, ws.selectname,ws.selectvalue " + + "from workflow_billfield wbf left join workflow_bill wb on wbf.billid = wb.id " + + "left join workflow_selectitem ws on ws.fieldid = wbf.id where wb.tablename = #{tableName} and fieldname = #{fileName}") + List selectSelectFieldValue(@ParamMapper("tableName") String tableName, @ParamMapper("fileName") String fileName); + + @Select("select ws.selectname " + + "from workflow_billfield wbf left join workflow_bill wb on wbf.billid = wb.id " + + "left join workflow_selectitem ws on ws.fieldid = wbf.id where wb.tablename = #{tableName} and fieldname = #{fileName} and selectvalue = #{value}") + String selectSelectFieldValueByValue(@ParamMapper("tableName") String tableName, @ParamMapper("fileName") String fileName, + @ParamMapper("value") String value); + + /** + * 查询文件信息 + * + * @param imageFileId 查询文件名 + * @return 文件名 + */ + @Select("select * from imagefile where imagefileid = #{imageFileId}") + Map selectFileInfoByImageFileId(@ParamMapper("imageFileId") int imageFileId); + + /** + * 删除文件信息 + * + * @param imageFileId 文件ID + * @return 是否删除成功 + */ + @Delete("delete from imagefile where imagefileid = #{imageFileId}") + boolean deleteImageFileInfo(@ParamMapper("imageFileId") Integer imageFileId); + + /** + *

插入自定义配置数据

+ * + * @param onlyMark 唯一标识 + * @param value 参数值 + * @param desc 描述 + * @return 是否插入成功 + */ + @Update("update $t{configTableName} set only_mark = #{onlyMark},param_value = #{paramValue}, \n" + + "param_desc = #{paramDesc} where id = #{id}") + boolean updateConfigValueById(@ParamMapper("onlyMark") String onlyMark, + @ParamMapper("paramValue") String value, + @ParamMapper("paramDesc") String desc, + @ParamMapper("id") String id, + @ParamMapper("configTableName") String configTableName); + + /** + *

修改自定义配置数据

+ * + * @param onlyMark 唯一标识 + * @param value 值 + * @param desc 描述 + * @return 是否更新成功 + */ + @Update("update $t{configTableName} set param_value = #{paramValue}, \n" + + "param_desc = #{paramDesc} where only_mark = #{onlyMark}") + boolean updateConfigValueByOnlyMark(@ParamMapper("onlyMark") String onlyMark, + @ParamMapper("paramValue") String value, + @ParamMapper("paramDesc") String desc, + @ParamMapper("configTableName") String configTableName); + + /** + *

selectBillTableByFromId 根据fromId查询billTable表明

+ * 2023/2/6 13:40 + * ************************************************************ + * + * @param fromId fromId + * @return String 表名 + * @author youHong.ai + * ****************************************** + */ + @Select("select * from workflow_bill where id = #{fromId}") + String selectBillTableByFromId(@ParamMapper("fromId") String fromId); + + /** + *

删除指定表数据

+ * + * @param tableName 表名 + * @param dataId 数据id + */ + @Delete("delete from $t{tableName} where id = #{dataId}") + void deleteModeId(@ParamMapper("tableName") String tableName, @ParamMapper("dataId") Integer dataId); + + + /** + *

根据字段id查询字段信息

+ * + * @param id 字段id + * @return 字段信息 + */ + @Select("select id,fieldname field_name,tablename table_name,\n" + + " billid bill_id,fieldtype field_type,\n" + + " fieldhtmltype field_html_type\n" + + "from workflow_field_table_view where id = #{id}") + FieldViewInfo selectFieldInfo(Integer id); } diff --git a/src/main/java/aiyh/utils/recordset/RecordsetUtil.java b/src/main/java/aiyh/utils/recordset/RecordsetUtil.java index 29145e3..55220f9 100644 --- a/src/main/java/aiyh/utils/recordset/RecordsetUtil.java +++ b/src/main/java/aiyh/utils/recordset/RecordsetUtil.java @@ -21,463 +21,478 @@ import java.util.List; public class RecordsetUtil implements InvocationHandler { - - - public static final String SQL_LOG = "sql_log"; - private final RsThreadLocalManager rsManager = new RsThreadLocalManager(); - - private boolean autoCommit = true; - - public T getMapper(Class tClass) { - return getMapper(tClass, true); - } - - public T getMapper(Class tClass, boolean autoCommit) { - if (tClass == null) { - throw new BindingException("class is null!"); - } - if (tClass.getAnnotation(SqlMapper.class) == null) { - throw new BindingException("can not find SqlMapper annotation!"); - } - this.autoCommit = autoCommit; - return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, this); - } - - - @Override - public Object invoke(Object proxy, Method method, Object[] args) { - if (autoCommit) { - return invokeRs(proxy, method, args); - } - return invokeRsTrans(proxy, method, args); - } - - - private Object invokeRs(Object proxy, Method method, Object[] args) { - RecordSet rs = rsManager.getRs(method.getDeclaringClass().getName()); - if (rs == null) { - rsManager.setRecordSet(method.getDeclaringClass().getName()); - rs = rsManager.getRs(method.getDeclaringClass().getName()); - } - SqlHandler sqlHandler = new SqlHandler(); - ResultMapper resultMapper = new ResultMapper(); - Select select = method.getAnnotation(Select.class); - if (select != null) { - // 查询 - String sql = select.value(); - boolean custom = select.custom(); - PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - if (!handler.getSqlStr().trim().toLowerCase().startsWith("select ")) { - throw new CustomerException("The sql statement does not match, the @Select annotation can only getDataId the select statement, please check whether the sql statement matches!"); - } - Util.getLogger(SQL_LOG).info("解析sql===>" + handler); - if (handler.getArgs().isEmpty()) { - rs.executeQuery(handler.getSqlStr()); - } else { - rs.executeQuery(handler.getSqlStr(), handler.getArgs()); - } - return resultMapper.mapperResult(rs, method, method.getReturnType()); - } - Update update = method.getAnnotation(Update.class); - if (update != null) { - // 查询 - String sql = update.value(); - boolean custom = update.custom(); - PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - if (!handler.getSqlStr().trim().toLowerCase().startsWith("update ")) { - throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!"); - } - Util.getLogger(SQL_LOG).info(handler.toString()); - Class returnType = method.getReturnType(); - boolean b; - if (handler.getArgs().isEmpty()) { - b = rs.executeUpdate(handler.getSqlStr()); - } else { - b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); - } - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(int.class) || returnType.equals(Integer.class)) { - if (b) { - return 1; - } else { - return 0; - } - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return b; - } - } - Insert insert = method.getAnnotation(Insert.class); - if (insert != null) { - // 查询 - String sql = insert.value(); - boolean custom = insert.custom(); - PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - if (!handler.getSqlStr().trim().toLowerCase().startsWith("insert ")) { - throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!"); - } - Util.getLogger(SQL_LOG).info(handler.toString()); - Class returnType = method.getReturnType(); - boolean b; - if (handler.getArgs().isEmpty()) { - b = rs.executeUpdate(handler.getSqlStr()); - } else { - b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); - } - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return b; - } - } - Delete delete = method.getAnnotation(Delete.class); - if (delete != null) { - // 查询 - String sql = delete.value(); - boolean custom = delete.custom(); - PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - if (!handler.getSqlStr().trim().toLowerCase().startsWith("delete ")) { - throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!"); - } - Util.getLogger(SQL_LOG).info(handler.toString()); - Class returnType = method.getReturnType(); - boolean b; - if (handler.getArgs().isEmpty()) { - b = rs.executeUpdate(handler.getSqlStr()); - } else { - b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); - } - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return b; - } - } - boolean hasBatchInsert = method.isAnnotationPresent(BatchInsert.class); - if (hasBatchInsert) { - BatchInsert batchInsert = method.getAnnotation(BatchInsert.class); - String sql = batchInsert.value(); - Class returnType = method.getReturnType(); - boolean custom = batchInsert.custom(); - BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); - Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); - if (batchSqlResult.getBatchList().isEmpty()) { - throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); - } - if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("insert ")) { - throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!"); - } - boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return b; - } - - } - boolean hasBatchUpdate = method.isAnnotationPresent(BatchUpdate.class); - if (hasBatchUpdate) { - BatchUpdate batchUpdate = method.getAnnotation(BatchUpdate.class); - String sql = batchUpdate.value(); - Class returnType = method.getReturnType(); - boolean custom = batchUpdate.custom(); - BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); - Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); - if (batchSqlResult.getBatchList().isEmpty()) { - throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); - } - if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("update ")) { - throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!"); - } - boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return b; - } - - } - boolean hasBatchDelete = method.isAnnotationPresent(BatchDelete.class); - if (hasBatchDelete) { - BatchDelete batchDelete = method.getAnnotation(BatchDelete.class); - String sql = batchDelete.value(); - Class returnType = method.getReturnType(); - boolean custom = batchDelete.custom(); - BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); - Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); - if (batchSqlResult.getBatchList().isEmpty()) { - throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); - } - if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("delete ")) { - throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!"); - } - boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return b; - } - - } - throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete、@BatchUpdate、@BatchInsert、@BatchDelete"); - } - - private Object invokeRsTrans(Object proxy, Method method, Object[] args) { - RecordSetTrans rs = rsManager.getTrans(method.getDeclaringClass().getName()); - if (rs == null) { - rsManager.setRecordSetTrans(method.getDeclaringClass().getName()); - rs = rsManager.getTrans(method.getDeclaringClass().getName()); - } - SqlHandler sqlHandler = new SqlHandler(); - ResultMapper resultMapper = new ResultMapper(); - Select select = method.getAnnotation(Select.class); - if (select != null) { - // 查询 - String sql = select.value(); - boolean custom = select.custom(); - PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - if (!handler.getSqlStr().trim().toLowerCase().startsWith("select ")) { - throw new CustomerException("The sql statement does not match, the @Select annotation can only getDataId the select statement, please check whether the sql statement matches!"); - } - Util.getLogger(SQL_LOG).info("解析sql===>" + handler); - try { - if (handler.getArgs().isEmpty()) { - rs.executeQuery(handler.getSqlStr()); - } else { - rs.executeQuery(handler.getSqlStr(), handler.getArgs()); - } - } catch (Exception e) { - Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); - throw new CustomerException("execute sql error!" + e.getMessage()); - } - return resultMapper.mapperResult(rs, method, method.getReturnType()); - } - - Update update = method.getAnnotation(Update.class); - if (update != null) { - // 查询 - String sql = update.value(); - boolean custom = update.custom(); - PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - if (!handler.getSqlStr().trim().toLowerCase().startsWith("update ")) { - throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!"); - } - Util.getLogger(SQL_LOG).info(handler.toString()); - Class returnType = method.getReturnType(); - boolean b; - try { - if (handler.getArgs().isEmpty()) { - b = rs.executeUpdate(handler.getSqlStr()); - } else { - b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); - } - } catch (Exception e) { - Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); - throw new CustomerException("execute sql error!" + e.getMessage()); - } - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(int.class) || returnType.equals(Integer.class)) { - if (b) { - return 1; - } else { - return 0; - } - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return b; - } - } - Insert insert = method.getAnnotation(Insert.class); - if (insert != null) { - // 查询 - String sql = insert.value(); - boolean custom = insert.custom(); - PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - if (!handler.getSqlStr().trim().toLowerCase().startsWith("insert ")) { - throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!"); - } - Util.getLogger(SQL_LOG).info(handler.toString()); - Class returnType = method.getReturnType(); - boolean b; - try { - if (handler.getArgs().isEmpty()) { - b = rs.executeUpdate(handler.getSqlStr()); - } else { - b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); - } - } catch (Exception e) { - Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); - throw new CustomerException("execute sql error!" + e.getMessage()); - } - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return b; - } - } - Delete delete = method.getAnnotation(Delete.class); - if (delete != null) { - // 查询 - String sql = delete.value(); - boolean custom = delete.custom(); - PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - if (!handler.getSqlStr().trim().toLowerCase().startsWith("delete ")) { - throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!"); - } - Util.getLogger(SQL_LOG).info(handler.toString()); - Class returnType = method.getReturnType(); - boolean b; - try { - if (handler.getArgs().isEmpty()) { - b = rs.executeUpdate(handler.getSqlStr()); - } else { - b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); - } - } catch (Exception e) { - Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); - throw new CustomerException("execute sql error!" + e.getMessage()); - } - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return b; - } - } - boolean hasBatchInsert = method.isAnnotationPresent(BatchInsert.class); - if (hasBatchInsert) { - BatchInsert batchInsert = method.getAnnotation(BatchInsert.class); - String sql = batchInsert.value(); - Class returnType = method.getReturnType(); - boolean custom = batchInsert.custom(); - BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); - Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); - List batchList = batchSqlResult.getBatchList(); - if (batchList.isEmpty()) { - throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); - } - List> batchListTrans = new ArrayList<>(); - for (List list : batchList) { - List listItem = new ArrayList<>(); - for (Object o : list) { - listItem.add(o); - } - batchListTrans.add(listItem); - } - - if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("insert ")) { - throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!"); - } - boolean b = true; - try { - rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans); - } catch (Exception e) { - Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); - throw new CustomerException("execute sql error!" + e.getMessage()); - } - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return b; - } - - } - boolean hasBatchUpdate = method.isAnnotationPresent(BatchUpdate.class); - if (hasBatchUpdate) { - BatchUpdate batchUpdate = method.getAnnotation(BatchUpdate.class); - String sql = batchUpdate.value(); - Class returnType = method.getReturnType(); - boolean custom = batchUpdate.custom(); - BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); - Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); - if (batchSqlResult.getBatchList().isEmpty()) { - throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); - } - if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("update ")) { - throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!"); - } - - List batchList = batchSqlResult.getBatchList(); - if (batchList.isEmpty()) { - throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); - } - List> batchListTrans = new ArrayList<>(); - for (List list : batchList) { - List listItem = new ArrayList<>(); - for (Object o : list) { - listItem.add(o); - } - batchListTrans.add(listItem); - } - try { - rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans); - } catch (Exception e) { - Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); - throw new CustomerException("execute sql error!" + e.getMessage()); - } - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return true; - } - - } - boolean hasBatchDelete = method.isAnnotationPresent(BatchDelete.class); - if (hasBatchDelete) { - BatchDelete batchDelete = method.getAnnotation(BatchDelete.class); - String sql = batchDelete.value(); - Class returnType = method.getReturnType(); - boolean custom = batchDelete.custom(); - BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); - Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); - if (batchSqlResult.getBatchList().isEmpty()) { - throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); - } - if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("delete ")) { - throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!"); - } - List batchList = batchSqlResult.getBatchList(); - if (batchList.isEmpty()) { - throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); - } - List> batchListTrans = new ArrayList<>(); - for (List list : batchList) { - List listItem = new ArrayList<>(); - for (Object o : list) { - listItem.add(o); - } - batchListTrans.add(listItem); - } - try { - rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans); - } catch (Exception e) { - Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); - throw new CustomerException("execute sql error!" + e.getMessage()); - } - if (returnType.equals(void.class)) { - return null; - } - if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { - return true; - } - - } - throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete、@BatchUpdate、@BatchInsert、@BatchDelete"); - } - - public RsThreadLocalManager getRsManager() { - return rsManager; - } + + + public static final String SQL_LOG = "sql_log"; + private final RsThreadLocalManager rsManager = new RsThreadLocalManager(); + + private boolean autoCommit = true; + + public T getMapper(Class tClass) { + return getMapper(tClass, true); + } + + public T getMapper(Class tClass, boolean autoCommit) { + if (tClass == null) { + throw new BindingException("class is null!"); + } + if (tClass.getAnnotation(SqlMapper.class) == null) { + throw new BindingException("can not find SqlMapper annotation!"); + } + this.autoCommit = autoCommit; + return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, this); + } + + + @Override + public Object invoke(Object proxy, Method method, Object[] args) { + if (autoCommit) { + return invokeRs(proxy, method, args, ""); + } + return invokeRsTrans(proxy, method, args, ""); + } + + public Object invoke(Object proxy, Method method, Object[] args, String name) { + if (autoCommit) { + return invokeRs(proxy, method, args, name); + } + return invokeRsTrans(proxy, method, args, name); + } + + + private Object invokeRs(Object proxy, Method method, Object[] args, String name) { + String mapperKey = method.getDeclaringClass().getName(); + if (!"".equals(name) && null != name) { + mapperKey += "." + name; + } + RecordSet rs = rsManager.getRs(mapperKey); + if (rs == null) { + rsManager.setRecordSet(mapperKey); + rs = rsManager.getRs(mapperKey); + } + SqlHandler sqlHandler = new SqlHandler(); + ResultMapper resultMapper = new ResultMapper(); + Select select = method.getAnnotation(Select.class); + if (select != null) { + // 查询 + String sql = select.value(); + boolean custom = select.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("select ")) { + throw new CustomerException("The sql statement does not match, the @Select annotation can only execute the select statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info("解析sql===>" + handler); + if (handler.getArgs().isEmpty()) { + rs.executeQuery(handler.getSqlStr()); + } else { + rs.executeQuery(handler.getSqlStr(), handler.getArgs()); + } + return resultMapper.mapperResult(rs, method, method.getReturnType(), this); + } + Update update = method.getAnnotation(Update.class); + if (update != null) { + // 查询 + String sql = update.value(); + boolean custom = update.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("update ")) { + throw new CustomerException("The sql statement does not match, the @Update annotation can only execute the update statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info(handler.toString()); + Class returnType = method.getReturnType(); + boolean b; + if (handler.getArgs().isEmpty()) { + b = rs.executeUpdate(handler.getSqlStr()); + } else { + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(int.class) || returnType.equals(Integer.class)) { + if (b) { + return 1; + } else { + return 0; + } + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + } + Insert insert = method.getAnnotation(Insert.class); + if (insert != null) { + // 查询 + String sql = insert.value(); + boolean custom = insert.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("insert ")) { + throw new CustomerException("The sql statement does not match, the @Insert annotation can only execute the insert statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info(handler.toString()); + Class returnType = method.getReturnType(); + boolean b; + if (handler.getArgs().isEmpty()) { + b = rs.executeUpdate(handler.getSqlStr()); + } else { + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + } + Delete delete = method.getAnnotation(Delete.class); + if (delete != null) { + // 查询 + String sql = delete.value(); + boolean custom = delete.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("delete ")) { + throw new CustomerException("The sql statement does not match, the @Delete annotation can only execute the delete statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info(handler.toString()); + Class returnType = method.getReturnType(); + boolean b; + if (handler.getArgs().isEmpty()) { + b = rs.executeUpdate(handler.getSqlStr()); + } else { + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + } + boolean hasBatchInsert = method.isAnnotationPresent(BatchInsert.class); + if (hasBatchInsert) { + BatchInsert batchInsert = method.getAnnotation(BatchInsert.class); + String sql = batchInsert.value(); + Class returnType = method.getReturnType(); + boolean custom = batchInsert.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); + if (batchSqlResult.getBatchList().isEmpty()) { + throw new CustomerException("execute batch sql error , batch sql args is empty!"); + } + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("insert ")) { + throw new CustomerException("The sql statement does not match, the @Insert annotation can only execute the insert statement, please check whether the sql statement matches!"); + } + boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + + } + boolean hasBatchUpdate = method.isAnnotationPresent(BatchUpdate.class); + if (hasBatchUpdate) { + BatchUpdate batchUpdate = method.getAnnotation(BatchUpdate.class); + String sql = batchUpdate.value(); + Class returnType = method.getReturnType(); + boolean custom = batchUpdate.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); + if (batchSqlResult.getBatchList().isEmpty()) { + throw new CustomerException("execute batch sql error , batch sql args is empty!"); + } + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("update ")) { + throw new CustomerException("The sql statement does not match, the @Update annotation can only execute the update statement, please check whether the sql statement matches!"); + } + boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + + } + boolean hasBatchDelete = method.isAnnotationPresent(BatchDelete.class); + if (hasBatchDelete) { + BatchDelete batchDelete = method.getAnnotation(BatchDelete.class); + String sql = batchDelete.value(); + Class returnType = method.getReturnType(); + boolean custom = batchDelete.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); + if (batchSqlResult.getBatchList().isEmpty()) { + throw new CustomerException("execute batch sql error , batch sql args is empty!"); + } + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("delete ")) { + throw new CustomerException("The sql statement does not match, the @Delete annotation can only execute the delete statement, please check whether the sql statement matches!"); + } + boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + + } + throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete、@BatchUpdate、@BatchInsert、@BatchDelete"); + } + + private Object invokeRsTrans(Object proxy, Method method, Object[] args, String name) { + String mapperKey = method.getDeclaringClass().getName(); + if (!"".equals(name) && null != name) { + mapperKey += "." + name; + } + RecordSetTrans rs = rsManager.getTrans(mapperKey); + if (rs == null) { + rsManager.setRecordSetTrans(mapperKey); + rs = rsManager.getTrans(mapperKey); + } + SqlHandler sqlHandler = new SqlHandler(); + ResultMapper resultMapper = new ResultMapper(); + Select select = method.getAnnotation(Select.class); + if (select != null) { + // 查询 + String sql = select.value(); + boolean custom = select.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("select ")) { + throw new CustomerException("The sql statement does not match, the @Select annotation can only execute the select statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info("解析sql===>" + handler); + try { + if (handler.getArgs().isEmpty()) { + rs.executeQuery(handler.getSqlStr()); + } else { + rs.executeQuery(handler.getSqlStr(), handler.getArgs()); + } + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + return resultMapper.mapperResult(rs, method, method.getReturnType(), this); + } + + Update update = method.getAnnotation(Update.class); + if (update != null) { + // 查询 + String sql = update.value(); + boolean custom = update.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("update ")) { + throw new CustomerException("The sql statement does not match, the @Update annotation can only execute the update statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info(handler.toString()); + Class returnType = method.getReturnType(); + boolean b; + try { + if (handler.getArgs().isEmpty()) { + b = rs.executeUpdate(handler.getSqlStr()); + } else { + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); + } + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(int.class) || returnType.equals(Integer.class)) { + if (b) { + return 1; + } else { + return 0; + } + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + } + Insert insert = method.getAnnotation(Insert.class); + if (insert != null) { + // 查询 + String sql = insert.value(); + boolean custom = insert.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("insert ")) { + throw new CustomerException("The sql statement does not match, the @Insert annotation can only execute the insert statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info(handler.toString()); + Class returnType = method.getReturnType(); + boolean b; + try { + if (handler.getArgs().isEmpty()) { + b = rs.executeUpdate(handler.getSqlStr()); + } else { + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); + } + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + } + Delete delete = method.getAnnotation(Delete.class); + if (delete != null) { + // 查询 + String sql = delete.value(); + boolean custom = delete.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("delete ")) { + throw new CustomerException("The sql statement does not match, the @Delete annotation can only execute the delete statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info(handler.toString()); + Class returnType = method.getReturnType(); + boolean b; + try { + if (handler.getArgs().isEmpty()) { + b = rs.executeUpdate(handler.getSqlStr()); + } else { + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); + } + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + } + boolean hasBatchInsert = method.isAnnotationPresent(BatchInsert.class); + if (hasBatchInsert) { + BatchInsert batchInsert = method.getAnnotation(BatchInsert.class); + String sql = batchInsert.value(); + Class returnType = method.getReturnType(); + boolean custom = batchInsert.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); + List batchList = batchSqlResult.getBatchList(); + if (batchList.isEmpty()) { + throw new CustomerException("execute batch sql error , batch sql args is empty!"); + } + List> batchListTrans = new ArrayList<>(); + for (List list : batchList) { + List listItem = new ArrayList<>(); + for (Object o : list) { + listItem.add(o); + } + batchListTrans.add(listItem); + } + + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("insert ")) { + throw new CustomerException("The sql statement does not match, the @Insert annotation can only execute the insert statement, please check whether the sql statement matches!"); + } + boolean b = true; + try { + rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans); + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + + } + boolean hasBatchUpdate = method.isAnnotationPresent(BatchUpdate.class); + if (hasBatchUpdate) { + BatchUpdate batchUpdate = method.getAnnotation(BatchUpdate.class); + String sql = batchUpdate.value(); + Class returnType = method.getReturnType(); + boolean custom = batchUpdate.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); + if (batchSqlResult.getBatchList().isEmpty()) { + throw new CustomerException("execute batch sql error , batch sql args is empty!"); + } + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("update ")) { + throw new CustomerException("The sql statement does not match, the @Update annotation can only execute the update statement, please check whether the sql statement matches!"); + } + + List batchList = batchSqlResult.getBatchList(); + if (batchList.isEmpty()) { + throw new CustomerException("execute batch sql error , batch sql args is empty!"); + } + List> batchListTrans = new ArrayList<>(); + for (List list : batchList) { + List listItem = new ArrayList<>(); + for (Object o : list) { + listItem.add(o); + } + batchListTrans.add(listItem); + } + try { + rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans); + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return true; + } + + } + boolean hasBatchDelete = method.isAnnotationPresent(BatchDelete.class); + if (hasBatchDelete) { + BatchDelete batchDelete = method.getAnnotation(BatchDelete.class); + String sql = batchDelete.value(); + Class returnType = method.getReturnType(); + boolean custom = batchDelete.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); + if (batchSqlResult.getBatchList().isEmpty()) { + throw new CustomerException("execute batch sql error , batch sql args is empty!"); + } + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("delete ")) { + throw new CustomerException("The sql statement does not match, the @Delete annotation can only execute the delete statement, please check whether the sql statement matches!"); + } + List batchList = batchSqlResult.getBatchList(); + if (batchList.isEmpty()) { + throw new CustomerException("execute batch sql error , batch sql args is empty!"); + } + List> batchListTrans = new ArrayList<>(); + for (List list : batchList) { + List listItem = new ArrayList<>(); + for (Object o : list) { + listItem.add(o); + } + batchListTrans.add(listItem); + } + try { + rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans); + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return true; + } + + } + throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete、@BatchUpdate、@BatchInsert、@BatchDelete"); + } + + public RsThreadLocalManager getRsManager() { + return rsManager; + } } diff --git a/src/main/java/aiyh/utils/recordset/ResultMapper.java b/src/main/java/aiyh/utils/recordset/ResultMapper.java index 9621a4e..80467bf 100644 --- a/src/main/java/aiyh/utils/recordset/ResultMapper.java +++ b/src/main/java/aiyh/utils/recordset/ResultMapper.java @@ -1,7 +1,7 @@ package aiyh.utils.recordset; import aiyh.utils.Util; -import aiyh.utils.annotation.recordset.CaseConversion; +import aiyh.utils.annotation.recordset.*; import aiyh.utils.excention.CustomerException; import aiyh.utils.excention.TypeNonsupportException; import com.google.common.base.Strings; @@ -13,486 +13,661 @@ import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.*; import java.util.*; +import java.util.function.Function; /** * @author EBU7-dev1-ayh create 2021/12/21 0021 11:03 */ +@SuppressWarnings("all") public class ResultMapper { - - private static Map, TypeHandler> typeHandler = new HashMap<>(); - - static { - IntegerTypeHandler integerTypeHandler = new IntegerTypeHandler(); - typeHandler.put(String.class, new StringTypeHandler()); - typeHandler.put(Integer.class, integerTypeHandler); - typeHandler.put(int.class, integerTypeHandler); - typeHandler.put(byte.class, integerTypeHandler); - typeHandler.put(short.class, integerTypeHandler); - typeHandler.put(long.class, integerTypeHandler); - typeHandler.put(Long.class, integerTypeHandler); - typeHandler.put(Boolean.class, new BooleanTypeHandler()); - typeHandler.put(boolean.class, new BooleanTypeHandler()); - typeHandler.put(Date.class, new DataTypeHandler()); - typeHandler.put(Float.class, new FloatTypeHandler()); - typeHandler.put(float.class, new FloatTypeHandler()); - } - - public T mapperResult(RecordSet rs, Method method, Class tClass) { - if (tClass.equals(void.class)) { - return null; - } - if (tClass.equals(RecordSet.class) || tClass.equals(RecordSetTrans.class)) { - return (T) rs; - } - try { - if (tClass.equals(List.class)) { - tClass = (Class) ArrayList.class; - } - if (tClass.equals(Map.class)) { - tClass = (Class) HashMap.class; - } - if (ResultMapper.typeHandler.containsKey(tClass)) { - rs.next(); - return (T) ResultMapper.typeHandler.get(tClass).getValue(rs, 1, null); - } - T t = tClass.newInstance(); - if (t instanceof Collection) { - // 集合求出泛型 - //获取返回值的类型 - Type genericReturnType = method.getGenericReturnType(); - Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; - Class rawType = this.getRawType(actualTypeArgument); - if (rawType.equals(Map.class)) { - rawType = HashMap.class; - } - while (rs.next()) { - Object o = null; - try { - Constructor constructor = rawType.getConstructor(); - o = constructor.newInstance(); - } catch (NoSuchMethodException | InvocationTargetException ignored) { - if (Number.class.isAssignableFrom(rawType)) { - Constructor constructor; - try { - constructor = rawType.getConstructor(String.class); - o = constructor.newInstance("-1"); - } catch (NoSuchMethodException | InvocationTargetException e) { - throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); - } - } - } - if (o == null) { - throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); - } - Object object = getObject(rs, o, method); - ((Collection) t).add(object); - } - return t; - } - if (t instanceof Map) { - // map - Type genericReturnType = method.getGenericReturnType(); - Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; - Class rawType = this.getRawType(actualTypeArgument); - if (rawType.equals(List.class)) { - rawType = (Class) ArrayList.class; - } - if (rawType.equals(Map.class)) { - rawType = HashMap.class; - } - // Object o = rawType.newInstance(); - Object o = null; - try { - Constructor constructor = rawType.getConstructor(); - o = constructor.newInstance(); - } catch (NoSuchMethodException | InvocationTargetException ignored) { - if (Number.class.isAssignableFrom(rawType)) { - Constructor constructor; - try { - constructor = rawType.getConstructor(String.class); - o = constructor.newInstance("-1"); - } catch (NoSuchMethodException | InvocationTargetException e) { - throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); - } - } - } - if (o == null) { - throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); - } - if (o instanceof Map || o instanceof Collection) { - throw new TypeNonsupportException("An unsupported return type!"); - } - if (rs.next()) { - return (T) getObject(rs, t, method); - } - return null; - } - if (t.getClass().isArray()) { - throw new TypeNonsupportException("An unsupported return type!"); - } - if (rs.next()) { - return (T) getObject(rs, t, method); - } - return null; - } catch (InstantiationException | IllegalAccessException e) { - e.printStackTrace(); - } - return null; - } - - public T mapperResult(RecordSetTrans rs, Method method, Class tClass) { - if (tClass.equals(void.class)) { - return null; - } - if (tClass.equals(RecordSet.class) || tClass.equals(RecordSetTrans.class)) { - return (T) rs; - } - try { - if (tClass.equals(List.class)) { - tClass = (Class) ArrayList.class; - } - if (tClass.equals(Map.class)) { - tClass = (Class) HashMap.class; - } - if (ResultMapper.typeHandler.containsKey(tClass)) { - rs.next(); - return (T) ResultMapper.typeHandler.get(tClass).getValue(rs, 1, null); - } - T t = tClass.newInstance(); - if (t instanceof Collection) { - // 集合求出泛型 - //获取返回值的类型 - Type genericReturnType = method.getGenericReturnType(); - Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; - Class rawType = this.getRawType(actualTypeArgument); - if (rawType.equals(Map.class)) { - rawType = HashMap.class; - } - while (rs.next()) { - Object o = null; - try { - Constructor constructor = rawType.getConstructor(); - o = constructor.newInstance(); - } catch (NoSuchMethodException | InvocationTargetException ignored) { - if (Number.class.isAssignableFrom(rawType)) { - Constructor constructor; - try { - constructor = rawType.getConstructor(String.class); - o = constructor.newInstance("-1"); - } catch (NoSuchMethodException | InvocationTargetException e) { - throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); - } - } - } - if (o == null) { - throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); - } - Object object = getObjectTrans(rs, o, method); - ((Collection) t).add(object); - } - return t; - } - if (t instanceof Map) { - // map - Type genericReturnType = method.getGenericReturnType(); - Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; - Class rawType = this.getRawType(actualTypeArgument); - if (rawType.equals(List.class)) { - rawType = (Class) ArrayList.class; - } - if (rawType.equals(Map.class)) { - rawType = HashMap.class; - } - // Object o = rawType.newInstance(); - Object o = null; - try { - Constructor constructor = rawType.getConstructor(); - o = constructor.newInstance(); - } catch (NoSuchMethodException | InvocationTargetException ignored) { - if (Number.class.isAssignableFrom(rawType)) { - Constructor constructor; - try { - constructor = rawType.getConstructor(String.class); - o = constructor.newInstance("-1"); - } catch (NoSuchMethodException | InvocationTargetException e) { - throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); - } - } - } - if (o == null) { - throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); - } - if (o instanceof Map || o instanceof Collection) { - throw new TypeNonsupportException("An unsupported return type!"); - } - if (rs.next()) { - return (T) getObjectTrans(rs, t, method); - } - return null; - } - if (t.getClass().isArray()) { - throw new TypeNonsupportException("An unsupported return type!"); - } - if (rs.next()) { - return (T) getObjectTrans(rs, t, method); - } - return null; - } catch (InstantiationException | IllegalAccessException e) { - e.printStackTrace(); - } - return null; - } - - public Object getObjectTrans(RecordSetTrans rs, Object o, Method method) { - CaseConversion annotation = method.getAnnotation(CaseConversion.class); - boolean enable = annotation == null ? true : annotation.value(); - String[] columnName = rs.getColumnName(); - String[] columnTypeName = rs.getColumnTypeName(); - int[] columnTypes = rs.getColumnType(); - if (columnTypeName == null) { - columnTypeName = new String[columnTypes.length]; - for (int i = 0; i < columnTypes.length; i++) { - int type = columnTypes[i]; - switch (type) { - case -1: - columnTypeName[i] = "TEXT"; - break; - case 4: - columnTypeName[i] = "INT"; - break; - case 12: - columnTypeName[i] = "VARCHAR"; - break; - default: - columnTypeName[i] = "VARCHAR"; - } - } - } - - try { - if (o instanceof Map) { - for (int i = 0; i < columnName.length; i++) { - String columnType = columnTypeName[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 (enable) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getInt(i + 1)); - continue; - } - ((Map) o).put(columnName[i], rs.getInt(i + 1)); - continue; - } - if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { - if (enable) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1)); - continue; - } - ((Map) o).put(columnName[i], rs.getFloat(i + 1)); - continue; - } - if (enable) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1)); - continue; - } - ((Map) o).put(columnName[i], rs.getString(i + 1)); - continue; - } - return o; - } - if (o instanceof Collection) { - throw new TypeNonsupportException("An unsupported return type!"); - } - if (o instanceof Number) { - for (int i = 0; i < columnName.length; i++) { - String columnType = columnTypeName[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)) { - return rs.getInt(i + 1); - } - if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { - return rs.getFloat(i + 1); - } - } - return o; - } - if (o instanceof String) { - for (int i = 0; i < columnName.length; i++) { - return rs.getString(i + 1); - } - return o; - } - if (o instanceof Boolean) { - for (int i = 0; i < columnName.length; i++) { - return rs.getBoolean(i + 1); - } - return o; - } - - // Util.getLogger().info("获取对象:" + o.toString()); - BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class); - PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); - for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { - Class propertyType = propertyDescriptor.getPropertyType(); - Object value = null; - String fieldName = propertyDescriptor.getName(); - - if (Strings.isNullOrEmpty(fieldName)) { - fieldName = propertyDescriptor.getDisplayName(); - } - // Util.getLogger().info("获取类字段:" + fieldName); - // Util.getLogger().info("获取类字段1:" + propertyDescriptor.getDisplayName()); - // Util.getLogger().info("获取的数据库数据:" + rs.getString(fieldName)); - Field declaredField = o.getClass().getDeclaredField(fieldName); - if (enable) { - value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, Util.toUnderlineCase(fieldName), declaredField); - } else { - value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, fieldName, declaredField); - } - propertyDescriptor.getWriteMethod().invoke(o, value); - } - - } catch (Exception e) { - e.printStackTrace(); - Util.getLogger().error("报错了,写入数据到实体类报错!\n" + Util.getErrString(e)); - } - return o; - } - - public Object getObject(RecordSet rs, Object o, Method method) { - CaseConversion annotation = method.getAnnotation(CaseConversion.class); - boolean enable = annotation == null ? true : annotation.value(); - String[] columnName = rs.getColumnName(); - String[] columnTypeName = rs.getColumnTypeName(); - int[] columnTypes = rs.getColumnType(); - if (columnTypeName == null) { - columnTypeName = new String[columnTypes.length]; - for (int i = 0; i < columnTypes.length; i++) { - int type = columnTypes[i]; - switch (type) { - case -1: - columnTypeName[i] = "TEXT"; - break; - case 4: - columnTypeName[i] = "INT"; - break; - case 12: - columnTypeName[i] = "VARCHAR"; - break; - default: - columnTypeName[i] = "VARCHAR"; - } - } - } - - try { - if (o instanceof Map) { - for (int i = 0; i < columnName.length; i++) { - String columnType = ""; - if(i >= columnTypeName.length){ - columnType = "varchar"; - }else { - columnType = columnTypeName[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 (enable) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getInt(i + 1)); - continue; - } - ((Map) o).put(columnName[i], rs.getInt(i + 1)); - continue; - } - if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { - if (enable) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1)); - continue; - } - ((Map) o).put(columnName[i], rs.getFloat(i + 1)); - continue; - } - if (enable) { - ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1)); - continue; - } - ((Map) o).put(columnName[i], rs.getString(i + 1)); - continue; - } - return o; - } - if (o instanceof Collection) { - throw new TypeNonsupportException("An unsupported return type!"); - } - if (o instanceof Number) { - for (int i = 0; i < columnName.length; i++) { - String columnType = columnTypeName[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)) { - return rs.getInt(i + 1); - } - if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { - return rs.getFloat(i + 1); - } - } - return o; - } - if (o instanceof String) { - for (int i = 0; i < columnName.length; i++) { - return rs.getString(i + 1); - } - return o; - } - if (o instanceof Boolean) { - for (int i = 0; i < columnName.length; i++) { - return rs.getBoolean(i + 1); - } - return o; - } - - // Util.getLogger().info("获取对象:" + o.toString()); - BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class); - PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); - for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { - Class propertyType = propertyDescriptor.getPropertyType(); - Object value = null; - String fieldName = propertyDescriptor.getName(); - - if (Strings.isNullOrEmpty(fieldName)) { - fieldName = propertyDescriptor.getDisplayName(); - } - // Util.getLogger().info("获取类字段:" + fieldName); - // Util.getLogger().info("获取类字段1:" + propertyDescriptor.getDisplayName()); - // Util.getLogger().info("获取的数据库数据:" + rs.getString(fieldName)); - Field declaredField = o.getClass().getDeclaredField(fieldName); - if (enable) { - value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, Util.toUnderlineCase(fieldName), declaredField); - } else { - value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, fieldName, declaredField); - } - propertyDescriptor.getWriteMethod().invoke(o, value); - } - - } catch (Exception e) { - e.printStackTrace(); - Util.getLogger().error("报错了,写入数据到实体类报错!\n" + Util.getErrString(e)); - } - return o; - } - - public Class getRawType(Type type) { - if (type instanceof Class) { - return (Class) type; - } else if (type instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) type; - Type rawType = parameterizedType.getRawType(); - return (Class) rawType; - } else if (type instanceof GenericArrayType) { - Type componentType = ((GenericArrayType) type).getGenericComponentType(); - return Array.newInstance(getRawType(componentType), 0).getClass(); - } else if (type instanceof TypeVariable) { - return Object.class; - } else if (type instanceof WildcardType) { - return getRawType(((WildcardType) type).getUpperBounds()[0]); - } else { - String className = type == null ? "null" : type.getClass().getName(); - throw new IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <" + type + "> is of type " + className); - } - } + + private static final Map, TypeHandler> typeHandler = new HashMap<>(); + private static final Map, Function> paramType = new HashMap<>(); + + private RecordsetUtil recordsetUtil = null; + + static { + IntegerTypeHandler integerTypeHandler = new IntegerTypeHandler(); + typeHandler.put(String.class, new StringTypeHandler()); + typeHandler.put(Integer.class, integerTypeHandler); + typeHandler.put(int.class, integerTypeHandler); + typeHandler.put(byte.class, integerTypeHandler); + typeHandler.put(short.class, integerTypeHandler); + typeHandler.put(long.class, integerTypeHandler); + typeHandler.put(Long.class, integerTypeHandler); + typeHandler.put(Boolean.class, new BooleanTypeHandler()); + typeHandler.put(boolean.class, new BooleanTypeHandler()); + typeHandler.put(Date.class, new DataTypeHandler()); + typeHandler.put(Float.class, new FloatTypeHandler()); + typeHandler.put(float.class, new FloatTypeHandler()); + } + + static { + paramType.put(String.class, value -> value); + paramType.put(Integer.class, Integer::parseInt); + paramType.put(int.class, Integer::parseInt); + paramType.put(byte.class, Byte::parseByte); + paramType.put(short.class, Short::parseShort); + paramType.put(long.class, Long::parseLong); + paramType.put(Boolean.class, Boolean::parseBoolean); + paramType.put(boolean.class, Boolean::parseBoolean); + paramType.put(Float.class, Float::parseFloat); + paramType.put(float.class, Float::parseFloat); + } + + public T mapperResult(RecordSet rs, Method method, Class tClass, RecordsetUtil recordsetUtil) { + this.recordsetUtil = recordsetUtil; + if (tClass.equals(void.class)) { + return null; + } + if (tClass.equals(RecordSet.class) || tClass.equals(RecordSetTrans.class)) { + return (T) rs; + } + try { + if (tClass.equals(List.class)) { + tClass = (Class) ArrayList.class; + } + if (tClass.equals(Map.class)) { + tClass = (Class) HashMap.class; + } + if (ResultMapper.typeHandler.containsKey(tClass)) { + rs.next(); + return (T) ResultMapper.typeHandler.get(tClass).getValue(rs, 1, null); + } + T t = tClass.newInstance(); + if (t instanceof Collection) { + // 集合求出泛型 + // 获取返回值的类型 + Type genericReturnType = method.getGenericReturnType(); + Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; + Class rawType = this.getRawType(actualTypeArgument); + if (rawType.equals(Map.class)) { + rawType = HashMap.class; + } + while (rs.next()) { + Object o = null; + try { + Constructor constructor = rawType.getConstructor(); + o = constructor.newInstance(); + } catch (NoSuchMethodException | InvocationTargetException ignored) { + if (Number.class.isAssignableFrom(rawType)) { + Constructor constructor; + try { + constructor = rawType.getConstructor(String.class); + o = constructor.newInstance("-1"); + } catch (NoSuchMethodException | InvocationTargetException e) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); + } + } + } + if (o == null) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); + } + Object object = getObject(rs, o, method); + + ((Collection) t).add(object); + } + return t; + } + if (t instanceof Map) { + // map + Type genericReturnType = method.getGenericReturnType(); + Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; + Class rawType = this.getRawType(actualTypeArgument); + if (rawType.equals(List.class)) { + rawType = ArrayList.class; + } + if (rawType.equals(Map.class)) { + rawType = HashMap.class; + } + // Object o = rawType.newInstance(); + Object o = null; + try { + Constructor constructor = rawType.getConstructor(); + o = constructor.newInstance(); + } catch (NoSuchMethodException | InvocationTargetException ignored) { + if (Number.class.isAssignableFrom(rawType)) { + Constructor constructor; + try { + constructor = rawType.getConstructor(String.class); + o = constructor.newInstance("-1"); + } catch (NoSuchMethodException | InvocationTargetException e) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); + } + } + } + if (o == null) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); + } + if (o instanceof Map || o instanceof Collection) { + throw new TypeNonsupportException("An unsupported return type!"); + } + if (rs.next()) { + return (T) getObject(rs, t, method); + } + return null; + } + if (t.getClass().isArray()) { + throw new TypeNonsupportException("An unsupported return type!"); + } + if (rs.next()) { + return (T) getObject(rs, t, method); + } + return null; + } catch (InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + public T mapperResult(RecordSetTrans rs, Method method, Class tClass, RecordsetUtil recordsetUtil) { + this.recordsetUtil = recordsetUtil; + if (tClass.equals(void.class)) { + return null; + } + if (tClass.equals(RecordSet.class) || tClass.equals(RecordSetTrans.class)) { + return (T) rs; + } + try { + if (tClass.equals(List.class)) { + tClass = (Class) ArrayList.class; + } + if (tClass.equals(Map.class)) { + tClass = (Class) HashMap.class; + } + if (ResultMapper.typeHandler.containsKey(tClass)) { + rs.next(); + return (T) ResultMapper.typeHandler.get(tClass).getValue(rs, 1, null); + } + T t = tClass.newInstance(); + if (t instanceof Collection) { + // 集合求出泛型 + // 获取返回值的类型 + Type genericReturnType = method.getGenericReturnType(); + Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; + Class rawType = this.getRawType(actualTypeArgument); + if (rawType.equals(Map.class)) { + rawType = HashMap.class; + } + while (rs.next()) { + Object o = null; + try { + Constructor constructor = rawType.getConstructor(); + o = constructor.newInstance(); + } catch (NoSuchMethodException | InvocationTargetException ignored) { + if (Number.class.isAssignableFrom(rawType)) { + Constructor constructor; + try { + constructor = rawType.getConstructor(String.class); + o = constructor.newInstance("-1"); + } catch (NoSuchMethodException | InvocationTargetException e) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); + } + } + } + if (o == null) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); + } + Object object = getObjectTrans(rs, o, method); + ((Collection) t).add(object); + } + return t; + } + if (t instanceof Map) { + // map + Type genericReturnType = method.getGenericReturnType(); + Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; + Class rawType = this.getRawType(actualTypeArgument); + if (rawType.equals(List.class)) { + rawType = ArrayList.class; + } + if (rawType.equals(Map.class)) { + rawType = HashMap.class; + } + // Object o = rawType.newInstance(); + Object o = null; + try { + Constructor constructor = rawType.getConstructor(); + o = constructor.newInstance(); + } catch (NoSuchMethodException | InvocationTargetException ignored) { + if (Number.class.isAssignableFrom(rawType)) { + Constructor constructor; + try { + constructor = rawType.getConstructor(String.class); + o = constructor.newInstance("-1"); + } catch (NoSuchMethodException | InvocationTargetException e) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); + } + } + } + if (o == null) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); + } + if (o instanceof Map || o instanceof Collection) { + throw new TypeNonsupportException("An unsupported return type!"); + } + if (rs.next()) { + return (T) getObjectTrans(rs, t, method); + } + return null; + } + if (t.getClass().isArray()) { + throw new TypeNonsupportException("An unsupported return type!"); + } + if (rs.next()) { + return (T) getObjectTrans(rs, t, method); + } + return null; + } catch (InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + public Object getObjectTrans(RecordSetTrans rs, Object o, Method method) { + CaseConversion annotation = method.getAnnotation(CaseConversion.class); + boolean enable = annotation == null || annotation.value(); + String[] columnName = rs.getColumnName(); + String[] columnTypeName = rs.getColumnTypeName(); + int[] columnTypes = rs.getColumnType(); + if (columnTypeName == null) { + columnTypeName = new String[columnTypes.length]; + for (int i = 0; i < columnTypes.length; i++) { + int type = columnTypes[i]; + switch (type) { + case -1: + columnTypeName[i] = "TEXT"; + break; + case 4: + columnTypeName[i] = "INT"; + break; + case 12: + columnTypeName[i] = "VARCHAR"; + break; + default: + columnTypeName[i] = "VARCHAR"; + } + } + } + + try { + if (o instanceof Map) { + for (int i = 0; i < columnName.length; i++) { + String columnType = columnTypeName[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 (enable) { + ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getInt(i + 1)); + continue; + } + ((Map) o).put(columnName[i].toLowerCase(), rs.getInt(i + 1)); + continue; + } + if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { + if (enable) { + ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1)); + continue; + } + ((Map) o).put(columnName[i].toLowerCase(), rs.getFloat(i + 1)); + continue; + } + if (enable) { + ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1)); + continue; + } + ((Map) o).put(columnName[i].toLowerCase(), rs.getString(i + 1)); + continue; + } + return o; + } + if (o instanceof Collection) { + throw new TypeNonsupportException("An unsupported return type!"); + } + if (o instanceof Number) { + for (int i = 0; i < columnName.length; i++) { + String columnType = columnTypeName[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)) { + return rs.getInt(i + 1); + } + if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { + return rs.getFloat(i + 1); + } + } + return o; + } + if (o instanceof String) { + for (int i = 0; i < columnName.length; i++) { + return rs.getString(i + 1); + } + return o; + } + if (o instanceof Boolean) { + for (int i = 0; i < columnName.length; i++) { + return rs.getBoolean(i + 1); + } + return o; + } + + // Util.getLogger().info("获取对象:" + o.toString()); + BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class); + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + Class propertyType = propertyDescriptor.getPropertyType(); + Object value = null; + String fieldName = propertyDescriptor.getName(); + + if (Strings.isNullOrEmpty(fieldName)) { + fieldName = propertyDescriptor.getDisplayName(); + } + Field declaredField = o.getClass().getDeclaredField(fieldName); + if (enable) { + value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, Util.toUnderlineCase(fieldName), declaredField); + } else { + value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, fieldName, declaredField); + } + propertyDescriptor.getWriteMethod().invoke(o, value); + } + + } catch (Exception e) { + Util.getLogger().error("报错了,写入数据到实体类报错!\n" + Util.getErrString(e)); + throw new CustomerException(e); + } + return o; + } + + public Object getObject(RecordSet rs, Object o, Method method) { + CaseConversion annotation = method.getAnnotation(CaseConversion.class); + boolean enable = annotation == null || annotation.value(); + String[] columnName = rs.getColumnName(); + String[] columnTypeName = rs.getColumnTypeName(); + int[] columnTypes = rs.getColumnType(); + if (columnTypeName == null) { + columnTypeName = new String[columnTypes.length]; + for (int i = 0; i < columnTypes.length; i++) { + int type = columnTypes[i]; + switch (type) { + case -1: + columnTypeName[i] = "TEXT"; + break; + case 4: + columnTypeName[i] = "INT"; + break; + case 12: + columnTypeName[i] = "VARCHAR"; + break; + default: + columnTypeName[i] = "VARCHAR"; + } + } + } + + try { + if (o instanceof Map) { + for (int i = 0; i < columnName.length; i++) { + String columnType = ""; + if (i >= columnTypeName.length) { + columnType = "varchar"; + } else { + columnType = columnTypeName[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 (enable) { + ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getInt(i + 1)); + continue; + } + ((Map) o).put(columnName[i].toLowerCase(), rs.getInt(i + 1)); + continue; + } + if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { + if (enable) { + ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1)); + continue; + } + ((Map) o).put(columnName[i].toLowerCase(), rs.getFloat(i + 1)); + continue; + } + if (method.isAnnotationPresent(Associations.class)) { + Association association = searchAssociation(method, columnName[i], true); + if (association != null) { + if (association.column().equalsIgnoreCase(columnName[i])) { + Object cassociationValue = association(rs, association, method); + ((Map) o).put(association.property(), cassociationValue); + continue; + } + } + } + + if (method.isAnnotationPresent(CollectionMappings.class)) { + CollectionMapping collectionMapping = searchCollection(method, columnName[i], true); + if (collectionMapping != null) { + if (collectionMapping.column().equals(columnName[i])) { + Object collection = collection(rs, collectionMapping, method); + String property = collectionMapping.property(); + ((Map) o).put(property, collection); + continue; + } + } + } + if (enable) { + ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1)); + continue; + } + ((Map) o).put(columnName[i].toLowerCase(), rs.getString(i + 1)); + } + return o; + } + if (o instanceof Collection) { + throw new TypeNonsupportException("An unsupported return type!"); + } + if (o instanceof Number) { + for (int i = 0; i < columnName.length; i++) { + String columnType = columnTypeName[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)) { + return rs.getInt(i + 1); + } + if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { + return rs.getFloat(i + 1); + } + } + return o; + } + if (o instanceof String) { + for (int i = 0; i < columnName.length; i++) { + return rs.getString(i + 1); + } + return o; + } + if (o instanceof Boolean) { + for (int i = 0; i < columnName.length; i++) { + return rs.getBoolean(i + 1); + } + return o; + } + + // Util.getLogger().info("获取对象:" + o.toString()); + BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class); + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); + + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + Class propertyType = propertyDescriptor.getPropertyType(); + Object value = null; + String fieldName = propertyDescriptor.getName(); + + if (Strings.isNullOrEmpty(fieldName)) { + fieldName = propertyDescriptor.getDisplayName(); + } + if (method.isAnnotationPresent(Associations.class)) { + Association association = searchAssociation(method, fieldName, false); + if (association != null) { + if (association.property().equals(fieldName)) { + Object cassociationValue = association(rs, association, method); + propertyDescriptor.getWriteMethod().invoke(o, cassociationValue); + continue; + } + } + } + if (method.isAnnotationPresent(CollectionMappings.class)) { + CollectionMapping collectionMapping = searchCollection(method, fieldName, false); + if (collectionMapping != null) { + if (fieldName.equals(collectionMapping.property()) && !"".equals(collectionMapping.property())) { + Object collection = collection(rs, collectionMapping, method); + propertyDescriptor.getWriteMethod().invoke(o, collection); + continue; + } + } + } + Field declaredField = o.getClass().getDeclaredField(fieldName); + if (enable) { + value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, Util.toUnderlineCase(fieldName), declaredField); + } else { + value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, fieldName, declaredField); + } + propertyDescriptor.getWriteMethod().invoke(o, value); + } + + + } catch (Exception e) { + Util.getLogger().error("报错了,写入数据到实体类报错!\n" + Util.getErrString(e)); + throw new CustomerException(e.getMessage(), e); + } + return o; + } + + public Class getRawType(Type type) { + if (type instanceof Class) { + return (Class) type; + } else if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) type; + Type rawType = parameterizedType.getRawType(); + return (Class) rawType; + } else if (type instanceof GenericArrayType) { + Type componentType = ((GenericArrayType) type).getGenericComponentType(); + return Array.newInstance(getRawType(componentType), 0).getClass(); + } else if (type instanceof TypeVariable) { + return Object.class; + } else if (type instanceof WildcardType) { + return getRawType(((WildcardType) type).getUpperBounds()[0]); + } else { + String className = type == null ? "null" : type.getClass().getName(); + throw new IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <" + type + "> is of type " + className); + } + } + + + private Association searchAssociation(Method method, String filedName, boolean isMap) { + + Associations annotation = method.getAnnotation(Associations.class); + Association[] mappings = annotation.value(); + Association mapping = null; + for (Association item : mappings) { + String property = isMap ? item.column() : item.property(); + if (isMap ? filedName.equalsIgnoreCase(property) : filedName.equals(property)) { + mapping = item; + } + } + return mapping; + } + + private Object association(RecordSet rs, Association annotation, Method method) { + Id id = annotation.id(); + String column = annotation.column(); + String columnValue = rs.getString(column); + if (Objects.isNull(columnValue) || "".equals(columnValue)) { + return null; + } + if (id.methodId() != -1) { + Class declaringClass = method.getDeclaringClass(); + Method[] declaredMethods = declaringClass.getDeclaredMethods(); + for (Method declaredMethod : declaredMethods) { + if (declaredMethod.isAnnotationPresent(AssociationMethod.class)) { + AssociationMethod collectionMethod = declaredMethod.getAnnotation(AssociationMethod.class); + int value = collectionMethod.value(); + if (id.methodId() == value) { + return recordsetUtil.invoke(null, declaredMethod, + new Object[]{paramType.get(id.value()).apply(columnValue)}, declaredMethod.getName()); + } + } + } + } + String selectMethod = annotation.select(); + int i = selectMethod.lastIndexOf("."); + String selectClass = selectMethod.substring(0, i); + Class aClass = null; + try { + aClass = Class.forName(selectClass); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + Method associationMethod = null; + try { + associationMethod = aClass.getMethod(selectMethod.substring(i + 1), id.value()); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + Class returnType = associationMethod.getReturnType(); + if (List.class.isAssignableFrom(returnType)) { + throw new CustomerException("can not set result, association annotation not support result of list! Do you want to use @CollectionSql!"); + } + return recordsetUtil.invoke(null, associationMethod, + new Object[]{paramType.get(id.value()).apply(columnValue)}, selectMethod); + } + + + private CollectionMapping searchCollection(Method method, String filedName, boolean isMap) { + CollectionMappings annotation = method.getAnnotation(CollectionMappings.class); + CollectionMapping[] mappings = annotation.value(); + CollectionMapping mapping = null; + for (CollectionMapping item : mappings) { + String property = isMap ? item.column() : item.property(); + if (isMap ? filedName.equalsIgnoreCase(property) : filedName.equals(property)) { + mapping = item; + } + } + return mapping; + } + + private Object collection(RecordSet rs, CollectionMapping annotation, Method method) { + Id id = annotation.id(); + String column = annotation.column(); + String columnValue = rs.getString(column); + if (Objects.isNull(columnValue) || "".equals(columnValue)) { + return null; + } + if (id.methodId() != -1) { + Class declaringClass = method.getDeclaringClass(); + Method[] declaredMethods = declaringClass.getDeclaredMethods(); + for (Method declaredMethod : declaredMethods) { + if (declaredMethod.isAnnotationPresent(CollectionMethod.class)) { + CollectionMethod collectionMethod = declaredMethod.getAnnotation(CollectionMethod.class); + int value = collectionMethod.value(); + if (id.methodId() == value) { + return recordsetUtil.invoke(null, declaredMethod, + new Object[]{paramType.get(id.value()).apply(columnValue)}, declaredMethod.getName()); + } + } + } + } + String selectMethod = annotation.select(); + int i = selectMethod.lastIndexOf("."); + String selectClass = selectMethod.substring(0, i); + Class aClass = null; + try { + aClass = Class.forName(selectClass); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + Method associationMethod = null; + try { + associationMethod = aClass.getMethod(selectMethod.substring(i + 1), id.value()); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + Class returnType = associationMethod.getReturnType(); + if (!List.class.isAssignableFrom(returnType)) { + throw new CustomerException("can not set result, CollectionSql annotation only support result of list! Do you want to use @Association!"); + } + return recordsetUtil.invoke(null, associationMethod, + new Object[]{paramType.get(id.value()).apply(columnValue)}, selectMethod); + } } diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/controller/RaceTrackController.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/controller/RaceTrackController.java index 5438a33..6b77b3b 100644 --- a/src/main/java/com/api/youhong/ai/pcn/racetrack/controller/RaceTrackController.java +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/controller/RaceTrackController.java @@ -44,4 +44,33 @@ public class RaceTrackController { } } + + @GET + @Path("/get/stage-info") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getStageInfo(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + try { + return ApiResult.success(service.getStageInfo(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!"); + } + } + + @GET + @Path("/get/status") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getUserStatus(@Context HttpServletRequest request, @Context HttpServletResponse response) { + try { + User user = HrmUserVarify.getUser(request, response); + return ApiResult.success(user.getStatus()); + } catch (Exception e) { + log.info("get usr status fail!\n" + Util.getErrString(e)); + return ApiResult.error("get usr status fail!"); + } + } + } diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/dto/RaceTrackStage.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/dto/RaceTrackStage.java new file mode 100644 index 0000000..cf70d90 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/dto/RaceTrackStage.java @@ -0,0 +1,32 @@ +package com.api.youhong.ai.pcn.racetrack.dto; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + *

直道图数据库对象

+ * + *

create: 2023/2/17 11:41

+ * + * @author youHong.ai + */ +@Setter +@Getter +@ToString +public class RaceTrackStage { + /** id */ + private int id; + + /** 一阶段 */ + private String oneStage; + + /** 二阶段 */ + private String towStage; + + /** 三阶段 */ + private String threeStage; + /** 四阶段 */ + private String fourStage; + +} diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/mapper/RacetrackMapper.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/mapper/RacetrackMapper.java index f9b9867..bcfc4bd 100644 --- a/src/main/java/com/api/youhong/ai/pcn/racetrack/mapper/RacetrackMapper.java +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/mapper/RacetrackMapper.java @@ -4,6 +4,7 @@ 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 com.api.youhong.ai.pcn.racetrack.dto.RaceTrackStage; import java.util.List; @@ -47,4 +48,19 @@ public interface RacetrackMapper { */ @Select("select companyworkyear from hrmresource where id = #{userId}") String selectLengthOfEntryTime(@ParamMapper("userId") Integer userId); + + + @Select("select id, $t{raceTrackStageOneField} one_stage," + + "$t{raceTrackStageTwoField} tow_stage," + + "$t{raceTrackStageThreeField} three_stage ," + + "$t{raceTrackStageFourField} four_stage " + + "from $t{raceTrackStageTable} " + + "where $t{raceTrackStageUserField} = #{userId}") + RaceTrackStage selectStageInfoByUserId(@ParamMapper("userId") int uid, + @ParamMapper("raceTrackStageTable") String raceTrackStageTable, + @ParamMapper("raceTrackStageUserField") String raceTrackStageUserField, + @ParamMapper("raceTrackStageOneField") String raceTrackStageOneField, + @ParamMapper("raceTrackStageTwoField") String raceTrackStageTwoField, + @ParamMapper("raceTrackStageThreeField") String raceTrackStageThreeField, + @ParamMapper("raceTrackStageFourField") String raceTrackStageFourField); } diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/service/RaceTrackService.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/service/RaceTrackService.java index 046d023..756cfb7 100644 --- a/src/main/java/com/api/youhong/ai/pcn/racetrack/service/RaceTrackService.java +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/service/RaceTrackService.java @@ -1,13 +1,18 @@ package com.api.youhong.ai.pcn.racetrack.service; import aiyh.utils.Util; -import cn.hutool.core.lang.Assert; +import aiyh.utils.tool.Assert; import com.api.youhong.ai.pcn.racetrack.dto.RaceTrackEvent; +import com.api.youhong.ai.pcn.racetrack.dto.RaceTrackStage; import com.api.youhong.ai.pcn.racetrack.mapper.RacetrackMapper; +import com.api.youhong.ai.pcn.racetrack.vo.RaceTrackStageVo; import com.api.youhong.ai.pcn.racetrack.vo.RaceTrackVo; +import com.api.youhong.ai.pcn.racetrack.vo.StageInfoVo; +import com.google.common.base.Strings; import ebu7common.youhong.ai.bean.Builder; import weaver.hrm.User; +import java.util.ArrayList; import java.util.List; /** @@ -54,6 +59,114 @@ public class RaceTrackService { return Builder.builder(RaceTrackVo::new) .with(RaceTrackVo::setEventList, raceTrackEventList) .with(RaceTrackVo::setLengthOfEntryTime, lengthOfEntryTime) + .with(RaceTrackVo::setUserStatus, user.getStatus()) .build(); } + + /** + *

获取阶段信息列表

+ * + * @param user 当前用户 + * @return 阶段信息列表 + */ + public Object getStageInfo(User user) { + // 直到图数据表 + String raceTrackStageTable = Util.getCusConfigValue("RACE_TRACK_STAGE_TABLE"); + // 数据表用户字段 + String raceTrackStageUserField = Util.getCusConfigValue("RACE_TRACK_STAGE_USER_FIELD"); + // 一阶段列名 + String raceTrackStageOneField = Util.getCusConfigValue("RACE_TRACK_STAGE_ONE_FIELD"); + // 二阶段列名 + String raceTrackStageTwoField = Util.getCusConfigValue("RACE_TRACK_STAGE_TWO_FIELD"); + // 三阶段列名 + String raceTrackStageThreeField = Util.getCusConfigValue("RACE_TRACK_STAGE_THREE_FIELD"); + // 四阶段列名 + String raceTrackStageFourField = Util.getCusConfigValue("RACE_TRACK_STAGE_Four_FIELD"); + Assert.notBlank(raceTrackStageTable, + "race track stage info table can not be null! check configuration [RACE_TRACK_STAGE_TABLE] in uf_cus_dev_config table!"); + Assert.notBlank(raceTrackStageUserField, + "race track stage info user field can not be null! check configuration [RACE_TRACK_STAGE_USER_FIELD] in uf_cus_dev_config table!"); + Assert.notBlank(raceTrackStageOneField, + "race track stage info one stage filed can not be null! check configuration [RACE_TRACK_STAGE_ONE_FIELD] in uf_cus_dev_config table!"); + Assert.notBlank(raceTrackStageTwoField, + "race track stage info tow stage field can not be null! check configuration [RACE_TRACK_STAGE_TWO_FIELD] in uf_cus_dev_config table!"); + Assert.notBlank(raceTrackStageThreeField, + "race track stage info three stage field can not be null! check configuration [RACE_TRACK_STAGE_THREE_FIELD] in uf_cus_dev_config table!"); + Assert.notBlank(raceTrackStageFourField, + "race track stage info four stage field can not be null! check configuration [RACE_TRACK_STAGE_Four_FIELD] in uf_cus_dev_config table!"); + RaceTrackStage raceTrackStage = mapper.selectStageInfoByUserId(user.getUID(), raceTrackStageTable, + raceTrackStageUserField, + raceTrackStageOneField, + raceTrackStageTwoField, + raceTrackStageThreeField, + raceTrackStageFourField); + List stageInfoVos = pushRaceTrackVo(raceTrackStage); + return Builder.builder(RaceTrackStageVo::new) + .with(RaceTrackStageVo::setStageVoList, stageInfoVos) + .with(RaceTrackStageVo::setStatus, user.getStatus()) + .build(); + } + + + /** + *

添加阶段信息

+ * + * @param raceTrackStage 阶段信息 + * @return 阶段信息列表 + */ + private List pushRaceTrackVo(RaceTrackStage raceTrackStage) { + List raceTrackVos = new ArrayList<>(); + String oneStage = raceTrackStage.getOneStage(); + String towStage = raceTrackStage.getTowStage(); + String threeStage = raceTrackStage.getThreeStage(); + String fourStage = raceTrackStage.getFourStage(); + setRaceTrackValue(raceTrackVos, oneStage); + setRaceTrackValue(raceTrackVos, towStage); + setRaceTrackValue(raceTrackVos, threeStage); + setRaceTrackValue(raceTrackVos, fourStage); + for (int i = 0; i < raceTrackVos.size(); i++) { + StageInfoVo item = raceTrackVos.get(i); + if (i < raceTrackVos.size() - 1) { + if (item == null) { + raceTrackVos.set(i, Builder.builder(StageInfoVo::new) + .with(StageInfoVo::setFailedToArrive, true) + .build()); + } else { + item.setActive(true); + } + } else { + if (item == null) { + item = Builder.builder(StageInfoVo::new) + .with(StageInfoVo::setFailedToArrive, true) + .build(); + } + StageInfoVo nextItem = raceTrackVos.get(i + 1); + if (nextItem == null) { + item.setActive(true); + item.setFailedToArrive(false); + } else { + item.setPass(true); + } + } + } + return raceTrackVos; + } + + /** + *

阶段信息值设置

+ * + * @param raceTrackVos 阶段信息列表 + * @param stage 阶段字段值 + */ + private static void setRaceTrackValue(List raceTrackVos, String stage) { + if (Strings.isNullOrEmpty(stage)) { + raceTrackVos.add(null); + } else { + raceTrackVos.add( + Builder.builder(StageInfoVo::new) + .with(StageInfoVo::setTime, stage) + .build() + ); + } + } } diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/RaceTrackStageVo.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/RaceTrackStageVo.java new file mode 100644 index 0000000..0862caf --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/RaceTrackStageVo.java @@ -0,0 +1,25 @@ +package com.api.youhong.ai.pcn.racetrack.vo; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +/** + *

直道图阶段信息

+ * + *

create: 2023/2/17 11:06

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +public class RaceTrackStageVo { + private int id; + + private int status; + + private List stageVoList; +} diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/RaceTrackVo.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/RaceTrackVo.java index 70e1a1b..0cf965e 100644 --- a/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/RaceTrackVo.java +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/RaceTrackVo.java @@ -24,4 +24,7 @@ public class RaceTrackVo { /** 入职时长 */ private String lengthOfEntryTime; + + + private int userStatus; } diff --git a/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/StageInfoVo.java b/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/StageInfoVo.java new file mode 100644 index 0000000..053d84f --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/racetrack/vo/StageInfoVo.java @@ -0,0 +1,26 @@ +package com.api.youhong.ai.pcn.racetrack.vo; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + *

阶段信息

+ * + *

create: 2023/2/17 11:21

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +public class StageInfoVo { + /** 时间 */ + private String time; + /** 通过 */ + private boolean pass; + /** 是否当前节点 */ + private boolean active; + /** 未到达标识 */ + private boolean failedToArrive; +} diff --git a/src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java b/src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java index 8641e7d..fba8965 100644 --- a/src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java +++ b/src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java @@ -2,13 +2,11 @@ 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.annotation.*; import aiyh.utils.excention.CustomerException; import aiyh.utils.httpUtil.ResponeVo; import aiyh.utils.httpUtil.util.HttpUtils; +import com.google.common.base.Strings; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -16,8 +14,13 @@ 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 weaver.youhong.ai.intellectualproperty.mapper.CaElectronicSignatureMapper; import javax.ws.rs.core.MediaType; +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.Base64; import java.util.Map; /** @@ -30,7 +33,11 @@ import java.util.Map; @Setter @Getter @ToString +@ActionDesc(value = "电子签action", author = "youhong.ai") public class CaElectronicSignatureAction extends SafeCusBaseAction { + + public static final ThreadLocal docName = new ThreadLocal<>(); + public static final int SUCCESS_CODE = 200; @PrintParamMark @ActionOptionalParam(value = "false", desc = "是否自动提交流程") @ActionDefaultTestValue("false") @@ -46,10 +53,23 @@ public class CaElectronicSignatureAction extends SafeCusBaseAction { @RequiredMark("请求接口参数配置表中的唯一标识字段的值") private String onlyMark; + + @PrintParamMark + @ActionOptionalParam(value = "", desc = "签署后文件存储字段,只支持主表字段") + private String signFileField; + + + @PrintParamMark + @ActionOptionalParam(value = "", desc = "签署文件的文件唯一编号存储字段,只支持主表字段") + private String signFileNoField; + private final DealWithMapping dealWithMapping = new DealWithMapping(); private final HttpUtils httpUtils = new HttpUtils(); + + private final CaElectronicSignatureMapper mapper = Util.getMapper(CaElectronicSignatureMapper.class); + { httpUtils.getGlobalCache().header.put("Content-Type", MediaType.APPLICATION_JSON); } @@ -63,7 +83,19 @@ public class CaElectronicSignatureAction extends SafeCusBaseAction { String requestUrl = requestMappingConfig.getRequestUrl(); Map requestParam = dealWithMapping.getRequestParam(super.getObjMainTableValue(requestInfo), requestMappingConfig); ResponeVo responeVo = httpUtils.apiPost(requestUrl, requestParam); + if (responeVo.getCode() != SUCCESS_CODE) { + throw new CustomerException(responeVo.getCode() + ", fetch ca sign fail! "); + } Map responseMap = responeVo.getResponseMap(); + String documentNo = Util.null2String(responseMap.get("document_no")); + String pdf = Util.null2String(responseMap.get("pdf")); + InputStream inputStream = base64ContentToFile(pdf); + String docCategorys = Util.getDocCategorysByTable(String.valueOf(workflowId), signFileField, billTable); + String[] docCategoryArr = docCategorys.split(","); + int docCategory = Integer.parseInt(docCategoryArr[docCategoryArr.length - 1]); + int docId = Util.createDoc(Strings.isNullOrEmpty(docName.get()) ? "sign.pdf" : docName.get(), docCategory, inputStream, 1); + docName.remove(); + writeBack(documentNo, billTable, requestId, docId); } catch (Exception e) { if (Boolean.parseBoolean(block)) { throw new CustomerException(e.getMessage(), e); @@ -75,7 +107,49 @@ public class CaElectronicSignatureAction extends SafeCusBaseAction { } } + /** + *

回写数据

+ * + * @param documentNo 文档编号 + * @param billTable 表名 + * @param requestId 请求ID + * @param docId 文档id + */ + public void writeBack(String documentNo, String billTable, String requestId, int docId) { + if (!mapper.updateDocumentAndNo(billTable, signFileNoField, documentNo, signFileField, docId, requestId)) { + try { + Thread.sleep(500); + } catch (Exception ignore) { + + } + // 再次尝试 + if (!mapper.updateDocumentAndNo(billTable, signFileNoField, documentNo, signFileField, docId, requestId)) { + throw new CustomerException("can not update sign file to workflow!"); + } + } + } + + /** + *

提交流程

+ * + * @param requestId 请求id + * @param userId 用户id + */ public void submitWorkflow(String requestId, Integer userId) { Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "电子签自动提交流程"); } + + + /** + * 4. Base64字符串 转 文件(图片、pdf) -- 多用于测试 + * + * @param base64Content Base64 字符串 + */ + public InputStream base64ContentToFile(String base64Content) { + // Base64解码到字符数组 + byte[] bytes = Base64.getDecoder().decode(base64Content); + ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes); + return new BufferedInputStream(byteInputStream); + } + } diff --git a/src/main/java/weaver/youhong/ai/intellectualproperty/cusgetvalue/FileToBase64CusGetValue.java b/src/main/java/weaver/youhong/ai/intellectualproperty/cusgetvalue/FileToBase64CusGetValue.java new file mode 100644 index 0000000..24023ce --- /dev/null +++ b/src/main/java/weaver/youhong/ai/intellectualproperty/cusgetvalue/FileToBase64CusGetValue.java @@ -0,0 +1,41 @@ +package weaver.youhong.ai.intellectualproperty.cusgetvalue; + +import aiyh.utils.Util; +import aiyh.utils.entity.DocImageInfo; +import aiyh.utils.excention.CustomerException; +import org.apache.log4j.Logger; +import weaver.file.ImageFileManager; +import weaver.xiao.commons.config.interfacies.CusInterfaceGetValue; +import weaver.youhong.ai.intellectualproperty.action.CaElectronicSignatureAction; + +import java.io.InputStream; +import java.util.Base64; +import java.util.Map; + +/** + *

自定义接口获取值

+ * + *

create: 2023/2/17 15:44

+ * + * @author youHong.ai + */ +public class FileToBase64CusGetValue implements CusInterfaceGetValue { + private final Logger log = Util.getLogger(); + + @Override + public Object execute(Map mainMap, Map detailMap, + String currentValue, Map pathParam) { + try { + DocImageInfo docImageInfo = Util.selectImageInfoByDocId(currentValue); + InputStream inputStream = ImageFileManager.getInputStreamById(docImageInfo.getImageFileId()); + byte[] src = new byte[inputStream.available()]; + inputStream.read(src); + String fileBase64 = Base64.getEncoder().encodeToString(src); + CaElectronicSignatureAction.docName.set(docImageInfo.getImageFileName()); + return fileBase64; + } catch (Exception e) { + log.error("convert file to base64 fail!" + e.getMessage() + "\n" + Util.getErrString(e)); + throw new CustomerException("convert file to base64 fail!"); + } + } +} diff --git a/src/main/java/weaver/youhong/ai/intellectualproperty/mapper/CaElectronicSignatureMapper.java b/src/main/java/weaver/youhong/ai/intellectualproperty/mapper/CaElectronicSignatureMapper.java new file mode 100644 index 0000000..6f47d08 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/intellectualproperty/mapper/CaElectronicSignatureMapper.java @@ -0,0 +1,36 @@ +package weaver.youhong.ai.intellectualproperty.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.SqlMapper; +import aiyh.utils.annotation.recordset.Update; + +/** + *

+ * + *

create: 2023/2/17 15:27

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

更新回写文件信息

+ * + * @param billTable 表明 + * @param documentNoField 文件编号存储字段 + * @param documentNo 文档编号 + * @param documentField 文档存储字段 + * @param documentId 文档id + * @param requestId 请求id + * @return 是否更新成功 + */ + @Update("update $t{billTable} set $t{documentNoField} = #{documentNo}, " + + " $t{documentField} = #{documentId} where requestId = #{requestId}") + boolean updateDocumentAndNo(@ParamMapper("billTable") String billTable, + @ParamMapper("documentNoField") String documentNoField, + @ParamMapper("documentNo") String documentNo, + @ParamMapper("documentField") String documentField, + @ParamMapper("documentId") int documentId, + @ParamMapper("requestId") String requestId); +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/WorkflowConditionsSetValueAction.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/WorkflowConditionsSetValueAction.java new file mode 100644 index 0000000..32b0635 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/WorkflowConditionsSetValueAction.java @@ -0,0 +1,106 @@ +package weaver.youhong.ai.pcn.actioin.conditionssetvalue; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.*; +import aiyh.utils.excention.CustomerException; +import com.google.common.base.Strings; +import ebu7common.youhong.ai.bean.Builder; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto.UpdateDetailRowDto; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.service.WorkflowConditionsSetValueService; + +import java.util.*; + +/** + *

流程字段条件赋值action

+ * + *

create: 2023/2/19 13:27

+ * + * @author youHong.ai + */ +@Setter +@Getter +@ToString +@ActionDesc(value = "流程字段根据不同条件赋值", author = "youhong.ai") +public class WorkflowConditionsSetValueAction extends SafeCusBaseAction { + + @RequiredMark("流程条件赋值配置表唯一标识字段值") + @PrintParamMark + @ActionDefaultTestValue("test") + private String onlyMark; + + @ActionOptionalParam(desc = "条件修改所在明细表,1-明细1,2-明细2", value = "") + @PrintParamMark + @ActionDefaultTestValue("1") + private String detailNo; + + @PrintParamMark + @ActionOptionalParam(value = "false", desc = "是否自动提交流程") + private String submitAction = "false"; + + @PrintParamMark + @ActionOptionalParam(value = "true", desc = "是否失败后阻断流程") + private String block = "true"; + + private final WorkflowConditionsSetValueService service = new WorkflowConditionsSetValueService(); + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + try { + Map workflowData = new HashMap<>(16); + Map workflowMainData = super.getObjMainTableValue(requestInfo); + if (Strings.isNullOrEmpty(detailNo)) { + /* ******************* 数据修改主表 ******************* */ + Map conditionsValue = service.getConditionsValue(onlyMark, workflowData).get(billTable); + service.updateWorkflowData(conditionsValue, billTable, requestId); + return; + } + /* ******************* 明细表 ******************* */ + List> detailData = super.getDetailTableObjValueByDetailNo(Integer.parseInt(detailNo), requestInfo); + workflowData.put("main", workflowMainData); + workflowData.put("_user_", user); + workflowData.put("_workflowId_", workflowId); + workflowData.put("_requestId_", requestId); + workflowData.put("_billTable_", billTable); + List main = new ArrayList<>(); + List detail = new ArrayList<>(); + for (Map detailDatum : detailData) { + workflowData.put("detail_" + detailNo, detailDatum); + Map> conditionsValues = service.getConditionsValue(onlyMark, workflowData); + Map mainConditions = conditionsValues.get(billTable); + if (!Objects.isNull(mainConditions) && !mainConditions.isEmpty()) { + main.add(Builder.builder(UpdateDetailRowDto::new) + .with(UpdateDetailRowDto::setWhereValue, requestId) + .with(UpdateDetailRowDto::setWhereField, "requestid") + .with(UpdateDetailRowDto::setUpdateData, mainConditions) + .build()); + } + Map detailCondition = conditionsValues.get(billTable + "_dt" + detailNo); + if (!Objects.isNull(detailCondition) && !detailCondition.isEmpty()) { + detail.add(Builder.builder(UpdateDetailRowDto::new) + .with(UpdateDetailRowDto::setWhereValue, detailDatum.get("id")) + .with(UpdateDetailRowDto::setWhereField, "id") + .with(UpdateDetailRowDto::setUpdateData, detailCondition) + .build()); + } + } + service.updateWorkflowDetailData(main, billTable, null); + service.updateWorkflowDetailData(detail, billTable + "_dt" + detailNo, detailNo); + } catch (Exception e) { + if (Boolean.parseBoolean(block)) { + throw new CustomerException(e.getMessage(), e); + } + } finally { + this.submitWorkflow(requestId, user.getUID()); + } + } + + public void submitWorkflow(String requestId, Integer userId) { + Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "邮件发送附件提交流程!"); + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/dto/ConditionValueDto.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/dto/ConditionValueDto.java new file mode 100644 index 0000000..752e864 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/dto/ConditionValueDto.java @@ -0,0 +1,26 @@ +package weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + *

条件值dto

+ * + *

create: 2023/2/19 19:57

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +public class ConditionValueDto { + /** 字段名称 */ + private String fieldName; + + /** 对应值 */ + private Object value; + + /** 表名称 */ + private String tableName; +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/dto/UpdateDetailRowDto.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/dto/UpdateDetailRowDto.java new file mode 100644 index 0000000..79ebe5e --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/dto/UpdateDetailRowDto.java @@ -0,0 +1,25 @@ +package weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; + +/** + *

更新明细数据

+ * + *

create: 2023/2/20 13:46

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +public class UpdateDetailRowDto { + private String whereField; + + private Object whereValue; + + private Map updateData; +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionItem.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionItem.java new file mode 100644 index 0000000..f09f595 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionItem.java @@ -0,0 +1,40 @@ +package weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity; + +import aiyh.utils.entity.FieldViewInfo; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + *

流程条件赋值配置明细行

+ * + *

create: 2023/2/19 16:19

+ * + * @author youHong.ai + */ +@Setter +@Getter +@ToString +public class ConditionItem { + private Integer id; + + /** 赋值字段 */ + private FieldViewInfo targetField; + /** 条件取值字段 */ + private FieldViewInfo conditionsField; + /** 条件 */ + private Integer conditions; + /** 条件对比方式 */ + private Integer conditionsType; + /** 条件对比字段 */ + private FieldViewInfo conditionsContrastField; + /** 条件自定义值 */ + private String customerConditionsValue; + /** 赋值规则 */ + private Integer valueSetRules; + /** 自定义赋值 */ + private String customerSetValue; + + /** 取值字段 */ + private FieldViewInfo valueField; +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionsSetValueConfigMain.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionsSetValueConfigMain.java new file mode 100644 index 0000000..60b02fc --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionsSetValueConfigMain.java @@ -0,0 +1,32 @@ +package weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +/** + *

流程条件赋值配置主表

+ * + *

create: 2023/2/19 13:43

+ * + * @author youHong.ai + */ +@Setter +@Getter +@ToString +public class ConditionsSetValueConfigMain { + + /** id */ + private Integer id; + + /** 唯一标识 */ + private String onlyMark; + + /** 流程类型 */ + private Integer workflowType; + + /** 明细配置表,条件配置 */ + private List conditionItemList; +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/mapper/WorkflowConditionsSetValueMapper.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/mapper/WorkflowConditionsSetValueMapper.java new file mode 100644 index 0000000..c1cc5a7 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/mapper/WorkflowConditionsSetValueMapper.java @@ -0,0 +1,93 @@ +package weaver.youhong.ai.pcn.actioin.conditionssetvalue.mapper; + +import aiyh.utils.annotation.recordset.*; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity.ConditionItem; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity.ConditionsSetValueConfigMain; + +import java.util.List; +import java.util.Map; + +/** + *

流程字段条件值赋值mapper

+ * + *

create: 2023/2/19 13:37

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

根据唯一标识查询条件赋值配置数据

+ * + * @param onlyMark 唯一标识 + * @return 配置数据 + */ + @Select("select * from uf_wf_conditi_assig where only_mark = #{onlyMark}") + @CollectionMappings({ + @CollectionMapping(property = "conditionItemList", + column = "id", + id = @Id(value = Integer.class, methodId = 1)) + }) + ConditionsSetValueConfigMain selectConfigByOnlyMark(@ParamMapper("onlyMark") String onlyMark); + + + /** + *

根据主表id查询明细表数据

+ * + * @param mainId 主表ID + * @return 明细数据 + */ + @Select("select * from uf_wf_conditi_assig_dt1 where mainid = #{mainId}") + @Associations({ + @Association(property = "targetField", + column = "target_field", + select = "aiyh.utils.mapper.UtilMapper.selectFieldInfo", + id = @Id(Integer.class)), + @Association(property = "conditionsField", + column = "conditions_field", + select = "aiyh.utils.mapper.UtilMapper.selectFieldInfo", + id = @Id(Integer.class)), + @Association(property = "conditionsContrastField", + column = "conditions_contrast_field", + select = "aiyh.utils.mapper.UtilMapper.selectFieldInfo", + id = @Id(Integer.class)), + @Association(property = "valueField", + column = "value_field", + select = "aiyh.utils.mapper.UtilMapper.selectFieldInfo", + id = @Id(Integer.class)) + }) + @CollectionMethod(1) + List selectConditionItemsByMainId(Integer mainId); + + + /** + *

查询自定义sql

+ * + * @param sql 自定义sql + * @param workflowData 流程数据 + * @return 查询结果 + */ + @Select(custom = true) + String selectCustomerSql(@SqlString String sql, Map workflowData); + + /** + *

更新流程表单数据

+ * + * @param sql 自定义sql + * @param conditionData 条件值 + * @return 是否更新成功 + */ + @Update(custom = true) + boolean updateWorkflowData(@SqlString String sql, Map conditionData); + + /** + *

批量更新数据

+ * + * @param sql sql + * @param updateBatchData 批量参数 + * @return + */ + @BatchUpdate(custom = true) + boolean batchUpdateWorkflowData(@SqlString String sql, @BatchSqlArgs List> updateBatchData); +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/service/WorkflowConditionsSetValueService.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/service/WorkflowConditionsSetValueService.java new file mode 100644 index 0000000..ada3399 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/service/WorkflowConditionsSetValueService.java @@ -0,0 +1,150 @@ +package weaver.youhong.ai.pcn.actioin.conditionssetvalue.service; + +import aiyh.utils.Util; +import aiyh.utils.tool.Assert; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto.ConditionValueDto; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto.UpdateDetailRowDto; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity.ConditionItem; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity.ConditionsSetValueConfigMain; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.mapper.WorkflowConditionsSetValueMapper; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.util.ConditionsTreatment; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.util.ConditionsTypeTreatment; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.util.ValueSetRulesTreatment; + +import java.util.*; +import java.util.stream.Collectors; + +/** + *

流程字段值条件赋值service

+ * + *

create: 2023/2/19 13:37

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

获取条件赋值映射规则处理后的字段值

+ * + * @param onlyMark 配置表唯一标识 + * @param workflowData 流程表数据 + * @return 映射结果 + */ + public Map> getConditionsValue(String onlyMark, Map workflowData) { + + /* ******************* 查询配置表 ******************* */ + ConditionsSetValueConfigMain conditionsSetValueConfigMain = mapper.selectConfigByOnlyMark(onlyMark); + Assert.notNull(conditionsSetValueConfigMain, "can not query configuration by onlyMark [{}]", onlyMark); + List conditionItemList = conditionsSetValueConfigMain.getConditionItemList(); + Assert.notEmpty(conditionItemList, "can not query conditionItemList by onlyMark [{}]", onlyMark); + /* ******************* 映射规则处理 ,责任链初始化 ******************* */ + ConditionsTypeTreatment conditionsTypeTreatment = new ConditionsTypeTreatment( + new ConditionsTreatment( + new ValueSetRulesTreatment() + ) + ); + // 映射值处理 + List valueDtoList = new ArrayList<>(); + for (ConditionItem conditionItem : conditionItemList) { + ConditionValueDto conditionValueDto = conditionsTypeTreatment.conditionsTypeTreatment(conditionItem, workflowData); + if (!Objects.isNull(conditionValueDto)) { + valueDtoList.add(conditionValueDto); + } + } + Map> collect = valueDtoList.stream().collect(Collectors.groupingBy(ConditionValueDto::getTableName)); + + // 最终结果转为map + Map> result = new HashMap<>(valueDtoList.size()); + for (Map.Entry> entry : collect.entrySet()) { + Map map = new HashMap<>(valueDtoList.size()); + for (ConditionValueDto item : entry.getValue()) { + map.put(item.getFieldName(), item.getValue()); + } + result.put(entry.getKey(), map); + } + + return result; + } + + /** + *

更新明细表数据

+ * + * @param updateDetailRowDtoList 更新数据 + * @param billTable 表 + * @param detailNo 明细号 + */ + public void updateWorkflowDetailData(List updateDetailRowDtoList, String billTable, String detailNo) { + if (updateDetailRowDtoList.isEmpty()) { + return; + } + UpdateDetailRowDto updateDetailRow = updateDetailRowDtoList.get(0); + if (Objects.isNull(detailNo)) { + // 主表 + updateWorkflowData(updateDetailRow.getUpdateData(), billTable, Util.null2String(updateDetailRow.getWhereValue())); + return; + } + List> updateBatchData = new ArrayList<>(updateDetailRowDtoList.size()); + for (UpdateDetailRowDto updateDetailRowDto : updateDetailRowDtoList) { + Map updateData = updateDetailRowDto.getUpdateData(); + updateData.put("_id_", updateDetailRow.getWhereValue()); + updateBatchData.add(updateData); + } + StringBuilder sb = new StringBuilder("update "); + sb.append(billTable).append(" set "); + for (Map.Entry entry : updateBatchData.get(0).entrySet()) { + sb.append(entry.getKey()) + .append(" = #{item.") + .append(entry.getKey()) + .append("},"); + } + sb.deleteCharAt(sb.length() - 1); + sb.append(" where ") + .append(updateDetailRow.getWhereField()) + .append(" = #{item._id_}"); + String sql = sb.toString(); + boolean flag = mapper.batchUpdateWorkflowData(sql, updateBatchData); + if (!flag) { + try { + Thread.sleep(500); + } catch (InterruptedException ignore) { + } + mapper.batchUpdateWorkflowData(sql, updateBatchData); + } + } + + + /** + *

更新流程表单数据

+ * + * @param conditionData 条件值 + * @param billTable 表单表名 + * @param requestId 当前请求ID + */ + public void updateWorkflowData(Map conditionData, String billTable, String requestId) { + if (conditionData.isEmpty()) { + return; + } + StringBuilder sb = new StringBuilder("update "); + sb.append(billTable).append(" set "); + for (Map.Entry entry : conditionData.entrySet()) { + sb.append(entry.getKey()) + .append(" = #{") + .append(entry.getKey()) + .append("},"); + } + sb.deleteCharAt(sb.length() - 1); + sb.append(" where requestid = ") + .append(requestId); + String sql = sb.toString(); + boolean flag = mapper.updateWorkflowData(sql, conditionData); + if (!flag) { + try { + Thread.sleep(500); + } catch (InterruptedException ignore) { + } + mapper.updateWorkflowData(sql, conditionData); + } + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ConditionsTreatment.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ConditionsTreatment.java new file mode 100644 index 0000000..3355570 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ConditionsTreatment.java @@ -0,0 +1,82 @@ +package weaver.youhong.ai.pcn.actioin.conditionssetvalue.util; + +import aiyh.utils.Util; +import aiyh.utils.annotation.MethodRuleNo; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto.ConditionValueDto; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity.ConditionItem; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +/** + *

条件处理

+ * + *

create: 2023/2/19 17:41

+ * + * @author youHong.ai + */ +public class ConditionsTreatment { + + private final ValueSetRulesTreatment valueSetRulesTreatment; + + private static final Map> METHOD_MAP = new HashMap<>(); + + /* ******************* 初始化策略方法 ******************* */ { + Class valueRuleMethodClass = ConditionsTreatment.class; + Method[] methods = valueRuleMethodClass.getDeclaredMethods(); + for (Method method : methods) { + if (method.isAnnotationPresent(MethodRuleNo.class)) { + MethodRuleNo annotation = method.getAnnotation(MethodRuleNo.class); + int value = annotation.value(); + METHOD_MAP.put(value, (sourceValue, conditionValue) -> { + try { + return (Boolean) method.invoke(this, sourceValue, conditionValue); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + }); + } + } + } + + public ConditionsTreatment(ValueSetRulesTreatment valueSetRulesTreatment) { + this.valueSetRulesTreatment = valueSetRulesTreatment; + } + + public ConditionValueDto executeTreatment(ConditionItem conditionItem, Object value) { + Map workflowData = ConditionsTypeTreatment.WORKFLOW_DATA.get(); + Object sourceValue = workflowData.get(conditionItem.getConditionsField().getFieldName()); + Boolean apply = METHOD_MAP.get(conditionItem.getConditions()).apply( + Util.null2String(sourceValue), + Util.null2String(value) + ); + if (apply) { + return this.valueSetRulesTreatment.createConditionValue(conditionItem); + } + return null; + } + + @MethodRuleNo(value = 0, desc = "不等于") + private boolean notEqual(String sourceValue, String value) { + return !sourceValue.equals(value); + } + + @MethodRuleNo(value = 1, desc = "等于") + private boolean equalTo(String sourceValue, String value) { + return sourceValue.equals(value); + } + + @MethodRuleNo(value = 2, desc = "大于") + private boolean greaterThan(String sourceValue, String value) { + return Double.parseDouble(sourceValue) > Double.parseDouble(value); + } + + @MethodRuleNo(value = 3, desc = "小于") + private boolean lessThen(String sourceValue, String value) { + return Double.parseDouble(sourceValue) < Double.parseDouble(value); + } + +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ConditionsTypeTreatment.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ConditionsTypeTreatment.java new file mode 100644 index 0000000..fbf69a6 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ConditionsTypeTreatment.java @@ -0,0 +1,81 @@ +package weaver.youhong.ai.pcn.actioin.conditionssetvalue.util; + +import aiyh.utils.Util; +import aiyh.utils.annotation.MethodRuleNo; +import aiyh.utils.entity.FieldViewInfo; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto.ConditionValueDto; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity.ConditionItem; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.mapper.WorkflowConditionsSetValueMapper; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +/** + *

条件对比方式

+ * + *

create: 2023/2/19 17:44

+ * + * @author youHong.ai + */ +public class ConditionsTypeTreatment { + + private final WorkflowConditionsSetValueMapper mapper = Util.getMapper(WorkflowConditionsSetValueMapper.class); + + private final ConditionsTreatment conditionsTreatment; + + public final static ThreadLocal> WORKFLOW_DATA = new ThreadLocal<>(); + + private static final Map, Object>> METHOD_MAP = new HashMap<>(); + + public ConditionsTypeTreatment(ConditionsTreatment conditionsTreatment) { + this.conditionsTreatment = conditionsTreatment; + } + + /* ******************* 初始化策略方法 ******************* */ { + Class valueRuleMethodClass = ConditionsTypeTreatment.class; + Method[] methods = valueRuleMethodClass.getDeclaredMethods(); + for (Method method : methods) { + if (method.isAnnotationPresent(MethodRuleNo.class)) { + MethodRuleNo annotation = method.getAnnotation(MethodRuleNo.class); + int value = annotation.value(); + METHOD_MAP.put(value, (conditionItem, workflowData) -> { + try { + return method.invoke(this, conditionItem, workflowData); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + }); + } + } + } + + public ConditionValueDto conditionsTypeTreatment(ConditionItem conditionItem, Map workflowData) { + WORKFLOW_DATA.set(workflowData); + Object conditionValue = METHOD_MAP.get(conditionItem.getConditionsType()).apply(conditionItem, workflowData); + ConditionValueDto conditionValueDto = this.conditionsTreatment.executeTreatment(conditionItem, conditionValue); + WORKFLOW_DATA.remove(); + return conditionValueDto; + } + + + @MethodRuleNo(value = 0, desc = "流程字段") + private Object workflowField(ConditionItem conditionItem, Map workflowData) { + FieldViewInfo fieldInfo = conditionItem.getConditionsContrastField(); + return Util.getValueByFieldViwInfo(fieldInfo, workflowData); + } + + @MethodRuleNo(value = 1, desc = "固定值") + private Object fixValue(ConditionItem conditionItem, Map workflowData) { + return conditionItem.getCustomerConditionsValue(); + } + + @MethodRuleNo(value = 2, desc = "自定义sql") + private Object customerSql(ConditionItem conditionItem, Map workflowData) { + return mapper.selectCustomerSql(conditionItem.getCustomerConditionsValue(), workflowData); + } + + +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ValueSetRulesTreatment.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ValueSetRulesTreatment.java new file mode 100644 index 0000000..8999875 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ValueSetRulesTreatment.java @@ -0,0 +1,76 @@ +package weaver.youhong.ai.pcn.actioin.conditionssetvalue.util; + +import aiyh.utils.Util; +import aiyh.utils.annotation.MethodRuleNo; +import aiyh.utils.entity.FieldViewInfo; +import ebu7common.youhong.ai.bean.Builder; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto.ConditionValueDto; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity.ConditionItem; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.mapper.WorkflowConditionsSetValueMapper; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +/** + *

赋值规则处理

+ * + *

create: 2023/2/19 17:46

+ * + * @author youHong.ai + */ +public class ValueSetRulesTreatment { + + private static final Map, Object>> METHOD_MAP = new HashMap<>(); + + private final WorkflowConditionsSetValueMapper mapper = Util.getMapper(WorkflowConditionsSetValueMapper.class); + + /* ******************* 初始化策略方法 ******************* */ { + Class valueRuleMethodClass = ValueSetRulesTreatment.class; + Method[] methods = valueRuleMethodClass.getDeclaredMethods(); + for (Method method : methods) { + if (method.isAnnotationPresent(MethodRuleNo.class)) { + MethodRuleNo annotation = method.getAnnotation(MethodRuleNo.class); + int value = annotation.value(); + METHOD_MAP.put(value, (conditionItem, workflowData) -> { + try { + return method.invoke(this, conditionItem, workflowData); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + }); + } + } + } + + public ConditionValueDto createConditionValue(ConditionItem conditionItem) { + Map workflowData = ConditionsTypeTreatment.WORKFLOW_DATA.get(); + Object value = METHOD_MAP.get(conditionItem.getValueSetRules()).apply(conditionItem, workflowData); + return Builder.builder(ConditionValueDto::new) + .with(ConditionValueDto::setFieldName, conditionItem.getTargetField().getFieldName()) + .with(ConditionValueDto::setValue, value) + .build(); + } + + + @MethodRuleNo(value = 0, desc = "固定值") + private Object fixValue(ConditionItem conditionItem, Map workflowData) { + return conditionItem.getCustomerSetValue(); + } + + @MethodRuleNo(value = 1, desc = "流程字段") + private Object workflowField(ConditionItem conditionItem, Map workflowData) { + FieldViewInfo fieldInfo = conditionItem.getValueField(); + return Util.getValueByFieldViwInfo(fieldInfo, workflowData); + } + + + @MethodRuleNo(value = 2, desc = "自定义sql") + private Object customerSql(ConditionItem conditionItem, Map workflowData) { + return mapper.selectCustomerSql(conditionItem.getCustomerSetValue(), workflowData); + } + + +} diff --git a/src/test/java/youhong/ai/intellectualproperty/TestAction.java b/src/test/java/youhong/ai/intellectualproperty/TestAction.java new file mode 100644 index 0000000..2366906 --- /dev/null +++ b/src/test/java/youhong/ai/intellectualproperty/TestAction.java @@ -0,0 +1,22 @@ +package youhong.ai.intellectualproperty; + +import aiyh.utils.GenerateFileUtil; +import basetest.BaseTest; +import org.junit.Test; +import weaver.youhong.ai.intellectualproperty.action.CaElectronicSignatureAction; + +/** + *

测试

+ * + *

create: 2023/2/18 14:32

+ * + * @author youHong.ai + */ +public class TestAction extends BaseTest { + + + @Test + public void test() { + GenerateFileUtil.createActionDocument(CaElectronicSignatureAction.class); + } +} diff --git a/src/test/java/youhong/ai/pcn/MapperTest.java b/src/test/java/youhong/ai/pcn/MapperTest.java new file mode 100644 index 0000000..a4f252f --- /dev/null +++ b/src/test/java/youhong/ai/pcn/MapperTest.java @@ -0,0 +1,26 @@ +package youhong.ai.pcn; + +import aiyh.utils.Util; +import basetest.BaseTest; +import com.alibaba.fastjson.JSON; +import org.junit.Test; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity.ConditionsSetValueConfigMain; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.mapper.WorkflowConditionsSetValueMapper; + +/** + *

查询测试

+ * + *

create: 2023/2/19 16:33

+ * + * @author youHong.ai + */ +public class MapperTest extends BaseTest { + + + @Test + public void test() { + WorkflowConditionsSetValueMapper mapper = Util.getMapper(WorkflowConditionsSetValueMapper.class); + ConditionsSetValueConfigMain conditionsSetValueConfigMain = mapper.selectConfigByOnlyMark("test"); + System.out.println(JSON.toJSONString(conditionsSetValueConfigMain)); + } +} diff --git a/src/test/java/youhong/ai/pcn/RolesTest.java b/src/test/java/youhong/ai/pcn/RolesTest.java index fc2716b..7dc7d3c 100644 --- a/src/test/java/youhong/ai/pcn/RolesTest.java +++ b/src/test/java/youhong/ai/pcn/RolesTest.java @@ -7,6 +7,7 @@ import com.engine.common.util.ServiceUtil; import com.engine.hrm.service.impl.RolesMembersServiceImpl; import org.junit.Test; import weaver.hrm.User; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.WorkflowConditionsSetValueAction; import weaver.youhong.ai.pcn.schedule.addrolebyhasundering.RegisterRoleMemberByHasUnderingCronJob; import weaver.youhong.ai.pcn.schedule.addrolemember.RegisterRoleMemberCronJob; @@ -22,20 +23,20 @@ import java.util.Map; */ public class RolesTest extends BaseTest { - - - @Test - public void test() { - User user = new User(1); - RolesMembersServiceImpl service = ServiceUtil.getService(RolesMembersServiceImpl.class, user); - Map map = new HashMap<>(); - map.put("roleId", 2); - map.put("resourcetype", 1); - map.put("resourceid", 90); - map.put("rolelevel", 2); - map.put("cmd", "addRolesMembers"); - Map stringObjectMap = service.saveRolesMembers(map, user); - System.out.println(stringObjectMap); + + + @Test + public void test() { + User user = new User(1); + RolesMembersServiceImpl service = ServiceUtil.getService(RolesMembersServiceImpl.class, user); + Map map = new HashMap<>(); + map.put("roleId", 2); + map.put("resourcetype", 1); + map.put("resourceid", 90); + map.put("rolelevel", 2); + map.put("cmd", "addRolesMembers"); + Map stringObjectMap = service.saveRolesMembers(map, user); + System.out.println(stringObjectMap); /* String sql = " INSERT INTO HrmRoleMembers ( roleid ,resourceid ,rolelevel ,resourcetype ,alllevel ," + " seclevelfrom ,seclevelto ,subdepid ,jobtitlelevel) " + " VALUES ( " + roleId + ", " + arrObjIds[i] + " , '" + rolelevel + "', '" + resourcetype + "', " + @@ -44,18 +45,36 @@ public class RolesTest extends BaseTest { " " + (seclevelto.length() == 0 ? "null" : seclevelto) + ", " + (subdepid.length() == 0 ? "null" : "'" + subdepid + "'") + "," + (jobtitlelevel.length() == 0 ? "null" : jobtitlelevel) + ")";*/ - } - - - @Test - public void testCronJob() { - Util.cronJobTest(RegisterRoleMemberCronJob.class); - } - - - @Test - public void generateDoc() { - GenerateFileUtil.createCronJobDocument(RegisterRoleMemberByHasUnderingCronJob.class); - } - + } + + + @Test + public void testCronJob() { + Util.cronJobTest(RegisterRoleMemberCronJob.class); + } + + + @Test + public void generateDoc() { + GenerateFileUtil.createCronJobDocument(RegisterRoleMemberByHasUnderingCronJob.class); + } + + + @Test + public void test3() { + String value = "1"; + System.out.println(Double.parseDouble(value)); + } + + + @Test + public void testWorkflowConditionSetValue() { + Util.actionTest(WorkflowConditionsSetValueAction.class, 86088); + } + + + @Test + public void generateFile() { + GenerateFileUtil.createActionDocument(WorkflowConditionsSetValueAction.class); + } } diff --git a/src/test/java/youhong/ai/pcn/pojo/Student.java b/src/test/java/youhong/ai/pcn/pojo/Student.java index fc79ff1..c3dce88 100644 --- a/src/test/java/youhong/ai/pcn/pojo/Student.java +++ b/src/test/java/youhong/ai/pcn/pojo/Student.java @@ -17,18 +17,18 @@ import lombok.ToString; @Setter @ToString public class Student { - private int id; - - @SqlDbFieldAnn("a") - private String name; - - - @SqlDbFieldAnn("b") - private String test; - - @SqlDbFieldAnn("c") - private String bcd; - - private int age; - private int sex; + private int id; + + @SqlDbFieldAnn("WOLFLOWTYPE") + private String name; + + + @SqlDbFieldAnn("b") + private String test; + + @SqlDbFieldAnn("c") + private String bcd; + + private int age; + private int sex; }