diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index e4daf23..f1fddc4 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -297,4 +297,25 @@ $(() => { }) }) -/* ******************* apa(employee)流程明细分数控制end ******************* */ \ No newline at end of file +/* ******************* apa(employee)流程明细分数控制end ******************* */ + +const workflowInsertValueConfig = [ + { + table: '', + targetTable: '', + filedMapping: [{ + source: '', + target: '' + }] + }, { + table: '', + targetTable: '', + filedMapping: [] + } +] + + +/* ******************* 流程明细数据整合插入start ******************* */ + + +/* ******************* 流程明细数据整合插入end ******************* */ diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index 7933038..52a3cec 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -80,2060 +80,2060 @@ import java.util.zip.ZipEntry; public class Util extends weaver.general.Util { - - public static final ModeRightInfo MODE_RIGHT_INFO = new ModeRightInfo(); - public static final ModeDataIdUpdate mdu = ModeDataIdUpdate.getInstance(); - public static final char SBC_SPACE = 12288; // 全角空格 12288 - public static final char DBC_SPACE = 32; // 半角空格 32 - // ASCII character 33-126 <-> unicode 65281-65374 - public static final char ASCII_START = 33; - public static final char ASCII_END = 126; - public static final char UNICODE_START = 65281; - public static final char UNICODE_END = 65374; - public static final char DBC_SBC_STEP = 65248; // 全角半角转换间隔 - public static final ExecutorService threadPool = ThreadPoolConfig.createThreadPoolInstance(); - public static final String UF_CUS_DEV_CONFIG = "uf_cus_dev_config"; - private static final UtilService utilService = new UtilService(); - private static final RecordsetUtil recordsetUtil = new RecordsetUtil(); - private static final RecordsetUtil recordsetTransUtil = new RecordsetUtil(); - private static final UtilMapper mapper = recordsetUtil.getMapper(UtilMapper.class); - private static final Map otherLog = new HashMap<>(8); - static ToolUtil toolUtil = new ToolUtil(); - private static RecordSet rs; - private static volatile Logger log = null; - - static { - try { - rs = new RecordSet(); - } catch (Exception e) { - e.printStackTrace(); - new ToolUtil().writeErrorLog("\n初始化RecordSet失败!请检查系统是否正常启动!\n"); - } - } - - /** - * 获取指定格式的当前时间 - * - * @param format 格式化字符串 yyyy-MM-dd - * @return 指定格式日期的字符串 - */ - public static String getTime(String format) { - Date date = new Date(); - SimpleDateFormat formatter = new SimpleDateFormat(format); - return formatter.format(date); - } - - /** - * 创建一个SQL where条件,不推荐使用 - * - * @return Where对象 - */ - @Deprecated - public static Where createWhereImpl() { - return new WhereImpl(); - } - - /** - * 创建一个SQL where条件 - * - * @return Where对象 - */ - public static Where createPrepWhereImpl() { - return new PrepWhereImpl(); - } - - /** - * 创建一个Map工具,可以自定义一些功能,比如链式添加键值对,自定义过滤条件等 - * - * @return UtilHashMap对象 - */ - public static UtilHashMap createUtilHashMap() { - return new UtilHashMap<>(); - } - - /** - * 创建一个SQL构建工具类,通过构建工具可以实现SQL的构建 - * - * @return BuilderSqlImpl对象 - */ - public static BuilderSqlImpl createSqlBuilder() { - return new BuilderSqlImpl(); - } - - /** - * 创建一个Map工具,可以自定义一些功能,比如链式添加键值对,自定义过滤条件等 - * - * @return UtilLinkedHashMap对象 - */ - public static UtilLinkedHashMap createUtilLinkedHashMap() { - return new UtilLinkedHashMap<>(); - } - - /** - * 判断map是否为空或者是否没有数据 - * - * @param map 判断的map对象 - * @return 是否为空或者和大小为0 - */ - public static boolean mapIsNullOrEmpty(Map map) { - return Objects.isNull(map) || map.size() == 0; - } - - /** - * 去除前后的英文逗号 - * - * @param sqlBuilder 构建的SQL StringBuilder对象 - * @return 处理后的SQL字符串 - */ - public static String removeSeparator(StringBuilder sqlBuilder) { - String str = sqlBuilder.toString().trim(); - String removeSeparator = ","; - if (str.endsWith(removeSeparator)) { - // 如果以分割号结尾,则去除分割号 - str = str.substring(0, str.length() - 1); - } - if (str.trim().startsWith(removeSeparator)) { - str = str.substring(1); - } - return str; - } - - /** - * 移除前后的指定字符 - * - * @param sqlBuilder 需要移除的字符串的StringBuilder 对象 - * @param removeSeparator 移除的字符串 - * @return 移除前后指定字符后的字符串 - */ - public static String removeSeparator(StringBuilder sqlBuilder, String removeSeparator) { - String str = sqlBuilder.toString().trim(); - if (str.endsWith(removeSeparator)) { - // 如果以分割号结尾,则去除分割号 - str = str.substring(0, str.length() - 1); - } - if (str.trim().startsWith(removeSeparator)) { - str = str.substring(1); - } - return str; - } - - /** - * 移除前后的指定字符 - * - * @param string 需要移除的字符串的 - * @param removeSeparator 移除的字符串 - * @return 移除前后指定字符后的字符串 - */ - public static String removeSeparator(String string, String removeSeparator) { - String str = string.trim(); - if (str.endsWith(removeSeparator)) { - // 如果以分割号结尾,则去除分割号 - str = str.substring(0, str.length() - 1); - } - if (str.trim().startsWith(removeSeparator)) { - str = str.substring(1); - } - return str; - } - - /** - * 通过RecordSet对象,获取查询后的值,返回map - * - * @param rs 执行查询语句后的RecordSet对象 - * @param conversion 是否大小写转驼峰命名 - * @return 封装后的Map的值 - */ - private static Map getMapMapping(RecordSet rs, boolean conversion) { - Map map = new HashMap<>(); - String[] columnType = rs.getColumnTypeName(); - int colCounts = 0; - colCounts = rs.getColCounts() == 0 ? columnType.length : rs.getColCounts(); - for (int i = 1; i <= colCounts; i++) { - String key = null; - String type = "varchar"; - if (columnType != null) { - if (columnType.length != colCounts) { - type = "varchar"; - } else { - type = columnType[i - 1]; - } - } - if (conversion) { - key = toCamelCase(rs.getColumnName(i)); - } else { - key = rs.getColumnName(i); - } - rs.getColumnName(i); - if ("int".equalsIgnoreCase(type) || "Integer".equalsIgnoreCase(type) - || "Long".equalsIgnoreCase(type) || "BIGINT".equalsIgnoreCase(type) - || "NUMBER".equalsIgnoreCase(type) || "INTEGER".equalsIgnoreCase(type) - || "TINYINT".equalsIgnoreCase(type) || "SMALLINT".equalsIgnoreCase(type)) { - map.put(key, rs.getInt(i) == -1 ? rs.getString(i) : rs.getInt(i)); - continue; - } - if ("FLOAT".equalsIgnoreCase(type)) { - map.put(key, rs.getFloat(i)); - continue; - } - if ("DATE".equalsIgnoreCase(type) || "TIMESTAMP".equalsIgnoreCase(type) - || "DATETIME".equalsIgnoreCase(type)) { - map.put(key, rs.getString(i)); - continue; - } - if ("DOUBLE".equalsIgnoreCase(type)) { - map.put(key, rs.getDouble(i)); - continue; - } - if ("DECIMAL".equalsIgnoreCase(type) || "NUMERIC".equalsIgnoreCase(type)) { - map.put(key, rs.getDouble(i)); - continue; - } - map.put(key, rs.getString(i)); - } - return map; - } - - /** - * 通过RecordSet对象获取map结果 - * - * @param rs RecordSet对象 - * @return 查询结果map - */ - public static Map recordSet2Map(RecordSet rs) { - if (rs.next()) { - return getMapMapping(rs, false); - } - return null; - } - - /*** - * 通过RecordSet对象获取查询后的map结果 - * @param rs RecordSet对象 - * @param conversion 是否下划线转驼峰命名 - * @return 查询结果map对象 - */ - public static Map recordSet2Map(RecordSet rs, boolean conversion) { - if (rs.next()) { - return getMapMapping(rs, conversion); - } - return null; - } - - /** - * 通过RecordSet对象获取map结果 - * - * @param rs RecordSet对象 - * @return 查询结果map集合 - */ - public static List> recordSet2MapList(RecordSet rs) { - List> list = new ArrayList<>(); - while (rs.next()) { - list.add(getMapMapping(rs, false)); - } - return list; - } - - /*** - * 通过RecordSet对象获取查询后的map结果 - * @param rs RecordSet对象 - * @param conversion 是否下划线转驼峰命名 - * @return 查询结果map集合 - */ - public static List> recordSet2MapList(RecordSet rs, boolean conversion) { - List> list = new ArrayList<>(); - while (rs.next()) { - list.add(getMapMapping(rs, conversion)); - } - return list; - } - - - /** - * 获取查询SQL的映射实体 - * - * @param rs 查询结果 RecordSet类 - * @param t 反射获取的对象 - * @param emptyFields 对象的字段 - * @param 返回一个赋值后的对象 - * @return 处理后的对象 - * @throws IllegalAccessException IllegalAccessException异常 - */ - private static T getMappingEntity(RecordSet rs, T t, List emptyFields) throws IllegalAccessException { - for (Field field : emptyFields) { - String fieldName = field.getName(); - field.setAccessible(true); - if (field.getType().equals(String.class)) { - field.set(t, rs.getString(fieldName)); - continue; - } - if (field.getType().equals(Integer.class) || field.getType().equals(int.class) - || field.getType().equals(short.class) || field.getType().equals(long.class) - || field.getType().equals(Long.class)) { - field.set(t, rs.getInt(fieldName)); - continue; - } - if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) { - try { - BooleanConverter annotation = field.getAnnotation(BooleanConverter.class); - BooleanConverterEnum value = annotation.value(); - String trueStr = annotation.trueStr(); - String falseStr = annotation.falseStr(); - String trueInteger = annotation.trueInteger(); - String falseInteger = annotation.falseInteger(); - boolean defaultValue = annotation.defaultValue(); - String booleanVal = null; - try { - booleanVal = rs.getString(fieldName); - } catch (Exception ignored) { - } - boolean hasValueTrue = annotation.hasValueTrue(); - if (value == BooleanConverterEnum.STRING) { - if (booleanVal == null || booleanVal.equals(falseStr)) { - field.set(t, false); - } else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueStr)) { - field.set(t, true); - } else { - field.set(t, defaultValue); - } - } else if (value == BooleanConverterEnum.INTEGER) { - if (booleanVal == null || booleanVal.equals(falseInteger)) { - field.set(t, false); - } else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueInteger)) { - field.set(t, true); - } else { - field.set(t, defaultValue); - } - } - } catch (Exception e) { - throw new CustomerException("不支持的类型转换!"); - } - continue; - } - if (field.getType().equals(Float.class) || field.getType().equals(float.class)) { - field.set(t, rs.getFloat(fieldName)); - continue; - } - if (field.getType().equals(Double.class) || field.getType().equals(double.class)) { - field.set(t, rs.getDouble(fieldName)); - continue; - } - if (field.getType().equals(Date.class)) { - if (field.isAnnotationPresent(DateFormatAn.class)) { - DateFormatAn annotation = field.getAnnotation(DateFormatAn.class); - String value = annotation.value(); - try { - field.set(t, new SimpleDateFormat(value).parse(rs.getString(fieldName))); - } catch (ParseException e) { - e.printStackTrace(); - field.set(t, null); - } - } else { - try { - field.set(t, rs.getDate(fieldName)); - } catch (Exception e) { - field.set(t, null); - } - } - continue; - } - if (field.getType().equals(BigDecimal.class)) { - field.set(t, rs.getDouble(fieldName)); - } - } - return t; - } - - - /** - * 获取查询SQL的映射实体 - * - * @param rs 查询结果 RecordSet类 - * @param t 反射获取的对象 - * @param emptyFields 对象的字段 - * @param conversion 是否下划线转驼峰 - * @param 返回一个赋值后的对象 - * @return 处理后的对象 - * @throws IllegalAccessException IllegalAccessException 异常 - */ - private static T getMappingEntity(RecordSet rs, T t, List emptyFields, boolean conversion) throws IllegalAccessException { - if (!conversion) { - return getMappingEntity(rs, t, emptyFields); - } - for (Field field : emptyFields) { - String fieldName = toUnderlineCase(field.getName()); - field.setAccessible(true); - if (field.getType().equals(String.class)) { - field.set(t, rs.getString(fieldName)); - continue; - } - if (field.getType().equals(Integer.class) || field.getType().equals(int.class) - || field.getType().equals(short.class) || field.getType().equals(long.class) - || field.getType().equals(Long.class)) { - field.set(t, rs.getInt(fieldName)); - continue; - } - if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) { - try { - BooleanConverter annotation = field.getAnnotation(BooleanConverter.class); - BooleanConverterEnum value = annotation.value(); - String trueStr = annotation.trueStr(); - String falseStr = annotation.falseStr(); - String trueInteger = annotation.trueInteger(); - String falseInteger = annotation.falseInteger(); - boolean defaultValue = annotation.defaultValue(); - String booleanVal = null; - try { - booleanVal = rs.getString(fieldName); - } catch (Exception ignored) { - } - boolean hasValueTrue = annotation.hasValueTrue(); - if (value == BooleanConverterEnum.STRING) { - if (booleanVal == null || booleanVal.equals(falseStr)) { - field.set(t, false); - } else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueStr)) { - field.set(t, true); - } else { - field.set(t, defaultValue); - } - } else if (value == BooleanConverterEnum.INTEGER) { - if (booleanVal == null || booleanVal.equals(falseInteger)) { - field.set(t, false); - } else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueInteger)) { - field.set(t, true); - } else { - field.set(t, defaultValue); - } - } - } catch (Exception e) { - throw new CustomerException("不支持的类型转换!"); - } - continue; - } - if (field.getType().equals(Float.class) || field.getType().equals(float.class)) { - field.set(t, rs.getFloat(fieldName)); - continue; - } - if (field.getType().equals(Double.class) || field.getType().equals(double.class)) { - field.set(t, rs.getDouble(fieldName)); - continue; - } - if (field.getType().equals(Date.class)) { - if (field.isAnnotationPresent(DateFormatAn.class)) { - DateFormatAn annotation = field.getAnnotation(DateFormatAn.class); - String value = annotation.value(); - try { - field.set(t, new SimpleDateFormat(value).parse(rs.getString(fieldName))); - } catch (ParseException e) { - e.printStackTrace(); - field.set(t, null); - } - } else { - try { - field.set(t, rs.getDate(fieldName)); - } catch (Exception e) { - field.set(t, null); - } - } - continue; - } - if (field.getType().equals(BigDecimal.class)) { - field.set(t, rs.getDouble(fieldName)); - } - } - return t; - } - - @Deprecated - public static T recordeSet2Empty(RecordSet rs, Class clazz, boolean conversion) { - return recordeSet2Entity(rs, clazz, conversion); - } - - /** - * 通过查询结果获取到一个映射对象 - * - * @param rs 查询结果 - * @param clazz 需要映射的类 - * @param conversion 是否下划线转驼峰 - * @param 泛型 - * @return 转换后的对象 - */ - public static T recordeSet2Entity(RecordSet rs, Class clazz, boolean conversion) { - if (clazz == null) { - return null; - } - try { - if (rs.next()) { - T t = clazz.newInstance(); - List entityFields = getEmptyFields(clazz); - if (entityFields == null) { - toolUtil.writeErrorLog("emptyFields is empty!"); - return null; - } - return getMappingEntity(rs, t, entityFields, conversion); - } - } catch (InstantiationException | IllegalAccessException e) { - toolUtil.writeErrorLog("err" + "\n" + e); - return null; - } - return null; - } - - - @Deprecated - public static T recordeSet2Empty(RecordSet rs, Class clazz) { - return recordeSet2Entity(rs, clazz); - } - - /** - * 通过查询结果获取到一个映射对象 - * - * @param rs 查询结果 - * @param clazz 需要映射的类 - * @param 返回改类的实例对象 - * @return 处理后的实体类 - */ - public static T recordeSet2Entity(RecordSet rs, Class clazz) { - if (clazz == null) { - return null; - } - if (clazz.equals(String.class)) { - if (rs.next()) { - return (T) rs.getString(1); - } - return null; - } else if (clazz.equals(Integer.class)) { - if (rs.next()) { - return (T) Integer.valueOf(rs.getInt(1)); - } - return null; - } else if (clazz.equals(Double.class)) { - if (rs.next()) { - return (T) Double.valueOf(rs.getDouble(1)); - } - return null; - } else if (clazz.equals(Float.class)) { - if (rs.next()) { - return (T) Float.valueOf(rs.getFloat(1)); - } - return null; - } else if (clazz.equals(Boolean.class)) { - if (rs.next()) { - try { - return (T) Boolean.valueOf(rs.getBoolean(1)); - } catch (Exception e) { - return (T) Boolean.valueOf("false"); - } - } - return null; - } - try { - if (rs.next()) { - T t = clazz.newInstance(); - List emptyFields = getEmptyFields(clazz); - if (emptyFields == null) { - return null; - } - return getMappingEntity(rs, t, emptyFields); - } - } catch (InstantiationException | IllegalAccessException e) { - e.printStackTrace(); - return null; - } - return null; - } - - - /** - * 获取数据库映射的集合 - * - * @param rs 查询对象 - * @param clazz 需要映射的类 - * @param conversion 是否下划线转驼峰 - * @param 返回映射实体类集合 - * @return 处理后的实体类集合 - */ - public static List recordeSet2Array(RecordSet rs, Class clazz, boolean conversion) { - if (clazz == null) { - return null; - } - List list = new ArrayList<>(); - List entityFields = getEmptyFields(clazz); - if (entityFields == null) { - return null; - } - while (rs.next()) { - try { - T t = clazz.newInstance(); - list.add(getMappingEntity(rs, t, entityFields, conversion)); - } catch (InstantiationException | IllegalAccessException e) { - e.printStackTrace(); - return null; - } - } - return list; - } - - /** - * 获取数据库映射的集合 - * - * @param rs 查询对象 - * @param clazz 需要映射的类 - * @param 返回映射实体类集合 - * @return 转换后的实体类集合 - */ - public static List recordeSet2Array(RecordSet rs, Class clazz) { - if (clazz == null) { - return null; - } - List list = new ArrayList<>(); - List emptyFields = getEmptyFields(clazz); - if (emptyFields == null) { - return null; - } - while (rs.next()) { - try { - if (clazz.equals(String.class)) { - list.add((T) rs.getString(1)); - } else if (clazz.equals(Integer.class)) { - list.add((T) Integer.valueOf(rs.getInt(1))); - } else if (clazz.equals(Double.class)) { - list.add((T) Double.valueOf(rs.getDouble(1))); - } else if (clazz.equals(Float.class)) { - list.add((T) Float.valueOf(rs.getFloat(1))); - } else if (clazz.equals(Boolean.class)) { - list.add((T) Boolean.valueOf(rs.getBoolean(1))); - } else { - T t = clazz.newInstance(); - list.add(getMappingEntity(rs, t, emptyFields)); - } - } catch (InstantiationException | IllegalAccessException e) { - e.printStackTrace(); - return null; - } - } - return list; - } - - - /** - * 下划线转驼峰 - * - * @param underlineStr 带有下划线的字符串 - * @return 驼峰字符串 - */ - public static String toCamelCase(String underlineStr) { - if (underlineStr == null) { - return null; - } - // 分成数组 - char[] charArray = underlineStr.toCharArray(); - // 判断上次循环的字符是否是"_" - boolean underlineBefore = false; - StringBuilder buffer = new StringBuilder(); - for (int i = 0, l = charArray.length; i < l; i++) { - // 判断当前字符是否是"_",如果跳出本次循环 - if (charArray[i] == 95) { - underlineBefore = true; - } else if (underlineBefore) { - // 如果为true,代表上次的字符是"_",当前字符需要转成大写 - buffer.append(Character.toUpperCase(charArray[i])); - underlineBefore = false; - } else { - // 不是"_"后的字符就直接追加 - buffer.append(charArray[i]); - } - } - return buffer.toString(); - } - - /** - * 驼峰转 下划线 - * - * @param camelCaseStr 驼峰字符串 - * @return 带下滑线的String - */ - public static String toUnderlineCase(String camelCaseStr) { - if (camelCaseStr == null) { - return null; - } - // 将驼峰字符串转换成数组 - char[] charArray = camelCaseStr.toCharArray(); - StringBuilder buffer = new StringBuilder(); - // 处理字符串 - for (int i = 0, l = charArray.length; i < l; i++) { - if (charArray[i] >= 65 && charArray[i] <= 90) { - if (i == 0) { - buffer.append(charArray[i] += 32); - continue; - } - buffer.append("_").append(charArray[i] += 32); - } else { - buffer.append(charArray[i]); - } - } - return buffer.toString(); - } - - /** - * 根据类获取到对应的字段,包括父类的字段 - * - * @param clazz 需要获取字段的类 - * @return java字段信息 - */ - public static List getEntityFields(Class clazz) { - Class temClass = clazz; - List fieldList = new ArrayList<>(); - while (temClass != null && temClass != Object.class) { - fieldList.addAll(Arrays.asList(temClass.getDeclaredFields())); - temClass = temClass.getSuperclass(); - } - if (fieldList.size() == 0) { - return null; - } - return fieldList; - } - - - public static List getEmptyFields(Class clazz) { - return getEntityFields(clazz); - } - - /** - * 根据查询语句生成java文件 - * - * @param query 查询语句 - * @param javaName 文件名 - * @param packageName 包名 - * @throws IOException io异常 - */ - private static void createJavaFile(String query, String javaName, String packageName) throws IOException { - RecordSet rs = new RecordSet(); - rs.executeQuery(query); - List list = new ArrayList<>(); - int colCounts = rs.getColCounts() == 0 ? rs.getColumnTypeName().length : rs.getColCounts(); - for (int i = 1; i <= colCounts; i++) { - list.add(rs.getColumnName(i)); - } - String[] columnType = rs.getColumnTypeName(); - StringBuilder content = new StringBuilder(); - StringBuilder importBuilder = new StringBuilder(); - StringBuilder getBuilder = new StringBuilder(); - StringBuilder setBuilder = new StringBuilder(); - StringBuilder toStringBuilder = new StringBuilder("\n\t@Override\n"); - String packageStr = "\npackage " + packageName + "; \n\n"; - content.append("\npublic class "); - String className = Util.toCamelCase(javaName); - char[] chars = className.toCharArray(); - if (!Character.isUpperCase(chars[0])) { - chars[0] -= 32; - } - className = String.valueOf(chars) + "PO"; - toStringBuilder.append("\tpublic String toString() {\n\t\treturn \"") - .append(className) - .append("{\" +\n"); - content.append(className).append(" {\n\n"); - for (int i = 0; i < list.size(); i++) { - content.append(getClassField(columnType[i], list.get(i), importBuilder, getBuilder, setBuilder, toStringBuilder)); - } - toStringBuilder.append("\t\t\t\t'}';\n\t}"); - content.append(setBuilder) - .append(getBuilder) - .append(toStringBuilder.toString().replace("{\" +\n\t\t\t\t\", ", "{\" +\n\t\t\t\t\"")) - .append("\n}"); - String contentStr = packageStr + importBuilder + content; - String path = GCONST.getRootPath().replace(File.separator + "web" + File.separator, - File.separator + "src" + File.separator) + packageName.replace(".", File.separator) + File.separator + className + ".java"; - System.out.println(path); - File file = new File(URLDecoder.decode(path, "utf-8")); - if (!file.getParentFile().exists()) { - file.getParentFile().mkdirs(); - } - if (!file.exists()) { - file.createNewFile(); - } else { - try { - System.out.println("已存在文件:" + packageName + "." + className + ".java"); - System.out.print("你想如何处理该文件:替换[r/R] 重命名[w/W] 跳过[n/N] ? "); - Scanner scanner = new Scanner(System.in); - String next = scanner.next(); - System.out.println(next); - if ("w".equalsIgnoreCase(next)) { - System.out.print("请输入新的文件名:"); - String newName = scanner.next(); - System.out.println(newName); - System.out.println("处理中..."); - createJavaFile(query, newName, packageName); - } else if ("n".equalsIgnoreCase(next)) { - System.out.println("跳过文件生成!"); - return; - } - } catch (Exception e) { - System.out.println("已存在文件:" + packageName + "." + className + ".java"); - } - } - FileOutputStream fos = new FileOutputStream(file); - byte[] contentInBytes = contentStr.getBytes(); - fos.write(contentInBytes); - fos.flush(); - fos.close(); - System.out.println("完成"); - } - - /** - * 根据表名生成java文件 - * - * @param tableName 表名 - * @param packageName 包名 - * @throws IOException io异常 - */ - public static void creatJavaFileByTable(String tableName, String packageName) throws IOException { - RecordSet recordSet = new RecordSet(); - String dbType = recordSet.getDBType(); - String query; - System.out.println(dbType); - if ("mysql".equalsIgnoreCase(dbType)) { - query = "select * from " + tableName + " limit 1"; - } else if ("sqlserver".equalsIgnoreCase(dbType)) { - query = "select TOP 1 * from " + tableName; - } else { - query = "select TOP 1 * from " + tableName; - } - createJavaFile(query, tableName, packageName); - } - - /** - * 根据查询语句生成java问阿金 - * - * @param sql 查询语句 - * @param fileName java文件名 - * @param packageName 包名 - * @throws IOException io 异常 - */ - public static void creatJavaFileBySql(String sql, String fileName, String packageName) throws IOException { - RecordSet recordSet = new RecordSet(); - String dbType = recordSet.getDBType(); - String query; - System.out.println(dbType); - if ("mysql".equalsIgnoreCase(dbType)) { - query = "select * from (" + sql + ") as temp limit 1"; - } else if ("sqlserver".equalsIgnoreCase(dbType)) { - query = "select TOP 1 * from (" + sql + ") as temp"; - } else { - query = "select TOP 1 * from (" + sql + ") as temp"; - } - createJavaFile(query, fileName, packageName); - } - - /** - * java字段和数据库字段映射 - * - * @param type 数据库字段类型 - * @param name 数据库字段名 - * @param importBuilder 导包的构建 - * @param getBuilder getter方法的构建 - * @param setBuilder setter方法的构建 - * @param toStringBuilder toString方法的构建 - * @return java字段 - */ - public static String getClassField(String type, String name, StringBuilder importBuilder, - StringBuilder getBuilder, StringBuilder setBuilder, StringBuilder toStringBuilder) { - if ("TINYINT".equalsIgnoreCase(type)) { - getBuilder.append("\n\tpublic boolean is") - .append(getFirstCase(toCamelCase(name))) - .append("(){\n") - .append("\t\treturn this.") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - setBuilder.append("\n\tpublic void set") - .append(getFirstCase(toCamelCase(name))) - .append("(boolean ") - .append(toCamelCase(name)) - .append("){\n") - .append("\t\tthis.") - .append(toCamelCase(name)) - .append(" = ") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - toStringBuilder.append("\t\t\t\t\", ") - .append(toCamelCase(name)) - .append("='\" + ") - .append(toCamelCase(name)) - .append(" + '\\'' +\n"); - return "\tprivate boolean " + toCamelCase(name) + ";\n"; - } - if ("int".equalsIgnoreCase(type) || "SMALLINT".equalsIgnoreCase(type) - || "MEDIUMINT".equalsIgnoreCase(type) || "NUMBER".equalsIgnoreCase(type) - || "INTEGER".equalsIgnoreCase(type)) { - getBuilder.append("\n\tpublic int get") - .append(getFirstCase(toCamelCase(name))) - .append("(){\n") - .append("\t\treturn this.") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - setBuilder.append("\n\tpublic void set") - .append(getFirstCase(toCamelCase(name))) - .append("(int ") - .append(toCamelCase(name)) - .append("){\n") - .append("\t\tthis.") - .append(toCamelCase(name)) - .append(" = ") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - toStringBuilder.append("\t\t\t\t\", ") - .append(toCamelCase(name)) - .append("='\" + ") - .append(toCamelCase(name)) - .append(" + '\\'' +\n"); - return "\tprivate int " + toCamelCase(name) + ";\n"; - } - if ("BIGINT".equalsIgnoreCase(type)) { - getBuilder.append("\n\tpublic long get") - .append(getFirstCase(toCamelCase(name))) - .append("(){\n") - .append("\t\treturn this.") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - setBuilder.append("\n\tpublic void set") - .append(getFirstCase(toCamelCase(name))) - .append("(long ") - .append(toCamelCase(name)) - .append("){\n") - .append("\t\tthis.") - .append(toCamelCase(name)) - .append(" = ") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - toStringBuilder.append("\t\t\t\t\", ") - .append(toCamelCase(name)) - .append("='\" + ") - .append(toCamelCase(name)) - .append(" + '\\'' +\n"); - return "\tprivate long " + toCamelCase(name) + ";\n"; - } - if ("double".equalsIgnoreCase(type) || "BINARY_DOUBLE".equalsIgnoreCase(type)) { - getBuilder.append("\n\tpublic double get") - .append(getFirstCase(toCamelCase(name))) - .append("(){\n") - .append("\t\treturn this.") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - setBuilder.append("\n\tpublic void set") - .append(getFirstCase(toCamelCase(name))) - .append("(double ") - .append(toCamelCase(name)) - .append("){\n") - .append("\t\tthis.") - .append(toCamelCase(name)) - .append(" = ") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - toStringBuilder.append("\t\t\t\t\", ") - .append(toCamelCase(name)) - .append("='\" + ") - .append(toCamelCase(name)) - .append(" + '\\'' +\n"); - return "\tprivate double " + toCamelCase(name) + ";\n"; - } - if ("float".equalsIgnoreCase(type) || "BINARY_FLOAT".equalsIgnoreCase(type)) { - getBuilder.append("\n\tpublic float get") - .append(getFirstCase(toCamelCase(name))) - .append("(){\n") - .append("\t\treturn this.") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - setBuilder.append("\n\tpublic void set") - .append(getFirstCase(toCamelCase(name))) - .append("(float ") - .append(toCamelCase(name)) - .append("){\n") - .append("\t\tthis.") - .append(toCamelCase(name)) - .append(" = ") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - toStringBuilder.append("\t\t\t\t\", ") - .append(toCamelCase(name)) - .append("='\" + ") - .append(toCamelCase(name)) - .append(" + '\\'' +\n"); - return "\tprivate float " + toCamelCase(name) + ";\n"; - } - if ("DECIMAL".equalsIgnoreCase(type)) { - getBuilder.append("\n\tpublic BigDecimal get") - .append(getFirstCase(toCamelCase(name))) - .append("(){\n") - .append("\t\treturn this.") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - setBuilder.append("\n\tpublic void set") - .append(getFirstCase(toCamelCase(name))) - .append("(BigDecimal ") - .append(toCamelCase(name)) - .append("){\n") - .append("\t\tthis.") - .append(toCamelCase(name)) - .append(" = ") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - toStringBuilder.append("\t\t\t\t\", ") - .append(toCamelCase(name)) - .append("='\" + ") - .append(toCamelCase(name)) - .append(" + '\\'' +\n"); - importBuilder.append("import java.math.BigDecimal;\n"); - return "\tprivate BigDecimal " + toCamelCase(name) + ";\n"; - } - if ("DATE".equalsIgnoreCase(type) || "DATETIME".equalsIgnoreCase(type)) { - getBuilder.append("\n\tpublic Date get") - .append(getFirstCase(toCamelCase(name))) - .append("(){\n") - .append("\t\treturn this.") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - setBuilder.append("\n\tpublic void set") - .append(getFirstCase(toCamelCase(name))) - .append("(Date ") - .append(toCamelCase(name)) - .append("){\n") - .append("\t\tthis.") - .append(toCamelCase(name)) - .append(" = ") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - toStringBuilder.append("\t\t\t\t\", ") - .append(toCamelCase(name)) - .append("='\" + ") - .append(toCamelCase(name)) - .append(" + '\\'' +\n"); - importBuilder.append("import java.util.Date;\n"); - return "\tprivate Date" + toCamelCase(name) + ";\n"; - } - if ("char".equalsIgnoreCase(type) || "VARCHAR".equalsIgnoreCase(type) || "TEXT".equalsIgnoreCase(type)) { - getBuilder.append("\n\tpublic String get") - .append(getFirstCase(toCamelCase(name))) - .append("(){\n") - .append("\t\treturn this.") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - setBuilder.append("\n\tpublic void set") - .append(getFirstCase(toCamelCase(name))) - .append("(String ") - .append(toCamelCase(name)) - .append("){\n") - .append("\t\tthis.") - .append(toCamelCase(name)) - .append(" = ") - .append(toCamelCase(name)) - .append(";\n\t}\n"); - toStringBuilder.append("\t\t\t\t\", ") - .append(toCamelCase(name)) - .append("='\" + ") - .append(toCamelCase(name)) - .append(" + '\\'' +\n"); - return "\tprivate String " + toCamelCase(name) + ";\n"; - } - return ""; - } - - /** - * 首字母转大写 - * - * @param str 需要转换的字符串 - * @return 首字母转为大写后的字符串 - */ - public static String getFirstCase(String str) { - char[] chars = str.toCharArray(); - if (!Character.isUpperCase(chars[0])) { - chars[0] -= 32; - } - return String.valueOf(chars); - } - - - /** - * 通过文件名获取到对应的配置文件map对象 - * - * @param fileName prop/prop2map/文件夹下的文件名(不包含.properties) - * @return 配置文件对应的map对象 - */ - public static Map getProperties2Map(String fileName) { - String propertyPath = GCONST.getPropertyPath(); - if (StringUtil.isNullOrEmpty(fileName)) { - return null; - } - if (fileName.contains(".properties")) { - fileName.replace(".properties", ""); - } - String path = propertyPath + "prop2map" + File.separator + fileName + ".properties"; - Properties prop = new Properties(); - Map map = new HashMap<>(); - InputStream inputStream = null; - try { - inputStream = new BufferedInputStream(new FileInputStream(path)); - prop.load(inputStream); - Enumeration enumeration = prop.propertyNames(); - while (enumeration.hasMoreElements()) { - String key = String.valueOf(enumeration.nextElement()); - map.put(key, prop.getProperty(key)); - } - } catch (IOException e) { - throw new RuntimeException("找不到文件:" + path); - } finally { - try { - if (inputStream != null) { - inputStream.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return map; - } - - /** - * 根据配置文件文件名以及前缀获取对应的配置文件信息 - * - * @param fileName - * @param prefix - * @return - */ - public static Map readProperties2Map(String fileName, String prefix) { - String propertyPath = GCONST.getPropertyPath(); - if (StringUtil.isNullOrEmpty(fileName)) { - return null; - } - if (fileName.contains(".properties")) { - fileName.replace(".properties", ""); - } - String path = propertyPath + "prop2map" + File.separator + fileName + ".properties"; - ProperUtil prop = new ProperUtil(); - Map map = new HashMap<>(); - InputStream inputStream = null; - InputStreamReader is = null; - try { - inputStream = new BufferedInputStream(new FileInputStream(path)); - is = new InputStreamReader(inputStream, StandardCharsets.UTF_8); - prop.load(is); - // Enumeration enumeration = prop.propertyNames(); - // 顺序读取 - Enumeration enumeration = prop.keys(); - while (enumeration.hasMoreElements()) { - String key = (String) enumeration.nextElement(); - String value = prop.getProperty(key); - keyHandler(prefix, key, value, map); - } - } catch (IOException e) { - throw new RuntimeException("找不到文件:" + path); - } finally { - try { - if (is != null) { - is.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - try { - if (inputStream != null) { - inputStream.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return map; - } - - - /** - * 处理配置文件的key和value映射关系 - * - * @param prePrefix 前缀 - * @param key key - * @param value value - * @param preResult 结果对象 - * @return - */ - public static Map keyHandler(String prePrefix, String key, Object value, Map preResult) { - String objRegex = "^(" + prePrefix + "\\.)(?(\\w+))$"; - Pattern compile = Pattern.compile(objRegex); - Matcher matcher = compile.matcher(key); - if (matcher.find()) { - // 只匹配前缀.key=value模式的 - String resultKey = matcher.group("key"); - preResult.put(resultKey, prop2MapPutValue(value)); - } - String moreKey = "^(" + prePrefix + "\\.)(?(?(\\w+))\\.(\\S)+(?!\\[))"; - compile = Pattern.compile(moreKey); - matcher = compile.matcher(key); - if (matcher.find()) { - // 匹配前缀.key1.key2=value模式的 - String objKey = matcher.group("objKey"); - String prefixStr = prePrefix + "." + objKey; - Map valueMap; - if (preResult.containsKey(objKey)) { - valueMap = (Map) preResult.get(objKey); - keyHandler(prefixStr, key, value, valueMap); - return null; - } - valueMap = new HashMap<>(); - keyHandler(prefixStr, key, value, valueMap); - preResult.put(objKey, valueMap); - return null; - } - String strList = "^(" + prePrefix + "\\.)(?(\\w+))(\\[(?([0-9])+)])$"; - compile = Pattern.compile(strList); - matcher = compile.matcher(key); - if (matcher.find()) { - // 匹配前缀.key[0]=value模式的 - String objKey = matcher.group("key"); - int index = Integer.parseInt(matcher.group("index")); - if (preResult.containsKey(objKey)) { - // 存在值 - List valueList = (List) preResult.get(objKey); - if (index >= valueList.size()) { - valueList.add(prop2MapPutValue(value)); - } else { - valueList.set(index, prop2MapPutValue(value)); - } - return null; - } - List valueList = new ArrayList<>(); - valueList.add(prop2MapPutValue(value)); - preResult.put(objKey, valueList); - return null; - } - String objArray = "^(" + prePrefix + "\\.)(?(\\w+))(\\[(?([0-9])+)])\\.(?(\\S)+)$"; - // String objArray = "^("+prePrefix+"\\.)(?(\\w+))(\\[(?([0-9])+)])(\\.(?(\\S)+))+"; - compile = Pattern.compile(objArray); - matcher = compile.matcher(key); - if (matcher.find()) { - // 匹配前缀.key[0].name=value的模式 - String arrKey = matcher.group("arrKey"); - String objKey = matcher.group("objKey"); - int index = Integer.parseInt(matcher.group("index")); - List> mapList; - if (preResult.containsKey(arrKey)) { - // 存在 - mapList = (List>) preResult.get(arrKey); - // mapList - Map valueMap; - if (index >= mapList.size()) { - valueMap = new HashMap<>(); - valueMap.put(objKey, prop2MapPutValue(value)); - mapList.add(valueMap); - return null; - } - valueMap = mapList.get(index); - String arrMoreKey = "(?(\\w+))\\.(\\S)+(?!\\[)"; - Pattern arrMoreKeyCompile = Pattern.compile(arrMoreKey); - Matcher arrMoreKeyMatcher = arrMoreKeyCompile.matcher(objKey); - if (arrMoreKeyMatcher.find()) { - String arrMoreObjKey = arrMoreKeyMatcher.group("key"); - Map arrMoreValue; - if (valueMap.containsKey(arrMoreObjKey)) { - arrMoreValue = (Map) valueMap.get(arrMoreObjKey); - keyHandler(arrMoreObjKey, objKey, value, arrMoreValue); - return null; - } - arrMoreValue = new HashMap<>(); - keyHandler(arrMoreObjKey, objKey, value, arrMoreValue); - valueMap.put(arrMoreObjKey, arrMoreValue); - return null; - } - arrMoreKey = "(?(\\w+))(\\[(?([0-9])+)])$"; - arrMoreKeyCompile = Pattern.compile(arrMoreKey); - arrMoreKeyMatcher = arrMoreKeyCompile.matcher(objKey); - if (arrMoreKeyMatcher.find()) { - String arrMoreArrKey = arrMoreKeyMatcher.group("key"); - int arrMoreIndex = Integer.parseInt(arrMoreKeyMatcher.group("index")); - List arrMoreListValue; - if (valueMap.containsKey(arrMoreArrKey)) { - // 存在值 - arrMoreListValue = (List) valueMap.get(arrMoreArrKey); - if (arrMoreIndex >= arrMoreListValue.size()) { - arrMoreListValue.add(prop2MapPutValue(value)); - } else { - arrMoreListValue.set(arrMoreIndex, prop2MapPutValue(value)); - } - return null; - } - arrMoreListValue = new ArrayList<>(); - arrMoreListValue.add(prop2MapPutValue(value)); - valueMap.put(arrMoreArrKey, arrMoreListValue); - return null; - } - - // 直接添加 - valueMap.put(objKey, prop2MapPutValue(value)); - return null; - } - // 不存在 - mapList = new ArrayList<>(); - Map valueMap = new HashMap<>(); - valueMap.put(objKey, prop2MapPutValue(value)); - mapList.add(valueMap); - preResult.put(arrKey, mapList); - } - return null; - } - - public static Object prop2MapPutValue(Object value) { - if (value == null) { - return null; - } - String valueStr = String.valueOf(value).trim(); - if (valueStr.startsWith("\"") && valueStr.endsWith("\"")) { - return valueStr.substring(1, valueStr.length() - 1); - } - if (valueStr.contains(",")) { - if (valueStr.contains("\\,")) { - String[] split = valueStr.split("(? getProperties2Map(String fileName, String prefix) { - String propertyPath = GCONST.getPropertyPath(); - if (StringUtil.isNullOrEmpty(fileName)) { - return null; - } - if (fileName.contains(".properties")) { - fileName.replace(".properties", ""); - } - String path = propertyPath + "prop2map" + File.separator + fileName + ".properties"; - Properties prop = new Properties(); - Map map = new HashMap<>(); - InputStream inputStream = null; - try { - inputStream = new BufferedInputStream(new FileInputStream(path)); - prop.load(inputStream); - Enumeration enumeration = prop.propertyNames(); - while (enumeration.hasMoreElements()) { - String key = (String) enumeration.nextElement(); - if (key.contains(prefix + ".")) { - map.put(key.replace(prefix + ".", ""), prop.getProperty(key)); - } - } - } catch (IOException e) { - throw new RuntimeException("找不到文件:" + path); - } finally { - try { - if (inputStream != null) { - inputStream.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return map; - } - - public static Map> parsingSq2Map(String sql) { - Map> map = new HashMap<>(); - String pattern = "\\{{2}(?((?!\\$)\\s\\S)+?)\\.(?\\s\\S+?)}{2}"; - Pattern compile = Pattern.compile(pattern); - Matcher matcher = compile.matcher(sql); - while (matcher.find()) { - if (map.containsKey(matcher.group("table"))) { - map.get(matcher.group("table")).add(matcher.group("field")); - } else { - map.put(matcher.group("table"), new ArrayList() {{ - add(matcher.group("field")); - }}); - } - } - return map; - } - - public static Matcher parsingSql2Matcher(String sql) { - String pattern = "\\{{2}(?
((?!\\$)\\s\\S)+?)\\.(?\\s\\S+?)}{2}"; - Pattern compile = Pattern.compile(pattern); - return compile.matcher(sql); - } - - public static String parsingSqlByRequestAndWorkflowId(String sql, String requestId, String workflowId) { - String requestIdPattern = "\\{{2}(\\$requestId)?}{2}"; - String workflowIdIdPattern = "\\{{2}(\\$workflowId)?}{2}"; - String result = sql.replaceAll(requestIdPattern, StringUtil.isNullOrEmpty(requestId) ? "''" : requestId); - result = result.replaceAll(workflowIdIdPattern, StringUtil.isNullOrEmpty(workflowId) ? "''" : workflowId); - return result; - } - - public static String parsingSq(String sql, Map params) { - String result = sql; - String requestIdPattern = "\\{{2}(\\$requestId)?}{2}"; - String workflowIdIdPattern = "\\{{2}(\\$workflowId)?}{2}"; - result = result.replaceAll(requestIdPattern, ObjectUtil.isNull(params.get("requestId")) ? "''" : "'" + params.get("requestId") + "'"); - result = result.replaceAll(workflowIdIdPattern, ObjectUtil.isNull(params.get("workflowId")) ? "''" : "'" + params.get("workflowId") + "'"); - for (Map.Entry param : params.entrySet()) { - String pattern_ = "#\\{{2}(" + param.getKey() + ")?}{2}"; - result = result.replaceAll(pattern_, ObjectUtil.isNull(param.getValue()) ? "''" : String.valueOf(param.getValue())); - String pattern = "\\{{2}(" + param.getKey() + ")?}{2}"; - result = result.replaceAll(pattern, ObjectUtil.isNull(param.getValue()) ? "''" : "'" + param.getValue() + "'"); - } - return result; - } - - // 去重 - public static List deWeight(List list, Function keyExtractor) { - return list.stream().filter(distinctByKey(keyExtractor)).collect(Collectors.toList()); - } - - // - private static Predicate distinctByKey(Function keyExtractor) { - Map seen = new ConcurrentHashMap<>(); - // putIfAbsent添加不存在的键,返回null,如果为null表示不重复 - return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; - } - - - public static Map object2Map(Object obj) { - if (obj == null) { - return null; - } - Map map = new HashMap<>(); - try { - BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); - PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); - for (PropertyDescriptor property : propertyDescriptors) { - String key = property.getName(); - if (key.compareToIgnoreCase("class") == 0) { - continue; - } - Method getter = property.getReadMethod(); - Object value = getter != null ? getter.invoke(obj) : null; - map.put(key, value); - } - } catch (Exception e) { - e.printStackTrace(); - } - return map; - } - - - public static String getWorkflowNameById(String workflowid) { - RecordSet rs = new RecordSet(); - String sql = "select workflowname from workflow_base where id = ?"; - rs.executeQuery(sql, workflowid); - if (rs.next()) { - return rs.getString("workflowname"); - } - return ""; - } - - public static Object getRequestTitleById(String requestid) { - RecordSet rs = new RecordSet(); - String sql = "select requestnamenew from workflow_requestbase where requestid = ?"; - rs.executeQuery(sql, requestid); - if (rs.next()) { - return rs.getString("requestnamenew"); - } - return ""; - } - - - public static ApiConfigMainDTO queryApiConfig(String id) { - // System.out.println(JSON.toJSONString(apiConfigMain)); - return utilService.getApiConfigMain(id); - } - - public static ApiConfigMainDTO queryApiConfigTree(String id) { - // System.out.println(JSON.toJSONString(apiConfigMain)); - return utilService.getApiConfigMainTree(id); - } - - public static AZipOutputStream createZip(List inputList) throws IOException { - return createZip(inputList, File.separator); - } - - private static AZipOutputStream createZip(List inputList, String base) throws IOException { - FileOutputStream fileOutputStream = null; - - try { - File file = new File(AZipOutputStream.filePath); - if (!file.exists()) { - // 先得到文件的上级目录,并创建上级目录,在创建文件 - file.getParentFile().mkdirs(); - try { - // 创建文件 - file.createNewFile(); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - fileOutputStream = new FileOutputStream(file); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - if (fileOutputStream == null) { - return null; - } - AZipOutputStream zipOut = new AZipOutputStream(fileOutputStream); - int catchLen = 10 * 1024; - for (int i = 0; i < inputList.size(); i++) { - T item = inputList.get(i); - if (item instanceof InputStream) { - // 属于单级文件,直接压缩并返回 - try { - zipOut.putNextEntry(new ZipEntry(base + i)); - } catch (IOException e) { - throw new IOException(e.toString()); - } - byte[] buffer = new byte[catchLen]; - int len = 0; - while ((len = ((InputStream) item).read(buffer)) != -1) { - zipOut.write(buffer, 0, len); - } - zipOut.closeEntry(); - } - if (item instanceof AInputStream) { - try { - zipOut.putNextEntry(new ZipEntry(((AInputStream) item).getFileName())); - } catch (IOException e) { - e.printStackTrace(); - } - byte[] buffer = new byte[catchLen]; - int len = 0; - while ((len = ((AInputStream) item).getInputStream().read(buffer)) != -1) { - try { - zipOut.write(buffer, 0, len); - } catch (IOException e) { - e.printStackTrace(); - } - } - zipOut.closeEntry(); - } - if (item instanceof ListZipEntity) { - ListZipEntity listZipEntity = (ListZipEntity) item; - if (listZipEntity.isDirectory()) { - // 表示属于文件夹,循环添加处理文件夹 - handlerDirectory(listZipEntity.getFileList(), zipOut, base + listZipEntity.getDirectory() + File.separator); - } else { - List aInputStreams = listZipEntity.getaInputStreamList(); - for (AInputStream aInputStream : aInputStreams) { - try { - zipOut.putNextEntry(new ZipEntry(aInputStream.getFileName())); - } catch (IOException e) { - e.printStackTrace(); - } - byte[] buffer = new byte[catchLen]; - int len = 0; - while ((len = (aInputStream.getInputStream()).read(buffer)) != -1) { - try { - zipOut.write(buffer, 0, len); - } catch (IOException e) { - e.printStackTrace(); - } - } - zipOut.closeEntry(); - } - } - } - } - return zipOut; - } - - private static void handlerDirectory(List fileList, AZipOutputStream zipOut, String base) throws IOException { - int catchLen = 10 * 1024; - for (ListZipEntity listZipEntity : fileList) { - if (listZipEntity.isDirectory()) { - // 如果是文件夹 - handlerDirectory(listZipEntity.getFileList(), zipOut, base + listZipEntity.getDirectory() + File.separator); - } else { - List aInputStreams = listZipEntity.getaInputStreamList(); - for (AInputStream aInputStream : aInputStreams) { - try { - zipOut.putNextEntry(new ZipEntry(aInputStream.getFileName())); - } catch (IOException e) { - e.printStackTrace(); - } - byte[] buffer = new byte[catchLen]; - int len = 0; - while ((len = (aInputStream.getInputStream()).read(buffer)) != -1) { - try { - zipOut.write(buffer, 0, len); - } catch (IOException e) { - e.printStackTrace(); - } - } - zipOut.closeEntry(); - } - } - } - } - - public static Map queryLanguage(int groupId, int languageId) { - return utilService.queryLanguage(groupId, languageId); - } - - public static Map queryLanguage(int groupId, HttpServletRequest request, HttpServletResponse response) { - User user = HrmUserVarify.getUser(request, response); - int languageId = user.getLanguage(); - return utilService.queryLanguage(groupId, languageId); - } - - - public static String getHtmlLabelName(int id, int languageId, String defaultStr) { - String htmlLabelName = SystemEnv.getHtmlLabelName(id, languageId); - return htmlLabelName == null ? defaultStr : htmlLabelName; - } - - public static String getHtmlLabelName(int id, int languageId) { - return SystemEnv.getHtmlLabelName(id, languageId); - } - - public static String getHtmlLabelName(LabelHtmlIndex labelHtmlIndex, User user) { - return Util.getHtmlLabelName(labelHtmlIndex.getLabelIndex(), - user.getLanguage(), labelHtmlIndex.getDefaultStr()); - } - - - /** - * 获取流程主表 - * - * @param workflowId - * @return - */ - public static String getMainTable(String workflowId) { - String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); - String query = "select tablename from workflow_bill " + - " where id in (select formid from workflow_base " + - " where id in (" + versionStringByWfid + ") )"; - rs.executeQuery(query); - rs.next(); - return rs.getString(1); - } - - - /** - * 根据流程和流程字段查询文档目录 - * - * @param workflowId - * @param docField - * @return - */ - @Deprecated - public static String getDocCategorys(String workflowId, String docField) { - RecordSet rs = new RecordSet(); - rs.executeQuery("select formid from workflow_base where id = ?", workflowId); - String formId = Util.recordeSet2Entity(rs, String.class); - String query = "select doccategory from workflow_fileupload where fieldid in (select id from workflow_billfield where fieldname = ? and billid = ?)"; - rs.executeQuery(query, docField, formId); - String docCategorys = Util.null2String(Util.recordeSet2Entity(rs, String.class)); - if (StringUtils.isNullOrEmpty(docCategorys)) { - query = "select doccategory from workflow_base where id = ?"; - rs.executeQuery(query, workflowId); - rs.next(); - docCategorys = Util.null2String(rs.getString(1)); - } - if (StringUtils.isNullOrEmpty(docCategorys)) { - docCategorys = ",,1"; - } - return docCategorys; - } - - @Deprecated - public static String getDocCategorys(int workflowId, String docField) { - return getDocCategorys(String.valueOf(workflowId), docField); - } - - /** - * 根据流程和流程字段查询文档目录 - * - * @param workflowId - * @param docFieldId - * @return - */ - @Deprecated - public static String getDocCategorysById(String workflowId, String docFieldId) { - RecordSet rs = new RecordSet(); - // rs.executeQuery("select formid from workflow_base where id = ?",workflowId); - // String formId = Util.recordeSet2Entity(rs, String.class); - String query = "select doccategory from workflow_fileupload where workflowid = ? and fieldid = ?"; - rs.executeQuery(query, workflowId, docFieldId); - String docCategorys = Util.null2String(Util.recordeSet2Entity(rs, String.class)); - if (StringUtils.isNullOrEmpty(docCategorys)) { - query = "select doccategory from workflow_base where id = ?"; - rs.executeQuery(query, workflowId); - rs.next(); - docCategorys = Util.null2String(rs.getString(1)); - } - if (StringUtils.isNullOrEmpty(docCategorys)) { - docCategorys = ",,1"; - } - return docCategorys; - } - - - /** - * 根据流程和流程字段查询文档目录 - * - * @param workflowId 流程ID - * @param docField 文档字段ID - * @param tableName 明细表名 - * @return 文档目录 - */ - public static String getDocCategorysByTable(String workflowId, String docField, String tableName) { - RecordSet rs = new RecordSet(); - rs.executeQuery("select formid from workflow_base where id = ?", workflowId); - String formId = Util.recordeSet2Entity(rs, String.class); - String query = "select doccategory from workflow_fileupload where fieldid in (select id from workflow_billfield where fieldname = ? and billid = ? and (detailtable = ? or detailtable is null))"; - if (!Strings.isNullOrEmpty(tableName) && tableName.contains("_dt")) { - query = "select doccategory from workflow_fileupload where fieldid in (select id from workflow_billfield where fieldname = ? and billid = ? and detailtable = ?)"; - } - if (Strings.isNullOrEmpty(tableName)) { - tableName = ""; - } - rs.executeQuery(query, docField, formId, tableName); - String docCategorys = Util.null2String(Util.recordeSet2Entity(rs, String.class)); - if (StringUtils.isNullOrEmpty(docCategorys)) { - query = "select doccategory from workflow_base where id = ?"; - rs.executeQuery(query, workflowId); - rs.next(); - docCategorys = Util.null2String(rs.getString(1)); - } - if (StringUtils.isNullOrEmpty(docCategorys)) { - docCategorys = ",,1"; - } - return docCategorys; - } - - public static String null2DefaultStr(Object obj, String defaultStr) { - String objStr = Util.null2String(obj); - if (StringUtils.isNullOrEmpty(objStr) && StringUtils.isNullOrEmpty(defaultStr)) { - return ""; - } - if (StringUtils.isNullOrEmpty(objStr) && !StringUtils.isNullOrEmpty(defaultStr)) { - return defaultStr; - } - return objStr; - } - - - public static T mapToObject(Map map, Class t) throws Exception { - if (map == null) { - return null; - } - T obj = t.newInstance(); - Field[] fields = obj.getClass().getDeclaredFields(); - for (Field field : fields) { - int mod = field.getModifiers(); - if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) { - continue; - } - field.setAccessible(true); - if (field.getType().equals(String.class)) { - if (map.containsKey(field.getName())) { - if (map.get(field.getName()) == null) { - field.set(obj, null); - } else { - field.set(obj, String.valueOf(map.get(field.getName()))); - } - } - continue; - } - if (field.getType().equals(Integer.class)) { - if (map.containsKey(field.getName())) { - if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { - field.set(obj, null); - } else { - field.set(obj, Integer.valueOf(String.valueOf(map.get(field.getName())))); - } - } - continue; - } - if (field.getType().equals(Boolean.class)) { - if (map.containsKey(field.getName())) { - if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { - field.set(obj, null); - } else { - field.set(obj, Boolean.valueOf(String.valueOf(map.get(field.getName())))); - } - } - continue; - } - if (field.getType().equals(Float.class)) { - if (map.containsKey(field.getName())) { - if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { - field.set(obj, null); - } else { - field.set(obj, Float.valueOf(String.valueOf(map.get(field.getName())))); - } - } - continue; - } - if (field.getType().equals(Double.class)) { - if (map.containsKey(field.getName())) { - if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { - field.set(obj, null); - } else { - field.set(obj, Double.valueOf(String.valueOf(map.get(field.getName())))); - } - } - continue; - } - if (field.getType().equals(int.class)) { - if (map.containsKey(field.getName())) { - if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { - field.set(obj, null); - } else { - field.set(obj, Integer.parseInt(String.valueOf(map.get(field.getName())))); - } - } - continue; - } - if (field.getType().equals(float.class)) { - if (map.containsKey(field.getName())) { - if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { - field.set(obj, null); - } else { - field.set(obj, Float.parseFloat(String.valueOf(map.get(field.getName())))); - } - } - continue; - } - if (field.getType().equals(double.class)) { - if (map.containsKey(field.getName())) { - if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { - field.set(obj, null); - } else { - field.set(obj, Double.parseDouble(String.valueOf(map.get(field.getName())))); - } - } - continue; - } - if (field.getType().equals(boolean.class)) { - if (map.containsKey(field.getName())) { - if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { - field.set(obj, null); - } else { - field.set(obj, Boolean.parseBoolean(String.valueOf(map.get(field.getName())))); - } - } - continue; - } - } - return obj; - } - - public static T strMapToObject(Map map, Class t) throws Exception { - if (map == null) { - return null; - } - T obj = t.newInstance(); - Field[] fields = obj.getClass().getDeclaredFields(); - for (Field field : fields) { - int mod = field.getModifiers(); - if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) { - continue; - } - field.setAccessible(true); - if (map.containsKey(field.getName())) { - field.set(obj, map.get(field.getName())); - } - } - return obj; - } - - /** - * 获取完整的错误信息 - * - * @param throwable 异常 - * @return 完整堆栈信息 - */ - public static String getErrString(Throwable throwable) { - StringWriter stringWriter = new StringWriter(); - throwable.printStackTrace(new PrintWriter(stringWriter, true)); - String errStr = stringWriter.getBuffer().toString(); - try { - stringWriter.close(); - } catch (IOException e) { - e.printStackTrace(); - } - return errStr; - } - - /** - * 获取RecordSetUtil的SQL代理类对象 - * - * @param t - * @param - * @return - */ - public static T getMapper(Class t) { - return recordsetUtil.getMapper(t); - } - - /** - *

getTransMapper 获取事务对象mapper

- * 2022/12/21 22:45 - * ************************************************************ - * - * @param t 类 - * @param 代理类 - * @return T - * @author youHong.ai ****************************************** - */ - public static T getTransMapper(Class t) { - return recordsetTransUtil.getMapper(t, false); - } - - /** - *

commitTransMapper 提交事务mapper的事务

- * 2022/12/21 22:46 - * ************************************************************ - * - * @return boolean 是否提交成功 - * @author youHong.ai ****************************************** - */ - public static boolean commitTransMapper(Class t) { - if (t == null) { - throw new NullPointerException("can not commit trans for null mapper proxy!"); - } - if (t.getAnnotation(SqlMapper.class) == null) { - throw new BindingException("can not find SqlMapper annotation!"); - } - return recordsetTransUtil.getRsManager().commit(t.getName()); - } - - /** - *

rollbackTransMapper 回滚事务mapper 的事务

- * 2022/12/21 22:46 - * ************************************************************ - * - * @return boolean 是否回滚成功 - * @author youHong.ai ****************************************** - */ - public static boolean rollbackTransMapper(Class t) { - if (t == null) { - throw new NullPointerException("can not commit trans for null mapper proxy!"); - } - if (t.getAnnotation(SqlMapper.class) == null) { - throw new BindingException("can not find SqlMapper annotation!"); - } - return recordsetTransUtil.getRsManager().rollback(t.getName()); - } - - /** - * join方法 - * - * @param coll - * @param split - * @return - */ - public static String join(Collection coll, String split) { - if (CollectionUtils.isEmpty(coll)) { - return ""; - } else { - StringBuilder sb = new StringBuilder(); - boolean isFirst = true; - - String s; - for (Iterator item = coll.iterator(); item.hasNext(); sb.append(s)) { - s = item.next(); - if (isFirst) { - isFirst = false; - } else { - sb.append(split); - } - } - return sb.toString(); - } - } - - /** - * join方法 - * - * @param coll - * @param split - * @return - */ - public static String joinEach(Collection coll, String split) { - if (CollectionUtils.isEmpty(coll)) { - return ""; - } else { - StringBuilder sb = new StringBuilder(); - boolean isFirst = true; - - String s; - for (Iterator item = coll.iterator(); item.hasNext(); sb.append(s)) { - s = (String) item.next(); - if (isFirst) { - isFirst = false; - } else { - sb.append(split); - } - } - return sb.toString(); - } - } - - /** - * 将数组使用指定的分隔符链接为字符串 - * - * @param coll 集合 - * @param split 分隔符 - * @return 字符串 - */ - public static String intJoin(Collection coll, String split) { - if (CollectionUtils.isEmpty(coll)) { - return ""; - } else { - StringBuilder sb = new StringBuilder(); - boolean isFirst = true; - - String s; - for (Iterator item = coll.iterator(); item.hasNext(); sb.append(s)) { - Object next = item.next(); - s = next == null ? "" : String.valueOf(next); - if (isFirst) { - isFirst = false; - } else { - sb.append(split); - } - } - - return sb.toString(); - } - } - - /** - * 获取日志对象 - * - * @return 日志对象 - */ - public static Logger getLogger() { - if (log == null) { - synchronized (Util.class) { - if (log == null) { - DailyRollingFileAppender appender = new DailyRollingFileAppender(); - log = Logger.getLogger("ayh_cus"); - appender.setName("ayh_cus"); - appender.setEncoding("UTF-8"); - appender.setDatePattern("'_'yyyyMMdd'.log'"); - appender.setFile(weaver.general.GCONST.getLogPath() + "cus" + File.separator + "util_cus" + File.separator + "cus.log"); - appender.setThreshold(Priority.DEBUG); - appender.setLayout(new PatternLayout("[%-5p] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%r] [Thread:%t][%F.%M:%L] ==> : %m %x %n")); - appender.setAppend(true); - appender.activateOptions(); - log.addAppender(appender); - log.setAdditivity(false); - log.setLevel(Level.INFO); + + public static final ModeRightInfo MODE_RIGHT_INFO = new ModeRightInfo(); + public static final ModeDataIdUpdate mdu = ModeDataIdUpdate.getInstance(); + public static final char SBC_SPACE = 12288; // 全角空格 12288 + public static final char DBC_SPACE = 32; // 半角空格 32 + // ASCII character 33-126 <-> unicode 65281-65374 + public static final char ASCII_START = 33; + public static final char ASCII_END = 126; + public static final char UNICODE_START = 65281; + public static final char UNICODE_END = 65374; + public static final char DBC_SBC_STEP = 65248; // 全角半角转换间隔 + public static final ExecutorService threadPool = ThreadPoolConfig.createThreadPoolInstance(); + public static final String UF_CUS_DEV_CONFIG = "uf_cus_dev_config"; + private static final UtilService utilService = new UtilService(); + private static final RecordsetUtil recordsetUtil = new RecordsetUtil(); + private static final RecordsetUtil recordsetTransUtil = new RecordsetUtil(); + private static final UtilMapper mapper = recordsetUtil.getMapper(UtilMapper.class); + private static final Map otherLog = new HashMap<>(8); + static ToolUtil toolUtil = new ToolUtil(); + private static RecordSet rs; + private static volatile Logger log = null; + + static { + try { + rs = new RecordSet(); + } catch (Exception e) { + e.printStackTrace(); + new ToolUtil().writeErrorLog("\n初始化RecordSet失败!请检查系统是否正常启动!\n"); + } + } + + /** + * 获取指定格式的当前时间 + * + * @param format 格式化字符串 yyyy-MM-dd + * @return 指定格式日期的字符串 + */ + public static String getTime(String format) { + Date date = new Date(); + SimpleDateFormat formatter = new SimpleDateFormat(format); + return formatter.format(date); + } + + /** + * 创建一个SQL where条件,不推荐使用 + * + * @return Where对象 + */ + @Deprecated + public static Where createWhereImpl() { + return new WhereImpl(); + } + + /** + * 创建一个SQL where条件 + * + * @return Where对象 + */ + public static Where createPrepWhereImpl() { + return new PrepWhereImpl(); + } + + /** + * 创建一个Map工具,可以自定义一些功能,比如链式添加键值对,自定义过滤条件等 + * + * @return UtilHashMap对象 + */ + public static UtilHashMap createUtilHashMap() { + return new UtilHashMap<>(); + } + + /** + * 创建一个SQL构建工具类,通过构建工具可以实现SQL的构建 + * + * @return BuilderSqlImpl对象 + */ + public static BuilderSqlImpl createSqlBuilder() { + return new BuilderSqlImpl(); + } + + /** + * 创建一个Map工具,可以自定义一些功能,比如链式添加键值对,自定义过滤条件等 + * + * @return UtilLinkedHashMap对象 + */ + public static UtilLinkedHashMap createUtilLinkedHashMap() { + return new UtilLinkedHashMap<>(); + } + + /** + * 判断map是否为空或者是否没有数据 + * + * @param map 判断的map对象 + * @return 是否为空或者和大小为0 + */ + public static boolean mapIsNullOrEmpty(Map map) { + return Objects.isNull(map) || map.size() == 0; + } + + /** + * 去除前后的英文逗号 + * + * @param sqlBuilder 构建的SQL StringBuilder对象 + * @return 处理后的SQL字符串 + */ + public static String removeSeparator(StringBuilder sqlBuilder) { + String str = sqlBuilder.toString().trim(); + String removeSeparator = ","; + if (str.endsWith(removeSeparator)) { + // 如果以分割号结尾,则去除分割号 + str = str.substring(0, str.length() - 1); + } + if (str.trim().startsWith(removeSeparator)) { + str = str.substring(1); + } + return str; + } + + /** + * 移除前后的指定字符 + * + * @param sqlBuilder 需要移除的字符串的StringBuilder 对象 + * @param removeSeparator 移除的字符串 + * @return 移除前后指定字符后的字符串 + */ + public static String removeSeparator(StringBuilder sqlBuilder, String removeSeparator) { + String str = sqlBuilder.toString().trim(); + if (str.endsWith(removeSeparator)) { + // 如果以分割号结尾,则去除分割号 + str = str.substring(0, str.length() - 1); + } + if (str.trim().startsWith(removeSeparator)) { + str = str.substring(1); + } + return str; + } + + /** + * 移除前后的指定字符 + * + * @param string 需要移除的字符串的 + * @param removeSeparator 移除的字符串 + * @return 移除前后指定字符后的字符串 + */ + public static String removeSeparator(String string, String removeSeparator) { + String str = string.trim(); + if (str.endsWith(removeSeparator)) { + // 如果以分割号结尾,则去除分割号 + str = str.substring(0, str.length() - 1); + } + if (str.trim().startsWith(removeSeparator)) { + str = str.substring(1); + } + return str; + } + + /** + * 通过RecordSet对象,获取查询后的值,返回map + * + * @param rs 执行查询语句后的RecordSet对象 + * @param conversion 是否大小写转驼峰命名 + * @return 封装后的Map的值 + */ + private static Map getMapMapping(RecordSet rs, boolean conversion) { + Map map = new HashMap<>(); + String[] columnType = rs.getColumnTypeName(); + int colCounts = 0; + colCounts = rs.getColCounts() == 0 ? columnType.length : rs.getColCounts(); + for (int i = 1; i <= colCounts; i++) { + String key = null; + String type = "varchar"; + if (columnType != null) { + if (columnType.length != colCounts) { + type = "varchar"; + } else { + type = columnType[i - 1]; + } + } + if (conversion) { + key = toCamelCase(rs.getColumnName(i)); + } else { + key = rs.getColumnName(i); + } + rs.getColumnName(i); + if ("int".equalsIgnoreCase(type) || "Integer".equalsIgnoreCase(type) + || "Long".equalsIgnoreCase(type) || "BIGINT".equalsIgnoreCase(type) + || "NUMBER".equalsIgnoreCase(type) || "INTEGER".equalsIgnoreCase(type) + || "TINYINT".equalsIgnoreCase(type) || "SMALLINT".equalsIgnoreCase(type)) { + map.put(key, rs.getInt(i) == -1 ? rs.getString(i) : rs.getInt(i)); + continue; + } + if ("FLOAT".equalsIgnoreCase(type)) { + map.put(key, rs.getFloat(i)); + continue; + } + if ("DATE".equalsIgnoreCase(type) || "TIMESTAMP".equalsIgnoreCase(type) + || "DATETIME".equalsIgnoreCase(type)) { + map.put(key, rs.getString(i)); + continue; + } + if ("DOUBLE".equalsIgnoreCase(type)) { + map.put(key, rs.getDouble(i)); + continue; + } + if ("DECIMAL".equalsIgnoreCase(type) || "NUMERIC".equalsIgnoreCase(type)) { + map.put(key, rs.getDouble(i)); + continue; + } + map.put(key, rs.getString(i)); + } + return map; + } + + /** + * 通过RecordSet对象获取map结果 + * + * @param rs RecordSet对象 + * @return 查询结果map + */ + public static Map recordSet2Map(RecordSet rs) { + if (rs.next()) { + return getMapMapping(rs, false); + } + return null; + } + + /*** + * 通过RecordSet对象获取查询后的map结果 + * @param rs RecordSet对象 + * @param conversion 是否下划线转驼峰命名 + * @return 查询结果map对象 + */ + public static Map recordSet2Map(RecordSet rs, boolean conversion) { + if (rs.next()) { + return getMapMapping(rs, conversion); + } + return null; + } + + /** + * 通过RecordSet对象获取map结果 + * + * @param rs RecordSet对象 + * @return 查询结果map集合 + */ + public static List> recordSet2MapList(RecordSet rs) { + List> list = new ArrayList<>(); + while (rs.next()) { + list.add(getMapMapping(rs, false)); + } + return list; + } + + /*** + * 通过RecordSet对象获取查询后的map结果 + * @param rs RecordSet对象 + * @param conversion 是否下划线转驼峰命名 + * @return 查询结果map集合 + */ + public static List> recordSet2MapList(RecordSet rs, boolean conversion) { + List> list = new ArrayList<>(); + while (rs.next()) { + list.add(getMapMapping(rs, conversion)); + } + return list; + } + + + /** + * 获取查询SQL的映射实体 + * + * @param rs 查询结果 RecordSet类 + * @param t 反射获取的对象 + * @param emptyFields 对象的字段 + * @param 返回一个赋值后的对象 + * @return 处理后的对象 + * @throws IllegalAccessException IllegalAccessException异常 + */ + private static T getMappingEntity(RecordSet rs, T t, List emptyFields) throws IllegalAccessException { + for (Field field : emptyFields) { + String fieldName = field.getName(); + field.setAccessible(true); + if (field.getType().equals(String.class)) { + field.set(t, rs.getString(fieldName)); + continue; + } + if (field.getType().equals(Integer.class) || field.getType().equals(int.class) + || field.getType().equals(short.class) || field.getType().equals(long.class) + || field.getType().equals(Long.class)) { + field.set(t, rs.getInt(fieldName)); + continue; + } + if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) { + try { + BooleanConverter annotation = field.getAnnotation(BooleanConverter.class); + BooleanConverterEnum value = annotation.value(); + String trueStr = annotation.trueStr(); + String falseStr = annotation.falseStr(); + String trueInteger = annotation.trueInteger(); + String falseInteger = annotation.falseInteger(); + boolean defaultValue = annotation.defaultValue(); + String booleanVal = null; + try { + booleanVal = rs.getString(fieldName); + } catch (Exception ignored) { + } + boolean hasValueTrue = annotation.hasValueTrue(); + if (value == BooleanConverterEnum.STRING) { + if (booleanVal == null || booleanVal.equals(falseStr)) { + field.set(t, false); + } else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueStr)) { + field.set(t, true); + } else { + field.set(t, defaultValue); + } + } else if (value == BooleanConverterEnum.INTEGER) { + if (booleanVal == null || booleanVal.equals(falseInteger)) { + field.set(t, false); + } else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueInteger)) { + field.set(t, true); + } else { + field.set(t, defaultValue); + } + } + } catch (Exception e) { + throw new CustomerException("不支持的类型转换!"); + } + continue; + } + if (field.getType().equals(Float.class) || field.getType().equals(float.class)) { + field.set(t, rs.getFloat(fieldName)); + continue; + } + if (field.getType().equals(Double.class) || field.getType().equals(double.class)) { + field.set(t, rs.getDouble(fieldName)); + continue; + } + if (field.getType().equals(Date.class)) { + if (field.isAnnotationPresent(DateFormatAn.class)) { + DateFormatAn annotation = field.getAnnotation(DateFormatAn.class); + String value = annotation.value(); + try { + field.set(t, new SimpleDateFormat(value).parse(rs.getString(fieldName))); + } catch (ParseException e) { + e.printStackTrace(); + field.set(t, null); + } + } else { + try { + field.set(t, rs.getDate(fieldName)); + } catch (Exception e) { + field.set(t, null); + } + } + continue; + } + if (field.getType().equals(BigDecimal.class)) { + field.set(t, rs.getDouble(fieldName)); + } + } + return t; + } + + + /** + * 获取查询SQL的映射实体 + * + * @param rs 查询结果 RecordSet类 + * @param t 反射获取的对象 + * @param emptyFields 对象的字段 + * @param conversion 是否下划线转驼峰 + * @param 返回一个赋值后的对象 + * @return 处理后的对象 + * @throws IllegalAccessException IllegalAccessException 异常 + */ + private static T getMappingEntity(RecordSet rs, T t, List emptyFields, boolean conversion) throws IllegalAccessException { + if (!conversion) { + return getMappingEntity(rs, t, emptyFields); + } + for (Field field : emptyFields) { + String fieldName = toUnderlineCase(field.getName()); + field.setAccessible(true); + if (field.getType().equals(String.class)) { + field.set(t, rs.getString(fieldName)); + continue; + } + if (field.getType().equals(Integer.class) || field.getType().equals(int.class) + || field.getType().equals(short.class) || field.getType().equals(long.class) + || field.getType().equals(Long.class)) { + field.set(t, rs.getInt(fieldName)); + continue; + } + if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) { + try { + BooleanConverter annotation = field.getAnnotation(BooleanConverter.class); + BooleanConverterEnum value = annotation.value(); + String trueStr = annotation.trueStr(); + String falseStr = annotation.falseStr(); + String trueInteger = annotation.trueInteger(); + String falseInteger = annotation.falseInteger(); + boolean defaultValue = annotation.defaultValue(); + String booleanVal = null; + try { + booleanVal = rs.getString(fieldName); + } catch (Exception ignored) { + } + boolean hasValueTrue = annotation.hasValueTrue(); + if (value == BooleanConverterEnum.STRING) { + if (booleanVal == null || booleanVal.equals(falseStr)) { + field.set(t, false); + } else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueStr)) { + field.set(t, true); + } else { + field.set(t, defaultValue); + } + } else if (value == BooleanConverterEnum.INTEGER) { + if (booleanVal == null || booleanVal.equals(falseInteger)) { + field.set(t, false); + } else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueInteger)) { + field.set(t, true); + } else { + field.set(t, defaultValue); + } + } + } catch (Exception e) { + throw new CustomerException("不支持的类型转换!"); + } + continue; + } + if (field.getType().equals(Float.class) || field.getType().equals(float.class)) { + field.set(t, rs.getFloat(fieldName)); + continue; + } + if (field.getType().equals(Double.class) || field.getType().equals(double.class)) { + field.set(t, rs.getDouble(fieldName)); + continue; + } + if (field.getType().equals(Date.class)) { + if (field.isAnnotationPresent(DateFormatAn.class)) { + DateFormatAn annotation = field.getAnnotation(DateFormatAn.class); + String value = annotation.value(); + try { + field.set(t, new SimpleDateFormat(value).parse(rs.getString(fieldName))); + } catch (ParseException e) { + e.printStackTrace(); + field.set(t, null); + } + } else { + try { + field.set(t, rs.getDate(fieldName)); + } catch (Exception e) { + field.set(t, null); + } + } + continue; + } + if (field.getType().equals(BigDecimal.class)) { + field.set(t, rs.getDouble(fieldName)); + } + } + return t; + } + + @Deprecated + public static T recordeSet2Empty(RecordSet rs, Class clazz, boolean conversion) { + return recordeSet2Entity(rs, clazz, conversion); + } + + /** + * 通过查询结果获取到一个映射对象 + * + * @param rs 查询结果 + * @param clazz 需要映射的类 + * @param conversion 是否下划线转驼峰 + * @param 泛型 + * @return 转换后的对象 + */ + public static T recordeSet2Entity(RecordSet rs, Class clazz, boolean conversion) { + if (clazz == null) { + return null; + } + try { + if (rs.next()) { + T t = clazz.newInstance(); + List entityFields = getEmptyFields(clazz); + if (entityFields == null) { + toolUtil.writeErrorLog("emptyFields is empty!"); + return null; + } + return getMappingEntity(rs, t, entityFields, conversion); + } + } catch (InstantiationException | IllegalAccessException e) { + toolUtil.writeErrorLog("err" + "\n" + e); + return null; + } + return null; + } + + + @Deprecated + public static T recordeSet2Empty(RecordSet rs, Class clazz) { + return recordeSet2Entity(rs, clazz); + } + + /** + * 通过查询结果获取到一个映射对象 + * + * @param rs 查询结果 + * @param clazz 需要映射的类 + * @param 返回改类的实例对象 + * @return 处理后的实体类 + */ + public static T recordeSet2Entity(RecordSet rs, Class clazz) { + if (clazz == null) { + return null; + } + if (clazz.equals(String.class)) { + if (rs.next()) { + return (T) rs.getString(1); + } + return null; + } else if (clazz.equals(Integer.class)) { + if (rs.next()) { + return (T) Integer.valueOf(rs.getInt(1)); + } + return null; + } else if (clazz.equals(Double.class)) { + if (rs.next()) { + return (T) Double.valueOf(rs.getDouble(1)); + } + return null; + } else if (clazz.equals(Float.class)) { + if (rs.next()) { + return (T) Float.valueOf(rs.getFloat(1)); + } + return null; + } else if (clazz.equals(Boolean.class)) { + if (rs.next()) { + try { + return (T) Boolean.valueOf(rs.getBoolean(1)); + } catch (Exception e) { + return (T) Boolean.valueOf("false"); + } + } + return null; + } + try { + if (rs.next()) { + T t = clazz.newInstance(); + List emptyFields = getEmptyFields(clazz); + if (emptyFields == null) { + return null; + } + return getMappingEntity(rs, t, emptyFields); + } + } catch (InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + return null; + } + return null; + } + + + /** + * 获取数据库映射的集合 + * + * @param rs 查询对象 + * @param clazz 需要映射的类 + * @param conversion 是否下划线转驼峰 + * @param 返回映射实体类集合 + * @return 处理后的实体类集合 + */ + public static List recordeSet2Array(RecordSet rs, Class clazz, boolean conversion) { + if (clazz == null) { + return null; + } + List list = new ArrayList<>(); + List entityFields = getEmptyFields(clazz); + if (entityFields == null) { + return null; + } + while (rs.next()) { + try { + T t = clazz.newInstance(); + list.add(getMappingEntity(rs, t, entityFields, conversion)); + } catch (InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + return null; + } + } + return list; + } + + /** + * 获取数据库映射的集合 + * + * @param rs 查询对象 + * @param clazz 需要映射的类 + * @param 返回映射实体类集合 + * @return 转换后的实体类集合 + */ + public static List recordeSet2Array(RecordSet rs, Class clazz) { + if (clazz == null) { + return null; + } + List list = new ArrayList<>(); + List emptyFields = getEmptyFields(clazz); + if (emptyFields == null) { + return null; + } + while (rs.next()) { + try { + if (clazz.equals(String.class)) { + list.add((T) rs.getString(1)); + } else if (clazz.equals(Integer.class)) { + list.add((T) Integer.valueOf(rs.getInt(1))); + } else if (clazz.equals(Double.class)) { + list.add((T) Double.valueOf(rs.getDouble(1))); + } else if (clazz.equals(Float.class)) { + list.add((T) Float.valueOf(rs.getFloat(1))); + } else if (clazz.equals(Boolean.class)) { + list.add((T) Boolean.valueOf(rs.getBoolean(1))); + } else { + T t = clazz.newInstance(); + list.add(getMappingEntity(rs, t, emptyFields)); + } + } catch (InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + return null; + } + } + return list; + } + + + /** + * 下划线转驼峰 + * + * @param underlineStr 带有下划线的字符串 + * @return 驼峰字符串 + */ + public static String toCamelCase(String underlineStr) { + if (underlineStr == null) { + return null; + } + // 分成数组 + char[] charArray = underlineStr.toCharArray(); + // 判断上次循环的字符是否是"_" + boolean underlineBefore = false; + StringBuilder buffer = new StringBuilder(); + for (int i = 0, l = charArray.length; i < l; i++) { + // 判断当前字符是否是"_",如果跳出本次循环 + if (charArray[i] == 95) { + underlineBefore = true; + } else if (underlineBefore) { + // 如果为true,代表上次的字符是"_",当前字符需要转成大写 + buffer.append(Character.toUpperCase(charArray[i])); + underlineBefore = false; + } else { + // 不是"_"后的字符就直接追加 + buffer.append(charArray[i]); + } + } + return buffer.toString(); + } + + /** + * 驼峰转 下划线 + * + * @param camelCaseStr 驼峰字符串 + * @return 带下滑线的String + */ + public static String toUnderlineCase(String camelCaseStr) { + if (camelCaseStr == null) { + return null; + } + // 将驼峰字符串转换成数组 + char[] charArray = camelCaseStr.toCharArray(); + StringBuilder buffer = new StringBuilder(); + // 处理字符串 + for (int i = 0, l = charArray.length; i < l; i++) { + if (charArray[i] >= 65 && charArray[i] <= 90) { + if (i == 0) { + buffer.append(charArray[i] += 32); + continue; + } + buffer.append("_").append(charArray[i] += 32); + } else { + buffer.append(charArray[i]); + } + } + return buffer.toString(); + } + + /** + * 根据类获取到对应的字段,包括父类的字段 + * + * @param clazz 需要获取字段的类 + * @return java字段信息 + */ + public static List getEntityFields(Class clazz) { + Class temClass = clazz; + List fieldList = new ArrayList<>(); + while (temClass != null && temClass != Object.class) { + fieldList.addAll(Arrays.asList(temClass.getDeclaredFields())); + temClass = temClass.getSuperclass(); + } + if (fieldList.size() == 0) { + return null; + } + return fieldList; + } + + + public static List getEmptyFields(Class clazz) { + return getEntityFields(clazz); + } + + /** + * 根据查询语句生成java文件 + * + * @param query 查询语句 + * @param javaName 文件名 + * @param packageName 包名 + * @throws IOException io异常 + */ + private static void createJavaFile(String query, String javaName, String packageName) throws IOException { + RecordSet rs = new RecordSet(); + rs.executeQuery(query); + List list = new ArrayList<>(); + int colCounts = rs.getColCounts() == 0 ? rs.getColumnTypeName().length : rs.getColCounts(); + for (int i = 1; i <= colCounts; i++) { + list.add(rs.getColumnName(i)); + } + String[] columnType = rs.getColumnTypeName(); + StringBuilder content = new StringBuilder(); + StringBuilder importBuilder = new StringBuilder(); + StringBuilder getBuilder = new StringBuilder(); + StringBuilder setBuilder = new StringBuilder(); + StringBuilder toStringBuilder = new StringBuilder("\n\t@Override\n"); + String packageStr = "\npackage " + packageName + "; \n\n"; + content.append("\npublic class "); + String className = Util.toCamelCase(javaName); + char[] chars = className.toCharArray(); + if (!Character.isUpperCase(chars[0])) { + chars[0] -= 32; + } + className = String.valueOf(chars) + "PO"; + toStringBuilder.append("\tpublic String toString() {\n\t\treturn \"") + .append(className) + .append("{\" +\n"); + content.append(className).append(" {\n\n"); + for (int i = 0; i < list.size(); i++) { + content.append(getClassField(columnType[i], list.get(i), importBuilder, getBuilder, setBuilder, toStringBuilder)); + } + toStringBuilder.append("\t\t\t\t'}';\n\t}"); + content.append(setBuilder) + .append(getBuilder) + .append(toStringBuilder.toString().replace("{\" +\n\t\t\t\t\", ", "{\" +\n\t\t\t\t\"")) + .append("\n}"); + String contentStr = packageStr + importBuilder + content; + String path = GCONST.getRootPath().replace(File.separator + "web" + File.separator, + File.separator + "src" + File.separator) + packageName.replace(".", File.separator) + File.separator + className + ".java"; + System.out.println(path); + File file = new File(URLDecoder.decode(path, "utf-8")); + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + if (!file.exists()) { + file.createNewFile(); + } else { + try { + System.out.println("已存在文件:" + packageName + "." + className + ".java"); + System.out.print("你想如何处理该文件:替换[r/R] 重命名[w/W] 跳过[n/N] ? "); + Scanner scanner = new Scanner(System.in); + String next = scanner.next(); + System.out.println(next); + if ("w".equalsIgnoreCase(next)) { + System.out.print("请输入新的文件名:"); + String newName = scanner.next(); + System.out.println(newName); + System.out.println("处理中..."); + createJavaFile(query, newName, packageName); + } else if ("n".equalsIgnoreCase(next)) { + System.out.println("跳过文件生成!"); + return; + } + } catch (Exception e) { + System.out.println("已存在文件:" + packageName + "." + className + ".java"); + } + } + FileOutputStream fos = new FileOutputStream(file); + byte[] contentInBytes = contentStr.getBytes(); + fos.write(contentInBytes); + fos.flush(); + fos.close(); + System.out.println("完成"); + } + + /** + * 根据表名生成java文件 + * + * @param tableName 表名 + * @param packageName 包名 + * @throws IOException io异常 + */ + public static void creatJavaFileByTable(String tableName, String packageName) throws IOException { + RecordSet recordSet = new RecordSet(); + String dbType = recordSet.getDBType(); + String query; + System.out.println(dbType); + if ("mysql".equalsIgnoreCase(dbType)) { + query = "select * from " + tableName + " limit 1"; + } else if ("sqlserver".equalsIgnoreCase(dbType)) { + query = "select TOP 1 * from " + tableName; + } else { + query = "select TOP 1 * from " + tableName; + } + createJavaFile(query, tableName, packageName); + } + + /** + * 根据查询语句生成java问阿金 + * + * @param sql 查询语句 + * @param fileName java文件名 + * @param packageName 包名 + * @throws IOException io 异常 + */ + public static void creatJavaFileBySql(String sql, String fileName, String packageName) throws IOException { + RecordSet recordSet = new RecordSet(); + String dbType = recordSet.getDBType(); + String query; + System.out.println(dbType); + if ("mysql".equalsIgnoreCase(dbType)) { + query = "select * from (" + sql + ") as temp limit 1"; + } else if ("sqlserver".equalsIgnoreCase(dbType)) { + query = "select TOP 1 * from (" + sql + ") as temp"; + } else { + query = "select TOP 1 * from (" + sql + ") as temp"; + } + createJavaFile(query, fileName, packageName); + } + + /** + * java字段和数据库字段映射 + * + * @param type 数据库字段类型 + * @param name 数据库字段名 + * @param importBuilder 导包的构建 + * @param getBuilder getter方法的构建 + * @param setBuilder setter方法的构建 + * @param toStringBuilder toString方法的构建 + * @return java字段 + */ + public static String getClassField(String type, String name, StringBuilder importBuilder, + StringBuilder getBuilder, StringBuilder setBuilder, StringBuilder toStringBuilder) { + if ("TINYINT".equalsIgnoreCase(type)) { + getBuilder.append("\n\tpublic boolean is") + .append(getFirstCase(toCamelCase(name))) + .append("(){\n") + .append("\t\treturn this.") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + setBuilder.append("\n\tpublic void set") + .append(getFirstCase(toCamelCase(name))) + .append("(boolean ") + .append(toCamelCase(name)) + .append("){\n") + .append("\t\tthis.") + .append(toCamelCase(name)) + .append(" = ") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + toStringBuilder.append("\t\t\t\t\", ") + .append(toCamelCase(name)) + .append("='\" + ") + .append(toCamelCase(name)) + .append(" + '\\'' +\n"); + return "\tprivate boolean " + toCamelCase(name) + ";\n"; + } + if ("int".equalsIgnoreCase(type) || "SMALLINT".equalsIgnoreCase(type) + || "MEDIUMINT".equalsIgnoreCase(type) || "NUMBER".equalsIgnoreCase(type) + || "INTEGER".equalsIgnoreCase(type)) { + getBuilder.append("\n\tpublic int get") + .append(getFirstCase(toCamelCase(name))) + .append("(){\n") + .append("\t\treturn this.") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + setBuilder.append("\n\tpublic void set") + .append(getFirstCase(toCamelCase(name))) + .append("(int ") + .append(toCamelCase(name)) + .append("){\n") + .append("\t\tthis.") + .append(toCamelCase(name)) + .append(" = ") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + toStringBuilder.append("\t\t\t\t\", ") + .append(toCamelCase(name)) + .append("='\" + ") + .append(toCamelCase(name)) + .append(" + '\\'' +\n"); + return "\tprivate int " + toCamelCase(name) + ";\n"; + } + if ("BIGINT".equalsIgnoreCase(type)) { + getBuilder.append("\n\tpublic long get") + .append(getFirstCase(toCamelCase(name))) + .append("(){\n") + .append("\t\treturn this.") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + setBuilder.append("\n\tpublic void set") + .append(getFirstCase(toCamelCase(name))) + .append("(long ") + .append(toCamelCase(name)) + .append("){\n") + .append("\t\tthis.") + .append(toCamelCase(name)) + .append(" = ") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + toStringBuilder.append("\t\t\t\t\", ") + .append(toCamelCase(name)) + .append("='\" + ") + .append(toCamelCase(name)) + .append(" + '\\'' +\n"); + return "\tprivate long " + toCamelCase(name) + ";\n"; + } + if ("double".equalsIgnoreCase(type) || "BINARY_DOUBLE".equalsIgnoreCase(type)) { + getBuilder.append("\n\tpublic double get") + .append(getFirstCase(toCamelCase(name))) + .append("(){\n") + .append("\t\treturn this.") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + setBuilder.append("\n\tpublic void set") + .append(getFirstCase(toCamelCase(name))) + .append("(double ") + .append(toCamelCase(name)) + .append("){\n") + .append("\t\tthis.") + .append(toCamelCase(name)) + .append(" = ") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + toStringBuilder.append("\t\t\t\t\", ") + .append(toCamelCase(name)) + .append("='\" + ") + .append(toCamelCase(name)) + .append(" + '\\'' +\n"); + return "\tprivate double " + toCamelCase(name) + ";\n"; + } + if ("float".equalsIgnoreCase(type) || "BINARY_FLOAT".equalsIgnoreCase(type)) { + getBuilder.append("\n\tpublic float get") + .append(getFirstCase(toCamelCase(name))) + .append("(){\n") + .append("\t\treturn this.") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + setBuilder.append("\n\tpublic void set") + .append(getFirstCase(toCamelCase(name))) + .append("(float ") + .append(toCamelCase(name)) + .append("){\n") + .append("\t\tthis.") + .append(toCamelCase(name)) + .append(" = ") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + toStringBuilder.append("\t\t\t\t\", ") + .append(toCamelCase(name)) + .append("='\" + ") + .append(toCamelCase(name)) + .append(" + '\\'' +\n"); + return "\tprivate float " + toCamelCase(name) + ";\n"; + } + if ("DECIMAL".equalsIgnoreCase(type)) { + getBuilder.append("\n\tpublic BigDecimal get") + .append(getFirstCase(toCamelCase(name))) + .append("(){\n") + .append("\t\treturn this.") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + setBuilder.append("\n\tpublic void set") + .append(getFirstCase(toCamelCase(name))) + .append("(BigDecimal ") + .append(toCamelCase(name)) + .append("){\n") + .append("\t\tthis.") + .append(toCamelCase(name)) + .append(" = ") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + toStringBuilder.append("\t\t\t\t\", ") + .append(toCamelCase(name)) + .append("='\" + ") + .append(toCamelCase(name)) + .append(" + '\\'' +\n"); + importBuilder.append("import java.math.BigDecimal;\n"); + return "\tprivate BigDecimal " + toCamelCase(name) + ";\n"; + } + if ("DATE".equalsIgnoreCase(type) || "DATETIME".equalsIgnoreCase(type)) { + getBuilder.append("\n\tpublic Date get") + .append(getFirstCase(toCamelCase(name))) + .append("(){\n") + .append("\t\treturn this.") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + setBuilder.append("\n\tpublic void set") + .append(getFirstCase(toCamelCase(name))) + .append("(Date ") + .append(toCamelCase(name)) + .append("){\n") + .append("\t\tthis.") + .append(toCamelCase(name)) + .append(" = ") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + toStringBuilder.append("\t\t\t\t\", ") + .append(toCamelCase(name)) + .append("='\" + ") + .append(toCamelCase(name)) + .append(" + '\\'' +\n"); + importBuilder.append("import java.util.Date;\n"); + return "\tprivate Date" + toCamelCase(name) + ";\n"; + } + if ("char".equalsIgnoreCase(type) || "VARCHAR".equalsIgnoreCase(type) || "TEXT".equalsIgnoreCase(type)) { + getBuilder.append("\n\tpublic String get") + .append(getFirstCase(toCamelCase(name))) + .append("(){\n") + .append("\t\treturn this.") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + setBuilder.append("\n\tpublic void set") + .append(getFirstCase(toCamelCase(name))) + .append("(String ") + .append(toCamelCase(name)) + .append("){\n") + .append("\t\tthis.") + .append(toCamelCase(name)) + .append(" = ") + .append(toCamelCase(name)) + .append(";\n\t}\n"); + toStringBuilder.append("\t\t\t\t\", ") + .append(toCamelCase(name)) + .append("='\" + ") + .append(toCamelCase(name)) + .append(" + '\\'' +\n"); + return "\tprivate String " + toCamelCase(name) + ";\n"; + } + return ""; + } + + /** + * 首字母转大写 + * + * @param str 需要转换的字符串 + * @return 首字母转为大写后的字符串 + */ + public static String getFirstCase(String str) { + char[] chars = str.toCharArray(); + if (!Character.isUpperCase(chars[0])) { + chars[0] -= 32; + } + return String.valueOf(chars); + } + + + /** + * 通过文件名获取到对应的配置文件map对象 + * + * @param fileName prop/prop2map/文件夹下的文件名(不包含.properties) + * @return 配置文件对应的map对象 + */ + public static Map getProperties2Map(String fileName) { + String propertyPath = GCONST.getPropertyPath(); + if (StringUtil.isNullOrEmpty(fileName)) { + return null; + } + if (fileName.contains(".properties")) { + fileName.replace(".properties", ""); + } + String path = propertyPath + "prop2map" + File.separator + fileName + ".properties"; + Properties prop = new Properties(); + Map map = new HashMap<>(); + InputStream inputStream = null; + try { + inputStream = new BufferedInputStream(new FileInputStream(path)); + prop.load(inputStream); + Enumeration enumeration = prop.propertyNames(); + while (enumeration.hasMoreElements()) { + String key = String.valueOf(enumeration.nextElement()); + map.put(key, prop.getProperty(key)); + } + } catch (IOException e) { + throw new RuntimeException("找不到文件:" + path); + } finally { + try { + if (inputStream != null) { + inputStream.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return map; + } + + /** + * 根据配置文件文件名以及前缀获取对应的配置文件信息 + * + * @param fileName + * @param prefix + * @return + */ + public static Map readProperties2Map(String fileName, String prefix) { + String propertyPath = GCONST.getPropertyPath(); + if (StringUtil.isNullOrEmpty(fileName)) { + return null; + } + if (fileName.contains(".properties")) { + fileName.replace(".properties", ""); + } + String path = propertyPath + "prop2map" + File.separator + fileName + ".properties"; + ProperUtil prop = new ProperUtil(); + Map map = new HashMap<>(); + InputStream inputStream = null; + InputStreamReader is = null; + try { + inputStream = new BufferedInputStream(new FileInputStream(path)); + is = new InputStreamReader(inputStream, StandardCharsets.UTF_8); + prop.load(is); + // Enumeration enumeration = prop.propertyNames(); + // 顺序读取 + Enumeration enumeration = prop.keys(); + while (enumeration.hasMoreElements()) { + String key = (String) enumeration.nextElement(); + String value = prop.getProperty(key); + keyHandler(prefix, key, value, map); + } + } catch (IOException e) { + throw new RuntimeException("找不到文件:" + path); + } finally { + try { + if (is != null) { + is.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + try { + if (inputStream != null) { + inputStream.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return map; + } + + + /** + * 处理配置文件的key和value映射关系 + * + * @param prePrefix 前缀 + * @param key key + * @param value value + * @param preResult 结果对象 + * @return + */ + public static Map keyHandler(String prePrefix, String key, Object value, Map preResult) { + String objRegex = "^(" + prePrefix + "\\.)(?(\\w+))$"; + Pattern compile = Pattern.compile(objRegex); + Matcher matcher = compile.matcher(key); + if (matcher.find()) { + // 只匹配前缀.key=value模式的 + String resultKey = matcher.group("key"); + preResult.put(resultKey, prop2MapPutValue(value)); + } + String moreKey = "^(" + prePrefix + "\\.)(?(?(\\w+))\\.(\\S)+(?!\\[))"; + compile = Pattern.compile(moreKey); + matcher = compile.matcher(key); + if (matcher.find()) { + // 匹配前缀.key1.key2=value模式的 + String objKey = matcher.group("objKey"); + String prefixStr = prePrefix + "." + objKey; + Map valueMap; + if (preResult.containsKey(objKey)) { + valueMap = (Map) preResult.get(objKey); + keyHandler(prefixStr, key, value, valueMap); + return null; + } + valueMap = new HashMap<>(); + keyHandler(prefixStr, key, value, valueMap); + preResult.put(objKey, valueMap); + return null; + } + String strList = "^(" + prePrefix + "\\.)(?(\\w+))(\\[(?([0-9])+)])$"; + compile = Pattern.compile(strList); + matcher = compile.matcher(key); + if (matcher.find()) { + // 匹配前缀.key[0]=value模式的 + String objKey = matcher.group("key"); + int index = Integer.parseInt(matcher.group("index")); + if (preResult.containsKey(objKey)) { + // 存在值 + List valueList = (List) preResult.get(objKey); + if (index >= valueList.size()) { + valueList.add(prop2MapPutValue(value)); + } else { + valueList.set(index, prop2MapPutValue(value)); + } + return null; + } + List valueList = new ArrayList<>(); + valueList.add(prop2MapPutValue(value)); + preResult.put(objKey, valueList); + return null; + } + String objArray = "^(" + prePrefix + "\\.)(?(\\w+))(\\[(?([0-9])+)])\\.(?(\\S)+)$"; + // String objArray = "^("+prePrefix+"\\.)(?(\\w+))(\\[(?([0-9])+)])(\\.(?(\\S)+))+"; + compile = Pattern.compile(objArray); + matcher = compile.matcher(key); + if (matcher.find()) { + // 匹配前缀.key[0].name=value的模式 + String arrKey = matcher.group("arrKey"); + String objKey = matcher.group("objKey"); + int index = Integer.parseInt(matcher.group("index")); + List> mapList; + if (preResult.containsKey(arrKey)) { + // 存在 + mapList = (List>) preResult.get(arrKey); + // mapList + Map valueMap; + if (index >= mapList.size()) { + valueMap = new HashMap<>(); + valueMap.put(objKey, prop2MapPutValue(value)); + mapList.add(valueMap); + return null; + } + valueMap = mapList.get(index); + String arrMoreKey = "(?(\\w+))\\.(\\S)+(?!\\[)"; + Pattern arrMoreKeyCompile = Pattern.compile(arrMoreKey); + Matcher arrMoreKeyMatcher = arrMoreKeyCompile.matcher(objKey); + if (arrMoreKeyMatcher.find()) { + String arrMoreObjKey = arrMoreKeyMatcher.group("key"); + Map arrMoreValue; + if (valueMap.containsKey(arrMoreObjKey)) { + arrMoreValue = (Map) valueMap.get(arrMoreObjKey); + keyHandler(arrMoreObjKey, objKey, value, arrMoreValue); + return null; + } + arrMoreValue = new HashMap<>(); + keyHandler(arrMoreObjKey, objKey, value, arrMoreValue); + valueMap.put(arrMoreObjKey, arrMoreValue); + return null; + } + arrMoreKey = "(?(\\w+))(\\[(?([0-9])+)])$"; + arrMoreKeyCompile = Pattern.compile(arrMoreKey); + arrMoreKeyMatcher = arrMoreKeyCompile.matcher(objKey); + if (arrMoreKeyMatcher.find()) { + String arrMoreArrKey = arrMoreKeyMatcher.group("key"); + int arrMoreIndex = Integer.parseInt(arrMoreKeyMatcher.group("index")); + List arrMoreListValue; + if (valueMap.containsKey(arrMoreArrKey)) { + // 存在值 + arrMoreListValue = (List) valueMap.get(arrMoreArrKey); + if (arrMoreIndex >= arrMoreListValue.size()) { + arrMoreListValue.add(prop2MapPutValue(value)); + } else { + arrMoreListValue.set(arrMoreIndex, prop2MapPutValue(value)); + } + return null; + } + arrMoreListValue = new ArrayList<>(); + arrMoreListValue.add(prop2MapPutValue(value)); + valueMap.put(arrMoreArrKey, arrMoreListValue); + return null; + } + + // 直接添加 + valueMap.put(objKey, prop2MapPutValue(value)); + return null; + } + // 不存在 + mapList = new ArrayList<>(); + Map valueMap = new HashMap<>(); + valueMap.put(objKey, prop2MapPutValue(value)); + mapList.add(valueMap); + preResult.put(arrKey, mapList); + } + return null; + } + + public static Object prop2MapPutValue(Object value) { + if (value == null) { + return null; + } + String valueStr = String.valueOf(value).trim(); + if (valueStr.startsWith("\"") && valueStr.endsWith("\"")) { + return valueStr.substring(1, valueStr.length() - 1); + } + if (valueStr.contains(",")) { + if (valueStr.contains("\\,")) { + String[] split = valueStr.split("(? getProperties2Map(String fileName, String prefix) { + String propertyPath = GCONST.getPropertyPath(); + if (StringUtil.isNullOrEmpty(fileName)) { + return null; + } + if (fileName.contains(".properties")) { + fileName.replace(".properties", ""); + } + String path = propertyPath + "prop2map" + File.separator + fileName + ".properties"; + Properties prop = new Properties(); + Map map = new HashMap<>(); + InputStream inputStream = null; + try { + inputStream = new BufferedInputStream(new FileInputStream(path)); + prop.load(inputStream); + Enumeration enumeration = prop.propertyNames(); + while (enumeration.hasMoreElements()) { + String key = (String) enumeration.nextElement(); + if (key.contains(prefix + ".")) { + map.put(key.replace(prefix + ".", ""), prop.getProperty(key)); + } + } + } catch (IOException e) { + throw new RuntimeException("找不到文件:" + path); + } finally { + try { + if (inputStream != null) { + inputStream.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return map; + } + + public static Map> parsingSq2Map(String sql) { + Map> map = new HashMap<>(); + String pattern = "\\{{2}(?
((?!\\$)\\s\\S)+?)\\.(?\\s\\S+?)}{2}"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(sql); + while (matcher.find()) { + if (map.containsKey(matcher.group("table"))) { + map.get(matcher.group("table")).add(matcher.group("field")); + } else { + map.put(matcher.group("table"), new ArrayList() {{ + add(matcher.group("field")); + }}); + } + } + return map; + } + + public static Matcher parsingSql2Matcher(String sql) { + String pattern = "\\{{2}(?
((?!\\$)\\s\\S)+?)\\.(?\\s\\S+?)}{2}"; + Pattern compile = Pattern.compile(pattern); + return compile.matcher(sql); + } + + public static String parsingSqlByRequestAndWorkflowId(String sql, String requestId, String workflowId) { + String requestIdPattern = "\\{{2}(\\$requestId)?}{2}"; + String workflowIdIdPattern = "\\{{2}(\\$workflowId)?}{2}"; + String result = sql.replaceAll(requestIdPattern, StringUtil.isNullOrEmpty(requestId) ? "''" : requestId); + result = result.replaceAll(workflowIdIdPattern, StringUtil.isNullOrEmpty(workflowId) ? "''" : workflowId); + return result; + } + + public static String parsingSq(String sql, Map params) { + String result = sql; + String requestIdPattern = "\\{{2}(\\$requestId)?}{2}"; + String workflowIdIdPattern = "\\{{2}(\\$workflowId)?}{2}"; + result = result.replaceAll(requestIdPattern, ObjectUtil.isNull(params.get("requestId")) ? "''" : "'" + params.get("requestId") + "'"); + result = result.replaceAll(workflowIdIdPattern, ObjectUtil.isNull(params.get("workflowId")) ? "''" : "'" + params.get("workflowId") + "'"); + for (Map.Entry param : params.entrySet()) { + String pattern_ = "#\\{{2}(" + param.getKey() + ")?}{2}"; + result = result.replaceAll(pattern_, ObjectUtil.isNull(param.getValue()) ? "''" : String.valueOf(param.getValue())); + String pattern = "\\{{2}(" + param.getKey() + ")?}{2}"; + result = result.replaceAll(pattern, ObjectUtil.isNull(param.getValue()) ? "''" : "'" + param.getValue() + "'"); + } + return result; + } + + // 去重 + public static List deWeight(List list, Function keyExtractor) { + return list.stream().filter(distinctByKey(keyExtractor)).collect(Collectors.toList()); + } + + // + private static Predicate distinctByKey(Function keyExtractor) { + Map seen = new ConcurrentHashMap<>(); + // putIfAbsent添加不存在的键,返回null,如果为null表示不重复 + return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + } + + + public static Map object2Map(Object obj) { + if (obj == null) { + return null; + } + Map map = new HashMap<>(); + try { + BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor property : propertyDescriptors) { + String key = property.getName(); + if (key.compareToIgnoreCase("class") == 0) { + continue; + } + Method getter = property.getReadMethod(); + Object value = getter != null ? getter.invoke(obj) : null; + map.put(key, value); + } + } catch (Exception e) { + e.printStackTrace(); + } + return map; + } + + + public static String getWorkflowNameById(String workflowid) { + RecordSet rs = new RecordSet(); + String sql = "select workflowname from workflow_base where id = ?"; + rs.executeQuery(sql, workflowid); + if (rs.next()) { + return rs.getString("workflowname"); + } + return ""; + } + + public static Object getRequestTitleById(String requestid) { + RecordSet rs = new RecordSet(); + String sql = "select requestnamenew from workflow_requestbase where requestid = ?"; + rs.executeQuery(sql, requestid); + if (rs.next()) { + return rs.getString("requestnamenew"); + } + return ""; + } + + + public static ApiConfigMainDTO queryApiConfig(String id) { + // System.out.println(JSON.toJSONString(apiConfigMain)); + return utilService.getApiConfigMain(id); + } + + public static ApiConfigMainDTO queryApiConfigTree(String id) { + // System.out.println(JSON.toJSONString(apiConfigMain)); + return utilService.getApiConfigMainTree(id); + } + + public static AZipOutputStream createZip(List inputList) throws IOException { + return createZip(inputList, File.separator); + } + + private static AZipOutputStream createZip(List inputList, String base) throws IOException { + FileOutputStream fileOutputStream = null; + + try { + File file = new File(AZipOutputStream.filePath); + if (!file.exists()) { + // 先得到文件的上级目录,并创建上级目录,在创建文件 + file.getParentFile().mkdirs(); + try { + // 创建文件 + file.createNewFile(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + fileOutputStream = new FileOutputStream(file); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + if (fileOutputStream == null) { + return null; + } + AZipOutputStream zipOut = new AZipOutputStream(fileOutputStream); + int catchLen = 10 * 1024; + for (int i = 0; i < inputList.size(); i++) { + T item = inputList.get(i); + if (item instanceof InputStream) { + // 属于单级文件,直接压缩并返回 + try { + zipOut.putNextEntry(new ZipEntry(base + i)); + } catch (IOException e) { + throw new IOException(e.toString()); + } + byte[] buffer = new byte[catchLen]; + int len = 0; + while ((len = ((InputStream) item).read(buffer)) != -1) { + zipOut.write(buffer, 0, len); + } + zipOut.closeEntry(); + } + if (item instanceof AInputStream) { + try { + zipOut.putNextEntry(new ZipEntry(((AInputStream) item).getFileName())); + } catch (IOException e) { + e.printStackTrace(); + } + byte[] buffer = new byte[catchLen]; + int len = 0; + while ((len = ((AInputStream) item).getInputStream().read(buffer)) != -1) { + try { + zipOut.write(buffer, 0, len); + } catch (IOException e) { + e.printStackTrace(); + } + } + zipOut.closeEntry(); + } + if (item instanceof ListZipEntity) { + ListZipEntity listZipEntity = (ListZipEntity) item; + if (listZipEntity.isDirectory()) { + // 表示属于文件夹,循环添加处理文件夹 + handlerDirectory(listZipEntity.getFileList(), zipOut, base + listZipEntity.getDirectory() + File.separator); + } else { + List aInputStreams = listZipEntity.getaInputStreamList(); + for (AInputStream aInputStream : aInputStreams) { + try { + zipOut.putNextEntry(new ZipEntry(aInputStream.getFileName())); + } catch (IOException e) { + e.printStackTrace(); + } + byte[] buffer = new byte[catchLen]; + int len = 0; + while ((len = (aInputStream.getInputStream()).read(buffer)) != -1) { + try { + zipOut.write(buffer, 0, len); + } catch (IOException e) { + e.printStackTrace(); + } + } + zipOut.closeEntry(); + } + } + } + } + return zipOut; + } + + private static void handlerDirectory(List fileList, AZipOutputStream zipOut, String base) throws IOException { + int catchLen = 10 * 1024; + for (ListZipEntity listZipEntity : fileList) { + if (listZipEntity.isDirectory()) { + // 如果是文件夹 + handlerDirectory(listZipEntity.getFileList(), zipOut, base + listZipEntity.getDirectory() + File.separator); + } else { + List aInputStreams = listZipEntity.getaInputStreamList(); + for (AInputStream aInputStream : aInputStreams) { + try { + zipOut.putNextEntry(new ZipEntry(aInputStream.getFileName())); + } catch (IOException e) { + e.printStackTrace(); + } + byte[] buffer = new byte[catchLen]; + int len = 0; + while ((len = (aInputStream.getInputStream()).read(buffer)) != -1) { + try { + zipOut.write(buffer, 0, len); + } catch (IOException e) { + e.printStackTrace(); + } + } + zipOut.closeEntry(); + } + } + } + } + + public static Map queryLanguage(int groupId, int languageId) { + return utilService.queryLanguage(groupId, languageId); + } + + public static Map queryLanguage(int groupId, HttpServletRequest request, HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + int languageId = user.getLanguage(); + return utilService.queryLanguage(groupId, languageId); + } + + + public static String getHtmlLabelName(int id, int languageId, String defaultStr) { + String htmlLabelName = SystemEnv.getHtmlLabelName(id, languageId); + return htmlLabelName == null ? defaultStr : htmlLabelName; + } + + public static String getHtmlLabelName(int id, int languageId) { + return SystemEnv.getHtmlLabelName(id, languageId); + } + + public static String getHtmlLabelName(LabelHtmlIndex labelHtmlIndex, User user) { + return Util.getHtmlLabelName(labelHtmlIndex.getLabelIndex(), + user.getLanguage(), labelHtmlIndex.getDefaultStr()); + } + + + /** + * 获取流程主表 + * + * @param workflowId + * @return + */ + public static String getMainTable(String workflowId) { + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + String query = "select tablename from workflow_bill " + + " where id in (select formid from workflow_base " + + " where id in (" + versionStringByWfid + ") )"; + rs.executeQuery(query); + rs.next(); + return rs.getString(1); + } + + + /** + * 根据流程和流程字段查询文档目录 + * + * @param workflowId + * @param docField + * @return + */ + @Deprecated + public static String getDocCategorys(String workflowId, String docField) { + RecordSet rs = new RecordSet(); + rs.executeQuery("select formid from workflow_base where id = ?", workflowId); + String formId = Util.recordeSet2Entity(rs, String.class); + String query = "select doccategory from workflow_fileupload where fieldid in (select id from workflow_billfield where fieldname = ? and billid = ?)"; + rs.executeQuery(query, docField, formId); + String docCategorys = Util.null2String(Util.recordeSet2Entity(rs, String.class)); + if (StringUtils.isNullOrEmpty(docCategorys)) { + query = "select doccategory from workflow_base where id = ?"; + rs.executeQuery(query, workflowId); + rs.next(); + docCategorys = Util.null2String(rs.getString(1)); + } + if (StringUtils.isNullOrEmpty(docCategorys)) { + docCategorys = ",,1"; + } + return docCategorys; + } + + @Deprecated + public static String getDocCategorys(int workflowId, String docField) { + return getDocCategorys(String.valueOf(workflowId), docField); + } + + /** + * 根据流程和流程字段查询文档目录 + * + * @param workflowId + * @param docFieldId + * @return + */ + @Deprecated + public static String getDocCategorysById(String workflowId, String docFieldId) { + RecordSet rs = new RecordSet(); + // rs.executeQuery("select formid from workflow_base where id = ?",workflowId); + // String formId = Util.recordeSet2Entity(rs, String.class); + String query = "select doccategory from workflow_fileupload where workflowid = ? and fieldid = ?"; + rs.executeQuery(query, workflowId, docFieldId); + String docCategorys = Util.null2String(Util.recordeSet2Entity(rs, String.class)); + if (StringUtils.isNullOrEmpty(docCategorys)) { + query = "select doccategory from workflow_base where id = ?"; + rs.executeQuery(query, workflowId); + rs.next(); + docCategorys = Util.null2String(rs.getString(1)); + } + if (StringUtils.isNullOrEmpty(docCategorys)) { + docCategorys = ",,1"; + } + return docCategorys; + } + + + /** + * 根据流程和流程字段查询文档目录 + * + * @param workflowId 流程ID + * @param docField 文档字段ID + * @param tableName 明细表名 + * @return 文档目录 + */ + public static String getDocCategorysByTable(String workflowId, String docField, String tableName) { + RecordSet rs = new RecordSet(); + rs.executeQuery("select formid from workflow_base where id = ?", workflowId); + String formId = Util.recordeSet2Entity(rs, String.class); + String query = "select doccategory from workflow_fileupload where fieldid in (select id from workflow_billfield where fieldname = ? and billid = ? and (detailtable = ? or detailtable is null))"; + if (!Strings.isNullOrEmpty(tableName) && tableName.contains("_dt")) { + query = "select doccategory from workflow_fileupload where fieldid in (select id from workflow_billfield where fieldname = ? and billid = ? and detailtable = ?)"; + } + if (Strings.isNullOrEmpty(tableName)) { + tableName = ""; + } + rs.executeQuery(query, docField, formId, tableName); + String docCategorys = Util.null2String(Util.recordeSet2Entity(rs, String.class)); + if (StringUtils.isNullOrEmpty(docCategorys)) { + query = "select doccategory from workflow_base where id = ?"; + rs.executeQuery(query, workflowId); + rs.next(); + docCategorys = Util.null2String(rs.getString(1)); + } + if (StringUtils.isNullOrEmpty(docCategorys)) { + docCategorys = ",,1"; + } + return docCategorys; + } + + public static String null2DefaultStr(Object obj, String defaultStr) { + String objStr = Util.null2String(obj); + if (StringUtils.isNullOrEmpty(objStr) && StringUtils.isNullOrEmpty(defaultStr)) { + return ""; + } + if (StringUtils.isNullOrEmpty(objStr) && !StringUtils.isNullOrEmpty(defaultStr)) { + return defaultStr; + } + return objStr; + } + + + public static T mapToObject(Map map, Class t) throws Exception { + if (map == null) { + return null; + } + T obj = t.newInstance(); + Field[] fields = obj.getClass().getDeclaredFields(); + for (Field field : fields) { + int mod = field.getModifiers(); + if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) { + continue; + } + field.setAccessible(true); + if (field.getType().equals(String.class)) { + if (map.containsKey(field.getName())) { + if (map.get(field.getName()) == null) { + field.set(obj, null); + } else { + field.set(obj, String.valueOf(map.get(field.getName()))); + } + } + continue; + } + if (field.getType().equals(Integer.class)) { + if (map.containsKey(field.getName())) { + if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { + field.set(obj, null); + } else { + field.set(obj, Integer.valueOf(String.valueOf(map.get(field.getName())))); + } + } + continue; + } + if (field.getType().equals(Boolean.class)) { + if (map.containsKey(field.getName())) { + if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { + field.set(obj, null); + } else { + field.set(obj, Boolean.valueOf(String.valueOf(map.get(field.getName())))); + } + } + continue; + } + if (field.getType().equals(Float.class)) { + if (map.containsKey(field.getName())) { + if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { + field.set(obj, null); + } else { + field.set(obj, Float.valueOf(String.valueOf(map.get(field.getName())))); + } + } + continue; + } + if (field.getType().equals(Double.class)) { + if (map.containsKey(field.getName())) { + if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { + field.set(obj, null); + } else { + field.set(obj, Double.valueOf(String.valueOf(map.get(field.getName())))); + } + } + continue; + } + if (field.getType().equals(int.class)) { + if (map.containsKey(field.getName())) { + if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { + field.set(obj, null); + } else { + field.set(obj, Integer.parseInt(String.valueOf(map.get(field.getName())))); + } + } + continue; + } + if (field.getType().equals(float.class)) { + if (map.containsKey(field.getName())) { + if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { + field.set(obj, null); + } else { + field.set(obj, Float.parseFloat(String.valueOf(map.get(field.getName())))); + } + } + continue; + } + if (field.getType().equals(double.class)) { + if (map.containsKey(field.getName())) { + if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { + field.set(obj, null); + } else { + field.set(obj, Double.parseDouble(String.valueOf(map.get(field.getName())))); + } + } + continue; + } + if (field.getType().equals(boolean.class)) { + if (map.containsKey(field.getName())) { + if (map.get(field.getName()) == null || "".equals(map.get(field.getName()))) { + field.set(obj, null); + } else { + field.set(obj, Boolean.parseBoolean(String.valueOf(map.get(field.getName())))); + } + } + continue; + } + } + return obj; + } + + public static T strMapToObject(Map map, Class t) throws Exception { + if (map == null) { + return null; + } + T obj = t.newInstance(); + Field[] fields = obj.getClass().getDeclaredFields(); + for (Field field : fields) { + int mod = field.getModifiers(); + if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) { + continue; + } + field.setAccessible(true); + if (map.containsKey(field.getName())) { + field.set(obj, map.get(field.getName())); + } + } + return obj; + } + + /** + * 获取完整的错误信息 + * + * @param throwable 异常 + * @return 完整堆栈信息 + */ + public static String getErrString(Throwable throwable) { + StringWriter stringWriter = new StringWriter(); + throwable.printStackTrace(new PrintWriter(stringWriter, true)); + String errStr = stringWriter.getBuffer().toString(); + try { + stringWriter.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return errStr; + } + + /** + * 获取RecordSetUtil的SQL代理类对象 + * + * @param t + * @param + * @return + */ + public static T getMapper(Class t) { + return recordsetUtil.getMapper(t); + } + + /** + *

getTransMapper 获取事务对象mapper

+ * 2022/12/21 22:45 + * ************************************************************ + * + * @param t 类 + * @param 代理类 + * @return T + * @author youHong.ai ****************************************** + */ + public static T getTransMapper(Class t) { + return recordsetTransUtil.getMapper(t, false); + } + + /** + *

commitTransMapper 提交事务mapper的事务

+ * 2022/12/21 22:46 + * ************************************************************ + * + * @return boolean 是否提交成功 + * @author youHong.ai ****************************************** + */ + public static boolean commitTransMapper(Class t) { + if (t == null) { + throw new NullPointerException("can not commit trans for null mapper proxy!"); + } + if (t.getAnnotation(SqlMapper.class) == null) { + throw new BindingException("can not find SqlMapper annotation!"); + } + return recordsetTransUtil.getRsManager().commit(t.getName()); + } + + /** + *

rollbackTransMapper 回滚事务mapper 的事务

+ * 2022/12/21 22:46 + * ************************************************************ + * + * @return boolean 是否回滚成功 + * @author youHong.ai ****************************************** + */ + public static boolean rollbackTransMapper(Class t) { + if (t == null) { + throw new NullPointerException("can not commit trans for null mapper proxy!"); + } + if (t.getAnnotation(SqlMapper.class) == null) { + throw new BindingException("can not find SqlMapper annotation!"); + } + return recordsetTransUtil.getRsManager().rollback(t.getName()); + } + + /** + * join方法 + * + * @param coll + * @param split + * @return + */ + public static String join(Collection coll, String split) { + if (CollectionUtils.isEmpty(coll)) { + return ""; + } else { + StringBuilder sb = new StringBuilder(); + boolean isFirst = true; + + String s; + for (Iterator item = coll.iterator(); item.hasNext(); sb.append(s)) { + s = item.next(); + if (isFirst) { + isFirst = false; + } else { + sb.append(split); + } + } + return sb.toString(); + } + } + + /** + * join方法 + * + * @param coll + * @param split + * @return + */ + public static String joinEach(Collection coll, String split) { + if (CollectionUtils.isEmpty(coll)) { + return ""; + } else { + StringBuilder sb = new StringBuilder(); + boolean isFirst = true; + + String s; + for (Iterator item = coll.iterator(); item.hasNext(); sb.append(s)) { + s = (String) item.next(); + if (isFirst) { + isFirst = false; + } else { + sb.append(split); + } + } + return sb.toString(); + } + } + + /** + * 将数组使用指定的分隔符链接为字符串 + * + * @param coll 集合 + * @param split 分隔符 + * @return 字符串 + */ + public static String intJoin(Collection coll, String split) { + if (CollectionUtils.isEmpty(coll)) { + return ""; + } else { + StringBuilder sb = new StringBuilder(); + boolean isFirst = true; + + String s; + for (Iterator item = coll.iterator(); item.hasNext(); sb.append(s)) { + Object next = item.next(); + s = next == null ? "" : String.valueOf(next); + if (isFirst) { + isFirst = false; + } else { + sb.append(split); + } + } + + return sb.toString(); + } + } + + /** + * 获取日志对象 + * + * @return 日志对象 + */ + public static Logger getLogger() { + if (log == null) { + synchronized (Util.class) { + if (log == null) { + DailyRollingFileAppender appender = new DailyRollingFileAppender(); + log = Logger.getLogger("ayh_cus"); + appender.setName("ayh_cus"); + appender.setEncoding("UTF-8"); + appender.setDatePattern("'_'yyyyMMdd'.log'"); + appender.setFile(weaver.general.GCONST.getLogPath() + "cus" + File.separator + "util_cus" + File.separator + "cus.log"); + appender.setThreshold(Priority.DEBUG); + appender.setLayout(new PatternLayout("[%-5p] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%r] [Thread:%t][%F.%M:%L] ==> : %m %x %n")); + appender.setAppend(true); + appender.activateOptions(); + log.addAppender(appender); + log.setAdditivity(false); + log.setLevel(Level.INFO); /* boolean enableDebug = false; try { @@ -2152,35 +2152,35 @@ public class Util extends weaver.general.Util { log.setLevel(Level.INFO); } */ - } - } - } - return log; - } - - - public static Logger getLogger(String name) { - - if (otherLog.containsKey(name)) { - return otherLog.get(name); - } - if (!otherLog.containsKey(name)) { - synchronized (Util.otherLog) { - if (otherLog.containsKey(name)) { - return otherLog.get(name); - } - DailyRollingFileAppender appender = new DailyRollingFileAppender(); - Logger cusLog = Logger.getLogger("cus_" + name); - appender.setName("cus_" + name); - appender.setEncoding("UTF-8"); - appender.setDatePattern("'_'yyyyMMdd'.log'"); - appender.setFile(weaver.general.GCONST.getLogPath() + "cus" + File.separator + name + File.separator + "cus.log"); - appender.setThreshold(Priority.DEBUG); - appender.setLayout(new PatternLayout("[%-5p] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%r] [Thread:%t][%F.%M:%L] ==> : %m %x %n")); - appender.setAppend(true); - appender.activateOptions(); - cusLog.addAppender(appender); - cusLog.setAdditivity(false); + } + } + } + return log; + } + + + public static Logger getLogger(String name) { + + if (otherLog.containsKey(name)) { + return otherLog.get(name); + } + if (!otherLog.containsKey(name)) { + synchronized (Util.otherLog) { + if (otherLog.containsKey(name)) { + return otherLog.get(name); + } + DailyRollingFileAppender appender = new DailyRollingFileAppender(); + Logger cusLog = Logger.getLogger("cus_" + name); + appender.setName("cus_" + name); + appender.setEncoding("UTF-8"); + appender.setDatePattern("'_'yyyyMMdd'.log'"); + appender.setFile(weaver.general.GCONST.getLogPath() + "cus" + File.separator + name + File.separator + "cus.log"); + appender.setThreshold(Priority.DEBUG); + appender.setLayout(new PatternLayout("[%-5p] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%r] [Thread:%t][%F.%M:%L] ==> : %m %x %n")); + appender.setAppend(true); + appender.activateOptions(); + cusLog.addAppender(appender); + cusLog.setAdditivity(false); /* boolean enableDebug = false; try { @@ -2199,1357 +2199,1353 @@ public class Util extends weaver.general.Util { cusLog.setLevel(Level.INFO); } */ - cusLog.setLevel(Level.INFO); - otherLog.put(name, cusLog); - return cusLog; - } - } - return null; - } - - /** - * 查询自定义配置参数值 - * - * @param onlyMark 唯一标识 - * @return 参数值 - */ - public static String getCusConfigValue(String onlyMark) { - return mapper.selectCusConfigParam(onlyMark, UF_CUS_DEV_CONFIG); - } - - /** - * 查询自定义配置参数值 - * - * @param onlyMark 唯一标识 - * @return 参数值 - */ - public static String getCusConfigValue(String onlyMark, String configTable) { - return mapper.selectCusConfigParam(onlyMark, configTable); - } - - /** - *

更新或插入自定义配置参数

- * - * @param onlyMark 唯一标识 - * @param value 参数值 - * @param desc 描述信息 - * @return 是否插入成功 - */ - public static boolean insertOrUpdateConfigValue(String onlyMark, String value, String desc) { - String selectValue = getCusConfigValue(onlyMark); - if (Util.isNullOrEmpty(selectValue)) { - String modeId = getModeIdByTableName(UF_CUS_DEV_CONFIG); - int dataId = getModeDataId(UF_CUS_DEV_CONFIG, Integer.parseInt(modeId), 1); - boolean success = mapper.updateConfigValueById(onlyMark, value, desc, String.valueOf(dataId), UF_CUS_DEV_CONFIG); - rebuildModeDataShare(1, Integer.valueOf(modeId), dataId); - return success; - } - return mapper.updateConfigValueByOnlyMark(onlyMark, value, desc, UF_CUS_DEV_CONFIG); - } - - public static boolean insertOrUpdateConfigValue(String onlyMark, String value, String desc, String configTable) { - String selectValue = mapper.selectCusConfigParam(onlyMark, configTable); - if (Util.isNullOrEmpty(selectValue)) { - String modeId = getModeIdByTableName(UF_CUS_DEV_CONFIG); - int dataId = getModeDataId(UF_CUS_DEV_CONFIG, Integer.parseInt(modeId), 1); - boolean success = mapper.updateConfigValueById(onlyMark, value, desc, String.valueOf(dataId), configTable); - rebuildModeDataShare(1, Integer.valueOf(modeId), dataId); - return success; - } - return mapper.updateConfigValueByOnlyMark(onlyMark, value, desc, configTable); - } - - /** - * 获取自定义配置参数值 - * - * @param onlyMark 唯一标识 - * @param defaultStr 默认值 - * @return 参数值 - */ - public static String getCusConfigDefaultValue(String onlyMark, String defaultStr) { - String cusConfigValue = getCusConfigValue(onlyMark); - return cusConfigValue == null ? defaultStr : cusConfigValue; - } - - /** - * 获取自定义配置参数值 - * - * @param onlyMark 唯一标识 - * @param defaultStr 默认值 - * @return 参数值 - */ - public static String getCusConfigValueNullOrEmpty(String onlyMark, String defaultStr) { - String cusConfigValue = getCusConfigValue(onlyMark); - return StringUtils.isNullOrEmpty(cusConfigValue) ? defaultStr : cusConfigValue; - } - - - /** - * 将list转化为树形list - * - * @param dataList 元数据 - * @param getIdFn 获取元数据的id - * @param getParentId 获取父类id的方法 - * @param setChildFn 设置子结点方法 - * @param predicate 判断是否属于根结点的方法 - * @param list的泛型 - * @param 元数据id的泛型 - * @return 树形的list - */ - public static List listToTree(List dataList, Function getIdFn, - Function getParentId, BiConsumer setChildFn, Predicate predicate) { - if (dataList == null || dataList.isEmpty() || dataList.size() == 1) { - return dataList; - } - return buildTree(dataList, new HashMap<>(dataList.size()), new HashMap<>(dataList.size()), 0, - getIdFn, getParentId, setChildFn, predicate); - } - - /** - * 将list转化为树形list - * - * @param dataList 元数据 - * @param getIdFn 获取元数据的id - * @param getParentId 获取父类id的方法 - * @param setChildFn 设置子结点方法 - * @param getChildFn 获取子结点方法 - * @param predicate 判断是否属于根结点的方法 - * @param list的泛型 - * @param 元数据id的泛型 - * @return 树形的list - */ - public static List listToTree(List dataList, Function getIdFn, - Function getParentId, Function> getChildFn, - BiConsumer> setChildFn, Predicate predicate) { - if (dataList == null || dataList.isEmpty() || dataList.size() == 1) { - return dataList; - } - return buildTree(dataList, new HashMap<>(dataList.size()), new HashMap<>(dataList.size()), - 0, getIdFn, getParentId, getChildFn, setChildFn, predicate); - } - - /** - * 将list转为树形list - * - * @param dataList 元数据list - * @param dataMap 数据map - * @param childMap 已添加过的子元素 - * @param index 从第几个开始格式化 - * @param getIdFn 获取id的方法 - * @param getParentId 获取父类id的方法 - * @param setChildFn 设置孩子节点的方法 - * @param predicate 判断是否属于根节点的方法 - * @param list的泛型 - * @param 泛型的id的类型 - * @return 树形结构 - */ - - private static List buildTree(List dataList, Map dataMap, Map childMap, int index, Function getIdFn, - Function getParentId, BiConsumer setChildFn, - Predicate predicate) { - List treeList = new ArrayList<>(dataList.size()); - while (index < dataList.size()) { - T item = dataList.get(index); - index++; - K id = getIdFn.apply(item); - K parentId = getParentId.apply(item); - if (dataMap.containsKey(id)) { - continue; - } - dataMap.put(id, item); - // 判断是否属于根节点,如果是根节点,则将数据添加到树中 - if (predicate.test(parentId)) { - if (childMap.containsKey(id)) { - continue; - } - treeList.add(item); - childMap.put(id, item); - } else { - // 如果不是根节点,则通过id查找到父级 - T parent = dataMap.get(parentId); - if (Objects.isNull(parent)) { - // 如果父级为空,则说明他的父级还没有遍历到,需要从之后的数据进行遍历,直到找到父级为止 - List list = buildTree(dataList, dataMap, childMap, index, getIdFn, getParentId, setChildFn, predicate); - parent = dataMap.get(parentId); - if (Objects.isNull(parent)) { - // 如果还是没有查询到父节点,则表明是顶层节点,将他添加到顶层节点中 - treeList.add(item); - } else { - // 如果找到了父节点,则将自己挂到父节点上 - if (childMap.containsKey(id)) { - continue; - } - setChildFn.accept(parent, item); - childMap.put(id, item); - } - // 如果查找的list不为空并且有值,那就说明属于根节点 - if (list != null && list.size() > 0) { - treeList.addAll(list); - } - } else { - // 如果找到了父节点,则将自己挂到父节点上 - if (childMap.containsKey(id)) { - continue; - } - setChildFn.accept(parent, item); - childMap.put(id, item); - } - } - } - return treeList; - } - - - /** - * 将list转为树形list - * - * @param dataList 元数据list - * @param dataMap 数据map - * @param childMap 已添加过的子元素 - * @param index 从第几个开始格式化 - * @param getIdFn 获取id的方法 - * @param getParentId 获取父类id的方法 - * @param getChildFn 获取子结点方法 - * @param setChildFn 设置孩子节点的方法 - * @param predicate 判断是否属于根节点的方法 - * @param list的泛型 - * @param 泛型的id的类型 - * @return 树形结构 - */ - private static List buildTree(List dataList, Map dataMap, Map childMap, int index, Function getIdFn, - Function getParentId, Function> getChildFn, - BiConsumer> setChildFn, Predicate predicate) { - List treeList = new ArrayList<>(dataList.size()); - while (index < dataList.size()) { - T item = dataList.get(index); - index++; - K id = getIdFn.apply(item); - K parentId = getParentId.apply(item); - if (dataMap.containsKey(id)) { - continue; - } - dataMap.put(id, item); - // 判断是否属于根节点,如果是根节点,则将数据添加到树中 - if (predicate.test(parentId)) { - if (childMap.containsKey(id)) { - continue; - } - treeList.add(item); - childMap.put(id, item); - } else { - // 如果不是根节点,则通过id查找到父级 - T parent = dataMap.get(parentId); - if (Objects.isNull(parent)) { - // 如果父级为空,则说明他的父级还没有遍历到,需要从之后的数据进行遍历,直到找到父级为止 - List list = buildTree(dataList, dataMap, childMap, index, getIdFn, getParentId, getChildFn, setChildFn, predicate); - parent = dataMap.get(parentId); - if (Objects.isNull(parent)) { - // 如果还是没有查询到父节点,则表明是顶层节点,将他添加到顶层节点中 - treeList.add(item); - } else { - // 如果找到了父节点,则将自己挂到父节点上 - if (childMap.containsKey(id)) { - continue; - } - List childList = Optional.ofNullable(getChildFn.apply(parent)).orElse(new ArrayList<>()); - childList.add(item); - setChildFn.accept(parent, childList); - childMap.put(id, item); - } - // 如果查找的list不为空并且有值,那就说明属于根节点 - if (list != null && list.size() > 0) { - treeList.addAll(list); - } - } else { - // 如果找到了父节点,则将自己挂到父节点上 - if (childMap.containsKey(id)) { - continue; - } - List childList = Optional.ofNullable(getChildFn.apply(parent)).orElse(new ArrayList<>()); - childList.add(item); - setChildFn.accept(parent, childList); - childMap.put(id, item); - } - } - } - return treeList; - } - - /** - * 复制java bean中的基本属性,引用类型除外 - * - * @param source 原对象 - * @param target 目标对象 - * @param 原对象泛型 - * @param 目标对象泛型 - * @return 复制后的目标对象 - */ - public static K copyBeanBaseField(T source, K target) { - if (Objects.isNull(source)) { - return target; - } - if (Objects.isNull(target)) { - throw new RuntimeException("target is null, You cannot pass a null bean"); - } - BeanInfo beanInfo = null; - try { - beanInfo = Introspector.getBeanInfo(target.getClass()); - } catch (IntrospectionException e) { - e.printStackTrace(); - } - if (Objects.isNull(beanInfo)) { - throw new RuntimeException("无法获取对象信息!can not get bean info"); - } - Class sourceClass = source.getClass(); - PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); - for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { - Method writeMethod = propertyDescriptor.getWriteMethod(); - String name = propertyDescriptor.getName(); - if (writeMethod == null) { - continue; - } - try { - Field sourceClassField = sourceClass.getDeclaredField(name); - Class propertyType = propertyDescriptor.getPropertyType(); - Class classFieldType = sourceClassField.getType(); - if (propertyType.equals(classFieldType)) { - Method getMethod = sourceClass.getMethod("get" + name.substring(0, 1).toUpperCase() + name.substring(1)); - Object invoke = getMethod.invoke(source); - writeMethod.invoke(target, invoke); - } - } catch (NoSuchFieldException | IllegalAccessException | InvocationTargetException ignored) { - } catch (NoSuchMethodException e) { - throw new RuntimeException("invoke method err, cant not invoke method set" + name.substring(0, 1).toUpperCase() + name.substring(1)); - } - } - // TODO 复制bean - return target; - } - - /** - * 随机数字字符串 - * - * @param length 长度 - * @return 随机字符串 - */ - public static String randomNumber(int length) { - return creatRandom("0123456789", length); - } - - /** - * 随机家字符串 - * - * @param length 长度 - * @return 随机字符串 - */ - public static String randomString(int length) { - return creatRandom("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", length); - } - - /** - * 生成随机英文字符 - * - * @param length 长度 - * @return 随机字符串 - */ - public static String randomLetter(int length) { - return creatRandom("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", length); - } - - - /** - * 创建随机字符串 - * - * @param randomStr 随机字符串范围 - * @param length 长度 - * @return 随机字符串 - */ - public static String creatRandom(String randomStr, int length) { - StringBuffer sb = new StringBuffer(); - Random random = new Random(); - for (int i = 0; i < length; i++) { - int rand = random.nextInt(randomStr.length()); - sb.append(randomStr.charAt(rand)); - } - return sb.toString(); - } - - /** - * 获取建模模块ID通过表名 - * - * @param tableName 表名 - * @return 模块ID - */ - public static String getModeIdByTableName(String tableName) { - String modeId = ""; - String querySql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = ?)"; - RecordSet recordSet = new RecordSet(); - recordSet.executeQuery(querySql, tableName); - if (recordSet.next()) { - modeId = Util.null2String(recordSet.getString("id")); - } - return modeId; - } - - /** - * 获取建模表数据ID - * - * @param tableName 表名 - * @param formModeId 模块ID - * @param userId 用户ID - * @return 数据ID - */ - public static int getModeDataId(String tableName, int formModeId, int userId) { - return mdu.getModeDataNewId(tableName, formModeId, userId, 0, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString()); - } - - /** - * 获取建模表数据ID - * - * @param tableName 表名 - * @param userId 用户ID - * @return 数据ID - */ - public static int getModeDataId(String tableName, int userId) { - return mdu.getModeDataNewId(tableName, Integer.parseInt(getModeIdByTableName(tableName)), userId, 0, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString()); - } - - /** - * 建模表数据权限重构 - * - * @param userId 用户ID - * @param formId 表单ID - * @param id 数据ID - */ - public static void rebuildModeDataShare(Integer userId, Integer formId, Integer id) { - MODE_RIGHT_INFO.rebuildModeDataShareByEdit(userId, formId, id); - } - - /** - * 建模表数据权限重构 - * - * @param userId 用户ID - * @param tableName 表单名称 - * @param id 数据ID - */ - public static void rebuildModeDataShare(Integer userId, String tableName, Integer id) { - MODE_RIGHT_INFO.rebuildModeDataShareByEdit(userId, Integer.parseInt(getModeIdByTableName(tableName)), id); - } - - /** - * 异步权限重构数据 - * - * @param userId 用户ID - * @param formId 表单ID - * @param id 数据ID - */ - public static void rebuildModeDataShareByAsync(Integer userId, Integer formId, Integer id) { - threadPool.execute(() -> Util.rebuildModeDataShare(userId, formId, id)); - } - - /** - * 异步权限重构数据 - * - * @param userId 用户ID - * @param tableName 表单名称 - * @param id 数据ID - */ - public static void rebuildModeDataShareByAsync(Integer userId, String tableName, Integer id) { - threadPool.execute(() -> Util.rebuildModeDataShare(userId, Integer.parseInt(getModeIdByTableName(tableName)), id)); - } - - /** - * 异步权限重构数据 - * - * @param userId 用户ID - * @param formId 表单ID - * @param idList 数据ID - */ - public static void rebuildModeDataShareByAsyncList(Integer userId, Integer formId, List idList) { - threadPool.execute(() -> { - for (Integer id : idList) { - Util.rebuildModeDataShare(userId, formId, id); - } - }); - } - - - /** - * 异步权限重构数据 - * - * @param userId 用户ID - * @param tableName 表单名称 - * @param idList 数据ID - */ - public static void rebuildModeDataShareByAsyncList(Integer userId, String tableName, List idList) { - threadPool.execute(() -> { - for (Integer id : idList) { - Util.rebuildModeDataShare(userId, Integer.parseInt(getModeIdByTableName(tableName)), id); - } - }); - } - - - /** - * 生成文件并创建文档信息,权限继承文档目录 - * - * @param fileName 文件名称 - * @param seccategory 目录ID - * @param inputStream 文件流 - * @return 创建的文档信息 - * @throws Exception 异常细信息 - */ - public static int createDoc(String fileName, int seccategory, InputStream inputStream, Integer userId) throws Exception { - int imageFileId = createFileByInputSteam(inputStream, fileName); - return createDocByImageFileId(fileName, seccategory, imageFileId, userId); - } - - - public static int createDocByImageFileId(int seccategory, int imageFileId, Integer userId) throws Exception { - String fileName = mapper.selectFileNameByImageFileId(imageFileId); - return createDocByImageFileId(fileName, seccategory, imageFileId, userId); - } - - /** - * 创建文件信息,文件权限继承文档目录权限 - * - * @param fileName 文件名称 - * @param seccategory 文件目录 - * @param imageFileId 物理文件ID - * @param userId 用户ID - * @return 文档ID - * @throws Exception 可能会出现的异常 - */ - - - public static int createDocByImageFileId(String fileName, int seccategory, int imageFileId, Integer userId) throws Exception { - DocInfo docInfo = new DocInfo(); - docInfo.setImagefileId(imageFileId); - docInfo.setSeccategory(seccategory); - docInfo.setDocSubject(fileName); - docInfo.setDoccontent(""); - DocServiceImpl docService = new DocServiceImpl(); - int docId = docService.createDocByUser(docInfo, new User(userId)); - DocImageManager imgManger = new DocImageManager(); - imgManger.resetParameter(); - imgManger.setDocid(docId); - imgManger.setImagefileid(imageFileId); - imgManger.setImagefilename(fileName); - imgManger.setIsextfile("1"); - String ext = fileName.substring(fileName.lastIndexOf(".") + 1); - if ("doc".equalsIgnoreCase(ext)) { - imgManger.setDocfiletype("3"); - } else if ("xls".equalsIgnoreCase(ext)) { - imgManger.setDocfiletype("4"); - } else if ("ppt".equalsIgnoreCase(ext)) { - imgManger.setDocfiletype("5"); - } else if ("wps".equalsIgnoreCase(ext)) { - imgManger.setDocfiletype("6"); - } else if ("docx".equalsIgnoreCase(ext)) { - imgManger.setDocfiletype("7"); - } else if ("xlsx".equalsIgnoreCase(ext)) { - imgManger.setDocfiletype("8"); - } else if ("pptx".equalsIgnoreCase(ext)) { - imgManger.setDocfiletype("9"); - } else { - imgManger.setDocfiletype("2"); - } - imgManger.AddDocImageInfo(); - return docId; - } - - - public static String builderUpdateSql(String modelTableName, Map mapping) { - StringBuilder sb = new StringBuilder("update "); - sb.append(modelTableName) - .append(" set "); - int n = 0; - for (Map.Entry entry : mapping.entrySet()) { - n++; - sb.append(entry.getKey()).append("=#{").append(entry.getKey()).append("}"); - if (n < mapping.size()) { - sb.append(","); - } - } - return sb.toString(); - } - - - /** - *

提交流程

- * - * @param requestId 流程请求ID - * @param userId 用户ID - * @param remark 签字意见 - * @return - */ - public static boolean submitWorkflow(Integer requestId, Integer userId, String remark) { - RequestService requestService = new RequestService(); - RequestInfo req = requestService.getRequest(requestId); - if (remark == null) { - remark = "流程自动提交"; - } - return requestService.nextNodeBySubmit(req, requestId, userId, remark); - } - - /** - *

异步提交流程,一般作用于action在节点前

- * - * @param requestId 流程ID - * @param userId 用户id - * @param remark 签字意见 - */ - public static void submitWorkflowThread(Integer requestId, Integer userId, String remark) { - submitWorkflowThread(requestId, userId, remark, 60); - } - - /** - *

异步提交流程,一般作用于action在节点前

- * - * @param requestId 流程ID - * @param userId 用户id - * @param remark 签字意见 - * @param seconds 延时多少秒提交 - */ - public static void submitWorkflowThread(Integer requestId, Integer userId, String remark, int seconds) { - if (seconds <= 0) { - seconds = 1; - } - int finalSeconds = seconds; - new Thread(() -> { - try { - Thread.sleep(1000 * finalSeconds); - } catch (InterruptedException e) { - e.printStackTrace(); - Util.getLogger().error("线程休眠失败", e); - } - int n = 0; - while (!Util.submitWorkflow(requestId, userId, remark)) { - n++; - try { - Thread.sleep(1000 * 10); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if (n > 5) { - Util.getLogger().error("异步流程自动提交失败!"); - break; - } - } - }).start(); - } - - /** - *

通过流程信息(RequestInfo)提交流程

- * - * @param requestInfo requestInfo对象 - * @param userId 用户id - * @param remark 提交签字意见 - * @return 是否提交成功 - */ - public static boolean submitWorkflowByRequestInfo(RequestInfo requestInfo, Integer userId, String remark) { - RequestService requestService = new RequestService(); - if (remark == null) { - remark = "流程自动提交"; - } - return requestService.nextNodeBySubmit(requestInfo, Integer.parseInt(requestInfo.getRequestid()), userId, remark); - } - - - /** - * 全角转半角 - * - * @param src 全角字符 - * @return 半角字符 - */ - public static char sbc2dbc(char src) { - if (src == SBC_SPACE) { - return DBC_SPACE; - } - - if (src >= UNICODE_START && src <= UNICODE_END) { - return (char) (src - DBC_SBC_STEP); - } - - return src; - } - - /** - * 全角转半角 - * - * @param src 全角字符串 - * @return DBC case - */ - public static String sbc2dbcCase(String src) { - if (src == null) { - return null; - } - char[] c = src.toCharArray(); - for (int i = 0; i < c.length; i++) { - c[i] = sbc2dbc(c[i]); - } - return new String(c); - } - - /** - * 半角转全角 - * - * @param src 半角字符 - * @return SBC case - */ - public static char dbc2sbc(char src) { - if (src == DBC_SPACE) { - return SBC_SPACE; - } - if (src <= ASCII_END) { - return (char) (src + DBC_SBC_STEP); - } - return src; - } - - /** - * 半角转全角 - * - * @param src 半角字符 - * @return SBC case string - */ - public static String dbc2sbcCase(String src) { - if (src == null) { - return null; - } - - char[] c = src.toCharArray(); - for (int i = 0; i < c.length; i++) { - c[i] = dbc2sbc(c[i]); - } - - return new String(c); - } - - /** - *

通过流程Id查询流程主表表明

- * - * @param workflowId 流程id - * @return 流程表名 - */ - public static String getWorkflowMainTable(String workflowId) { - return mapper.selectWorkfowMainTable(workflowId); - } - - /** - * 创建物理文件 - * - * @param content 文件流 - * @param fileName 文件名 - * @return 文件id - */ - public static int createFileByInputSteam(InputStream content, String fileName) { - ImageFileManager imageFileManager = new ImageFileManager(); - int imgFileId; - try { - Method saveImageFileByInputStream = ImageFileManager.class.getMethod("saveImageFileByInputStream", InputStream.class, String.class); - imgFileId = (int) saveImageFileByInputStream.invoke(imageFileManager, content, fileName); - } catch (NoSuchMethodException e) { - imageFileManager.setImagFileName(fileName); - try { - imageFileManager.setData(IOUtils.toBytes(content)); - } catch (Exception ex) { - throw new CustomerException("创建文件失败,文件流转换失败", e); - } - imgFileId = imageFileManager.saveImageFile(); - } catch (Exception e) { - throw new CustomerException("创建文件失败"); - } - return imgFileId; - } - - /** - * 流程失败返回 - * - * @param requestManager 流程请求管理 - * @param msg 失败信息 - * @return 失败 - */ - public static String actionFail(RequestManager requestManager, String msg) { - requestManager.setMessageid(System.currentTimeMillis() + ""); - requestManager.setMessagecontent(msg); - return Action.FAILURE_AND_CONTINUE; - } - - /** - * 流程失败返回 - * - * @param requestManager 流程请求管理 - * @param msg 失败信息 - * @return 失败 - */ - public static String actionFailException(RequestManager requestManager, String msg) { - requestManager.setMessageid(System.currentTimeMillis() + ""); - requestManager.setMessagecontent(msg); - throw new CustomerException(msg, 500); - } - - /** - * 查询文档信息 - * - * @param docId 文档ID - * @return 文档信息 - */ - public static DocImageInfo selectImageInfoByDocId(String docId) { - return mapper.selectDocImageInfo(docId); - } - - /** - * 查询文档信息 - * - * @param docIds 文档ID - * @return 文档信息 - */ - public static List selectImageInfoByDocIds(String docIds) { - return mapper.selectDocImageInfos(docIds); - } - - /** - * 查询流程节点配置 - * - * @param allVersion 流程所有版本第 - * @param markOnly 唯一标识 - * @return 流程节点配置 - */ - public static WorkflowNodeConfig selectNodeConfig(String allVersion, String markOnly) { - return mapper.selectNodeConfig(allVersion, markOnly); - } - - /** - * 查询下拉框选项信息 - * - * @param tableName 表名 - * @param fileName 字段名 - * @return 下拉选项框值信息 - */ - public static List getSelectFiledValue(String tableName, String fileName) { - return mapper.selectSelectFieldValue(tableName, fileName); - } - - /** - * 通过下拉框选项值查询显示名 - * - * @param tableName 表名 - * @param fileName 字段名 - * @param value 下拉框选项值 - * @return 显示名 - */ - public static String getSelectFiledValueByValue(String tableName, String fileName, String value) { - return mapper.selectSelectFieldValueByValue(tableName, fileName, value); - } - - /** - * 判断字符串是否为空 - * - * @param str 判断字符串 - * @return 空标识 - */ - public static boolean isNullOrEmpty(String str) { - return str == null || str.length() == 0; - } - - /** - * 必填字段验证 - * - * @param obj 验证对象 - * @param 范型 - * @return 是否通过验证 - */ - public static boolean verifyRequiredField(T obj) throws CustomerException { - if (obj == null) { - return false; - } - Class aClass = obj.getClass(); - List entityFields = getEntityFields(aClass); - if (entityFields == null) { - return false; - } - Map printParam = new HashMap<>(); - for (Field field : entityFields) { - String modifiers = Modifier.toString(field.getModifiers()); - if (modifiers.contains("static") || modifiers.contains("final")) { - continue; - } - RequiredMark annotation = field.getAnnotation(RequiredMark.class); - PrintParamMark printParamMark = field.getAnnotation(PrintParamMark.class); - Object value = null; - field.setAccessible(true); - try { - value = field.get(obj); - if (printParamMark != null) { - printParam.put(field.getName(), value); - } - } catch (IllegalAccessException e) { - return false; - } - if (annotation != null) { - String valueStr = null2String(value); - if (isNullOrEmpty(valueStr)) { - throw new CustomerException("参数校验未通过,字段必填[ " + field.getName() + " ]未填写: " + annotation.value()); - } - } - } - if (printParam.size() > 0) { - - getLogger().info(Util.logStr("Acton[{}]参数:\n{}", obj.getClass().toString(), - JSONObject.toJSONString(printParam, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); - } - return true; - } - - /** - * 通过文件ID数组删除文件 - * - * @param integers 文件id数组 - */ - public static void deleteImageFile(List integers) { - for (Integer integer : integers) { - deleteImageFile(integer); - } - } - - /** - * 通过文件id删除文件 - * - * @param imageFileId 文件ID - */ - public static void deleteImageFile(Integer imageFileId) { - Map imageInfo = mapper.selectFileInfoByImageFileId(imageFileId); - String filerealpath = String.valueOf(imageInfo.get("filerealpath")); - File file = new File(filerealpath); - if (file.exists()) { - file.delete(); - } - mapper.deleteImageFileInfo(imageFileId); - } - - /** - *

将日期字符串转换为Date对象

- * - * @param dateStr 日期字符串 - * @return 日期对象 - */ - public static Date parseDate(String dateStr) { - ThreadLocal SIMPLE_DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd")); - if (dateStr == null || dateStr.length() == 0) { - return null; - } - String regex = "\\/|\\.|年|月|日"; - Date date = null; - try { - date = SIMPLE_DATE_FORMAT.get().parse(dateStr.replaceAll(regex, "-")); - return date; - } catch (ParseException e) { - // TODO Auto-generated catch block - throw new CustomerException("无法将" + dateStr + "转换为日期对象!", e); - } finally { - SIMPLE_DATE_FORMAT.remove(); - } - } - - /** - *

格式化日期字符串为指定格式的日期字符串

- * - * @param dateStr 源日期字符串 - * @param formatStr 目标日期字符串的格式 - * @return 目标日期字符串的格式 - */ - public static String formatDate(String dateStr, String formatStr) { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr); - return simpleDateFormat.format(parseDate(dateStr)); - } - - /** - * 构建日志字符串 - * - * @param logStr 日志字符串 - * @param args 其他参数 - */ - public static String logStr(String logStr, Object... args) { - try { - if (Strings.isNullOrEmpty(logStr)) { - return ""; - } - if (args == null || args.length == 0) { - return logStr; - } - String pattern = "\\{}"; - Pattern compile = Pattern.compile(pattern); - Matcher matcher = compile.matcher(logStr); - int n = 0; - while (matcher.find()) { - if (n + 1 > args.length) { - break; - } - logStr = logStr.replaceFirst(pattern, "{" + n++ + "}"); - } - try { - Object arg = args[args.length - 1]; - if (arg instanceof Throwable) { - for (int i = 0; i < args.length - 1; i++) { - pattern = "\\{" + i + "}"; - logStr = logStr.replaceFirst(pattern, Matcher.quoteReplacement(String.valueOf(args[i]))); - } - return logStr + "\n" + getErrString((Throwable) arg); - } - } catch (Exception ignore) { - } - for (int i = 0; i < args.length; i++) { - pattern = "\\{" + i + "}"; - logStr = logStr.replaceFirst(pattern, Matcher.quoteReplacement(String.valueOf(args[i]))); - } - return logStr; - } catch (Exception e) { - return logStr; - } - } - - - /** - *

测试流程工具类

- * - * @param actionClass 流程class - * @param requestId 请求ID - */ - public static void actionTest(Class actionClass, Integer requestId) { - actionTest(actionClass, requestId, new HashMap<>()); - } - - /** - *

测试流程工具类

- * - * @param actionClass 流程class - * @param requestId 请求ID - * @param params 参数 - * @param action - */ - public static void actionTest(Class actionClass, Integer requestId, Map params) { - actionTest(actionClass, requestId, params, CusBaseAction.ActionRunType.SUBMIT); - } - - /** - *

测试流程工具类 其他方式执行方法

- * - * @param actionClass 流程class - * @param requestId 请求ID - * @param runType action执行方式 - */ - public static void actionTestByOther(Class actionClass, Integer requestId, String runType) { - actionTestByOther(actionClass, requestId, new HashMap<>(), runType); - } - - /** - *

测试流程工具类 其他方式执行方法

- * - * @param actionClass 流程class - * @param requestId 请求ID - * @param params 流程参数 - * @param runType action执行方式 - */ - public static void actionTestByOther(Class actionClass, Integer requestId, Map params, String runType) { - actionTest(actionClass, requestId, params, runType); - } - - /** - *

测试流程工具类 退回方法

- * - * @param actionClass 流程class - * @param requestId 请求ID - */ - public static void actionTestReject(Class actionClass, Integer requestId) { - actionTest(actionClass, requestId, new HashMap<>(), CusBaseAction.ActionRunType.REJECT); - } - - /** - *

测试流程工具类 退回方法

- * - * @param actionClass 流程class - * @param requestId 请求ID - * @param params 流程参数 - */ - public static void actionTestReject(Class actionClass, Integer requestId, Map params) { - actionTest(actionClass, requestId, params, CusBaseAction.ActionRunType.REJECT); - } - - - /** - *

测试流程工具类 强制收回

- * - * @param actionClass 流程class - * @param requestId 请求ID - */ - public static void actionTestDrawBack(Class actionClass, Integer requestId) { - actionTest(actionClass, requestId, new HashMap<>(), CusBaseAction.ActionRunType.DRAW_BACK); - } - - /** - *

测试流程工具类 强制收回

- * - * @param actionClass 流程class - * @param requestId 请求ID - * @param params 流程参数 - */ - public static void actionTestDrawBack(Class actionClass, Integer requestId, Map params) { - actionTest(actionClass, requestId, params, CusBaseAction.ActionRunType.DRAW_BACK); - } - - - /** - *

测试流程工具类 撤回

- * - * @param actionClass 流程class - * @param requestId 请求ID - */ - public static void actionTestWithdraw(Class actionClass, Integer requestId) { - actionTest(actionClass, requestId, new HashMap<>(), CusBaseAction.ActionRunType.WITHDRAW); - } - - /** - *

测试流程工具类 撤回

- * - * @param actionClass 流程class - * @param requestId 请求ID - * @param params 流程参数 - */ - public static void actionTestWithdraw(Class actionClass, Integer requestId, Map params) { - actionTest(actionClass, requestId, params, CusBaseAction.ActionRunType.WITHDRAW); - } - - /** - *

测试定时任务工具类

- * - * @param cronJobClass 定时任务类 - * @param 范型 - */ - public static void cronJobTest(Class cronJobClass) { - cronJobTest(cronJobClass, new HashMap<>()); - } - - /** - *

测试定时任务类

- * - * @param cronJobClass 定时任务类 - * @param params 参数 - * @param 范型 - */ - public static void cronJobTest(Class cronJobClass, Map params) { - Field[] declaredFields = cronJobClass.getDeclaredFields(); - T action; - if (params == null) { - params = new HashMap<>(); - } - try { - action = cronJobClass.newInstance(); - if (declaredFields.length > 0) { - 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); - // 如果存在默认值,并且是必填参数 - if (hasDefaultValue && hasRequiredMark) { - // 如果参数map中没有则赋值为默认值 - if (null == value) { - // 获取默认值赋值 - String defaultValue = defaultTestValue.value(); - if (defaultValue == null) { - throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); - } - value = defaultValue; - } - // 如果没有默认值,并且是必填参数 - } else if (!hasDefaultValue && hasRequiredMark) { - // 如果没有从param中获取到,则抛出异常 - if (Util.isNullOrEmpty(value)) { + cusLog.setLevel(Level.INFO); + otherLog.put(name, cusLog); + return cusLog; + } + } + return null; + } + + /** + * 查询自定义配置参数值 + * + * @param onlyMark 唯一标识 + * @return 参数值 + */ + public static String getCusConfigValue(String onlyMark) { + return mapper.selectCusConfigParam(onlyMark, UF_CUS_DEV_CONFIG); + } + + /** + * 查询自定义配置参数值 + * + * @param onlyMark 唯一标识 + * @return 参数值 + */ + public static String getCusConfigValue(String onlyMark, String configTable) { + return mapper.selectCusConfigParam(onlyMark, configTable); + } + + /** + *

更新或插入自定义配置参数

+ * + * @param onlyMark 唯一标识 + * @param value 参数值 + * @param desc 描述信息 + * @return 是否插入成功 + */ + public static boolean insertOrUpdateConfigValue(String onlyMark, String value, String desc) { + String selectValue = getCusConfigValue(onlyMark); + if (Util.isNullOrEmpty(selectValue)) { + String modeId = getModeIdByTableName(UF_CUS_DEV_CONFIG); + int dataId = getModeDataId(UF_CUS_DEV_CONFIG, Integer.parseInt(modeId), 1); + boolean success = mapper.updateConfigValueById(onlyMark, value, desc, String.valueOf(dataId), UF_CUS_DEV_CONFIG); + rebuildModeDataShare(1, Integer.valueOf(modeId), dataId); + return success; + } + return mapper.updateConfigValueByOnlyMark(onlyMark, value, desc, UF_CUS_DEV_CONFIG); + } + + public static boolean insertOrUpdateConfigValue(String onlyMark, String value, String desc, String configTable) { + String selectValue = mapper.selectCusConfigParam(onlyMark, configTable); + if (Util.isNullOrEmpty(selectValue)) { + String modeId = getModeIdByTableName(UF_CUS_DEV_CONFIG); + int dataId = getModeDataId(UF_CUS_DEV_CONFIG, Integer.parseInt(modeId), 1); + boolean success = mapper.updateConfigValueById(onlyMark, value, desc, String.valueOf(dataId), configTable); + rebuildModeDataShare(1, Integer.valueOf(modeId), dataId); + return success; + } + return mapper.updateConfigValueByOnlyMark(onlyMark, value, desc, configTable); + } + + /** + * 获取自定义配置参数值 + * + * @param onlyMark 唯一标识 + * @param defaultStr 默认值 + * @return 参数值 + */ + public static String getCusConfigDefaultValue(String onlyMark, String defaultStr) { + String cusConfigValue = getCusConfigValue(onlyMark); + return cusConfigValue == null ? defaultStr : cusConfigValue; + } + + /** + * 获取自定义配置参数值 + * + * @param onlyMark 唯一标识 + * @param defaultStr 默认值 + * @return 参数值 + */ + public static String getCusConfigValueNullOrEmpty(String onlyMark, String defaultStr) { + String cusConfigValue = getCusConfigValue(onlyMark); + return StringUtils.isNullOrEmpty(cusConfigValue) ? defaultStr : cusConfigValue; + } + + + /** + * 将list转化为树形list + * + * @param dataList 元数据 + * @param getIdFn 获取元数据的id + * @param getParentId 获取父类id的方法 + * @param setChildFn 设置子结点方法 + * @param predicate 判断是否属于根结点的方法 + * @param list的泛型 + * @param 元数据id的泛型 + * @return 树形的list + */ + public static List listToTree(List dataList, Function getIdFn, + Function getParentId, BiConsumer setChildFn, Predicate predicate) { + if (dataList == null || dataList.isEmpty() || dataList.size() == 1) { + return dataList; + } + return buildTree(dataList, new HashMap<>(dataList.size()), new HashMap<>(dataList.size()), 0, + getIdFn, getParentId, setChildFn, predicate); + } + + /** + * 将list转化为树形list + * + * @param dataList 元数据 + * @param getIdFn 获取元数据的id + * @param getParentId 获取父类id的方法 + * @param setChildFn 设置子结点方法 + * @param getChildFn 获取子结点方法 + * @param predicate 判断是否属于根结点的方法 + * @param list的泛型 + * @param 元数据id的泛型 + * @return 树形的list + */ + public static List listToTree(List dataList, Function getIdFn, + Function getParentId, Function> getChildFn, + BiConsumer> setChildFn, Predicate predicate) { + if (dataList == null || dataList.isEmpty() || dataList.size() == 1) { + return dataList; + } + return buildTree(dataList, new HashMap<>(dataList.size()), new HashMap<>(dataList.size()), + 0, getIdFn, getParentId, getChildFn, setChildFn, predicate); + } + + /** + * 将list转为树形list + * + * @param dataList 元数据list + * @param dataMap 数据map + * @param childMap 已添加过的子元素 + * @param index 从第几个开始格式化 + * @param getIdFn 获取id的方法 + * @param getParentId 获取父类id的方法 + * @param setChildFn 设置孩子节点的方法 + * @param predicate 判断是否属于根节点的方法 + * @param list的泛型 + * @param 泛型的id的类型 + * @return 树形结构 + */ + + private static List buildTree(List dataList, Map dataMap, Map childMap, int index, Function getIdFn, + Function getParentId, BiConsumer setChildFn, + Predicate predicate) { + List treeList = new ArrayList<>(dataList.size()); + while (index < dataList.size()) { + T item = dataList.get(index); + index++; + K id = getIdFn.apply(item); + K parentId = getParentId.apply(item); + if (dataMap.containsKey(id)) { + continue; + } + dataMap.put(id, item); + // 判断是否属于根节点,如果是根节点,则将数据添加到树中 + if (predicate.test(parentId)) { + if (childMap.containsKey(id)) { + continue; + } + treeList.add(item); + childMap.put(id, item); + } else { + // 如果不是根节点,则通过id查找到父级 + T parent = dataMap.get(parentId); + if (Objects.isNull(parent)) { + // 如果父级为空,则说明他的父级还没有遍历到,需要从之后的数据进行遍历,直到找到父级为止 + List list = buildTree(dataList, dataMap, childMap, index, getIdFn, getParentId, setChildFn, predicate); + parent = dataMap.get(parentId); + if (Objects.isNull(parent)) { + // 如果还是没有查询到父节点,则表明是顶层节点,将他添加到顶层节点中 + treeList.add(item); + } else { + // 如果找到了父节点,则将自己挂到父节点上 + if (childMap.containsKey(id)) { + continue; + } + setChildFn.accept(parent, item); + childMap.put(id, item); + } + // 如果查找的list不为空并且有值,那就说明属于根节点 + if (list != null && list.size() > 0) { + treeList.addAll(list); + } + } else { + // 如果找到了父节点,则将自己挂到父节点上 + if (childMap.containsKey(id)) { + continue; + } + setChildFn.accept(parent, item); + childMap.put(id, item); + } + } + } + return treeList; + } + + + /** + * 将list转为树形list + * + * @param dataList 元数据list + * @param dataMap 数据map + * @param childMap 已添加过的子元素 + * @param index 从第几个开始格式化 + * @param getIdFn 获取id的方法 + * @param getParentId 获取父类id的方法 + * @param getChildFn 获取子结点方法 + * @param setChildFn 设置孩子节点的方法 + * @param predicate 判断是否属于根节点的方法 + * @param list的泛型 + * @param 泛型的id的类型 + * @return 树形结构 + */ + private static List buildTree(List dataList, Map dataMap, Map childMap, int index, Function getIdFn, + Function getParentId, Function> getChildFn, + BiConsumer> setChildFn, Predicate predicate) { + List treeList = new ArrayList<>(dataList.size()); + while (index < dataList.size()) { + T item = dataList.get(index); + index++; + K id = getIdFn.apply(item); + K parentId = getParentId.apply(item); + if (dataMap.containsKey(id)) { + continue; + } + dataMap.put(id, item); + // 判断是否属于根节点,如果是根节点,则将数据添加到树中 + if (predicate.test(parentId)) { + if (childMap.containsKey(id)) { + continue; + } + treeList.add(item); + childMap.put(id, item); + } else { + // 如果不是根节点,则通过id查找到父级 + T parent = dataMap.get(parentId); + if (Objects.isNull(parent)) { + // 如果父级为空,则说明他的父级还没有遍历到,需要从之后的数据进行遍历,直到找到父级为止 + List list = buildTree(dataList, dataMap, childMap, index, getIdFn, getParentId, getChildFn, setChildFn, predicate); + parent = dataMap.get(parentId); + if (Objects.isNull(parent)) { + // 如果还是没有查询到父节点,则表明是顶层节点,将他添加到顶层节点中 + treeList.add(item); + } else { + // 如果找到了父节点,则将自己挂到父节点上 + if (childMap.containsKey(id)) { + continue; + } + List childList = Optional.ofNullable(getChildFn.apply(parent)).orElse(new ArrayList<>()); + childList.add(item); + setChildFn.accept(parent, childList); + childMap.put(id, item); + } + // 如果查找的list不为空并且有值,那就说明属于根节点 + if (list != null && list.size() > 0) { + treeList.addAll(list); + } + } else { + // 如果找到了父节点,则将自己挂到父节点上 + if (childMap.containsKey(id)) { + continue; + } + List childList = Optional.ofNullable(getChildFn.apply(parent)).orElse(new ArrayList<>()); + childList.add(item); + setChildFn.accept(parent, childList); + childMap.put(id, item); + } + } + } + return treeList; + } + + /** + * 复制java bean中的基本属性,引用类型除外 + * + * @param source 原对象 + * @param target 目标对象 + * @param 原对象泛型 + * @param 目标对象泛型 + * @return 复制后的目标对象 + */ + public static K copyBeanBaseField(T source, K target) { + if (Objects.isNull(source)) { + return target; + } + if (Objects.isNull(target)) { + throw new RuntimeException("target is null, You cannot pass a null bean"); + } + BeanInfo beanInfo = null; + try { + beanInfo = Introspector.getBeanInfo(target.getClass()); + } catch (IntrospectionException e) { + e.printStackTrace(); + } + if (Objects.isNull(beanInfo)) { + throw new RuntimeException("无法获取对象信息!can not get bean info"); + } + Class sourceClass = source.getClass(); + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + Method writeMethod = propertyDescriptor.getWriteMethod(); + String name = propertyDescriptor.getName(); + if (writeMethod == null) { + continue; + } + try { + Field sourceClassField = sourceClass.getDeclaredField(name); + Class propertyType = propertyDescriptor.getPropertyType(); + Class classFieldType = sourceClassField.getType(); + if (propertyType.equals(classFieldType)) { + Method getMethod = sourceClass.getMethod("get" + name.substring(0, 1).toUpperCase() + name.substring(1)); + Object invoke = getMethod.invoke(source); + writeMethod.invoke(target, invoke); + } + } catch (NoSuchFieldException | IllegalAccessException | InvocationTargetException ignored) { + } catch (NoSuchMethodException e) { + throw new RuntimeException("invoke method err, cant not invoke method set" + name.substring(0, 1).toUpperCase() + name.substring(1)); + } + } + // TODO 复制bean + return target; + } + + /** + * 随机数字字符串 + * + * @param length 长度 + * @return 随机字符串 + */ + public static String randomNumber(int length) { + return creatRandom("0123456789", length); + } + + /** + * 随机家字符串 + * + * @param length 长度 + * @return 随机字符串 + */ + public static String randomString(int length) { + return creatRandom("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", length); + } + + /** + * 生成随机英文字符 + * + * @param length 长度 + * @return 随机字符串 + */ + public static String randomLetter(int length) { + return creatRandom("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", length); + } + + + /** + * 创建随机字符串 + * + * @param randomStr 随机字符串范围 + * @param length 长度 + * @return 随机字符串 + */ + public static String creatRandom(String randomStr, int length) { + StringBuffer sb = new StringBuffer(); + Random random = new Random(); + for (int i = 0; i < length; i++) { + int rand = random.nextInt(randomStr.length()); + sb.append(randomStr.charAt(rand)); + } + return sb.toString(); + } + + /** + * 获取建模模块ID通过表名 + * + * @param tableName 表名 + * @return 模块ID + */ + public static String getModeIdByTableName(String tableName) { + String modeId = ""; + String querySql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = ?)"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(querySql, tableName); + if (recordSet.next()) { + modeId = Util.null2String(recordSet.getString("id")); + } + return modeId; + } + + /** + * 获取建模表数据ID + * + * @param tableName 表名 + * @param formModeId 模块ID + * @param userId 用户ID + * @return 数据ID + */ + public static int getModeDataId(String tableName, int formModeId, int userId) { + return mdu.getModeDataNewId(tableName, formModeId, userId, 0, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString()); + } + + /** + * 获取建模表数据ID + * + * @param tableName 表名 + * @param userId 用户ID + * @return 数据ID + */ + public static int getModeDataId(String tableName, int userId) { + return mdu.getModeDataNewId(tableName, Integer.parseInt(getModeIdByTableName(tableName)), userId, 0, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString()); + } + + /** + * 建模表数据权限重构 + * + * @param userId 用户ID + * @param formId 表单ID + * @param id 数据ID + */ + public static void rebuildModeDataShare(Integer userId, Integer formId, Integer id) { + MODE_RIGHT_INFO.rebuildModeDataShareByEdit(userId, formId, id); + } + + /** + * 建模表数据权限重构 + * + * @param userId 用户ID + * @param tableName 表单名称 + * @param id 数据ID + */ + public static void rebuildModeDataShare(Integer userId, String tableName, Integer id) { + MODE_RIGHT_INFO.rebuildModeDataShareByEdit(userId, Integer.parseInt(getModeIdByTableName(tableName)), id); + } + + /** + * 异步权限重构数据 + * + * @param userId 用户ID + * @param formId 表单ID + * @param id 数据ID + */ + public static void rebuildModeDataShareByAsync(Integer userId, Integer formId, Integer id) { + threadPool.execute(() -> Util.rebuildModeDataShare(userId, formId, id)); + } + + /** + * 异步权限重构数据 + * + * @param userId 用户ID + * @param tableName 表单名称 + * @param id 数据ID + */ + public static void rebuildModeDataShareByAsync(Integer userId, String tableName, Integer id) { + threadPool.execute(() -> Util.rebuildModeDataShare(userId, Integer.parseInt(getModeIdByTableName(tableName)), id)); + } + + /** + * 异步权限重构数据 + * + * @param userId 用户ID + * @param formId 表单ID + * @param idList 数据ID + */ + public static void rebuildModeDataShareByAsyncList(Integer userId, Integer formId, List idList) { + threadPool.execute(() -> { + for (Integer id : idList) { + Util.rebuildModeDataShare(userId, formId, id); + } + }); + } + + + /** + * 异步权限重构数据 + * + * @param userId 用户ID + * @param tableName 表单名称 + * @param idList 数据ID + */ + public static void rebuildModeDataShareByAsyncList(Integer userId, String tableName, List idList) { + threadPool.execute(() -> { + for (Integer id : idList) { + Util.rebuildModeDataShare(userId, Integer.parseInt(getModeIdByTableName(tableName)), id); + } + }); + } + + + /** + * 生成文件并创建文档信息,权限继承文档目录 + * + * @param fileName 文件名称 + * @param seccategory 目录ID + * @param inputStream 文件流 + * @return 创建的文档信息 + * @throws Exception 异常细信息 + */ + public static int createDoc(String fileName, int seccategory, InputStream inputStream, Integer userId) throws Exception { + int imageFileId = createFileByInputSteam(inputStream, fileName); + return createDocByImageFileId(fileName, seccategory, imageFileId, userId); + } + + + public static int createDocByImageFileId(int seccategory, int imageFileId, Integer userId) throws Exception { + String fileName = mapper.selectFileNameByImageFileId(imageFileId); + return createDocByImageFileId(fileName, seccategory, imageFileId, userId); + } + + /** + * 创建文件信息,文件权限继承文档目录权限 + * + * @param fileName 文件名称 + * @param seccategory 文件目录 + * @param imageFileId 物理文件ID + * @param userId 用户ID + * @return 文档ID + * @throws Exception 可能会出现的异常 + */ + + + public static int createDocByImageFileId(String fileName, int seccategory, int imageFileId, Integer userId) throws Exception { + DocInfo docInfo = new DocInfo(); + docInfo.setImagefileId(imageFileId); + docInfo.setSeccategory(seccategory); + docInfo.setDocSubject(fileName); + docInfo.setDoccontent(""); + DocServiceImpl docService = new DocServiceImpl(); + int docId = docService.createDocByUser(docInfo, new User(userId)); + DocImageManager imgManger = new DocImageManager(); + imgManger.resetParameter(); + imgManger.setDocid(docId); + imgManger.setImagefileid(imageFileId); + imgManger.setImagefilename(fileName); + imgManger.setIsextfile("1"); + String ext = fileName.substring(fileName.lastIndexOf(".") + 1); + if ("doc".equalsIgnoreCase(ext)) { + imgManger.setDocfiletype("3"); + } else if ("xls".equalsIgnoreCase(ext)) { + imgManger.setDocfiletype("4"); + } else if ("ppt".equalsIgnoreCase(ext)) { + imgManger.setDocfiletype("5"); + } else if ("wps".equalsIgnoreCase(ext)) { + imgManger.setDocfiletype("6"); + } else if ("docx".equalsIgnoreCase(ext)) { + imgManger.setDocfiletype("7"); + } else if ("xlsx".equalsIgnoreCase(ext)) { + imgManger.setDocfiletype("8"); + } else if ("pptx".equalsIgnoreCase(ext)) { + imgManger.setDocfiletype("9"); + } else { + imgManger.setDocfiletype("2"); + } + imgManger.AddDocImageInfo(); + return docId; + } + + + public static String builderUpdateSql(String modelTableName, Map mapping) { + StringBuilder sb = new StringBuilder("update "); + sb.append(modelTableName) + .append(" set "); + int n = 0; + for (Map.Entry entry : mapping.entrySet()) { + n++; + sb.append(entry.getKey()).append("=#{").append(entry.getKey()).append("}"); + if (n < mapping.size()) { + sb.append(","); + } + } + return sb.toString(); + } + + + /** + *

提交流程

+ * + * @param requestId 流程请求ID + * @param userId 用户ID + * @param remark 签字意见 + * @return + */ + public static boolean submitWorkflow(Integer requestId, Integer userId, String remark) { + RequestService requestService = new RequestService(); + RequestInfo req = requestService.getRequest(requestId); + if (remark == null) { + remark = "流程自动提交"; + } + return requestService.nextNodeBySubmit(req, requestId, userId, remark); + } + + /** + *

异步提交流程,一般作用于action在节点前

+ * + * @param requestId 流程ID + * @param userId 用户id + * @param remark 签字意见 + */ + public static void submitWorkflowThread(Integer requestId, Integer userId, String remark) { + submitWorkflowThread(requestId, userId, remark, 60); + } + + /** + *

异步提交流程,一般作用于action在节点前

+ * + * @param requestId 流程ID + * @param userId 用户id + * @param remark 签字意见 + * @param seconds 延时多少秒提交 + */ + public static void submitWorkflowThread(Integer requestId, Integer userId, String remark, int seconds) { + if (seconds <= 0) { + seconds = 1; + } + int finalSeconds = seconds; + new Thread(() -> { + try { + Thread.sleep(1000L * finalSeconds); + } catch (InterruptedException e) { + e.printStackTrace(); + Util.getLogger().error("线程休眠失败", e); + } + int n = 0; + while (!Util.submitWorkflow(requestId, userId, remark)) { + n++; + try { + Thread.sleep(1000 * 10); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (n > 5) { + Util.getLogger().error("异步流程自动提交失败!"); + break; + } + } + }).start(); + } + + /** + *

通过流程信息(RequestInfo)提交流程

+ * + * @param requestInfo requestInfo对象 + * @param userId 用户id + * @param remark 提交签字意见 + * @return 是否提交成功 + */ + public static boolean submitWorkflowByRequestInfo(RequestInfo requestInfo, Integer userId, String remark) { + RequestService requestService = new RequestService(); + if (remark == null) { + remark = "流程自动提交"; + } + return requestService.nextNodeBySubmit(requestInfo, Integer.parseInt(requestInfo.getRequestid()), userId, remark); + } + + + /** + * 全角转半角 + * + * @param src 全角字符 + * @return 半角字符 + */ + public static char sbc2dbc(char src) { + if (src == SBC_SPACE) { + return DBC_SPACE; + } + + if (src >= UNICODE_START && src <= UNICODE_END) { + return (char) (src - DBC_SBC_STEP); + } + + return src; + } + + /** + * 全角转半角 + * + * @param src 全角字符串 + * @return DBC case + */ + public static String sbc2dbcCase(String src) { + if (src == null) { + return null; + } + char[] c = src.toCharArray(); + for (int i = 0; i < c.length; i++) { + c[i] = sbc2dbc(c[i]); + } + return new String(c); + } + + /** + * 半角转全角 + * + * @param src 半角字符 + * @return SBC case + */ + public static char dbc2sbc(char src) { + if (src == DBC_SPACE) { + return SBC_SPACE; + } + if (src <= ASCII_END) { + return (char) (src + DBC_SBC_STEP); + } + return src; + } + + /** + * 半角转全角 + * + * @param src 半角字符 + * @return SBC case string + */ + public static String dbc2sbcCase(String src) { + if (src == null) { + return null; + } + + char[] c = src.toCharArray(); + for (int i = 0; i < c.length; i++) { + c[i] = dbc2sbc(c[i]); + } + + return new String(c); + } + + /** + *

通过流程Id查询流程主表表明

+ * + * @param workflowId 流程id + * @return 流程表名 + */ + public static String getWorkflowMainTable(String workflowId) { + return mapper.selectWorkfowMainTable(workflowId); + } + + /** + * 创建物理文件 + * + * @param content 文件流 + * @param fileName 文件名 + * @return 文件id + */ + public static int createFileByInputSteam(InputStream content, String fileName) { + ImageFileManager imageFileManager = new ImageFileManager(); + int imgFileId; + try { + Method saveImageFileByInputStream = ImageFileManager.class.getMethod("saveImageFileByInputStream", InputStream.class, String.class); + imgFileId = (int) saveImageFileByInputStream.invoke(imageFileManager, content, fileName); + } catch (NoSuchMethodException e) { + imageFileManager.setImagFileName(fileName); + try { + imageFileManager.setData(IOUtils.toBytes(content)); + } catch (Exception ex) { + throw new CustomerException("创建文件失败,文件流转换失败", e); + } + imgFileId = imageFileManager.saveImageFile(); + } catch (Exception e) { + throw new CustomerException("创建文件失败"); + } + return imgFileId; + } + + /** + * 流程失败返回 + * + * @param requestManager 流程请求管理 + * @param msg 失败信息 + * @return 失败 + */ + public static String actionFail(RequestManager requestManager, String msg) { + requestManager.setMessageid(System.currentTimeMillis() + ""); + requestManager.setMessagecontent(msg); + return Action.FAILURE_AND_CONTINUE; + } + + /** + * 流程失败返回 + * + * @param requestManager 流程请求管理 + * @param msg 失败信息 + * @return 失败 + */ + public static String actionFailException(RequestManager requestManager, String msg) { + requestManager.setMessageid(System.currentTimeMillis() + ""); + requestManager.setMessagecontent(msg); + throw new CustomerException(msg, 500); + } + + /** + * 查询文档信息 + * + * @param docId 文档ID + * @return 文档信息 + */ + public static DocImageInfo selectImageInfoByDocId(String docId) { + return mapper.selectDocImageInfo(docId); + } + + /** + * 查询文档信息 + * + * @param docIds 文档ID + * @return 文档信息 + */ + public static List selectImageInfoByDocIds(String docIds) { + return mapper.selectDocImageInfos(docIds); + } + + /** + * 查询流程节点配置 + * + * @param allVersion 流程所有版本第 + * @param markOnly 唯一标识 + * @return 流程节点配置 + */ + public static WorkflowNodeConfig selectNodeConfig(String allVersion, String markOnly) { + return mapper.selectNodeConfig(allVersion, markOnly); + } + + /** + * 查询下拉框选项信息 + * + * @param tableName 表名 + * @param fileName 字段名 + * @return 下拉选项框值信息 + */ + public static List getSelectFiledValue(String tableName, String fileName) { + return mapper.selectSelectFieldValue(tableName, fileName); + } + + /** + * 通过下拉框选项值查询显示名 + * + * @param tableName 表名 + * @param fileName 字段名 + * @param value 下拉框选项值 + * @return 显示名 + */ + public static String getSelectFiledValueByValue(String tableName, String fileName, String value) { + return mapper.selectSelectFieldValueByValue(tableName, fileName, value); + } + + /** + * 判断字符串是否为空 + * + * @param str 判断字符串 + * @return 空标识 + */ + public static boolean isNullOrEmpty(String str) { + return str == null || str.length() == 0; + } + + /** + * 必填字段验证 + * + * @param obj 验证对象 + * @param 范型 + * @return 是否通过验证 + */ + public static boolean verifyRequiredField(T obj) throws CustomerException { + if (obj == null) { + return false; + } + Class aClass = obj.getClass(); + List entityFields = getEntityFields(aClass); + if (entityFields == null) { + return false; + } + Map printParam = new HashMap<>(); + for (Field field : entityFields) { + String modifiers = Modifier.toString(field.getModifiers()); + if (modifiers.contains("static") || modifiers.contains("final")) { + continue; + } + RequiredMark annotation = field.getAnnotation(RequiredMark.class); + PrintParamMark printParamMark = field.getAnnotation(PrintParamMark.class); + Object value = null; + field.setAccessible(true); + try { + value = field.get(obj); + if (printParamMark != null) { + printParam.put(field.getName(), value); + } + } catch (IllegalAccessException e) { + return false; + } + if (annotation != null) { + String valueStr = null2String(value); + if (isNullOrEmpty(valueStr)) { + throw new CustomerException("参数校验未通过,字段必填[ " + field.getName() + " ]未填写: " + annotation.value()); + } + } + } + if (printParam.size() > 0) { + + getLogger().info(Util.logStr("Acton[{}]参数:\n{}", obj.getClass().toString(), + JSONObject.toJSONString(printParam, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); + } + return true; + } + + /** + * 通过文件ID数组删除文件 + * + * @param integers 文件id数组 + */ + public static void deleteImageFile(List integers) { + for (Integer integer : integers) { + deleteImageFile(integer); + } + } + + /** + * 通过文件id删除文件 + * + * @param imageFileId 文件ID + */ + public static void deleteImageFile(Integer imageFileId) { + Map imageInfo = mapper.selectFileInfoByImageFileId(imageFileId); + String filerealpath = String.valueOf(imageInfo.get("filerealpath")); + File file = new File(filerealpath); + if (file.exists()) { + file.delete(); + } + mapper.deleteImageFileInfo(imageFileId); + } + + /** + *

将日期字符串转换为Date对象

+ * + * @param dateStr 日期字符串 + * @return 日期对象 + */ + public static Date parseDate(String dateStr) { + ThreadLocal SIMPLE_DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd")); + if (dateStr == null || dateStr.length() == 0) { + return null; + } + String regex = "\\/|\\.|年|月|日"; + Date date = null; + try { + date = SIMPLE_DATE_FORMAT.get().parse(dateStr.replaceAll(regex, "-")); + return date; + } catch (ParseException e) { + // TODO Auto-generated catch block + throw new CustomerException("无法将" + dateStr + "转换为日期对象!", e); + } finally { + SIMPLE_DATE_FORMAT.remove(); + } + } + + /** + *

格式化日期字符串为指定格式的日期字符串

+ * + * @param dateStr 源日期字符串 + * @param formatStr 目标日期字符串的格式 + * @return 目标日期字符串的格式 + */ + public static String formatDate(String dateStr, String formatStr) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr); + return simpleDateFormat.format(parseDate(dateStr)); + } + + /** + * 构建日志字符串 + * + * @param logStr 日志字符串 + * @param args 其他参数 + */ + public static String logStr(String logStr, Object... args) { + try { + if (Strings.isNullOrEmpty(logStr)) { + return ""; + } + if (args == null || args.length == 0) { + return logStr; + } + String pattern = "\\{}"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(logStr); + int n = 0; + while (matcher.find()) { + if (n + 1 > args.length) { + break; + } + logStr = logStr.replaceFirst(pattern, "{" + n++ + "}"); + } + try { + Object arg = args[args.length - 1]; + if (arg instanceof Throwable) { + for (int i = 0; i < args.length - 1; i++) { + pattern = "\\{" + i + "}"; + logStr = logStr.replaceFirst(pattern, Matcher.quoteReplacement(String.valueOf(args[i]))); + } + return logStr + "\n" + getErrString((Throwable) arg); + } + } catch (Exception ignore) { + } + for (int i = 0; i < args.length; i++) { + pattern = "\\{" + i + "}"; + logStr = logStr.replaceFirst(pattern, Matcher.quoteReplacement(String.valueOf(args[i]))); + } + return logStr; + } catch (Exception e) { + return logStr; + } + } + + + /** + *

测试流程工具类

+ * + * @param actionClass 流程class + * @param requestId 请求ID + */ + public static void actionTest(Class actionClass, Integer requestId) { + actionTest(actionClass, requestId, new HashMap<>()); + } + + /** + *

测试流程工具类

+ * + * @param actionClass 流程class + * @param requestId 请求ID + * @param params 参数 + * @param action + */ + public static void actionTest(Class actionClass, Integer requestId, Map params) { + actionTest(actionClass, requestId, params, CusBaseAction.ActionRunType.SUBMIT); + } + + /** + *

测试流程工具类 其他方式执行方法

+ * + * @param actionClass 流程class + * @param requestId 请求ID + * @param runType action执行方式 + */ + public static void actionTestByOther(Class actionClass, Integer requestId, String runType) { + actionTestByOther(actionClass, requestId, new HashMap<>(), runType); + } + + /** + *

测试流程工具类 其他方式执行方法

+ * + * @param actionClass 流程class + * @param requestId 请求ID + * @param params 流程参数 + * @param runType action执行方式 + */ + public static void actionTestByOther(Class actionClass, Integer requestId, Map params, String runType) { + actionTest(actionClass, requestId, params, runType); + } + + /** + *

测试流程工具类 退回方法

+ * + * @param actionClass 流程class + * @param requestId 请求ID + */ + public static void actionTestReject(Class actionClass, Integer requestId) { + actionTest(actionClass, requestId, new HashMap<>(), CusBaseAction.ActionRunType.REJECT); + } + + /** + *

测试流程工具类 退回方法

+ * + * @param actionClass 流程class + * @param requestId 请求ID + * @param params 流程参数 + */ + public static void actionTestReject(Class actionClass, Integer requestId, Map params) { + actionTest(actionClass, requestId, params, CusBaseAction.ActionRunType.REJECT); + } + + + /** + *

测试流程工具类 强制收回

+ * + * @param actionClass 流程class + * @param requestId 请求ID + */ + public static void actionTestDrawBack(Class actionClass, Integer requestId) { + actionTest(actionClass, requestId, new HashMap<>(), CusBaseAction.ActionRunType.DRAW_BACK); + } + + /** + *

测试流程工具类 强制收回

+ * + * @param actionClass 流程class + * @param requestId 请求ID + * @param params 流程参数 + */ + public static void actionTestDrawBack(Class actionClass, Integer requestId, Map params) { + actionTest(actionClass, requestId, params, CusBaseAction.ActionRunType.DRAW_BACK); + } + + + /** + *

测试流程工具类 撤回

+ * + * @param actionClass 流程class + * @param requestId 请求ID + */ + public static void actionTestWithdraw(Class actionClass, Integer requestId) { + actionTest(actionClass, requestId, new HashMap<>(), CusBaseAction.ActionRunType.WITHDRAW); + } + + /** + *

测试流程工具类 撤回

+ * + * @param actionClass 流程class + * @param requestId 请求ID + * @param params 流程参数 + */ + public static void actionTestWithdraw(Class actionClass, Integer requestId, Map params) { + actionTest(actionClass, requestId, params, CusBaseAction.ActionRunType.WITHDRAW); + } + + /** + *

测试定时任务工具类

+ * + * @param cronJobClass 定时任务类 + * @param 范型 + */ + public static void cronJobTest(Class cronJobClass) { + cronJobTest(cronJobClass, new HashMap<>()); + } + + /** + *

测试定时任务类

+ * + * @param cronJobClass 定时任务类 + * @param params 参数 + * @param 范型 + */ + public static void cronJobTest(Class cronJobClass, Map params) { + Field[] declaredFields = cronJobClass.getDeclaredFields(); + T action; + if (params == null) { + params = new HashMap<>(); + } + try { + action = cronJobClass.newInstance(); + 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); +// 如果存在默认值,并且是必填参数 + if (hasDefaultValue && hasRequiredMark) { +// 如果参数map中没有则赋值为默认值 + if (null == value) { +// 获取默认值赋值 + String defaultValue = defaultTestValue.value(); + if (defaultValue == null) { throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); } - // 如果有默认值,并且没有从params中获得,则赋值 - } else if (hasDefaultValue) { - if (null == value) { - value = defaultTestValue.value(); - } - } else if (hasOptional) { - // 如果存在可选值 - ActionOptionalParam optionalParam = declaredField.getAnnotation(ActionOptionalParam.class); - String defaultValue = optionalParam.value(); - // 可选值没有在param中存在 - if (null == value) { - value = defaultValue; - } - } else { - - // 都不符合必填和默认值的参数,判断params中是否存在,如果不存在则直接跳过 - if (null == value) { - continue; - } - value = params.get(name); + value = defaultValue; } - 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())); - } - - - /** - *

测试流程工具类

- * - * @param actionClass 流程class - * @param requestId 请求ID - * @param params 参数 - * @param runType 流程执行方式 - * @param action - */ - private static void actionTest(Class actionClass, Integer requestId, Map params, String runType) { - Field[] declaredFields = actionClass.getDeclaredFields(); - T action; - RequestInfo requestInfo; - String execute; - if (params == null) { - params = new HashMap<>(); - } - try { - action = actionClass.newInstance(); - if (declaredFields.length > 0) { - 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) { +// 如果没有默认值,并且是必填参数 + } else if (!hasDefaultValue && hasRequiredMark) { +// 如果没有从param中获取到,则抛出异常 + if (Util.isNullOrEmpty(value)) { + throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); + } +// 如果有默认值,并且没有从params中获得,则赋值 + } else if (hasDefaultValue) { + if (null == value) { value = defaultTestValue.value(); } - if (!params.containsKey(name) && Util.isNullOrEmpty(value)) { + } else if (hasOptional) { +// 如果存在可选值 + ActionOptionalParam optionalParam = declaredField.getAnnotation(ActionOptionalParam.class); + String defaultValue = optionalParam.value(); +// 可选值没有在param中存在 + if (null == value) { + value = defaultValue; + } + } else { + +// 都不符合必填和默认值的参数,判断params中是否存在,如果不存在则直接跳过 + if (null == value) { continue; } - if (params.containsKey(name)) { - value = params.get(name); - } - Method method = actionClass.getMethod(setMethodName, String.class); - method.invoke(action, value); + value = params.get(name); } + Method method = cronJobClass.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); - execute = action.execute(requestInfo); - } catch (Exception e) { - throw new CustomerException("action执行异常!异常信息:\n" + Util.getErrString(e)); - } - 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())); - } - - public static String getSetMethodName(String fieldName) { - if (fieldName == null || fieldName.length() == 0) { - throw new CustomerException("字段名称不能为空!"); - } - char[] chars = fieldName.toCharArray(); - StringBuilder sb = new StringBuilder("set"); - for (int i = 0; i < chars.length; i++) { - if (i == 0) { - if (chars[i] >= 97 && chars[i] <= 122) { - sb.append((char) (chars[i] - 32)); + action.execute(); + } catch (Exception e) { + throw new CustomerException("计划任务执行异常!异常信息:\n" + Util.getErrString(e)); + } + + getLogger().info(Util.logStr("\n\t计划任务 [{}] getDataId success!\n", cronJobClass.getName())); + } + + + /** + *

测试流程工具类

+ * + * @param actionClass 流程class + * @param requestId 请求ID + * @param params 参数 + * @param runType 流程执行方式 + * @param action + */ + private static void actionTest(Class actionClass, Integer requestId, Map params, String runType) { + Field[] declaredFields = actionClass.getDeclaredFields(); + T action; + RequestInfo requestInfo; + String execute; + if (params == null) { + params = new HashMap<>(); + } + try { + action = actionClass.newInstance(); + 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); } - sb.append(chars[i]); - } - return sb.toString(); - } - - /** - *

通过keyStr获取value

- * - * @param keyStr keyString - * @param arg map对象 - * @return value - */ - public static Object getValueByKeyStr(String keyStr, Object arg) { - if (arg == null) { - return null; - } - if (!keyStr.contains(".")) { - return valueHandler(arg, keyStr); - } - String pattern = "(?^[\\w]+[\\w$]*)\\.*(?(\\S+)*)"; - Pattern compile = Pattern.compile(pattern); - Matcher matcher = compile.matcher(keyStr); - if (matcher.find()) { - String field = matcher.group("field"); - String otherKeyStr = matcher.group("other"); - Object o = valueHandler(arg, field); - if (null == o) { - throw new CustomerException(Util.logStr("can not get value of [{}] from [{}], this keyStr is [{}]", - field, JSON.toJSONString(arg), keyStr)); - } - return getValueByKeyStr(otherKeyStr, o); - } - throw new CustomerException("Unable to find value of key [" + keyStr + "]"); - } - - /** - *

获取value

- * - * @param obj 对象 - * @param key key - * @return 值 - */ - private static Object valueHandler(Object obj, String key) { - return ((Map) obj).get(key); - } - - - /** - * 解析自定义接口的参数 - * - * @param cusInterfaceStr 自定义接口字符串 - * @return 自定义接口参数对象以及接口全路径类名 - */ - public static Map parseCusInterfacePathParam(String cusInterfaceStr) { - String[] split = cusInterfaceStr.split("\\?"); - String classPath = split[0]; - String paramStr = ""; - if (split.length > 1) { - paramStr = Arrays.stream(split).skip(1).collect(Collectors.joining("?")); - } + RequestService requestService = new RequestService(); + requestInfo = requestService.getRequest(requestId); + if (null == requestInfo) { + throw new CustomerException("没有查找到对应的请求requestId : " + requestId); + } + requestInfo.getRequestManager().setSrc(runType); + execute = action.execute(requestInfo); + } catch (Exception e) { + throw new CustomerException("action执行异常!异常信息:\n" + Util.getErrString(e)); + } + 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())); + } + + public static String getSetMethodName(String fieldName) { + if (fieldName == null || fieldName.length() == 0) { + throw new CustomerException("字段名称不能为空!"); + } + char[] chars = fieldName.toCharArray(); + StringBuilder sb = new StringBuilder("set"); + for (int i = 0; i < chars.length; i++) { + if (i == 0) { + if (chars[i] >= 97 && chars[i] <= 122) { + sb.append((char) (chars[i] - 32)); + continue; + } + } + sb.append(chars[i]); + } + return sb.toString(); + } + + /** + *

通过keyStr获取value

+ * + * @param keyStr keyString + * @param arg map对象 + * @return value + */ + public static Object getValueByKeyStr(String keyStr, Object arg) { + if (arg == null) { + return null; + } + if (!keyStr.contains(".")) { + return valueHandler(arg, keyStr); + } + String pattern = "(?^[\\w]+[\\w$]*)\\.*(?(\\S+)*)"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(keyStr); + if (matcher.find()) { + String field = matcher.group("field"); + String otherKeyStr = matcher.group("other"); + Object o = valueHandler(arg, field); + if (null == o) { + throw new CustomerException(Util.logStr("can not get value of [{}] from [{}], this keyStr is [{}]", + field, JSON.toJSONString(arg), keyStr)); + } + return getValueByKeyStr(otherKeyStr, o); + } + throw new CustomerException("Unable to find value of key [" + keyStr + "]"); + } + + /** + *

获取value

+ * + * @param obj 对象 + * @param key key + * @return 值 + */ + private static Object valueHandler(Object obj, String key) { + return ((Map) obj).get(key); + } + + + /** + * 解析自定义接口的参数 + * + * @param cusInterfaceStr 自定义接口字符串 + * @return 自定义接口参数对象以及接口全路径类名 + */ + public static Map parseCusInterfacePathParam(String cusInterfaceStr) { + String[] split = cusInterfaceStr.split("\\?"); + String classPath = split[0]; + String paramStr = ""; + if (split.length > 1) { + paramStr = Arrays.stream(split).skip(1).collect(Collectors.joining("?")); + } /* 获取?后的参数:"weaver.aiyh_jitu.pushdata.service.toones.GetRequestValueCusGetValueImpl?" + "requestType=get&apiOnlyMark=getAssign&valueKey=data&assign=#{main.zd2}&" + "#processorClass=weaver.aiyh_jitu.pushdata.service.toones.GetAssignProcessorProcessorImpl" + @@ -3576,78 +3572,78 @@ public class Util extends weaver.general.Util { value:#sql{select workcode from hrmresource where id = #{main.zd1} and test = #{h-hah} and a in (${hrmids})} key:hah value:haode*/ - // 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类,将参数传递给这个类, - // String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + - // "(?(`([\\s():/\\t\\-&*'?$#={ }.\\w\\u4E00-\\u9FA5]*)`|" + - // "((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; - String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + - "(?(`([^`]*)`|" + - "((#(\\{|sql\\{))?([():/\\-$_*#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; - Pattern compile = Pattern.compile(pattern); - Matcher matcher = compile.matcher(paramStr); - Map pathParamMap = new HashMap<>(8); - pathParamMap.put("_ClassPath", classPath); - while (matcher.find()) { - String key = matcher.group("key"); - String paramValue = matcher.group("value"); - if (paramValue.startsWith("`") && paramValue.endsWith("`")) { - paramValue = paramValue.substring(1, paramValue.length() - 1); - } - pathParamMap.put(key, paramValue); - } - return pathParamMap; - } - - public static Object executeActionProcess(String process, RequestInfo requestInfo) { - if (StringUtils.isNullOrEmpty(process)) { - return null; - } - 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); - } - Class clazz = SafeCusActionProcessInterface.class; - Class aClass; - try { - aClass = Class.forName(process); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("未能找到自定义接口:" + process); - } - if (!clazz.isAssignableFrom(aClass)) { - throw new IllegalArgumentException("自定义接口:" + process + " 不是" - + clazz.getName() + "的子类或实现类!"); - } - Constructor constructor; - try { - constructor = aClass.getConstructor(); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException(process + "没有空参构造方法,无法获取构造方法对象!"); - } - SafeCusActionProcessInterface o; - try { - o = (SafeCusActionProcessInterface) constructor.newInstance(); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { - throw new IllegalArgumentException("无法构造" + process + "对象!"); - } - Map pathParam = Util.parseCusInterfacePathParam(process); - return o.execute(pathParam, requestId, billTable, workflowId, user, requestInfo); - } - - - public static String selectBillTableByFromId(String fromId) { - return mapper.selectBillTableByFromId(fromId); - } - - public static void deleteModeId(String tableName, Integer dataId) { - mapper.deleteModeId(tableName, dataId); - } + // 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类,将参数传递给这个类, + // String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + + // "(?(`([\\s():/\\t\\-&*'?$#={ }.\\w\\u4E00-\\u9FA5]*)`|" + + // "((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; + String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + + "(?(`([^`]*)`|" + + "((#(\\{|sql\\{))?([():/\\-$_*#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(paramStr); + Map pathParamMap = new HashMap<>(8); + pathParamMap.put("_ClassPath", classPath); + while (matcher.find()) { + String key = matcher.group("key"); + String paramValue = matcher.group("value"); + if (paramValue.startsWith("`") && paramValue.endsWith("`")) { + paramValue = paramValue.substring(1, paramValue.length() - 1); + } + pathParamMap.put(key, paramValue); + } + return pathParamMap; + } + + public static Object executeActionProcess(String process, RequestInfo requestInfo) { + if (StringUtils.isNullOrEmpty(process)) { + return null; + } + 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); + } + Class clazz = SafeCusActionProcessInterface.class; + Class aClass; + try { + aClass = Class.forName(process); + } catch (ClassNotFoundException e) { + throw new IllegalArgumentException("未能找到自定义接口:" + process); + } + if (!clazz.isAssignableFrom(aClass)) { + throw new IllegalArgumentException("自定义接口:" + process + " 不是" + + clazz.getName() + "的子类或实现类!"); + } + Constructor constructor; + try { + constructor = aClass.getConstructor(); + } catch (NoSuchMethodException e) { + throw new IllegalArgumentException(process + "没有空参构造方法,无法获取构造方法对象!"); + } + SafeCusActionProcessInterface o; + try { + o = (SafeCusActionProcessInterface) constructor.newInstance(); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalArgumentException("无法构造" + process + "对象!"); + } + Map pathParam = Util.parseCusInterfacePathParam(process); + return o.execute(pathParam, requestId, billTable, workflowId, user, requestInfo); + } + + + public static String selectBillTableByFromId(String fromId) { + return mapper.selectBillTableByFromId(fromId); + } + + public static void deleteModeId(String tableName, Integer dataId) { + mapper.deleteModeId(tableName, dataId); + } } diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/ApaLevelByScoreController.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/ApaLevelByScoreController.java index 5476d7c..5923512 100644 --- a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/ApaLevelByScoreController.java +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/ApaLevelByScoreController.java @@ -4,8 +4,13 @@ import aiyh.utils.ApiResult; import aiyh.utils.Util; import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.service.ApaLevelByScoreService; import org.apache.log4j.Logger; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import javax.ws.rs.*; +import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; /** @@ -18,21 +23,36 @@ import javax.ws.rs.core.MediaType; @Path("ayh/workflow/apa") public class ApaLevelByScoreController { - - private final Logger log = Util.getLogger(); - private final ApaLevelByScoreService service = new ApaLevelByScoreService(); - - @Path("/level") - @GET - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - public String getLevelByScore(@QueryParam("score") Double score) { - try { - Integer level = service.getLevelByScore(score); - return ApiResult.success(level); - } catch (Exception e) { - log.error("get level error \n" + Util.getErrString(e)); - return ApiResult.error("get level error " + e.getMessage()); - } - } + + private final Logger log = Util.getLogger(); + private final ApaLevelByScoreService service = new ApaLevelByScoreService(); + + @Path("/level") + @GET + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getLevelByScore(@QueryParam("score") Double score) { + try { + Integer level = service.getLevelByScore(score); + return ApiResult.success(level); + } catch (Exception e) { + log.error("get level error \n" + Util.getErrString(e)); + return ApiResult.error("get level error " + e.getMessage()); + } + } + + + @GET + @Path("/get-data-id") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getApaLastDateId(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + try { + return ApiResult.success(service.getApaLastDateId(user)); + } catch (Exception e) { + log.error("get apa workflow param(mode id) error ! \n" + Util.getErrString(e)); + return ApiResult.error(e.getMessage()); + } + } } \ No newline at end of file diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java index f011991..4d5b9d3 100644 --- a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java @@ -1,5 +1,6 @@ package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper; +import aiyh.utils.annotation.recordset.ParamMapper; import aiyh.utils.annotation.recordset.Select; import aiyh.utils.annotation.recordset.SqlMapper; @@ -13,16 +14,22 @@ import aiyh.utils.annotation.recordset.SqlMapper; @SqlMapper public interface ApaLevelByScoreMapper { - - /** - *

通过apa分数查询对应的分数等级

- * 2022/12/13 10:47 - * ************************************************************ - * - * @param score 分数 - * @return Integer 当前分数对应的等级 - * @author youHong.ai ****************************************** - */ - @Select("select level1 from uf_APAlevel where #{score} between zdf and zgf") - Integer selectLevelByScore(Double score); + + /** + *

通过apa分数查询对应的分数等级

+ * 2022/12/13 10:47 + * ************************************************************ + * + * @param score 分数 + * @return Integer 当前分数对应的等级 + * @author youHong.ai ****************************************** + */ + @Select("select level1 from uf_APAlevel where #{score} between zdf and zgf") + Integer selectLevelByScore(Double score); + + + @Select("select id from $t{tableName} where $t{userField} = #{uId}") + Integer selectLevelByUserId(@ParamMapper("uId") int uid, + @ParamMapper("tableName") String tableName, + @ParamMapper("userField") String userField); } diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java index 8302ceb..5a54b73 100644 --- a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java @@ -2,7 +2,9 @@ package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.service; import aiyh.utils.Util; import aiyh.utils.excention.CustomerException; +import cn.hutool.core.lang.Assert; import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper.ApaLevelByScoreMapper; +import weaver.hrm.User; /** *

@@ -13,22 +15,30 @@ import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper.ApaLevelByScoreM */ public class ApaLevelByScoreService { - private final ApaLevelByScoreMapper mapper = Util.getMapper(ApaLevelByScoreMapper.class); - - /** - *

根据分数查询等级

- * 2022/12/13 10:55 - * ************************************************************ - * - * @param score 分数 - * @return Integer 等级 - * @author youHong.ai ****************************************** - */ - public Integer getLevelByScore(Double score) { - Integer level = mapper.selectLevelByScore(score); - if (level < -1) { - throw new CustomerException("query level error, score is [" + score + ""); - } - return level; - } + private final ApaLevelByScoreMapper mapper = Util.getMapper(ApaLevelByScoreMapper.class); + + /** + *

根据分数查询等级

+ * 2022/12/13 10:55 + * ************************************************************ + * + * @param score 分数 + * @return Integer 等级 + * @author youHong.ai ****************************************** + */ + public Integer getLevelByScore(Double score) { + Integer level = mapper.selectLevelByScore(score); + if (level < -1) { + throw new CustomerException("query level error, score is [" + score + ""); + } + return level; + } + + public Integer getApaLastDateId(User user) { + String apaLastIdTableName = Util.getCusConfigValue("APA_LAST_ID_TABLE_NAME"); + String apaLastIdUserField = Util.getCusConfigValue("APA_LAST_ID_USER_FIELD"); + Assert.notBlank(apaLastIdTableName, "can not get config [APA_LAST_ID_TABLE_NAME] from uf_cus_dev_config!"); + Assert.notBlank(apaLastIdUserField, "can not get config [APA_LAST_ID_USER_FIELD] from uf_cus_dev_config!"); + return mapper.selectLevelByUserId(user.getUID(), apaLastIdTableName, apaLastIdUserField); + } } diff --git a/src/main/java/com/api/youhong/ai/zhishichanquan/ssocaiwu/controller/SingleSignOnController.java b/src/main/java/com/api/youhong/ai/zhishichanquan/ssocaiwu/controller/SingleSignOnController.java new file mode 100644 index 0000000..02db8c1 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/zhishichanquan/ssocaiwu/controller/SingleSignOnController.java @@ -0,0 +1,57 @@ +package com.api.youhong.ai.zhishichanquan.ssocaiwu.controller; + +import aiyh.utils.Util; +import cn.hutool.core.lang.Assert; +import com.alibaba.fastjson.JSON; +import com.api.youhong.ai.zhishichanquan.ssocaiwu.util.AES; +import com.sun.jersey.api.view.Viewable; +import org.apache.log4j.Logger; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.core.Context; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +/** + *

知识产权局单点登录到财务系统

+ * + *

create: 2023/2/8 17:10

+ * + * @author youHong.ai + */ +@Path("/aiyh/sso/caiwu/") +public class SingleSignOnController { + + private final Logger log = Util.getLogger(); + + @Path("/send-redirect") + @GET + public Viewable ssoSendRedirect(@Context HttpServletRequest request, @Context HttpServletResponse response) { + try { + String url = Util.getCusConfigValue("FinancialAffairsURL"); + String key = Util.getCusConfigValue("FinancialAffairsKey"); + String initVector = Util.getCusConfigValue("FinancialAffairsInitVector"); + Assert.notBlank(url, "sendRedirect url is null, check config [FinancialAffairsURL] on uf_cus_dev_config table!"); + Assert.notBlank(key, "sendRedirect AES encrypt key is null, check config [FinancialAffairsKey] on uf_cus_dev_config table!"); + Assert.notBlank(initVector, "sendRedirect AES encrypt initVector is null, check config [FinancialAffairsInitVector] on uf_cus_dev_config table!"); + User user = HrmUserVarify.getUser(request, response); + String userCodeMethod = Util.getCusConfigValueNullOrEmpty("FinancialAffairsUserCodeMethod", "getLoginid"); + Method method = User.class.getMethod(userCodeMethod); + Object value = method.invoke(user); + Map param = new HashMap<>(8); + param.put("user", value); + param.put("ts", System.currentTimeMillis()); + String encrypt = AES.encrypt(key, initVector, JSON.toJSONString(param)); + response.sendRedirect(url + "?params=" + encrypt); + } catch (Exception e) { + log.error("单点登录路径处理失败!" + e.getMessage() + "\n" + Util.getErrString(e)); + } + return null; + } +} diff --git a/src/main/java/com/api/youhong/ai/zhishichanquan/ssocaiwu/util/AES.java b/src/main/java/com/api/youhong/ai/zhishichanquan/ssocaiwu/util/AES.java new file mode 100644 index 0000000..093837f --- /dev/null +++ b/src/main/java/com/api/youhong/ai/zhishichanquan/ssocaiwu/util/AES.java @@ -0,0 +1,43 @@ +package com.api.youhong.ai.zhishichanquan.ssocaiwu.util; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.util.Base64; + +public class AES { + public static String encrypt(String key, String initVector, String value) { + try { + IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); + SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); + + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); + + byte[] encrypted = cipher.doFinal(value.getBytes()); + return Base64.getEncoder().encodeToString(encrypted); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return null; + } + + public static String decrypt(String key, String initVector, String encrypted) { + try { + IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); + SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); + + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); + + byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted)); + + return new String(original); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return null; + } +} diff --git a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java index 1c74219..712fc01 100644 --- a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java +++ b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java @@ -38,1377 +38,1422 @@ import java.util.stream.Collectors; @AllArgsConstructor @NoArgsConstructor public class DealWithMapping extends ToolUtil { - - public static final char SBC_SPACE = 12288; // 全角空格 12288 - public static final char DBC_SPACE = 32; // 半角空格 32 - // ASCII character 33-126 <-> unicode 65281-65374 - public static final char ASCII_START = 33; - public static final char ASCII_END = 126; - public static final char UNICODE_START = 65281; - public static final char UNICODE_END = 65374; - public static final char DBC_SBC_STEP = 65248; // - private final ConfigMappingCMD mappingCMD = new ConfigMappingCMD(); - private String mainTable; - private String forMatString; - private List fileNames = new ArrayList<>(); - private List fileInputStreams = new ArrayList<>(); - private List multipartFileList = new ArrayList<>(); - - private RecordSet tempRs; - - /** - *

将日期字符串转换为Date对象

- * - * @param dateStr 日期字符串 - * @return 日期对象 - */ - public static Date parseDate(String dateStr) { - ThreadLocal SIMPLE_DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd")); - if (dateStr == null || dateStr.length() == 0) { - return null; - } - String regex = "\\/|\\.|年|月|日"; - Date date = null; - try { - date = SIMPLE_DATE_FORMAT.get().parse(dateStr.replaceAll(regex, "-")); - return date; - } catch (ParseException e) { - // TODO Auto-generated catch block - throw new ValueDealException("无法将" + dateStr + "转换为日期对象!", e); - } - } - - private static Map getMapMapping(RecordSet rs) { - Map map = new HashMap<>(); - String[] columnType = rs.getColumnTypeName(); - int colCounts; - colCounts = rs.getColCounts() == 0 ? columnType.length : rs.getColCounts(); - for (int i = 1; i <= colCounts; i++) { - String key; - String type = "varchar"; - if (columnType != null) { - if (columnType.length != colCounts) { - type = "varchar"; - } else { - type = columnType[i - 1]; - } - } - key = rs.getColumnName(i).toLowerCase(); - if ("int".equalsIgnoreCase(type) || "Integer".equalsIgnoreCase(type) - || "Long".equalsIgnoreCase(type) || "BIGINT".equalsIgnoreCase(type) - || "NUMBER".equalsIgnoreCase(type) || "INTEGER".equalsIgnoreCase(type) - || "TINYINT".equalsIgnoreCase(type) || "SMALLINT".equalsIgnoreCase(type)) { - map.put(key, rs.getInt(i) == -1 ? rs.getString(i) : rs.getInt(i)); - continue; - } - if ("FLOAT".equalsIgnoreCase(type)) { - map.put(key, rs.getFloat(i)); - continue; - } - if ("DATE".equalsIgnoreCase(type) || "TIMESTAMP".equalsIgnoreCase(type) - || "DATETIME".equalsIgnoreCase(type)) { - map.put(key, rs.getString(i)); - continue; - } - if ("DOUBLE".equalsIgnoreCase(type)) { - map.put(key, rs.getDouble(i)); - continue; - } - if ("DECIMAL".equalsIgnoreCase(type) || "NUMERIC".equalsIgnoreCase(type)) { - map.put(key, rs.getDouble(i)); - continue; - } - map.put(key, rs.getString(i)); - } - return map; - } - - /** - * 全角转半角 - * - * @param src 全角字符 - * @return 半角字符 - */ - public static char sbc2dbc(char src) { - if (src == SBC_SPACE) { - return DBC_SPACE; - } - - if (src >= UNICODE_START && src <= UNICODE_END) { - return (char) (src - DBC_SBC_STEP); - } - - return src; - } - - /** - * 全角转半角 - * - * @param src 全角字符串 - * @return DBC case - */ - public static String sbc2dbcCase(String src) { - if (src == null) { - return null; - } - char[] c = src.toCharArray(); - for (int i = 0; i < c.length; i++) { - c[i] = sbc2dbc(c[i]); - } - return new String(c); - } - - /** - * 将配置参数通过唯一标识查询处理成树形结构 - * - * @param uniqueCode 唯一标识 - * @return - */ - public RequestMappingConfig treeDealWithUniqueCode(String uniqueCode) { - this.writeDebuggerLog("============== 根据uniqueCode查询请求配置树形列表 treeDealWith begin ================="); - RequestMappingConfig tempConfig = mappingCMD.selectByUniqueCode(uniqueCode); - return this.dealWith(tempConfig); - } - - /** - * 处理成树形结构 - * - * @param tempConfig 配置列表 - * @return - */ - public RequestMappingConfig dealWith(RequestMappingConfig tempConfig) { - this.writeDebuggerLog("查询到的请求配置列表 query RequestMappingConfig list >>>" + JSON.toJSONString(tempConfig)); - List mappingDetails = tempConfig.getConfigDetail(); - List subMappingDetailList = new ArrayList<>(); - // 过滤出指定节点的子节点,并返回除去子节点之外的节点列表 - List collect = this.filterList(mappingDetails, subMappingDetailList, "rootNode"); - // 将数据库查询出来的信息赋值给要返回的配置信息树 - RequestMappingConfig requestMappingConfig = new RequestMappingConfig(); - requestMappingConfig.setRequestUrl(tempConfig.getRequestUrl()); - requestMappingConfig.setWorkflow(tempConfig.getWorkflow()); - requestMappingConfig.setResponseMappingList(tempConfig.getResponseMappingList()); - requestMappingConfig.setRelationWorkFlow(tempConfig.getRelationWorkFlow()); - requestMappingConfig.setCusWhereSql(tempConfig.getCusWhereSql()); - List mappingDetailList = new ArrayList<>(); - // 循环判断根节点 - for (MappingDetail mappingDetail : collect) { - String paramType = mappingDetail.getParamType(); - ParamTypeEnum anEnum = ParamTypeEnum.getEnum(paramType); - if (ParamTypeEnum.OBJECT == anEnum || ParamTypeEnum.LIST == anEnum) { - List childList = new ArrayList<>(); - mappingDetail.setChildList(childList); - this.getChildList(mappingDetail, mappingDetails, childList); - } - mappingDetailList.add(mappingDetail); - } - requestMappingConfig.setConfigDetail(mappingDetailList); - this.writeDebuggerLog("通过处理后得到的树形参数列表 deal with tree >>>" + JSON.toJSONString(requestMappingConfig)); - return requestMappingConfig; - } - - /** - * 通过递归的方式设置子节点信息 - * - * @param mappingDetail 当前节点 - * @param mappingDetailList 所有节点 - * @param childList 子节点 - */ - private void getChildList(MappingDetail mappingDetail, List mappingDetailList, List childList) { - String paramName = mappingDetail.getParamName(); - String paramType = mappingDetail.getParamType(); - if ("5".equals(paramType) || "6".equals(paramType)) { - List list = new ArrayList<>(); - mappingDetail.setChildList(list); - List subMappingDetailList = new ArrayList<>(); - List collect = this.filterList(mappingDetailList, subMappingDetailList, paramName); - for (MappingDetail detail : collect) { - this.getChildList(detail, subMappingDetailList, list); - } - } - childList.add(mappingDetail); - } - - /** - * 过滤list集合信息 - * - * @param mappingDetailList 原始集合 - * @param subMappingDetailList 过滤后集合 - * @param paramName 过滤信息 - * @return - */ - private List filterList(List mappingDetailList, List subMappingDetailList, String paramName) { - List tempList = new ArrayList<>(); - for (MappingDetail mappingDetail : mappingDetailList) { - String belongTo = mappingDetail.getBelongTo(); - if (paramName.equals(belongTo)) { - tempList.add(mappingDetail); - } else { - subMappingDetailList.add(mappingDetail); - } - } - return tempList; - } - - /** - * 解析请求参数配置树,转换成请求参数 - * - * @param recordSet 主表数据结果集 - * @param requestMappingConfig 配置树 - * @return - */ - public Map getRequestParam(RecordSet recordSet, RequestMappingConfig requestMappingConfig) { - this.fileInputStreams.clear(); - this.multipartFileList.clear(); - this.fileNames.clear(); - Map requestParam = new HashMap<>(); - List configDetail = requestMappingConfig.getConfigDetail(); - Map mainMap = getMapMapping(recordSet); - this.objValueDeal(mainMap, null, configDetail, requestParam); - return requestParam; - } - - /** - * 解析请求参数配置树,转换成请求参数 - * - * @param recordSet 主表数据结果集 - * @param requestMappingConfig 配置树 - * @param relationRs 关联表数据 - * @return - */ - public Map getRequestParamsByRelationWorkFlow(RecordSet recordSet, RequestMappingConfig requestMappingConfig, RecordSet relationRs, String sql) { - this.fileInputStreams.clear(); - this.multipartFileList.clear(); - this.fileNames.clear(); - Map requestParam = new HashMap<>(); - List configDetail = requestMappingConfig.getConfigDetail(); - Map mainMap = getMapMapping(recordSet); - tempRs = new RecordSet(); - tempRs.executeQuery(sql); - tempRs.next(); - this.objValueDeal(mainMap, null, relationRs, configDetail, requestParam); - return requestParam; - } - - /** - * 解析请求参数配置树,转换成请求参数 - * - * @param recordSet 主表数据结果集 - * @param requestMappingConfig 配置树 - * @return - */ - public List getRequestListParam(RecordSet recordSet, RequestMappingConfig requestMappingConfig) { - this.fileInputStreams.clear(); - this.multipartFileList.clear(); - this.fileNames.clear(); - Map requestParam = new HashMap<>(); - List configDetail = requestMappingConfig.getConfigDetail(); - Map mainMap = getMapMapping(recordSet); - this.objValueDeal(mainMap, null, configDetail, requestParam); - List rootList = (List) requestParam.get("rootList"); - return rootList; - } - - /** - *

方法重载 通过主表数据map转为请求参数

- * - * @param mainMap 主表数据集合 - * @param requestMappingConfig 配置树 - * @return 请求参数集合 - */ - public List getRequestListParam(Map mainMap, RequestMappingConfig requestMappingConfig) { - this.fileInputStreams.clear(); - this.multipartFileList.clear(); - this.fileNames.clear(); - Map requestParam = new HashMap<>(); - List configDetail = requestMappingConfig.getConfigDetail(); - this.objValueDeal(mainMap, null, configDetail, requestParam); - List rootList = (List) requestParam.get("rootList"); - return rootList; - } - - /** - *

方法重载 通过主表数据map转为请求参数

- * - * @param mainMap 主表数据集合 - * @param requestMappingConfig 配置树 - * @return 请求参数 - */ - public Map getRequestParam(Map mainMap, RequestMappingConfig requestMappingConfig) { - this.fileInputStreams.clear(); - this.multipartFileList.clear(); - this.fileNames.clear(); - Map requestParam = new HashMap<>(); - List configDetail = requestMappingConfig.getConfigDetail(); - this.objValueDeal(mainMap, null, configDetail, requestParam); - return requestParam; - } - - /** - * 解析请求参数配置树,转换成请求参数 - * - * @param recordSet 主表数据结果集 - * @param detailRecordSet 明细表数据集 - * @param requestMappingConfig 配置树 - * @return - */ - public List> getRequestParams(RecordSet recordSet, RecordSet detailRecordSet, RequestMappingConfig requestMappingConfig) { - this.fileInputStreams.clear(); - this.multipartFileList.clear(); - this.fileNames.clear(); - List> list = new ArrayList<>(); - while (detailRecordSet.next()) { - Map requestParam = new HashMap<>(); - List configDetail = requestMappingConfig.getConfigDetail(); - Map mainMap = getMapMapping(recordSet); - Map detailMap = getMapMapping(detailRecordSet); - this.objValueDeal(mainMap, detailMap, configDetail, requestParam); - list.add(requestParam); - } - return list; - } - - /** - * 对象类型处理 - * - * @param mainMap 主表数据结果集 - * @param detailMap 明细数据结果集 - * @param configDetail 配置列表集合 - * @param requestParam 节点参数 - */ - private void objValueDeal(Map mainMap, Map detailMap, List configDetail, Map requestParam) { - for (MappingDetail mappingDetail : configDetail) { - String paramType = mappingDetail.getParamType(); - ParamTypeEnum anEnum = ParamTypeEnum.getEnum(paramType); - String paramName = mappingDetail.getParamName(); - // 5为对象类型 - if (ParamTypeEnum.OBJECT == anEnum) { - List childList = mappingDetail.getChildList(); - Map map = new HashMap<>(); - requestParam.put(paramName, map); - this.objValueDeal(mainMap, detailMap, childList, map); - } - // 6为List类型 - else if (ParamTypeEnum.LIST == anEnum) { - String childType = mappingDetail.getChildType(); - List childList = mappingDetail.getChildList(); - List list = new ArrayList<>(); - requestParam.put(paramName, list); - this.listValueDeal(mainMap, childList, list, mappingDetail); - List tempList = new ArrayList(); - for (Object o : list) { - if (o instanceof Map) { - // map处理 key->1的类型 - Map mapItem = (Map) o; - Map> tempMap = new HashMap<>(8); - for (Map.Entry entry : mapItem.entrySet()) { - String key = entry.getKey(); - String pattern = "(?\\S+)->(\\[(?[0-9]+)])"; - Pattern compile = Pattern.compile(pattern); - Matcher matcher = compile.matcher(key); - Object value = entry.getValue(); - if (matcher.find()) { - String tempKey = matcher.group("key"); - if (key.endsWith("_")) { - tempKey = tempKey + "_"; - } - ListMapIndexValue listMapIndexValue = new ListMapIndexValue(); - listMapIndexValue.setValue(value); - listMapIndexValue.setKey(tempKey); - String index = matcher.group("index"); - List listMapIndexValues = tempMap.get(index); - if (null == listMapIndexValues) { - listMapIndexValues = new ArrayList<>(); - } - listMapIndexValues.add(listMapIndexValue); - tempMap.put(index, listMapIndexValues); - } else { - ListMapIndexValue listMapIndexValue = new ListMapIndexValue(); - listMapIndexValue.setValue(value); - listMapIndexValue.setKey(key); - List listMapIndexValues = tempMap.get("default"); - if (null == listMapIndexValues) { - listMapIndexValues = new ArrayList<>(); - } - listMapIndexValues.add(listMapIndexValue); - tempMap.put("default", listMapIndexValues); - } - } - for (Map.Entry> entrty : tempMap.entrySet()) { - Map map = new HashMap<>(); - List valueList = entrty.getValue(); - for (ListMapIndexValue listMapIndexValue : valueList) { - map.put(listMapIndexValue.getKey(), listMapIndexValue.getValue()); - } - tempList.add(map); - } - } - } - // tempList.addAll(list); - requestParam.put(paramName, tempList); - // if (!tempList.isEmpty()) { - // requestParam.put(paramName, tempList); - // } - } else { - Object value = this.normalValueDeal(mainMap, detailMap, mappingDetail); - if (!Objects.isNull(value)) { - requestParam.put(paramName, value); - } - } - } - } - - /** - * 对象类型处理 方法重载 - * - * @param mainMap 主表数据结果集 - * @param detailMap 明细数据结果集 - * @param configDetail 配置列表集合 - * @param requestParam 节点参数 - * @auhor XuanRan.Wang - */ - private void objValueDeal(Map mainMap, Map detailMap, RecordSet relationRs, List configDetail, Map requestParam) { - for (MappingDetail mappingDetail : configDetail) { - String paramType = mappingDetail.getParamType(); - ParamTypeEnum anEnum = ParamTypeEnum.getEnum(paramType); - String paramName = mappingDetail.getParamName(); - // 5为对象类型 - if (ParamTypeEnum.OBJECT == anEnum) { - List childList = mappingDetail.getChildList(); - Map map = new HashMap<>(); - requestParam.put(paramName, map); - this.objValueDeal(mainMap, detailMap, relationRs, childList, map); - } - // 6为List类型 - else if (ParamTypeEnum.LIST == anEnum) { - String childType = mappingDetail.getChildType(); - List childList = mappingDetail.getChildList(); - List list = new ArrayList<>(); - requestParam.put(paramName, list); - this.listValueDeal(mainMap, childList, list, mappingDetail, relationRs); - List tempList = new ArrayList(); - for (Object o : list) { - if (o instanceof Map) { - // map处理 - Map mapItem = (Map) o; - Map> tempMap = new HashMap<>(8); - for (Map.Entry entry : mapItem.entrySet()) { - String key = entry.getKey(); - String pattern = "(?\\S+)->(\\[(?[0-9]+)])"; - Pattern compile = Pattern.compile(pattern); - Matcher matcher = compile.matcher(key); - Object value = entry.getValue(); - if (matcher.find()) { - String tempKey = matcher.group("key"); - if (key.endsWith("_")) { - tempKey = tempKey + "_"; - } - ListMapIndexValue listMapIndexValue = new ListMapIndexValue(); - listMapIndexValue.setValue(value); - listMapIndexValue.setKey(tempKey); - String index = matcher.group("index"); - List listMapIndexValues = tempMap.get(index); - if (null == listMapIndexValues) { - listMapIndexValues = new ArrayList<>(); - } - listMapIndexValues.add(listMapIndexValue); - tempMap.put(index, listMapIndexValues); - } else { - ListMapIndexValue listMapIndexValue = new ListMapIndexValue(); - listMapIndexValue.setValue(value); - listMapIndexValue.setKey(key); - List listMapIndexValues = tempMap.get("default"); - if (null == listMapIndexValues) { - listMapIndexValues = new ArrayList<>(); - } - listMapIndexValues.add(listMapIndexValue); - tempMap.put("default", listMapIndexValues); - } - } - for (Map.Entry> entrty : tempMap.entrySet()) { - Map map = new HashMap<>(); - List valueList = entrty.getValue(); - for (ListMapIndexValue listMapIndexValue : valueList) { - map.put(listMapIndexValue.getKey(), listMapIndexValue.getValue()); - } - tempList.add(map); - } - } - } - // tempList.addAll(list); - requestParam.put(paramName, tempList); - // if (!tempList.isEmpty()) { - // requestParam.put(paramName, tempList); - // } - } else { - Object value = this.normalValueDeal(mainMap, detailMap, relationRs, mappingDetail); - if (!Objects.isNull(value)) { - requestParam.put(paramName, value); - } - } - } - } - - /** - * 普通类型处理 - * - * @param mainMap 主表数据结果集 - * @param detailMap 明细数据结果集 - * @param mappingDetail 配置节点信息 - * - *

代码版本改动说明:

- *

- * v2.0 xuanran.wang 转换类型是默认值时增加替换规则 将自定义文本中的{?requestid}替换成requestid 以及将 {?} 替换成选择的流程字段对应的值 - *

- */ - private Object normalValueDeal(Map mainMap, Map detailMap, MappingDetail mappingDetail) { - - String paramType = mappingDetail.getParamType(); - ParamTypeEnum typeEnum = ParamTypeEnum.getEnum(paramType); - String getValueType = mappingDetail.getGetValueType(); - GetValueTypeEnum getValueTypeEnum = GetValueTypeEnum.getEnum(getValueType); - String valueContext = mappingDetail.getValueContext(); - String childSource = mappingDetail.getDataSource(); - String paramName = mappingDetail.getParamName(); - Object value = ""; - switch (getValueTypeEnum) { - // 流程字段 - case WORKFLOW_FIELD: { - FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - String fieldName = fieldMassage.getFieldName(); - String fieldNameLower = fieldName.toLowerCase(); - if ("1".equals(childSource)) { - value = Util.null2String(detailMap.get(fieldNameLower)); - if ("".equals(value)) { - value = Util.null2String(detailMap.get(fieldName)); - } - } else { - value = Util.null2String(mainMap.get(fieldNameLower)); - if ("".equals(value)) { - value = Util.null2String(mainMap.get(fieldName)); - } - } - } - break; - // 默认值 - case DEFAULT_VALUE: { - FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - String workFlowVal = ""; - if (fieldMassage != null) { - String fieldName = fieldMassage.getFieldName(); - String fieldNameLowe = fieldName.toLowerCase(); - if ("1".equals(childSource)) { - workFlowVal = Util.null2String(detailMap.get(fieldNameLowe)); - if ("".equals(workFlowVal)) { - workFlowVal = Util.null2String(detailMap.get(fieldName)); - } - } else if ("0".equals(childSource)) { - workFlowVal = Util.null2String(mainMap.get(fieldNameLowe)); - if ("".equals(workFlowVal)) { - workFlowVal = Util.null2String(mainMap.get(fieldName)); - } - } - } - value = Util.null2String(valueContext) - .replace("{?requestid}", String.valueOf(mainMap.get("requestid"))) - .replace("{?}", workFlowVal); - } - break; - // 当前时间 - case CURRENT_TIME: { - value = new Date(); - } - break; - // 自定义sql查询 - case CUS_SQL: { - FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - String tempValue = ""; - int detailId = -1; - if (fieldMassage != null) { - String fieldName = fieldMassage.getFieldName(); - if ("1".equals(childSource)) { - tempValue = Util.null2String(detailMap.get(fieldName)); - detailId = Util.getIntValue(Util.null2String(detailMap.get("id")), -1); - } else { - tempValue = Util.null2String(mainMap.get(fieldName)); - } - } - String requestId = Util.null2String(mainMap.get("requestid")); - tempValue = "'" + tempValue + "'"; - value = this.getValueByChangeRule(valueContext, tempValue, requestId, detailId); - } - break; - // requestId - case REQUEST_ID: { - value = Util.null2String(mainMap.get("requestid")); - } - break; - // 数据id - case MAIN_DATA_ID: { - if ("1".equals(childSource)) { - value = Util.null2String(detailMap.get("id")); - } else { - value = Util.null2String(mainMap.get("id")); - } - // value = Util.null2String(main.getString("id")); - } - break; - // 随机数 - case RANDOM: { - int bit = Util.getIntValue(valueContext, 10); - value = this.getGUID(bit); - } - break; - // 附件 - case ATTACHMENT: { + + public static final char SBC_SPACE = 12288; // 全角空格 12288 + public static final char DBC_SPACE = 32; // 半角空格 32 + // ASCII character 33-126 <-> unicode 65281-65374 + public static final char ASCII_START = 33; + public static final char ASCII_END = 126; + public static final char UNICODE_START = 65281; + public static final char UNICODE_END = 65374; + public static final char DBC_SBC_STEP = 65248; // + private final ConfigMappingCMD mappingCMD = new ConfigMappingCMD(); + private String mainTable; + private String forMatString; + private List fileNames = new ArrayList<>(); + private List fileInputStreams = new ArrayList<>(); + private List multipartFileList = new ArrayList<>(); + + private RecordSet tempRs; + + /** + *

将日期字符串转换为Date对象

+ * + * @param dateStr 日期字符串 + * @return 日期对象 + */ + public static Date parseDate(String dateStr) { + ThreadLocal SIMPLE_DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd")); + if (dateStr == null || dateStr.length() == 0) { + return null; + } + String regex = "\\/|\\.|年|月|日"; + Date date = null; + try { + date = SIMPLE_DATE_FORMAT.get().parse(dateStr.replaceAll(regex, "-")); + return date; + } catch (ParseException e) { + // TODO Auto-generated catch block + throw new ValueDealException("无法将" + dateStr + "转换为日期对象!", e); + } + } + + private static Map getMapMapping(RecordSet rs) { + Map map = new HashMap<>(); + String[] columnType = rs.getColumnTypeName(); + int colCounts; + colCounts = rs.getColCounts() == 0 ? columnType.length : rs.getColCounts(); + for (int i = 1; i <= colCounts; i++) { + String key; + String type = "varchar"; + if (columnType != null) { + if (columnType.length != colCounts) { + type = "varchar"; + } else { + type = columnType[i - 1]; + } + } + key = rs.getColumnName(i).toLowerCase(); + if ("int".equalsIgnoreCase(type) || "Integer".equalsIgnoreCase(type) + || "Long".equalsIgnoreCase(type) || "BIGINT".equalsIgnoreCase(type) + || "NUMBER".equalsIgnoreCase(type) || "INTEGER".equalsIgnoreCase(type) + || "TINYINT".equalsIgnoreCase(type) || "SMALLINT".equalsIgnoreCase(type)) { + map.put(key, rs.getInt(i) == -1 ? rs.getString(i) : rs.getInt(i)); + continue; + } + if ("FLOAT".equalsIgnoreCase(type)) { + map.put(key, rs.getFloat(i)); + continue; + } + if ("DATE".equalsIgnoreCase(type) || "TIMESTAMP".equalsIgnoreCase(type) + || "DATETIME".equalsIgnoreCase(type)) { + map.put(key, rs.getString(i)); + continue; + } + if ("DOUBLE".equalsIgnoreCase(type)) { + map.put(key, rs.getDouble(i)); + continue; + } + if ("DECIMAL".equalsIgnoreCase(type) || "NUMERIC".equalsIgnoreCase(type)) { + map.put(key, rs.getDouble(i)); + continue; + } + map.put(key, rs.getString(i)); + } + return map; + } + + /** + * 全角转半角 + * + * @param src 全角字符 + * @return 半角字符 + */ + public static char sbc2dbc(char src) { + if (src == SBC_SPACE) { + return DBC_SPACE; + } + + if (src >= UNICODE_START && src <= UNICODE_END) { + return (char) (src - DBC_SBC_STEP); + } + + return src; + } + + /** + * 全角转半角 + * + * @param src 全角字符串 + * @return DBC case + */ + public static String sbc2dbcCase(String src) { + if (src == null) { + return null; + } + char[] c = src.toCharArray(); + for (int i = 0; i < c.length; i++) { + c[i] = sbc2dbc(c[i]); + } + return new String(c); + } + + /** + * 将配置参数通过唯一标识查询处理成树形结构 + * + * @param uniqueCode 唯一标识 + * @return + */ + public RequestMappingConfig treeDealWithUniqueCode(String uniqueCode) { + this.writeDebuggerLog("============== 根据uniqueCode查询请求配置树形列表 treeDealWith begin ================="); + RequestMappingConfig tempConfig = mappingCMD.selectByUniqueCode(uniqueCode); + return this.dealWith(tempConfig); + } + + /** + * 处理成树形结构 + * + * @param tempConfig 配置列表 + * @return + */ + public RequestMappingConfig dealWith(RequestMappingConfig tempConfig) { + this.writeDebuggerLog("查询到的请求配置列表 query RequestMappingConfig list >>>" + JSON.toJSONString(tempConfig)); + List mappingDetails = tempConfig.getConfigDetail(); + List subMappingDetailList = new ArrayList<>(); + // 过滤出指定节点的子节点,并返回除去子节点之外的节点列表 + List collect = this.filterList(mappingDetails, subMappingDetailList, "rootNode"); + // 将数据库查询出来的信息赋值给要返回的配置信息树 + RequestMappingConfig requestMappingConfig = new RequestMappingConfig(); + requestMappingConfig.setRequestUrl(tempConfig.getRequestUrl()); + requestMappingConfig.setWorkflow(tempConfig.getWorkflow()); + requestMappingConfig.setResponseMappingList(tempConfig.getResponseMappingList()); + requestMappingConfig.setRelationWorkFlow(tempConfig.getRelationWorkFlow()); + requestMappingConfig.setCusWhereSql(tempConfig.getCusWhereSql()); + List mappingDetailList = new ArrayList<>(); + // 循环判断根节点 + for (MappingDetail mappingDetail : collect) { + String paramType = mappingDetail.getParamType(); + ParamTypeEnum anEnum = ParamTypeEnum.getEnum(paramType); + if (ParamTypeEnum.OBJECT == anEnum || ParamTypeEnum.LIST == anEnum) { + List childList = new ArrayList<>(); + mappingDetail.setChildList(childList); + this.getChildList(mappingDetail, mappingDetails, childList); + } + mappingDetailList.add(mappingDetail); + } + requestMappingConfig.setConfigDetail(mappingDetailList); + this.writeDebuggerLog("通过处理后得到的树形参数列表 deal with tree >>>" + JSON.toJSONString(requestMappingConfig)); + return requestMappingConfig; + } + + /** + * 通过递归的方式设置子节点信息 + * + * @param mappingDetail 当前节点 + * @param mappingDetailList 所有节点 + * @param childList 子节点 + */ + private void getChildList(MappingDetail mappingDetail, List mappingDetailList, List childList) { + String paramName = mappingDetail.getParamName(); + String paramType = mappingDetail.getParamType(); + if ("5".equals(paramType) || "6".equals(paramType)) { + List list = new ArrayList<>(); + mappingDetail.setChildList(list); + List subMappingDetailList = new ArrayList<>(); + List collect = this.filterList(mappingDetailList, subMappingDetailList, paramName); + for (MappingDetail detail : collect) { + this.getChildList(detail, subMappingDetailList, list); + } + } + childList.add(mappingDetail); + } + + /** + * 过滤list集合信息 + * + * @param mappingDetailList 原始集合 + * @param subMappingDetailList 过滤后集合 + * @param paramName 过滤信息 + * @return + */ + private List filterList(List mappingDetailList, List subMappingDetailList, String paramName) { + List tempList = new ArrayList<>(); + for (MappingDetail mappingDetail : mappingDetailList) { + String belongTo = mappingDetail.getBelongTo(); + if (paramName.equals(belongTo)) { + tempList.add(mappingDetail); + } else { + subMappingDetailList.add(mappingDetail); + } + } + return tempList; + } + + /** + * 解析请求参数配置树,转换成请求参数 + * + * @param recordSet 主表数据结果集 + * @param requestMappingConfig 配置树 + * @return + */ + public Map getRequestParam(RecordSet recordSet, RequestMappingConfig requestMappingConfig) { + this.fileInputStreams.clear(); + this.multipartFileList.clear(); + this.fileNames.clear(); + Map requestParam = new HashMap<>(); + List configDetail = requestMappingConfig.getConfigDetail(); + Map mainMap = getMapMapping(recordSet); + this.objValueDeal(mainMap, null, configDetail, requestParam); + return requestParam; + } + + /** + * 解析请求参数配置树,转换成请求参数 + * + * @param recordSet 主表数据结果集 + * @param requestMappingConfig 配置树 + * @param relationRs 关联表数据 + * @return + */ + public Map getRequestParamsByRelationWorkFlow(RecordSet recordSet, RequestMappingConfig requestMappingConfig, RecordSet relationRs, String sql) { + this.fileInputStreams.clear(); + this.multipartFileList.clear(); + this.fileNames.clear(); + Map requestParam = new HashMap<>(); + List configDetail = requestMappingConfig.getConfigDetail(); + Map mainMap = getMapMapping(recordSet); + tempRs = new RecordSet(); + tempRs.executeQuery(sql); + tempRs.next(); + this.objValueDeal(mainMap, null, relationRs, configDetail, requestParam); + return requestParam; + } + + /** + * 解析请求参数配置树,转换成请求参数 + * + * @param recordSet 主表数据结果集 + * @param requestMappingConfig 配置树 + * @return + */ + public List getRequestListParam(RecordSet recordSet, RequestMappingConfig requestMappingConfig) { + this.fileInputStreams.clear(); + this.multipartFileList.clear(); + this.fileNames.clear(); + Map requestParam = new HashMap<>(); + List configDetail = requestMappingConfig.getConfigDetail(); + Map mainMap = getMapMapping(recordSet); + this.objValueDeal(mainMap, null, configDetail, requestParam); + List rootList = (List) requestParam.get("rootList"); + return rootList; + } + + /** + *

方法重载 通过主表数据map转为请求参数

+ * + * @param mainMap 主表数据集合 + * @param requestMappingConfig 配置树 + * @return 请求参数集合 + */ + public List getRequestListParam(Map mainMap, RequestMappingConfig requestMappingConfig) { + this.fileInputStreams.clear(); + this.multipartFileList.clear(); + this.fileNames.clear(); + Map requestParam = new HashMap<>(); + List configDetail = requestMappingConfig.getConfigDetail(); + this.objValueDeal(mainMap, null, configDetail, requestParam); + List rootList = (List) requestParam.get("rootList"); + return rootList; + } + + /** + *

方法重载 通过主表数据map转为请求参数

+ * + * @param mainMap 主表数据集合 + * @param requestMappingConfig 配置树 + * @return 请求参数 + */ + public Map getRequestParam(Map mainMap, RequestMappingConfig requestMappingConfig) { + this.fileInputStreams.clear(); + this.multipartFileList.clear(); + this.fileNames.clear(); + Map requestParam = new HashMap<>(); + List configDetail = requestMappingConfig.getConfigDetail(); + this.objValueDeal(mainMap, null, configDetail, requestParam); + return requestParam; + } + + /** + * 解析请求参数配置树,转换成请求参数 + * + * @param recordSet 主表数据结果集 + * @param detailRecordSet 明细表数据集 + * @param requestMappingConfig 配置树 + * @return + */ + public List> getRequestParams(RecordSet recordSet, RecordSet detailRecordSet, RequestMappingConfig requestMappingConfig) { + this.fileInputStreams.clear(); + this.multipartFileList.clear(); + this.fileNames.clear(); + List> list = new ArrayList<>(); + while (detailRecordSet.next()) { + Map requestParam = new HashMap<>(); + List configDetail = requestMappingConfig.getConfigDetail(); + Map mainMap = getMapMapping(recordSet); + Map detailMap = getMapMapping(detailRecordSet); + this.objValueDeal(mainMap, detailMap, configDetail, requestParam); + list.add(requestParam); + } + return list; + } + + /** + * 对象类型处理 + * + * @param mainMap 主表数据结果集 + * @param detailMap 明细数据结果集 + * @param configDetail 配置列表集合 + * @param requestParam 节点参数 + */ + private void objValueDeal(Map mainMap, Map detailMap, List configDetail, Map requestParam) { + for (MappingDetail mappingDetail : configDetail) { + String paramType = mappingDetail.getParamType(); + ParamTypeEnum anEnum = ParamTypeEnum.getEnum(paramType); + String paramName = mappingDetail.getParamName(); + // 5为对象类型 + if (ParamTypeEnum.OBJECT == anEnum) { + List childList = mappingDetail.getChildList(); + Map map = new HashMap<>(); + requestParam.put(paramName, map); + this.objValueDeal(mainMap, detailMap, childList, map); + } + // 6为List类型 + else if (ParamTypeEnum.LIST == anEnum) { + String childType = mappingDetail.getChildType(); + List childList = mappingDetail.getChildList(); + List list = new ArrayList<>(); + requestParam.put(paramName, list); + this.listValueDeal(mainMap, childList, list, mappingDetail); + List tempList = new ArrayList(); + for (Object o : list) { + if (o instanceof Map) { + // map处理 key->1的类型 + Map mapItem = (Map) o; + Map> tempMap = new HashMap<>(8); + for (Map.Entry entry : mapItem.entrySet()) { + String key = entry.getKey(); + String pattern = "(?\\S+)->(\\[(?[0-9]+)])"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(key); + Object value = entry.getValue(); + if (matcher.find()) { + String tempKey = matcher.group("key"); + if (key.endsWith("_")) { + tempKey = tempKey + "_"; + } + ListMapIndexValue listMapIndexValue = new ListMapIndexValue(); + listMapIndexValue.setValue(value); + listMapIndexValue.setKey(tempKey); + String index = matcher.group("index"); + List listMapIndexValues = tempMap.get(index); + if (null == listMapIndexValues) { + listMapIndexValues = new ArrayList<>(); + } + listMapIndexValues.add(listMapIndexValue); + tempMap.put(index, listMapIndexValues); + } else { + ListMapIndexValue listMapIndexValue = new ListMapIndexValue(); + listMapIndexValue.setValue(value); + listMapIndexValue.setKey(key); + List listMapIndexValues = tempMap.get("default"); + if (null == listMapIndexValues) { + listMapIndexValues = new ArrayList<>(); + } + listMapIndexValues.add(listMapIndexValue); + tempMap.put("default", listMapIndexValues); + } + } + for (Map.Entry> entrty : tempMap.entrySet()) { + Map map = new HashMap<>(); + List valueList = entrty.getValue(); + for (ListMapIndexValue listMapIndexValue : valueList) { + map.put(listMapIndexValue.getKey(), listMapIndexValue.getValue()); + } + tempList.add(map); + } + } + } + // tempList.addAll(list); + requestParam.put(paramName, tempList); + // if (!tempList.isEmpty()) { + // requestParam.put(paramName, tempList); + // } + } else { + Object value = this.normalValueDeal(mainMap, detailMap, mappingDetail); + if (!Objects.isNull(value)) { + requestParam.put(paramName, value); + } + } + } + } + + /** + * 对象类型处理 方法重载 + * + * @param mainMap 主表数据结果集 + * @param detailMap 明细数据结果集 + * @param configDetail 配置列表集合 + * @param requestParam 节点参数 + * @auhor XuanRan.Wang + */ + private void objValueDeal(Map mainMap, Map detailMap, RecordSet relationRs, List configDetail, Map requestParam) { + for (MappingDetail mappingDetail : configDetail) { + String paramType = mappingDetail.getParamType(); + ParamTypeEnum anEnum = ParamTypeEnum.getEnum(paramType); + String paramName = mappingDetail.getParamName(); + // 5为对象类型 + if (ParamTypeEnum.OBJECT == anEnum) { + List childList = mappingDetail.getChildList(); + Map map = new HashMap<>(); + requestParam.put(paramName, map); + this.objValueDeal(mainMap, detailMap, relationRs, childList, map); + } + // 6为List类型 + else if (ParamTypeEnum.LIST == anEnum) { + String childType = mappingDetail.getChildType(); + List childList = mappingDetail.getChildList(); + List list = new ArrayList<>(); + requestParam.put(paramName, list); + this.listValueDeal(mainMap, childList, list, mappingDetail, relationRs); + List tempList = new ArrayList(); + for (Object o : list) { + if (o instanceof Map) { + // map处理 + Map mapItem = (Map) o; + Map> tempMap = new HashMap<>(8); + for (Map.Entry entry : mapItem.entrySet()) { + String key = entry.getKey(); + String pattern = "(?\\S+)->(\\[(?[0-9]+)])"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(key); + Object value = entry.getValue(); + if (matcher.find()) { + String tempKey = matcher.group("key"); + if (key.endsWith("_")) { + tempKey = tempKey + "_"; + } + ListMapIndexValue listMapIndexValue = new ListMapIndexValue(); + listMapIndexValue.setValue(value); + listMapIndexValue.setKey(tempKey); + String index = matcher.group("index"); + List listMapIndexValues = tempMap.get(index); + if (null == listMapIndexValues) { + listMapIndexValues = new ArrayList<>(); + } + listMapIndexValues.add(listMapIndexValue); + tempMap.put(index, listMapIndexValues); + } else { + ListMapIndexValue listMapIndexValue = new ListMapIndexValue(); + listMapIndexValue.setValue(value); + listMapIndexValue.setKey(key); + List listMapIndexValues = tempMap.get("default"); + if (null == listMapIndexValues) { + listMapIndexValues = new ArrayList<>(); + } + listMapIndexValues.add(listMapIndexValue); + tempMap.put("default", listMapIndexValues); + } + } + for (Map.Entry> entrty : tempMap.entrySet()) { + Map map = new HashMap<>(); + List valueList = entrty.getValue(); + for (ListMapIndexValue listMapIndexValue : valueList) { + map.put(listMapIndexValue.getKey(), listMapIndexValue.getValue()); + } + tempList.add(map); + } + } + } + // tempList.addAll(list); + requestParam.put(paramName, tempList); + // if (!tempList.isEmpty()) { + // requestParam.put(paramName, tempList); + // } + } else { + Object value = this.normalValueDeal(mainMap, detailMap, relationRs, mappingDetail); + if (!Objects.isNull(value)) { + requestParam.put(paramName, value); + } + } + } + } + + /** + * 普通类型处理 + * + * @param mainMap 主表数据结果集 + * @param detailMap 明细数据结果集 + * @param mappingDetail 配置节点信息 + * + *

代码版本改动说明:

+ *

+ * v2.0 xuanran.wang 转换类型是默认值时增加替换规则 将自定义文本中的{?requestid}替换成requestid 以及将 {?} 替换成选择的流程字段对应的值 + *

+ */ + private Object normalValueDeal(Map mainMap, Map detailMap, MappingDetail mappingDetail) { + + String paramType = mappingDetail.getParamType(); + ParamTypeEnum typeEnum = ParamTypeEnum.getEnum(paramType); + String getValueType = mappingDetail.getGetValueType(); + GetValueTypeEnum getValueTypeEnum = GetValueTypeEnum.getEnum(getValueType); + String valueContext = mappingDetail.getValueContext(); + String childSource = mappingDetail.getDataSource(); + String paramName = mappingDetail.getParamName(); + Object value = ""; + switch (getValueTypeEnum) { + // 流程字段 + case WORKFLOW_FIELD: { + FieldMessage fieldMassage = mappingDetail.getFieldMassage(); + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); + if ("1".equals(childSource)) { + value = Util.null2String(detailMap.get(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldName)); + } + } else { + value = Util.null2String(mainMap.get(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(mainMap.get(fieldName)); + } + } + } + break; + // 默认值 + case DEFAULT_VALUE: { + FieldMessage fieldMassage = mappingDetail.getFieldMassage(); + String workFlowVal = ""; + if (fieldMassage != null) { + String fieldName = fieldMassage.getFieldName(); + String fieldNameLowe = fieldName.toLowerCase(); + if ("1".equals(childSource)) { + workFlowVal = Util.null2String(detailMap.get(fieldNameLowe)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(detailMap.get(fieldName)); + } + } else if ("0".equals(childSource)) { + workFlowVal = Util.null2String(mainMap.get(fieldNameLowe)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(mainMap.get(fieldName)); + } + } + } + value = Util.null2String(valueContext) + .replace("{?requestid}", String.valueOf(mainMap.get("requestid"))) + .replace("{?}", workFlowVal); + } + break; + // 当前时间 + case CURRENT_TIME: { + value = new Date(); + } + break; + // 自定义sql查询 + case CUS_SQL: { + FieldMessage fieldMassage = mappingDetail.getFieldMassage(); + String tempValue = ""; + int detailId = -1; + if (fieldMassage != null) { + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); + if ("1".equals(childSource)) { + tempValue = Util.null2String(detailMap.get(fieldName)); + if ("".equals(tempValue)) { + tempValue = Util.null2String(detailMap.get(fieldNameLower)); + } + detailId = Util.getIntValue(Util.null2String(detailMap.get("id")), -1); + } else { + tempValue = Util.null2String(mainMap.get(fieldName)); + if ("".equals(tempValue)) { + tempValue = Util.null2String(detailMap.get(fieldNameLower)); + } + } + } + String requestId = Util.null2String(mainMap.get("requestid")); + tempValue = "'" + tempValue + "'"; + value = this.getValueByChangeRule(valueContext, tempValue, requestId, detailId); + } + break; + // requestId + case REQUEST_ID: { + value = Util.null2String(mainMap.get("requestid")); + } + break; + // 数据id + case MAIN_DATA_ID: { + if ("1".equals(childSource)) { + value = Util.null2String(detailMap.get("id")); + } else { + value = Util.null2String(mainMap.get("id")); + } + // value = Util.null2String(main.getString("id")); + } + break; + // 随机数 + case RANDOM: { + int bit = Util.getIntValue(valueContext, 10); + value = this.getGUID(bit); + } + break; + // 附件 + case ATTACHMENT: { /*int imageFileId = Util.getIntValue(String.valueOf(value)); InputStream inputStream = ImageFileManager.getInputStreamById(imageFileId); String fileName = this.getFileNameById(imageFileId); fileInputStreams.add(inputStream); fileNames.add(fileName);*/ - FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - String fieldName = fieldMassage.getFieldName(); - if ("1".equals(childSource)) { - value = Util.null2String(detailMap.get(fieldName)); - } else { - value = Util.null2String(mainMap.get(fieldName)); - } - String fileIds = Util.null2String(value); - if ("".equals(fileIds)) { - return null; - } - List docImageFiles = mappingCMD.selectDocImageFileList(fileIds); - for (DocImageFile docImageFile : docImageFiles) { - MultipartFile multipartFile = new MultipartFile(); - InputStream fileInputStream = ImageFileManager.getInputStreamById(docImageFile.getImageFileId()); - multipartFile.setDocId(docImageFile.getDocId()); - multipartFile.setImageFileId(docImageFile.getImageFileId()); - multipartFile.setFileKey(paramName); - multipartFile.setStream(fileInputStream); - multipartFile.setFileName(docImageFile.getImageFileName()); - multipartFile.setFileSize(docImageFile.getFileSize() / 1024); - multipartFileList.add(multipartFile); - } - return null; - } - // 自定义接口 - case CUS_INTERFACE: { - if (null == valueContext || valueContext.length() == 0) { - } else { - Map pathParamMap = new HashMap<>(8); - CusInterfaceGetValue o = getCusInterfaceObj(valueContext, CusInterfaceGetValue.class, pathParamMap); - FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - if (null != fieldMassage && !StringUtils.isEmpty(fieldMassage.getFieldName())) { - String fieldName = fieldMassage.getFieldName(); - if ("1".equals(childSource)) { - value = Util.null2String(detailMap.get(fieldName)); - } else { - value = Util.null2String(mainMap.get(fieldName)); - } - } - value = o.execute(mainMap, detailMap, String.valueOf(value == null ? "" : value), pathParamMap); - } - } - break; - case CUS_FIELD: { - value = detailMap.get(valueContext.trim()); - } - break; - default: - throw new ValueDealException("不支持的取值方式"); - } - switch (typeEnum) { - // String类型 - case STRING: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = ""; - break; - } - value = Util.null2String(String.valueOf(value)); - } - break; - // int类型 - case INT: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = -1; - break; - } - value = Util.getIntValue(String.valueOf(value)); - } - break; - // double类型 - case DOUBLE: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = 0.00; - break; - } - value = Util.getDoubleValue(String.valueOf(value)); - } - break; - // 日期类型 - case DATE: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = ""; - break; - } - try { - Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); - value = this.diyDateFortMat(date, "yyyy-MM-dd"); - } catch (Exception e) { - this.writeDebuggerLog("时间处理异常:" + e); - throw new ValueDealException("时间处理异常:参数>>" + paramName); - } - } - break; - // 时间日期类型 - case DATE_TIME: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = ""; - break; - } - try { - Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); - value = this.diyDateFortMat(date, "yyyy-MM-dd HH:mm:ss"); - } catch (Exception e) { - this.writeDebuggerLog("时间处理异常:" + e); - throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e); - } - } - break; - // 自定义时间格式化类型 - case CUS_DATE_STR: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = ""; - break; - } - try { - forMatString = valueContext; - Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); - value = this.diyDateFortMat(date, forMatString); - } catch (Exception e) { - this.writeDebuggerLog("时间处理异常:" + e); - throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage()); - } - } - break; - // 时间戳类型 - case TIME_STAMP: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = ""; - break; - } - try { - Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); - value = date.getTime(); - } catch (Exception e) { - this.writeDebuggerLog("时间处理异常:" + e); - throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage()); - } - } - break; - case Boolean: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = false; - break; - } - value = Boolean.valueOf(String.valueOf(value)); - } - break; - case Object: { - // 当是object类型时不转换 保留原有格式 - } - break; - default: - return value; - } - - return value; - } - - /** - * 普通类型处理 - * - * @param mainMap 主表数据结果集 - * @param detailMap 明细数据结果集 - * @param mappingDetail 配置节点信息 - * @param relationRs 关联流程数据集合 - * - *

代码版本改动说明:

- *

- * v2.0 xuanran.wang 转换类型是默认值时增加替换规则 将自定义文本中的{?requestid}替换成requestid 以及将 {?} 替换成选择的流程字段对应的值 - *

- */ - private Object normalValueDeal(Map mainMap, Map detailMap, RecordSet relationRs, MappingDetail mappingDetail) { - String paramType = mappingDetail.getParamType(); - ParamTypeEnum typeEnum = ParamTypeEnum.getEnum(paramType); - String getValueType = mappingDetail.getGetValueType(); - GetValueTypeEnum getValueTypeEnum = GetValueTypeEnum.getEnum(getValueType); - String valueContext = mappingDetail.getValueContext(); - String childSource = mappingDetail.getDataSource(); - String paramName = mappingDetail.getParamName(); - Object value = ""; - switch (getValueTypeEnum) { - // 流程字段 - case WORKFLOW_FIELD: { - FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - String fieldName = fieldMassage.getFieldName(); - String fieldNameLower = fieldName.toLowerCase(); - this.writeDebuggerLog("fieldName:" + fieldName); - if ("1".equals(childSource)) { - value = Util.null2String(detailMap.get(fieldNameLower)); - if ("".equals(value)) { - value = Util.null2String(detailMap.get(fieldName)); - } - } else if ("0".equals(childSource)) { - value = Util.null2String(mainMap.get(fieldNameLower)); - if ("".equals(value)) { - value = Util.null2String(mainMap.get(fieldName)); - } - } else { - value = Util.null2String(relationRs.getString(fieldNameLower)); - if ("".equals(value)) { - value = Util.null2String(relationRs.getString(fieldName)); - } - } - if ("rootNode".equals(mappingDetail.getBelongTo()) && "2".equals(childSource)) { - writeDebuggerLog("主表取关联流程字段 => " + paramName); - value = Util.null2String(tempRs.getString(fieldNameLower)); - if ("".equals(value)) { - value = Util.null2String(tempRs.getString(fieldName)); - } - } - } - break; - // 默认值 - case DEFAULT_VALUE: { - FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - String workFlowVal = ""; - if (fieldMassage != null) { - String fieldName = fieldMassage.getFieldName(); - String fieldNameLower = fieldName.toLowerCase(); - if ("1".equals(childSource)) { - workFlowVal = Util.null2String(detailMap.get(fieldNameLower)); - if ("".equals(workFlowVal)) { - workFlowVal = Util.null2String(detailMap.get(fieldName)); - } - } else if ("0".equals(childSource)) { - workFlowVal = Util.null2String(mainMap.get(fieldNameLower)); - if ("".equals(workFlowVal)) { - workFlowVal = Util.null2String(mainMap.get(fieldName)); - } - } else { - workFlowVal = Util.null2String(relationRs.getString(fieldNameLower)); - if ("".equals(workFlowVal)) { - workFlowVal = Util.null2String(relationRs.getString(fieldName)); - } - } - if ("rootNode".equals(mappingDetail.getBelongTo()) && "2".equals(childSource)) { - workFlowVal = Util.null2String(tempRs.getString(fieldNameLower)); - if ("".equals(workFlowVal)) { - workFlowVal = Util.null2String(tempRs.getString(fieldName)); - } - } - } - value = Util.null2String(valueContext) - .replace("{?requestid}", String.valueOf(mainMap.get("requestid"))) - .replace("{?}", workFlowVal); - } - break; - // 当前时间 - case CURRENT_TIME: { - value = new Date(); - } - break; - // 自定义sql查询 - case CUS_SQL: { - FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - String tempValue = ""; - String requestId = Util.null2String(mainMap.get("requestid")); - int detailId = -1; - if (fieldMassage != null) { - String fieldName = fieldMassage.getFieldName(); - if ("1".equals(childSource)) { - tempValue = Util.null2String(detailMap.get(fieldName)); - // 明细 - detailId = Util.getIntValue(Util.null2String(detailMap.get("id")), -1); - } else if ("0".equals(childSource)) { - tempValue = Util.null2String(mainMap.get(fieldName)); - } else { - tempValue = Util.null2String(relationRs.getString(fieldName)); - requestId = Util.null2String(relationRs.getString("requestid")); - } - if ("rootNode".equals(mappingDetail.getBelongTo()) && "2".equals(childSource)) { - writeDebuggerLog("主表取关联流程字段 => " + paramName); - tempValue = Util.null2String(tempRs.getString(fieldName)); - } - } - tempValue = "'" + tempValue + "'"; - value = this.getValueByChangeRule(valueContext, tempValue, requestId, detailId); - } - break; - // requestId - case REQUEST_ID: { - value = Util.null2String(mainMap.get("requestid")); - if ("2".equals(childSource)) { - value = Util.null2String(relationRs.getString("requestid")); - } - } - break; - // 数据id - case MAIN_DATA_ID: { - if ("1".equals(childSource)) { - value = Util.null2String(detailMap.get("id")); - } else if ("0".equals(childSource)) { - value = Util.null2String(mainMap.get("id")); - } else { - value = Util.null2String(relationRs.getString("id")); - } - } - break; - // 随机数 - case RANDOM: { - int bit = Util.getIntValue(valueContext, 10); - value = this.getGUID(bit); - } - break; - // 附件 - case ATTACHMENT: { + FieldMessage fieldMassage = mappingDetail.getFieldMassage(); + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); + if ("1".equals(childSource)) { + value = Util.null2String(detailMap.get(fieldName)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldNameLower)); + } + } else { + value = Util.null2String(mainMap.get(fieldName)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldNameLower)); + } + } + String fileIds = Util.null2String(value); + if ("".equals(fileIds)) { + return null; + } + List docImageFiles = mappingCMD.selectDocImageFileList(fileIds); + for (DocImageFile docImageFile : docImageFiles) { + MultipartFile multipartFile = new MultipartFile(); + InputStream fileInputStream = ImageFileManager.getInputStreamById(docImageFile.getImageFileId()); + multipartFile.setDocId(docImageFile.getDocId()); + multipartFile.setImageFileId(docImageFile.getImageFileId()); + multipartFile.setFileKey(paramName); + multipartFile.setStream(fileInputStream); + multipartFile.setFileName(docImageFile.getImageFileName()); + multipartFile.setFileSize(docImageFile.getFileSize() / 1024); + multipartFileList.add(multipartFile); + } + return null; + } + // 自定义接口 + case CUS_INTERFACE: { + if (null == valueContext || valueContext.length() == 0) { + } else { + Map pathParamMap = new HashMap<>(8); + CusInterfaceGetValue o = getCusInterfaceObj(valueContext, CusInterfaceGetValue.class, pathParamMap); + FieldMessage fieldMassage = mappingDetail.getFieldMassage(); + if (null != fieldMassage && !StringUtils.isEmpty(fieldMassage.getFieldName())) { + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); + if ("1".equals(childSource)) { + value = Util.null2String(detailMap.get(fieldName)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldNameLower)); + } + } else { + value = Util.null2String(mainMap.get(fieldName)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldNameLower)); + } + } + } + value = o.execute(mainMap, detailMap, String.valueOf(value == null ? "" : value), pathParamMap); + } + } + break; + case CUS_FIELD: { + value = detailMap.get(valueContext.trim()); + } + break; + default: + throw new ValueDealException("不支持的取值方式"); + } + switch (typeEnum) { + // String类型 + case STRING: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = ""; + break; + } + value = Util.null2String(String.valueOf(value)); + } + break; + // int类型 + case INT: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = -1; + break; + } + value = Util.getIntValue(String.valueOf(value)); + } + break; + // double类型 + case DOUBLE: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = 0.00; + break; + } + value = Util.getDoubleValue(String.valueOf(value)); + } + break; + // 日期类型 + case DATE: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = ""; + break; + } + try { + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + value = this.diyDateFortMat(date, "yyyy-MM-dd"); + } catch (Exception e) { + this.writeDebuggerLog("时间处理异常:" + e); + throw new ValueDealException("时间处理异常:参数>>" + paramName); + } + } + break; + // 时间日期类型 + case DATE_TIME: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = ""; + break; + } + try { + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + value = this.diyDateFortMat(date, "yyyy-MM-dd HH:mm:ss"); + } catch (Exception e) { + this.writeDebuggerLog("时间处理异常:" + e); + throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e); + } + } + break; + // 自定义时间格式化类型 + case CUS_DATE_STR: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = ""; + break; + } + try { + forMatString = valueContext; + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + value = this.diyDateFortMat(date, forMatString); + } catch (Exception e) { + this.writeDebuggerLog("时间处理异常:" + e); + throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage()); + } + } + break; + // 时间戳类型 + case TIME_STAMP: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = ""; + break; + } + try { + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + value = date.getTime(); + } catch (Exception e) { + this.writeDebuggerLog("时间处理异常:" + e); + throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage()); + } + } + break; + case Boolean: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = false; + break; + } + value = Boolean.valueOf(String.valueOf(value)); + } + break; + case Object: { + // 当是object类型时不转换 保留原有格式 + } + break; + default: + return value; + } + + return value; + } + + /** + * 普通类型处理 + * + * @param mainMap 主表数据结果集 + * @param detailMap 明细数据结果集 + * @param mappingDetail 配置节点信息 + * @param relationRs 关联流程数据集合 + * + *

代码版本改动说明:

+ *

+ * v2.0 xuanran.wang 转换类型是默认值时增加替换规则 将自定义文本中的{?requestid}替换成requestid 以及将 {?} 替换成选择的流程字段对应的值 + *

+ */ + private Object normalValueDeal(Map mainMap, Map detailMap, RecordSet relationRs, MappingDetail mappingDetail) { + String paramType = mappingDetail.getParamType(); + ParamTypeEnum typeEnum = ParamTypeEnum.getEnum(paramType); + String getValueType = mappingDetail.getGetValueType(); + GetValueTypeEnum getValueTypeEnum = GetValueTypeEnum.getEnum(getValueType); + String valueContext = mappingDetail.getValueContext(); + String childSource = mappingDetail.getDataSource(); + String paramName = mappingDetail.getParamName(); + Object value = ""; + switch (getValueTypeEnum) { + // 流程字段 + case WORKFLOW_FIELD: { + FieldMessage fieldMassage = mappingDetail.getFieldMassage(); + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); + this.writeDebuggerLog("fieldName:" + fieldName); + if ("1".equals(childSource)) { + value = Util.null2String(detailMap.get(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldName)); + } + } else if ("0".equals(childSource)) { + value = Util.null2String(mainMap.get(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(mainMap.get(fieldName)); + } + } else { + value = Util.null2String(relationRs.getString(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(relationRs.getString(fieldName)); + } + } + if ("rootNode".equals(mappingDetail.getBelongTo()) && "2".equals(childSource)) { + writeDebuggerLog("主表取关联流程字段 => " + paramName); + value = Util.null2String(tempRs.getString(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(tempRs.getString(fieldName)); + } + } + } + break; + // 默认值 + case DEFAULT_VALUE: { + FieldMessage fieldMassage = mappingDetail.getFieldMassage(); + String workFlowVal = ""; + if (fieldMassage != null) { + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); + if ("1".equals(childSource)) { + workFlowVal = Util.null2String(detailMap.get(fieldNameLower)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(detailMap.get(fieldName)); + } + } else if ("0".equals(childSource)) { + workFlowVal = Util.null2String(mainMap.get(fieldNameLower)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(mainMap.get(fieldName)); + } + } else { + workFlowVal = Util.null2String(relationRs.getString(fieldNameLower)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(relationRs.getString(fieldName)); + } + } + if ("rootNode".equals(mappingDetail.getBelongTo()) && "2".equals(childSource)) { + workFlowVal = Util.null2String(tempRs.getString(fieldNameLower)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(tempRs.getString(fieldName)); + } + } + } + value = Util.null2String(valueContext) + .replace("{?requestid}", String.valueOf(mainMap.get("requestid"))) + .replace("{?}", workFlowVal); + } + break; + // 当前时间 + case CURRENT_TIME: { + value = new Date(); + } + break; + // 自定义sql查询 + case CUS_SQL: { + FieldMessage fieldMassage = mappingDetail.getFieldMassage(); + String tempValue = ""; + String requestId = Util.null2String(mainMap.get("requestid")); + int detailId = -1; + if (fieldMassage != null) { + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); + if ("1".equals(childSource)) { + tempValue = Util.null2String(detailMap.get(fieldName)); + if ("".equals(tempValue)) { + tempValue = Util.null2String(detailMap.get(fieldNameLower)); + } + // 明细 + detailId = Util.getIntValue(Util.null2String(detailMap.get("id")), -1); + } else if ("0".equals(childSource)) { + tempValue = Util.null2String(mainMap.get(fieldName)); + if ("".equals(tempValue)) { + tempValue = Util.null2String(detailMap.get(fieldNameLower)); + } + } else { + tempValue = Util.null2String(relationRs.getString(fieldName)); + if ("".equals(tempValue)) { + tempValue = Util.null2String(detailMap.get(fieldNameLower)); + } + requestId = Util.null2String(relationRs.getString("requestid")); + } + if ("rootNode".equals(mappingDetail.getBelongTo()) && "2".equals(childSource)) { + writeDebuggerLog("主表取关联流程字段 => " + paramName); + tempValue = Util.null2String(tempRs.getString(fieldName)); + } + } + tempValue = "'" + tempValue + "'"; + value = this.getValueByChangeRule(valueContext, tempValue, requestId, detailId); + } + break; + // requestId + case REQUEST_ID: { + value = Util.null2String(mainMap.get("requestid")); + if ("2".equals(childSource)) { + value = Util.null2String(relationRs.getString("requestid")); + } + } + break; + // 数据id + case MAIN_DATA_ID: { + if ("1".equals(childSource)) { + value = Util.null2String(detailMap.get("id")); + } else if ("0".equals(childSource)) { + value = Util.null2String(mainMap.get("id")); + } else { + value = Util.null2String(relationRs.getString("id")); + } + } + break; + // 随机数 + case RANDOM: { + int bit = Util.getIntValue(valueContext, 10); + value = this.getGUID(bit); + } + break; + // 附件 + case ATTACHMENT: { /*int imageFileId = Util.getIntValue(String.valueOf(value)); InputStream inputStream = ImageFileManager.getInputStreamById(imageFileId); String fileName = this.getFileNameById(imageFileId); fileInputStreams.add(inputStream); fileNames.add(fileName);*/ - FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - String fieldName = fieldMassage.getFieldName(); - if ("1".equals(childSource)) { - value = Util.null2String(detailMap.get(fieldName)); - } else { - value = Util.null2String(mainMap.get(fieldName)); - } - String fileIds = Util.null2String(value); - if ("".equals(fileIds)) { - return null; - } - List docImageFiles = mappingCMD.selectDocImageFileList(fileIds); - for (DocImageFile docImageFile : docImageFiles) { - MultipartFile multipartFile = new MultipartFile(); - InputStream fileInputStream = ImageFileManager.getInputStreamById(docImageFile.getImageFileId()); - multipartFile.setFileKey(paramName); - multipartFile.setImageFileId(docImageFile.getImageFileId()); - multipartFile.setDocId(docImageFile.getDocId()); - multipartFile.setStream(fileInputStream); - multipartFile.setFileName(docImageFile.getImageFileName()); - multipartFile.setFileSize(docImageFile.getFileSize() / 1024); - this.writeDebuggerLog("multipartFile ==>"+multipartFile); - multipartFileList.add(multipartFile); - } - return null; - } - // 自定义接口 - case CUS_INTERFACE: { - if (null == valueContext || valueContext.length() == 0) { - } else { - Map pathParamMap = new HashMap<>(8); - CusInterfaceGetValue o = getCusInterfaceObj(valueContext, CusInterfaceGetValue.class, pathParamMap); - FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - if (null != fieldMassage && !StringUtils.isEmpty(fieldMassage.getFieldName())) { - String fieldName = fieldMassage.getFieldName(); - if ("1".equals(childSource)) { - value = Util.null2String(detailMap.get(fieldName)); - } else { - value = Util.null2String(mainMap.get(fieldName)); - } - } - value = o.execute(mainMap, detailMap, String.valueOf(value == null ? "" : value), pathParamMap); - } - } - break; - case CUS_FIELD: { - value = detailMap.get(valueContext.trim()); - if ("2".equals(childSource)) { - value = Util.null2String(relationRs.getString(valueContext.trim())); - } - } - break; - default: - throw new ValueDealException("不支持的取值方式"); - } - this.writeDebuggerLog("value1:" + value); - switch (typeEnum) { - // String类型 - case STRING: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = ""; - break; - } - value = Util.null2String(String.valueOf(value)); - } - break; - // int类型 - case INT: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = -1; - break; - } - value = Util.getIntValue(String.valueOf(value)); - } - break; - // double类型 - case DOUBLE: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = 0.00; - break; - } - value = Util.getDoubleValue(String.valueOf(value)); - } - break; - // 日期类型 - case DATE: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = ""; - break; - } - try { - Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); - value = this.diyDateFortMat(date, "yyyy-MM-dd"); - } catch (Exception e) { - throw new ValueDealException("时间处理异常:参数>>" + paramName); - } - - } - break; - // 时间日期类型 - case DATE_TIME: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = ""; - break; - } - try { - Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); - value = this.diyDateFortMat(date, "yyyy-MM-dd HH:mm:ss"); - } catch (Exception e) { - throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e); - } - } - break; - // 自定义时间格式化类型 - case CUS_DATE_STR: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = ""; - break; - } - try { - forMatString = valueContext; - Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); - value = this.diyDateFortMat(date, forMatString); - } catch (Exception e) { - throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage()); - } - } - break; - // 时间戳类型 - case TIME_STAMP: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = ""; - break; - } - try { - Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); - value = date.getTime(); - } catch (Exception e) { - throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage()); - } - } - break; - case Boolean: { - if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { - value = false; - break; - } - value = Boolean.valueOf(String.valueOf(value)); - } - break; - case Object: { - // 当是object类型时不转换 保留原有格式 - } - break; - default: - return value; - } - return value; - } - - /** - * list类型处理 - * - * @param mainMap 主表数据集 - * @param childList 子节点配置列表 - * @param list 子节点参数 - * @param detail 当前节点 - */ - private void listValueDeal(Map mainMap, List childList, List list, MappingDetail detail) throws ValueDealException { - String childSource = detail.getDataSource(); - String childType = detail.getChildType(); - if ("1".equals(childSource)) { - int mainId = Util.getIntValue(Util.null2String(mainMap.get("id"))); - int detailId = Util.getIntValue(detail.getDetailId()); - String detailTableName = mainTable + "_dt" + detailId; - // 自定义sql参数 - String cusWhere = Util.null2String(detail.getCusWhereSql()); - if (StringUtils.isNotBlank(cusWhere)) { - cusWhere = sbc2dbcCase(cusWhere); - } - String querySql = "select * from " + detailTableName + " where mainid = ? " + cusWhere; - RecordSet recordSetDetail = new RecordSet(); - recordSetDetail.executeQuery(querySql, mainId); - while (recordSetDetail.next()) { - Map detailMap = getMapMapping(recordSetDetail); - if ("0".equals(childType)) { - Map item = new HashMap<>(); - list.add(item); - this.objValueDeal(mainMap, detailMap, childList, item); - } else { - for (MappingDetail mappingDetail : childList) { - Object o = this.normalValueDeal(mainMap, detailMap, mappingDetail); - list.add(o); - } - } - } - } else if ("0".equals(childSource)) { - if ("0".equals(childType)) { - Map item = new HashMap<>(); - list.add(item); - this.objValueDeal(mainMap, null, childList, item); - } else { - for (MappingDetail mappingDetail : childList) { - Object o = this.normalValueDeal(mainMap, null, mappingDetail); - list.add(o); - } - } - // for (MappingDetail mappingDetail : childList) { - // Object o = this.normalValueDeal(recordSet, null, mappingDetail); - // list.add(o); - // } - } else if ("2".equals(childSource)) { - // 自定义接口 - Map pathParamMap = new HashMap<>(8); - CusInterfaceListValue cusInterfaceObj = getCusInterfaceObj(detail.getDetailId(), CusInterfaceListValue.class, pathParamMap); - List resultList = cusInterfaceObj.execute(pathParamMap, mainMap, mainTable); - if (null == resultList || resultList.isEmpty()) { - return; - } - if ("0".equals(childType)) { - - // 对象类型 - for (Object o : resultList) { - Map item = new HashMap<>(); - list.add(item); - this.objValueDeal(mainMap, (Map) o, childList, item); - } - } else { - // 普通数据类型 - for (Object o : resultList) { - for (MappingDetail mappingDetail : childList) { - if (o instanceof Map) { - Object value = this.normalValueDeal(mainMap, (Map) o, mappingDetail); - list.add(value); - } else { - list.add(o); - } - } - } - } - } - } - - /** - * list类型处理 - * - * @param mainMap 主表数据集 - * @param childList 子节点配置列表 - * @param list 子节点参数 - * @param detail 当前节点 - * @param relationRs 关联流程数据集合 - */ - private void listValueDeal(Map mainMap, List childList, List list, MappingDetail detail, RecordSet relationRs) throws ValueDealException { - String childSource = detail.getDataSource(); - String childType = detail.getChildType(); - if ("1".equals(childSource)) { - int mainId = Util.getIntValue(Util.null2String(mainMap.get("id"))); - int detailId = Util.getIntValue(detail.getDetailId()); - String detailTableName = mainTable + "_dt" + detailId; - String querySql = "select * from " + detailTableName + " where mainid = ?"; - RecordSet recordSetDetail = new RecordSet(); - recordSetDetail.executeQuery(querySql, mainId); - while (recordSetDetail.next() && relationRs.next()) { - Map detailMap = getMapMapping(recordSetDetail); - if ("0".equals(childType)) { - Map item = new HashMap<>(); - list.add(item); - this.objValueDeal(mainMap, detailMap, relationRs, childList, item); - } else { - for (MappingDetail mappingDetail : childList) { - Object o = this.normalValueDeal(mainMap, detailMap, relationRs, mappingDetail); - list.add(o); - } - } - } - } else if ("0".equals(childSource)) { - if ("0".equals(childType)) { - Map item = new HashMap<>(); - list.add(item); - this.objValueDeal(mainMap, null, relationRs, childList, item); - } else { - for (MappingDetail mappingDetail : childList) { - Object o = this.normalValueDeal(mainMap, null, relationRs, mappingDetail); - list.add(o); - } - } - // for (MappingDetail mappingDetail : childList) { - // Object o = this.normalValueDeal(recordSet, null, mappingDetail); - // list.add(o); - // } - } else if ("2".equals(childSource)) { - // 自定义接口 - Map pathParamMap = new HashMap<>(8); - CusInterfaceListValue cusInterfaceObj = getCusInterfaceObj(detail.getDetailId(), CusInterfaceListValue.class, pathParamMap); - List resultList = cusInterfaceObj.execute(pathParamMap, mainMap, mainTable); - if (null == resultList || resultList.isEmpty()) { - return; - } - if ("0".equals(childType)) { - - // 对象类型 - for (Object o : resultList) { - Map item = new HashMap<>(); - list.add(item); - this.objValueDeal(mainMap, (Map) o, childList, item); - } - } else { - // 普通数据类型 - for (Object o : resultList) { - for (MappingDetail mappingDetail : childList) { - if (o instanceof Map) { - Object value = this.normalValueDeal(mainMap, (Map) o, mappingDetail); - list.add(value); - } else { - list.add(o); - } - } - } - } - } - } - - /** - *

请求结果赋值到配置信息中

- * - * @param responseMappingList 回写信息配置列表 - * @param requestRes 请求结果 - * @return 要插入的信息 - */ - public Map> dealResponse(List responseMappingList, Map requestRes) { - this.writeDebuggerLog("回写信息转换处理 responseMappingList==>" + responseMappingList + " requestRes==>" + requestRes + "mainTable ==>"+mainTable); - Map> tableUpdateMap = new HashMap<>(); - if (responseMappingList != null && !responseMappingList.isEmpty()) { - Map mainUpdateMap = new HashMap<>(); - List detailResponseList = new ArrayList<>(); - for (ResponseMapping responseMapping : responseMappingList) { - if (responseMapping.getMainOrDetail() == 0) { - String resVal = Util.null2String(requestRes.get(responseMapping.getResponseFieldName())); - mainUpdateMap.put(responseMapping.getWorkflowFieldName(), resVal); - } else { - detailResponseList.add(responseMapping); - } - } - tableUpdateMap.put(mainTable, mainUpdateMap); - Map> groupMap = detailResponseList.stream().collect(Collectors.groupingBy(ResponseMapping::getDetailTableId)); - Set>> entries = groupMap.entrySet(); - for (Map.Entry> entry : entries) { - Map detailUpdateMap = new HashMap<>(); - String detailId = entry.getKey(); - List responseMappings = entry.getValue(); - String detailTableName = mainTable + "_dt" + detailId; - for (ResponseMapping responseMapping : responseMappings) { - String resVal = Util.null2String(requestRes.get(responseMapping.getResponseFieldName())); - detailUpdateMap.put(responseMapping.getWorkflowFieldName(), resVal); - } - tableUpdateMap.put(detailTableName, detailUpdateMap); - } - } - this.writeDebuggerLog("回写信息tableUpdateMap==> " + tableUpdateMap); - return tableUpdateMap; - } - - /** - * 自定义时间格式化 - * - * @param date 日期 - * @param tempStr 格式化字符串 - * @return - */ - private String diyDateFortMat(Date date, String tempStr) { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(tempStr); - return simpleDateFormat.format(date); - } - - private String getGUID(int bit) { - - StringBuilder uid = new StringBuilder(); - - // 产生16位的强随机数 - - Random rd = new SecureRandom(); - - for (int i = 0; i < bit; i++) { - - // 产生0-2的3位随机数 - int type = rd.nextInt(3); - - switch (type) { - case 0: - // 0-9的随机数 - uid.append(rd.nextInt(10)); - break; - case 1: - // ASCII在65-90之间为大写,获取大写随机 - uid.append((char) (rd.nextInt(25) + 65)); - break; - case 2: - // ASCII在97-122之间为小写,获取小写随机 - uid.append((char) (rd.nextInt(25) + 97)); - break; - default: - break; - } - } - return uid.toString(); - } - - /** - * 通过文件id获取文件名 - * - * @param fileId 文件id - * @return - */ - public String getFileNameById(int fileId) { - String fileName = ""; - String querySql = "select filename from docimagefile where imgagefileid = ?"; - RecordSet recordSet = new RecordSet(); - recordSet.executeQuery(querySql, fileId); - if (recordSet.next()) { - fileName = recordSet.getString("filename"); - } - return fileName; - } - - public T getCusInterfaceObj(String path, Class clazz, Map pathParamMap) { - path = sbc2dbcCase(path); - String[] split = path.split("\\?"); - String classPath = split[0]; - String paramStr = ""; - if (split.length > 1) { - paramStr = Arrays.stream(split).skip(1).collect(Collectors.joining("?")); - } + FieldMessage fieldMassage = mappingDetail.getFieldMassage(); + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); + if ("1".equals(childSource)) { + value = Util.null2String(detailMap.get(fieldName)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldNameLower)); + } + } else { + value = Util.null2String(mainMap.get(fieldName)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldNameLower)); + } + } + String fileIds = Util.null2String(value); + if ("".equals(fileIds)) { + return null; + } + List docImageFiles = mappingCMD.selectDocImageFileList(fileIds); + for (DocImageFile docImageFile : docImageFiles) { + MultipartFile multipartFile = new MultipartFile(); + InputStream fileInputStream = ImageFileManager.getInputStreamById(docImageFile.getImageFileId()); + multipartFile.setFileKey(paramName); + multipartFile.setImageFileId(docImageFile.getImageFileId()); + multipartFile.setDocId(docImageFile.getDocId()); + multipartFile.setStream(fileInputStream); + multipartFile.setFileName(docImageFile.getImageFileName()); + multipartFile.setFileSize(docImageFile.getFileSize() / 1024); + this.writeDebuggerLog("multipartFile ==>" + multipartFile); + multipartFileList.add(multipartFile); + } + return null; + } + // 自定义接口 + case CUS_INTERFACE: { + if (null == valueContext || valueContext.length() == 0) { + } else { + Map pathParamMap = new HashMap<>(8); + CusInterfaceGetValue o = getCusInterfaceObj(valueContext, CusInterfaceGetValue.class, pathParamMap); + FieldMessage fieldMassage = mappingDetail.getFieldMassage(); + if (null != fieldMassage && !StringUtils.isEmpty(fieldMassage.getFieldName())) { + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); + if ("1".equals(childSource)) { + value = Util.null2String(detailMap.get(fieldName)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldNameLower)); + } + } else { + value = Util.null2String(mainMap.get(fieldName)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldNameLower)); + } + } + } + value = o.execute(mainMap, detailMap, String.valueOf(value == null ? "" : value), pathParamMap); + } + } + break; + case CUS_FIELD: { + value = detailMap.get(valueContext.trim()); + if ("2".equals(childSource)) { + value = Util.null2String(relationRs.getString(valueContext.trim())); + } + } + break; + default: + throw new ValueDealException("不支持的取值方式"); + } + this.writeDebuggerLog("value1:" + value); + switch (typeEnum) { + // String类型 + case STRING: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = ""; + break; + } + value = Util.null2String(String.valueOf(value)); + } + break; + // int类型 + case INT: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = -1; + break; + } + value = Util.getIntValue(String.valueOf(value)); + } + break; + // double类型 + case DOUBLE: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = 0.00; + break; + } + value = Util.getDoubleValue(String.valueOf(value)); + } + break; + // 日期类型 + case DATE: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = ""; + break; + } + try { + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + value = this.diyDateFortMat(date, "yyyy-MM-dd"); + } catch (Exception e) { + throw new ValueDealException("时间处理异常:参数>>" + paramName); + } + + } + break; + // 时间日期类型 + case DATE_TIME: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = ""; + break; + } + try { + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + value = this.diyDateFortMat(date, "yyyy-MM-dd HH:mm:ss"); + } catch (Exception e) { + throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e); + } + } + break; + // 自定义时间格式化类型 + case CUS_DATE_STR: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = ""; + break; + } + try { + forMatString = valueContext; + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + value = this.diyDateFortMat(date, forMatString); + } catch (Exception e) { + throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage()); + } + } + break; + // 时间戳类型 + case TIME_STAMP: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = ""; + break; + } + try { + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + value = date.getTime(); + } catch (Exception e) { + throw new ValueDealException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage()); + } + } + break; + case Boolean: { + if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) { + value = false; + break; + } + value = Boolean.valueOf(String.valueOf(value)); + } + break; + case Object: { + // 当是object类型时不转换 保留原有格式 + } + break; + default: + return value; + } + return value; + } + + /** + * list类型处理 + * + * @param mainMap 主表数据集 + * @param childList 子节点配置列表 + * @param list 子节点参数 + * @param detail 当前节点 + */ + private void listValueDeal(Map mainMap, List childList, List list, MappingDetail detail) throws ValueDealException { + String childSource = detail.getDataSource(); + String childType = detail.getChildType(); + if ("1".equals(childSource)) { + int mainId = Util.getIntValue(Util.null2String(mainMap.get("id"))); + int detailId = Util.getIntValue(detail.getDetailId()); + String detailTableName = mainTable + "_dt" + detailId; + // 自定义sql参数 + String cusWhere = Util.null2String(detail.getCusWhereSql()); + if (StringUtils.isNotBlank(cusWhere)) { + cusWhere = sbc2dbcCase(cusWhere); + } + String querySql = "select * from " + detailTableName + " where mainid = ? " + cusWhere; + RecordSet recordSetDetail = new RecordSet(); + recordSetDetail.executeQuery(querySql, mainId); + while (recordSetDetail.next()) { + Map detailMap = getMapMapping(recordSetDetail); + if ("0".equals(childType)) { + Map item = new HashMap<>(); + list.add(item); + this.objValueDeal(mainMap, detailMap, childList, item); + } else { + for (MappingDetail mappingDetail : childList) { + Object o = this.normalValueDeal(mainMap, detailMap, mappingDetail); + list.add(o); + } + } + } + } else if ("0".equals(childSource)) { + if ("0".equals(childType)) { + Map item = new HashMap<>(); + list.add(item); + this.objValueDeal(mainMap, null, childList, item); + } else { + for (MappingDetail mappingDetail : childList) { + Object o = this.normalValueDeal(mainMap, null, mappingDetail); + list.add(o); + } + } + // for (MappingDetail mappingDetail : childList) { + // Object o = this.normalValueDeal(recordSet, null, mappingDetail); + // list.add(o); + // } + } else if ("2".equals(childSource)) { + // 自定义接口 + Map pathParamMap = new HashMap<>(8); + CusInterfaceListValue cusInterfaceObj = getCusInterfaceObj(detail.getDetailId(), CusInterfaceListValue.class, pathParamMap); + List resultList = cusInterfaceObj.execute(pathParamMap, mainMap, mainTable); + if (null == resultList || resultList.isEmpty()) { + return; + } + if ("0".equals(childType)) { + + // 对象类型 + for (Object o : resultList) { + Map item = new HashMap<>(); + list.add(item); + this.objValueDeal(mainMap, (Map) o, childList, item); + } + } else { + // 普通数据类型 + for (Object o : resultList) { + for (MappingDetail mappingDetail : childList) { + if (o instanceof Map) { + Object value = this.normalValueDeal(mainMap, (Map) o, mappingDetail); + list.add(value); + } else { + list.add(o); + } + } + } + } + } + } + + /** + * list类型处理 + * + * @param mainMap 主表数据集 + * @param childList 子节点配置列表 + * @param list 子节点参数 + * @param detail 当前节点 + * @param relationRs 关联流程数据集合 + */ + private void listValueDeal(Map mainMap, List childList, List list, MappingDetail detail, RecordSet relationRs) throws ValueDealException { + String childSource = detail.getDataSource(); + String childType = detail.getChildType(); + if ("1".equals(childSource)) { + int mainId = Util.getIntValue(Util.null2String(mainMap.get("id"))); + int detailId = Util.getIntValue(detail.getDetailId()); + String detailTableName = mainTable + "_dt" + detailId; + String querySql = "select * from " + detailTableName + " where mainid = ?"; + RecordSet recordSetDetail = new RecordSet(); + recordSetDetail.executeQuery(querySql, mainId); + while (recordSetDetail.next() && relationRs.next()) { + Map detailMap = getMapMapping(recordSetDetail); + if ("0".equals(childType)) { + Map item = new HashMap<>(); + list.add(item); + this.objValueDeal(mainMap, detailMap, relationRs, childList, item); + } else { + for (MappingDetail mappingDetail : childList) { + Object o = this.normalValueDeal(mainMap, detailMap, relationRs, mappingDetail); + list.add(o); + } + } + } + } else if ("0".equals(childSource)) { + if ("0".equals(childType)) { + Map item = new HashMap<>(); + list.add(item); + this.objValueDeal(mainMap, null, relationRs, childList, item); + } else { + for (MappingDetail mappingDetail : childList) { + Object o = this.normalValueDeal(mainMap, null, relationRs, mappingDetail); + list.add(o); + } + } + // for (MappingDetail mappingDetail : childList) { + // Object o = this.normalValueDeal(recordSet, null, mappingDetail); + // list.add(o); + // } + } else if ("2".equals(childSource)) { + // 自定义接口 + Map pathParamMap = new HashMap<>(8); + CusInterfaceListValue cusInterfaceObj = getCusInterfaceObj(detail.getDetailId(), CusInterfaceListValue.class, pathParamMap); + List resultList = cusInterfaceObj.execute(pathParamMap, mainMap, mainTable); + if (null == resultList || resultList.isEmpty()) { + return; + } + if ("0".equals(childType)) { + + // 对象类型 + for (Object o : resultList) { + Map item = new HashMap<>(); + list.add(item); + this.objValueDeal(mainMap, (Map) o, childList, item); + } + } else { + // 普通数据类型 + for (Object o : resultList) { + for (MappingDetail mappingDetail : childList) { + if (o instanceof Map) { + Object value = this.normalValueDeal(mainMap, (Map) o, mappingDetail); + list.add(value); + } else { + list.add(o); + } + } + } + } + } + } + + /** + *

请求结果赋值到配置信息中

+ * + * @param responseMappingList 回写信息配置列表 + * @param requestRes 请求结果 + * @return 要插入的信息 + */ + public Map> dealResponse(List responseMappingList, Map requestRes) { + this.writeDebuggerLog("回写信息转换处理 responseMappingList==>" + responseMappingList + " requestRes==>" + requestRes + "mainTable ==>" + mainTable); + Map> tableUpdateMap = new HashMap<>(); + if (responseMappingList != null && !responseMappingList.isEmpty()) { + Map mainUpdateMap = new HashMap<>(); + List detailResponseList = new ArrayList<>(); + for (ResponseMapping responseMapping : responseMappingList) { + if (responseMapping.getMainOrDetail() == 0) { + String resVal = Util.null2String(requestRes.get(responseMapping.getResponseFieldName())); + mainUpdateMap.put(responseMapping.getWorkflowFieldName(), resVal); + } else { + detailResponseList.add(responseMapping); + } + } + tableUpdateMap.put(mainTable, mainUpdateMap); + Map> groupMap = detailResponseList.stream().collect(Collectors.groupingBy(ResponseMapping::getDetailTableId)); + Set>> entries = groupMap.entrySet(); + for (Map.Entry> entry : entries) { + Map detailUpdateMap = new HashMap<>(); + String detailId = entry.getKey(); + List responseMappings = entry.getValue(); + String detailTableName = mainTable + "_dt" + detailId; + for (ResponseMapping responseMapping : responseMappings) { + String resVal = Util.null2String(requestRes.get(responseMapping.getResponseFieldName())); + detailUpdateMap.put(responseMapping.getWorkflowFieldName(), resVal); + } + tableUpdateMap.put(detailTableName, detailUpdateMap); + } + } + this.writeDebuggerLog("回写信息tableUpdateMap==> " + tableUpdateMap); + return tableUpdateMap; + } + + /** + * 自定义时间格式化 + * + * @param date 日期 + * @param tempStr 格式化字符串 + * @return + */ + private String diyDateFortMat(Date date, String tempStr) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(tempStr); + return simpleDateFormat.format(date); + } + + private String getGUID(int bit) { + + StringBuilder uid = new StringBuilder(); + + // 产生16位的强随机数 + + Random rd = new SecureRandom(); + + for (int i = 0; i < bit; i++) { + + // 产生0-2的3位随机数 + int type = rd.nextInt(3); + + switch (type) { + case 0: + // 0-9的随机数 + uid.append(rd.nextInt(10)); + break; + case 1: + // ASCII在65-90之间为大写,获取大写随机 + uid.append((char) (rd.nextInt(25) + 65)); + break; + case 2: + // ASCII在97-122之间为小写,获取小写随机 + uid.append((char) (rd.nextInt(25) + 97)); + break; + default: + break; + } + } + return uid.toString(); + } + + /** + * 通过文件id获取文件名 + * + * @param fileId 文件id + * @return + */ + public String getFileNameById(int fileId) { + String fileName = ""; + String querySql = "select filename from docimagefile where imgagefileid = ?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(querySql, fileId); + if (recordSet.next()) { + fileName = recordSet.getString("filename"); + } + return fileName; + } + + public T getCusInterfaceObj(String path, Class clazz, Map pathParamMap) { + path = sbc2dbcCase(path); + String[] split = path.split("\\?"); + String classPath = split[0]; + String paramStr = ""; + if (split.length > 1) { + paramStr = Arrays.stream(split).skip(1).collect(Collectors.joining("?")); + } /* 获取?后的参数:"weaver.aiyh_jitu.pushdata.service.toones.GetRequestValueCusGetValueImpl?" + "requestType=get&apiOnlyMark=getAssign&valueKey=data&assign=#{main.zd2}&" + "#processorClass=weaver.aiyh_jitu.pushdata.service.toones.GetAssignProcessorProcessorImpl" + @@ -1435,43 +1480,43 @@ public class DealWithMapping extends ToolUtil { value:#sql{select workcode from hrmresource where id = #{main.zd1} and test = #{h-hah} and a in (${hrmids})} key:hah value:haode*/ - // 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类,将参数传递给这个类, 使用``包裹的字符串会被解析为一个字符串 - String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + - "(?((`([^`]*)`)|" + - "((#(\\{|sql\\{))?([():/\\-$_#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; - Pattern compile = Pattern.compile(pattern); - Matcher matcher = compile.matcher(paramStr); - while (matcher.find()) { - String key = matcher.group("key"); - String paramValue = matcher.group("value"); - if (paramValue != null && paramValue.startsWith("`") && paramValue.endsWith("`")) { - paramValue = paramValue.substring(1, paramValue.length() - 1); - } - pathParamMap.put(key, paramValue); - } - Class aClass; - try { - aClass = Class.forName(classPath); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("未能找到自定义接口:" + classPath); - } - if (!clazz.isAssignableFrom(aClass)) { - throw new IllegalArgumentException("自定义接口:" + classPath + " 不是" - + clazz.getName() + "的子类或实现类!"); - } - Constructor constructor; - try { - constructor = aClass.getConstructor(); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException(classPath + "没有空参构造方法,无法获取构造方法对象!"); - } - T o; - try { - o = (T) constructor.newInstance(); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { - throw new IllegalArgumentException("无法构造" + classPath + "对象!"); - } - return o; - } - + // 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类,将参数传递给这个类, 使用``包裹的字符串会被解析为一个字符串 + String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + + "(?((`([^`]*)`)|" + + "((#(\\{|sql\\{))?([():/\\-$_#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(paramStr); + while (matcher.find()) { + String key = matcher.group("key"); + String paramValue = matcher.group("value"); + if (paramValue != null && paramValue.startsWith("`") && paramValue.endsWith("`")) { + paramValue = paramValue.substring(1, paramValue.length() - 1); + } + pathParamMap.put(key, paramValue); + } + Class aClass; + try { + aClass = Class.forName(classPath); + } catch (ClassNotFoundException e) { + throw new IllegalArgumentException("未能找到自定义接口:" + classPath); + } + if (!clazz.isAssignableFrom(aClass)) { + throw new IllegalArgumentException("自定义接口:" + classPath + " 不是" + + clazz.getName() + "的子类或实现类!"); + } + Constructor constructor; + try { + constructor = aClass.getConstructor(); + } catch (NoSuchMethodException e) { + throw new IllegalArgumentException(classPath + "没有空参构造方法,无法获取构造方法对象!"); + } + T o; + try { + o = (T) constructor.newInstance(); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalArgumentException("无法构造" + classPath + "对象!"); + } + return o; + } + } diff --git a/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/ReceiptAndPaymentAction.java b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/ReceiptAndPaymentAction.java index 4ecae21..1cdfa7c 100644 --- a/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/ReceiptAndPaymentAction.java +++ b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/ReceiptAndPaymentAction.java @@ -12,7 +12,10 @@ import lombok.ToString; import weaver.hrm.User; import weaver.soa.workflow.request.RequestInfo; import weaver.youhong.ai.haripijiu.action.sapdocking.service.VoucherPayableService; +import weaver.youhong.ai.haripijiu.action.sapdocking.util.SmbjUtil; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.List; /** @@ -26,55 +29,87 @@ import java.util.List; @ToString @ActionDesc(author = "youhong.ai", value = "sap对接action,收付款文件生成发送给sap服务方") public class ReceiptAndPaymentAction extends SafeCusBaseAction { - - - @PrintParamMark - @ActionOptionalParam(value = "false", desc = "是否自动提交流程 false : 不提交; true : 提交") - private String submitAction = "false"; - - @PrintParamMark - @ActionOptionalParam(value = "true", desc = "是否失败后阻断流程, false : 不阻断; true: 阻断") - private String block = "true"; - - - @PrintParamMark - @RequiredMark("sap对接配置表的唯一标识") - private String onlyMark; - - - @PrintParamMark - @RequiredMark("凭证类型,1- 付款单; 2- 收款单") - private String voucherType; - - @Override - public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { - try { - VoucherPayableService server = new VoucherPayableService(); - String fileName = ""; - if (Integer.parseInt(voucherType) == 1) { - /* ******************* 一个明细对应一个文件 ******************* */ - List paymentFilePathList = server.sendPaymentVoucher(onlyMark, requestId, billTable); - for (String filePath : paymentFilePathList) { - fileName = "Receipt" + Util.getTime("yyyyMMddHHmmss") + ".txt"; - // TODO 根据不同的规则生成不同的文件名并将文件存储到指定位置 - } - } else if (Integer.parseInt(voucherType) == 2) { - String tempFilePath = server.sendReceiptVoucher(onlyMark, requestId, billTable); - fileName = "Payment" + Util.getTime("yyyyMMddHHmmss") + ".txt"; - // TODO 根据不同的规则生成不同的文件名并将文件存储到指定位置 - } - /* ******************* 是否提交流程 ******************* */ - if (Boolean.parseBoolean(submitAction)) { - this.submitWorkflow(requestId, user.getUID()); - } - } catch (Exception e) { - if (Boolean.parseBoolean(block)) { - throw new CustomerException(e.getMessage(), e); - } - } - } - - public void submitWorkflow(String requestId, Integer userId) { - Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "sap对接自动提交流程!"); - } + + + @PrintParamMark + @ActionOptionalParam(value = "false", desc = "是否自动提交流程 false : 不提交; true : 提交") + private String submitAction = "false"; + + @PrintParamMark + @ActionOptionalParam(value = "true", desc = "是否失败后阻断流程, false : 不阻断; true: 阻断") + private String block = "true"; + + + @PrintParamMark + @RequiredMark("sap对接配置表的唯一标识") + private String onlyMark; + + + @PrintParamMark + @RequiredMark("凭证类型,1- 付款单; 2- 收款单") + private String voucherType; + + + @PrintParamMark + @RequiredMark("收款单远程路径存储") + private String receiptPath; + + @PrintParamMark + @RequiredMark("付款单远程路径存储") + private String paymentPath; + + @PrintParamMark + @RequiredMark("用户名") + private String userName; + + @PrintParamMark + @RequiredMark("密码") + private String password; + + + @PrintParamMark + @RequiredMark("ip") + private String ip; + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + try { + SmbjUtil smbjUtil = new SmbjUtil(); + VoucherPayableService server = new VoucherPayableService(); + String fileName = ""; + if (Integer.parseInt(voucherType) == 1) { + /* ******************* 一个明细对应一个文件 ******************* */ + List paymentFilePathList = server.sendPaymentVoucher(onlyMark, requestId, billTable); + for (String filePath : paymentFilePathList) { + fileName = "Receipt" + Util.getTime("yyyyMMddHHmmss") + ".txt"; + // TODO 根据不同的规则生成不同的文件名并将文件存储到指定位置 + log.info("远程连接地址:" + "smb://" + ip + receiptPath); + log.info("本地文件地址: " + filePath); + smbjUtil.smbPut("smb://" + ip + receiptPath, filePath, userName, password, fileName); + Files.delete(Paths.get(filePath)); + } + } else if (Integer.parseInt(voucherType) == 2) { + String tempFilePath = server.sendReceiptVoucher(onlyMark, requestId, billTable); + fileName = "Payment" + Util.getTime("yyyyMMddHHmmss") + ".txt"; + // TODO 根据不同的规则生成不同的文件名并将文件存储到指定位置 + log.info("远程连接地址:" + "smb://" + ip + paymentPath); + log.info("本地文件地址: " + tempFilePath); + smbjUtil.smbPut("smb://" + ip + paymentPath, tempFilePath, userName, password, fileName); + Files.delete(Paths.get(tempFilePath)); + } + /* ******************* 是否提交流程 ******************* */ + if (Boolean.parseBoolean(submitAction)) { + this.submitWorkflow(requestId, user.getUID()); + } + } catch (Exception e) { + log.error("推送收付款凭证失败!" + e.getMessage()); + if (Boolean.parseBoolean(block)) { + throw new CustomerException(e.getMessage(), e); + } + } + } + + public void submitWorkflow(String requestId, Integer userId) { + Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "sap对接自动提交流程!"); + } } diff --git a/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/VoucherPayableAction.java b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/VoucherPayableAction.java index 9dcfdb1..56fac0c 100644 --- a/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/VoucherPayableAction.java +++ b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/VoucherPayableAction.java @@ -12,6 +12,10 @@ import lombok.ToString; import weaver.hrm.User; import weaver.soa.workflow.request.RequestInfo; import weaver.youhong.ai.haripijiu.action.sapdocking.service.VoucherPayableService; +import weaver.youhong.ai.haripijiu.action.sapdocking.util.SmbjUtil; + +import java.nio.file.Files; +import java.nio.file.Paths; /** *

应付凭证接口

@@ -25,54 +29,83 @@ import weaver.youhong.ai.haripijiu.action.sapdocking.service.VoucherPayableServi @ToString @ActionDesc(author = "youhong.ai", value = "sap对接action,付款应付凭证文件生成发送给sap服务方") public class VoucherPayableAction extends SafeCusBaseAction { - - - @PrintParamMark - @ActionOptionalParam(value = "false", desc = "是否自动提交流程 false : 不提交; true : 提交") - private String submitAction = "false"; - - @PrintParamMark - @ActionOptionalParam(value = "true", desc = "是否失败后阻断流程, false : 不阻断; true: 阻断") - private String block = "true"; - - - @PrintParamMark - @RequiredMark("sap对接配置表的唯一标识") - private String onlyMark; - - - @PrintParamMark - @RequiredMark("凭证类型,1- 应付凭证; 2- 付款凭证") - private String voucherType; - - - @Override - public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { - - try { - VoucherPayableService server = new VoucherPayableService(); - String tempFilePath = server.sendSapVoucher(onlyMark, requestId, billTable); - String fileName = ""; - if (Integer.parseInt(voucherType) == 1) { - fileName = "Pav" + Util.getTime("yyyyMMddHHmmss") + ".txt"; - } else if (Integer.parseInt(voucherType) == 2) { - fileName = "Pmv" + Util.getTime("yyyyMMddHHmmss") + ".txt"; - } - // TODO 根据不同的规则生成不同的文件名并将文件存储到指定位置 - - /* ******************* 是否提交流程 ******************* */ - if (Boolean.parseBoolean(submitAction)) { - this.submitWorkflow(requestId, user.getUID()); - } - } catch (Exception e) { - if (Boolean.parseBoolean(block)) { - throw new CustomerException(e.getMessage(), e); - } - } - } - - public void submitWorkflow(String requestId, Integer userId) { - Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "sap对接自动提交流程!"); - } - + + + @PrintParamMark + @ActionOptionalParam(value = "false", desc = "是否自动提交流程 false : 不提交; true : 提交") + private String submitAction = "false"; + + @PrintParamMark + @ActionOptionalParam(value = "true", desc = "是否失败后阻断流程, false : 不阻断; true: 阻断") + private String block = "true"; + + + @PrintParamMark + @RequiredMark("sap对接配置表的唯一标识") + private String onlyMark; + + + @PrintParamMark + @RequiredMark("凭证类型,1- 应付凭证; 2- 付款凭证") + private String voucherType; + + + @PrintParamMark + @RequiredMark("应付凭证远程路径") + private String pavRemotePath; + + + @PrintParamMark + @RequiredMark("付款凭证远程路径") + private String pmvRemotePath; + + @PrintParamMark + @RequiredMark("用户名") + private String userName; + + @PrintParamMark + @RequiredMark("密码") + private String password; + + + @PrintParamMark + @RequiredMark("ip") + private String ip; + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + + try { + SmbjUtil smbjUtil = new SmbjUtil(); + VoucherPayableService server = new VoucherPayableService(); + String tempFilePath = server.sendSapVoucher(onlyMark, requestId, billTable); + String fileName = ""; + String remotePath = ""; + if (Integer.parseInt(voucherType) == 1) { + fileName = "Pav" + Util.getTime("yyyyMMddHHmmss") + ".txt"; + remotePath = pavRemotePath; + } else if (Integer.parseInt(voucherType) == 2) { + fileName = "Pmv" + Util.getTime("yyyyMMddHHmmss") + ".txt"; + remotePath = pmvRemotePath; + } + log.info("远程连接地址:" + "smb://" + ip + remotePath); + log.info("本地文件地址: " + tempFilePath); + smbjUtil.smbPut("smb://" + ip + remotePath, tempFilePath, userName, password, fileName); + Files.delete(Paths.get(tempFilePath)); + /* ******************* 是否提交流程 ******************* */ + if (Boolean.parseBoolean(submitAction)) { + this.submitWorkflow(requestId, user.getUID()); + } + } catch (Exception e) { + log.error("推送应付款凭证失败!" + e.getMessage()); + if (Boolean.parseBoolean(block)) { + throw new CustomerException(e.getMessage(), e); + } + } + } + + public void submitWorkflow(String requestId, Integer userId) { + Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "sap对接自动提交流程!"); + } + } diff --git a/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/util/SmbjUtil.java b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/util/SmbjUtil.java new file mode 100644 index 0000000..c99b060 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/util/SmbjUtil.java @@ -0,0 +1,120 @@ +package weaver.youhong.ai.haripijiu.action.sapdocking.util; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.google.common.base.Strings; +import jcifs.smb.*; +import org.apache.log4j.Logger; + +import java.io.*; +import java.net.MalformedURLException; +import java.nio.file.Files; +import java.util.Objects; + +/** + *

windows共享文件夹访问工具

+ * + *

create: 2023/2/8 17:55

+ * + * @author youHong.ai + */ +public class SmbjUtil { + + + private final Logger log = Util.getLogger(); + + /** + * Description: 从本地上传文件到共享目录 + * + * @param remoteUrl 共享文件目录 + * @param localFilePath 本地文件绝对路径 + */ + public void smbPut(String remoteUrl, String localFilePath, String userName, String pwd, String fileName) { + InputStream in = null; + OutputStream out = null; + try { + File localFile = new File(localFilePath); + if (Strings.isNullOrEmpty(fileName)) { + fileName = localFile.getName(); + } + // 这里推荐使用这种方式进行用户名密码的校验,在url中拼接,如果需要特殊字符可能无法转换 + NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, userName, pwd); + SmbFile remoteFile = new SmbFile(remoteUrl + "/" + fileName, auth); + in = new BufferedInputStream(Files.newInputStream(localFile.toPath())); + out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile)); + byte[] buffer = new byte[1024]; + while (in.read(buffer) != -1) { + out.write(buffer); + buffer = new byte[1024]; + } + } catch (Exception e) { + log.error("提交文件到 共享目录失败!\n" + Util.getErrString(e)); + throw new CustomerException("提交文件到 共享目录失败"); + } finally { + closeStream(in, out); + } + } + + private void closeStream(InputStream in, OutputStream out) { + try { + if (!Objects.isNull(out)) { + out.close(); + } + if (!Objects.isNull(in)) { + in.close(); + } + } catch (IOException e) { + log.error("流关闭失败!\n" + Util.getErrString(e)); + throw new CustomerException("流关闭失败"); + } + } + + /** + * Description: 从共享目录拷贝文件到本地 + * + * @param remoteUrl 共享目录上的文件路径 + * @param localDir 本地目录 + */ + public void smbGet(String remoteUrl, String localDir) { + InputStream in = null; + OutputStream out = null; + try { + SmbFile remoteFile = new SmbFile(remoteUrl); + String fileName = remoteFile.getName(); + File localFile = new File(localDir + File.separator + fileName); + in = new BufferedInputStream(new SmbFileInputStream(remoteFile)); + out = new BufferedOutputStream(Files.newOutputStream(localFile.toPath())); + byte[] buffer = new byte[1024]; + while (in.read(buffer) != -1) { + out.write(buffer); + buffer = new byte[1024]; + } + } catch (Exception e) { + log.error("从共享目录拷贝文件到本地失败!\n" + Util.getErrString(e)); + throw new CustomerException("从共享目录拷贝文件到本地失败"); + } finally { + closeStream(in, out); + } + } + + /** + * 删除文件 + * + * @param remoteUrl 共享文件目录 + * @param fileName 要删除的文件名 + */ + public void deleteFile(String remoteUrl, String fileName, String userName, String pwd) { + SmbFile smbFile; + try { + // smb://userName:passWord@host/path/shareFolderPath/fileName + NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, userName, pwd); + smbFile = new SmbFile(remoteUrl + "/" + fileName, auth); + if (smbFile.exists()) { + smbFile.delete(); + } + } catch (MalformedURLException | SmbException e) { + log.error("删除共享目录文件失败!\n" + Util.getErrString(e)); + throw new CustomerException("删除共享目录文件失败"); + } + } +} diff --git a/src/test/java/youhong/ai/haripijiu/TestHaRiPiJiu.java b/src/test/java/youhong/ai/haripijiu/TestHaRiPiJiu.java new file mode 100644 index 0000000..ceca37a --- /dev/null +++ b/src/test/java/youhong/ai/haripijiu/TestHaRiPiJiu.java @@ -0,0 +1,23 @@ +package youhong.ai.haripijiu; + +import aiyh.utils.GenerateFileUtil; +import basetest.BaseTest; +import org.junit.Test; +import weaver.youhong.ai.haripijiu.action.sapdocking.ReceiptAndPaymentAction; +import weaver.youhong.ai.haripijiu.action.sapdocking.VoucherPayableAction; + +/** + *

测试

+ * + *

create: 2023/2/12 13:24

+ * + * @author youHong.ai + */ +public class TestHaRiPiJiu extends BaseTest { + + @Test + public void testA() { + GenerateFileUtil.createActionDocument(VoucherPayableAction.class); + GenerateFileUtil.createActionDocument(ReceiptAndPaymentAction.class); + } +}