andy 1 year ago
parent
commit
bcf1d9a8bf

+ 24 - 24
src/main/java/com/scbfkj/uni/library/RequestUtil.java

@@ -47,6 +47,7 @@ public class RequestUtil {
         return Objects.nonNull(userToken) ? userToken.toString() : null;
 
     }
+
     public static String getAppId() {
 //        请求
         ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
@@ -61,33 +62,32 @@ public class RequestUtil {
 //
         Object application = requestAttributes.getAttribute("application", SCOPE_SESSION);
         if (Objects.isNull(application)) {
-            throw new RuntimeException("获取应用失败 当前连接没有找到应用");
-        }
-        if (Objects.nonNull(application)) {
-            return (Map<String, Object>) application;
+            String appToken = getAppToken();
+            String requestIp = getIpAddr();
+            String query = "select * from appconnectlog where apptoken=? and requestip =?";
+            List<Map<String, Object>> appConnectLogList = DataBase.query(Config.securityConnectionStr, query, new ArrayList<>() {{
+                add(new Object[]{appToken, requestIp});
+            }});
+            if (appConnectLogList.isEmpty()) {
+                throw new RuntimeException("当前连接未登录");
+            }
+            Map<String, Object> stringObjectMap = appConnectLogList.get(0);
+            Object applicationid = stringObjectMap.get("appid");
+
+            query = "select * from application where appid=?";
+            List<Map<String, Object>> applicationList = DataBase.query(Config.securityConnectionStr, query, new ArrayList<>() {{
+                add(new Object[]{applicationid});
+            }});
+            if (applicationList.isEmpty()) {
+                throw new RuntimeException("获取应用失败");
+            }
+            return applicationList.get(0);
         }
+        return (Map<String, Object>) application;
+
 
-        String appToken = getAppToken();
-        String requestIp = getIpAddr();
-        String query = "select * from appconnectlog where apptoken=? and requestip =?";
-        List<Map<String, Object>> appConnectLogList = DataBase.query(Config.securityConnectionStr, query, new ArrayList<>() {{
-            add(new Object[]{appToken, requestIp});
-        }});
-        if (appConnectLogList.isEmpty()) {
-            throw new RuntimeException("当前连接未登录");
-        }
-        Map<String, Object> stringObjectMap = appConnectLogList.get(0);
-        Object applicationid = stringObjectMap.get("applicationid");
-
-        query = "select * from application where applicationid=?";
-        List<Map<String, Object>> applicationList = DataBase.query(Config.securityConnectionStr, query, new ArrayList<>() {{
-            add(new Object[]{applicationid});
-        }});
-        if (applicationList.isEmpty()) {
-            throw new RuntimeException("获取应用失败");
-        }
-        return applicationList.get(0);
     }
+
     public static String getUserId() {
 //        请求
         ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();

+ 264 - 0
src/main/java/com/scbfkj/uni/library/script/DatabaseScriptUtil.java

@@ -0,0 +1,264 @@
+package com.scbfkj.uni.library.script;
+
+import com.scbfkj.uni.library.UniReturnUtil;
+import com.scbfkj.uni.process.DataBase;
+import org.springframework.util.StringUtils;
+
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+public class DatabaseScriptUtil {
+
+    public static Map<String, Object> exec(String connectionStr, String expression, List<Map<String, Object>> args, Object executionNumber, List<String> filterColumns, List<Map<String, Object>> filterLines) throws Exception {
+
+        if (Objects.isNull(executionNumber) || !StringUtils.hasText(executionNumber.toString())) {
+            throw new RuntimeException("执行编号不能为空");
+        }
+        expression = expression.replaceAll("\\s*(\\r)?\\n\\s*", " ").trim();
+        boolean isTableName = !expression.contains(" ");
+
+        if (Objects.isNull(filterColumns)) filterColumns = new ArrayList<>();
+        if (Objects.isNull(filterLines)) filterLines = new ArrayList<>();
+        String filterLineWhereStr =null;
+        for (Object f : filterLines) {
+            Map<String, Object> it = ((Map<String, Object>) f);
+            filterLineWhereStr = " %s %s %s %s %s %s %s %s ".formatted(
+                    filterLineWhereStr,
+                    it.getOrDefault("left", ""),
+                    it.get("column"),
+                    it.get("comparator"),
+                    Objects.equals(it.get("comparator"), " is null ") ? "" : "?",
+                    !Objects.equals(it.get("comparator"), " is null ")?" ":it.get("value"),
+                    it.getOrDefault("right", ""),
+                    it.getOrDefault("connector", "")
+            );
+        }
+
+//        只有表名
+        if (isTableName) {
+            List<String> valueNames = null;
+            List<String> filterNames = null;
+//            查询
+            if (Objects.equals("0", executionNumber)) {
+                Map<String, Object> map = args.get(0);
+                Map<String, Object> filter = ((Map<String, Object>) map.getOrDefault("filter", map));
+                filterNames = filter.keySet().stream().toList();
+                String whereStr =null;
+                for (Object f : filterLines) {
+                    Map<String, Object> it = ((Map<String, Object>) f);
+                    whereStr = " %s %s %s %s %s %s %s %s ".formatted(
+                            whereStr,
+                            it.getOrDefault("left", ""),
+                            it.get("column"),
+                            it.get("comparator"),
+                            Objects.equals(it.get("comparator"), " is null ") ? "" : "?",
+                            !Objects.equals(it.get("comparator"), " is null ")?" ":it.get("value"),
+                            it.getOrDefault("right", ""),
+                            it.getOrDefault("connector", "")
+                    );
+                }
+                expression = "select * from %s where %s and  %s".formatted(
+                        expression,
+                        filterNames.stream().map("%s = ?"::formatted).collect(Collectors.joining(" and ")),
+                        Objects.isNull(filterLineWhereStr) ? " 1=1 " : filterLineWhereStr);
+
+                if( !filterColumns.isEmpty()){
+                    expression= "select %s from (%s) as T".formatted(String.join(",", filterColumns),expression);
+                }
+
+                List<Object[]> values = new ArrayList<>();
+                for (Map<String, Object> arg : args) {
+                    List<Object> objects = new ArrayList<>();
+                    if (Objects.nonNull(valueNames)) {
+                        Map<String, Object> o1 = ((Map<String, Object>) arg.getOrDefault("value", arg));
+                        objects.addAll(valueNames.stream().map(o1::get).toList());
+                    }
+                    if (Objects.nonNull(filterNames)) {
+                        Map<String, Object> o1 = ((Map<String, Object>) arg.getOrDefault("filter", arg));
+                        objects.addAll(filterNames.stream().map(o1::get).toList());
+                    }
+                    values.add(objects.toArray());
+                }
+                List<Map<String, Object>> result = DataBase.query(connectionStr, expression, values);
+                return UniReturnUtil.success(result);
+//                更新或新增
+            } else if (Objects.equals("6", executionNumber)) {
+                Map<String, Object> map = args.get(0);
+                Map<String, Object> filter = ((Map<String, Object>) map.get("filter"));
+                filterNames = filter.keySet().stream().toList();
+
+                List<Map<String, Object>> insertValues = new ArrayList<>();
+                List<Map<String, Object>> updateValues = new ArrayList<>();
+
+                String sql = "select count(1) as existscount from %s where %s".formatted(expression, filterNames.stream().map("%s = ?"::formatted).collect(Collectors.joining(" and ")));
+                for (Map<String, Object> arg : args) {
+
+                    Map<String, Object> where = ((Map<String, Object>) arg.get("filter"));
+                    Object[] objects = filterNames.stream().map(where::get).toArray();
+                    if (exists(connectionStr, sql, objects)) {
+                        updateValues.add(arg);
+                    } else {
+                        insertValues.add(arg);
+                    }
+                }
+                Map<String, Object> insertResult = exec(connectionStr, expression, insertValues, "1", filterColumns, filterLines);
+                Map<String, Object> updateResult = exec(connectionStr, expression, updateValues, "2", filterColumns, filterLines);
+
+                return UniReturnUtil.success(new HashMap<>() {{
+                    put("insert", insertResult);
+                    put("update", updateResult);
+                }});
+
+            } else {
+
+//                新增
+                if (Objects.equals("1", executionNumber)) {
+                    Map<String, Object> map = args.get(0);
+                    Map<String, Object> value = ((Map<String, Object>) map.getOrDefault("value", map));
+                    valueNames = value.keySet().stream().toList();
+                    expression = "insert into %s ( %s) values(%s)".formatted(expression, String.join(",", valueNames), valueNames.stream().map(it -> "?").collect(Collectors.joining(",")));
+//                    更新
+                } else if (Objects.equals("2", executionNumber)) {
+                    Map<String, Object> map = args.get(0);
+                    Map<String, Object> value = ((Map<String, Object>) map.get("value"));
+                    valueNames = value.keySet().stream().toList();
+                    Map<String, Object> filter = ((Map<String, Object>) map.get("filter"));
+                    filterNames = filter.keySet().stream().toList();
+
+                    expression = "update %s set %s where %s and %s".formatted(expression, valueNames.stream().map("%s = ?"::formatted).collect(Collectors.joining(",")),
+                            filterNames.stream().map("%s = ?"::formatted).collect(Collectors.joining(" and ")),
+                            Objects.isNull(filterLineWhereStr)  ? " 1=1 " : filterLineWhereStr);
+//                    删除
+                } else if (Objects.equals("3", executionNumber)) {
+                    Map<String, Object> map = args.get(0);
+                    Map<String, Object> filter = ((Map<String, Object>) map.getOrDefault("filter", map));
+                    filterNames = filter.keySet().stream().toList();
+                    expression = "delete from %s where %s and  %s".formatted(expression,
+                            filterNames.stream().map("%s = ?"::formatted).collect(Collectors.joining(" and ")),
+                            Objects.isNull(filterLineWhereStr)  ? " 1=1 " : filterLineWhereStr);
+                }
+                List<Object[]> values = new ArrayList<>();
+//                按照名称 和过滤条件取值
+                final List<String> finalFilterColumns = filterColumns;
+                for (Map<String, Object> arg : args) {
+                    List<Object> objects = new ArrayList<>();
+                    if (Objects.nonNull(valueNames)) {
+                        Map<String, Object> o1 = ((Map<String, Object>) arg.getOrDefault("value", arg));
+                        objects.addAll(valueNames.stream().map(it -> {
+
+//                            新增 更新 对列过滤
+                            if (finalFilterColumns.contains(it) || finalFilterColumns.isEmpty()) {
+                                return o1.get(it);
+                            } else {
+                                return null;
+                            }
+                        }).toList());
+                    }
+                    if (Objects.nonNull(filterNames)) {
+                        Map<String, Object> o1 = ((Map<String, Object>) arg.getOrDefault("filter", arg));
+                        objects.addAll(filterNames.stream().map(o1::get).toList());
+                    }
+                    values.add(objects.toArray());
+                }
+                int[] ints =  DataBase.updateBatch(connectionStr, expression, values);
+                return UniReturnUtil.success(ints);
+            }
+
+//         目前只支持查询
+        } else if (expression.contains("《whereStr》")) {
+
+            String whereStr = " ";//初始化条件字符串
+            List<Object> dbFilter = new ArrayList<>();//初始化条件执行参数
+            Map<String, Object> map = args.get(0);
+            Object filter = map.get("filter");
+            if (filter instanceof List filterList && !filterList.isEmpty()) {//如果存在上传的条件参数或者存在行权限
+                Map<String, Object> filterMap = (Map<String, Object>) filterList.get(0);
+                if (filterMap.containsKey("column")) {
+                    for (Object f : filterList) {
+                        Map<String, Object> it = ((Map<String, Object>) f);
+                        whereStr = " %s %s %s %s %s %s %s".formatted(
+                                whereStr,
+                                it.getOrDefault("left", ""),
+                                it.get("column"),
+                                it.get("comparator"),
+                                Objects.equals(it.get("comparator"), " is null ") ? "" : "?",
+                                it.getOrDefault("right", ""),
+                                it.getOrDefault("connector", "")
+                        );
+                        if (!Objects.equals(it.get("comparator"), " is null ")) {
+                            dbFilter.add(it.get("value"));
+                        }
+                    }
+                } else {
+                    List<Map.Entry<String, Object>> list = filterMap.entrySet().stream().toList();
+                    whereStr += list.stream().map("%s = ?"::formatted).collect(Collectors.joining(" and "));
+                    dbFilter.addAll(list.stream().map(Map.Entry::getValue).toList());
+                }
+            }else if(filter instanceof Map<?,?> filterMap && !filterMap.isEmpty()){
+                List<? extends Map.Entry<?, ?>> list = filterMap.entrySet().stream().toList();
+                whereStr += list.stream().map(it->"%s = ?".formatted(it.getKey())).collect(Collectors.joining(" and "));
+                dbFilter.addAll(list.stream().map(Map.Entry::getValue).toList());
+            }
+            whereStr = " %s and  %s".formatted(whereStr, Objects.isNull(filterLineWhereStr)  ? " 1=1 " : filterLineWhereStr);
+            String sql = expression.replaceAll("《whereStr》", " " + whereStr);
+
+            if( !filterColumns.isEmpty()){
+                sql= "select %s from (%s) as T".formatted(String.join(",", filterColumns),sql);
+            }
+
+            List<Map<String, Object>> queryResult = DataBase.query(connectionStr, sql, Collections.singletonList(dbFilter.toArray()));
+            return UniReturnUtil.success(queryResult);
+
+        } else {
+            if (Objects.equals(executionNumber, "0")) {
+                List<Map<String, Object>> queryResult =  DataBase.query(connectionStr, expression, args, filterColumns, filterLines);
+                return UniReturnUtil.success(queryResult);
+            } else if (Objects.equals(executionNumber, "1")) {
+                if (sqlStrVarList.containsKey(expression)) {
+                    getSQLVarList(expression);
+                }
+                List<String> names = sqlStrVarList.get(expression);
+                String sql = sqlStrNewSQL.get(expression);
+                int[] updateResult = DataBase.updateBatch(connectionStr, sql, args.stream().map(it -> names.stream().map(it::get).toArray()).toList());
+                return UniReturnUtil.success(updateResult);
+            } else {
+                if (sqlStrVarList.containsKey(expression)) {
+                    getSQLVarList(expression);
+                }
+                List<String> names = sqlStrVarList.get(expression);
+                String sql = " %s  and %s".formatted(sqlStrNewSQL.get(expression), Objects.isNull(filterLineWhereStr)  ? " 1=1 " : filterLineWhereStr);
+                int[] updateResult = DataBase.updateBatch(connectionStr, sql, args.stream().map(it -> names.stream().map(it::get).toArray()).toList());
+                return UniReturnUtil.success(updateResult);
+            }
+        }
+    }
+
+
+    private static Pattern regExpression = Pattern.compile("(?<=《)([^》]+)?(?=》)");//提取书名号变量的正则表达式
+    private static Map<String, List<String>> sqlStrVarList = new HashMap<>();//SQL语句的书名号变量列表
+    public static Map<String, String> sqlStrNewSQL = new HashMap<>();//SQL语句更换书名号变量后的可执行SQL
+
+    public static List<String> getSQLVarList(String sqlStr) {
+        String newSqlStr = sqlStr;//不破坏之前SQL语句
+        List<String> sqlvarList = sqlStrVarList.containsKey(sqlStr) ? sqlStrVarList.get(sqlStr) : new ArrayList<>();//优先从缓存中取
+        if (!sqlStrNewSQL.containsKey(sqlStr)) {//缓存不存在则重新获取
+            Matcher matcher = regExpression.matcher(sqlStr);//正则提取
+            while (matcher.find()) {//循环提取到的所有书名号变量
+                String varName = matcher.group();
+                sqlvarList.add(varName.trim());
+                newSqlStr = newSqlStr.replaceFirst("《".concat(varName).concat("》"), " ? "); //修订SQL
+            }
+            sqlStrVarList.put(sqlStr, sqlvarList);//添加到缓存
+            sqlStrNewSQL.put(sqlStr, newSqlStr);//添加到缓存
+        }
+        return sqlvarList;
+    }
+    private static boolean exists(String connectionStr, String sql, Object[] args) throws Exception {
+        List<Map<String, Object>> mapList = DataBase.query(connectionStr, sql, Collections.singletonList(args));
+        if (mapList.isEmpty()) return false;
+        return !Objects.equals(mapList.get(0).get("existscount").toString(), "0");
+    }
+
+}

+ 4 - 265
src/main/java/com/scbfkj/uni/process/DataBase.java

@@ -2,19 +2,15 @@ package com.scbfkj.uni.process;
 
 import com.fasterxml.jackson.databind.JsonNode;
 import com.scbfkj.uni.library.DataFormatUtil;
-import com.scbfkj.uni.library.UniReturnUtil;
+import com.scbfkj.uni.library.script.DatabaseScriptUtil;
 import com.scbfkj.uni.system.Config;
 import com.zaxxer.hikari.HikariConfig;
 import com.zaxxer.hikari.pool.HikariPool;
 import jakarta.annotation.Nonnull;
-import org.springframework.util.StringUtils;
 
 import java.sql.*;
 import java.time.LocalDateTime;
 import java.util.*;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
 
 public class DataBase {
 
@@ -114,255 +110,7 @@ public class DataBase {
         }
     }
 
-    public static Map<String, Object> exec(String connectionStr, String expression, List<Map<String, Object>> args, Object executionNumber, List<String> filterColumns, List<Map<String, Object>> filterLines) throws Exception {
 
-        if (Objects.isNull(executionNumber) || !StringUtils.hasText(executionNumber.toString())) {
-            throw new RuntimeException("执行编号不能为空");
-        }
-        expression = expression.replaceAll("\\s*(\\r)?\\n\\s*", " ").trim();
-        boolean isTableName = !expression.contains(" ");
-
-        if (Objects.isNull(filterColumns)) filterColumns = new ArrayList<>();
-        if (Objects.isNull(filterLines)) filterLines = new ArrayList<>();
-        String filterLineWhereStr =null;
-        for (Object f : filterLines) {
-            Map<String, Object> it = ((Map<String, Object>) f);
-            filterLineWhereStr = " %s %s %s %s %s %s %s %s ".formatted(
-                    filterLineWhereStr,
-                    it.getOrDefault("left", ""),
-                    it.get("column"),
-                    it.get("comparator"),
-                    Objects.equals(it.get("comparator"), " is null ") ? "" : "?",
-                    !Objects.equals(it.get("comparator"), " is null ")?" ":it.get("value"),
-                    it.getOrDefault("right", ""),
-                    it.getOrDefault("connector", "")
-            );
-        }
-
-//        只有表名
-        if (isTableName) {
-            List<String> valueNames = null;
-            List<String> filterNames = null;
-//            查询
-            if (Objects.equals("0", executionNumber)) {
-                Map<String, Object> map = args.get(0);
-                Map<String, Object> filter = ((Map<String, Object>) map.getOrDefault("filter", map));
-                filterNames = filter.keySet().stream().toList();
-                String whereStr =null;
-                for (Object f : filterLines) {
-                    Map<String, Object> it = ((Map<String, Object>) f);
-                    whereStr = " %s %s %s %s %s %s %s %s ".formatted(
-                            whereStr,
-                            it.getOrDefault("left", ""),
-                            it.get("column"),
-                            it.get("comparator"),
-                            Objects.equals(it.get("comparator"), " is null ") ? "" : "?",
-                            !Objects.equals(it.get("comparator"), " is null ")?" ":it.get("value"),
-                            it.getOrDefault("right", ""),
-                            it.getOrDefault("connector", "")
-                    );
-                }
-                expression = "select * from %s where %s and  %s".formatted(
-                        expression,
-                        filterNames.stream().map("%s = ?"::formatted).collect(Collectors.joining(" and ")),
-                         Objects.isNull(filterLineWhereStr) ? " 1=1 " : filterLineWhereStr);
-
-                if( !filterColumns.isEmpty()){
-                    expression= "select %s from (%s) as T".formatted(String.join(",", filterColumns),expression);
-                }
-
-                List<Object[]> values = new ArrayList<>();
-                for (Map<String, Object> arg : args) {
-                    List<Object> objects = new ArrayList<>();
-                    if (Objects.nonNull(valueNames)) {
-                        Map<String, Object> o1 = ((Map<String, Object>) arg.getOrDefault("value", arg));
-                        objects.addAll(valueNames.stream().map(o1::get).toList());
-                    }
-                    if (Objects.nonNull(filterNames)) {
-                        Map<String, Object> o1 = ((Map<String, Object>) arg.getOrDefault("filter", arg));
-                        objects.addAll(filterNames.stream().map(o1::get).toList());
-                    }
-                    values.add(objects.toArray());
-                }
-                List<Map<String, Object>> result = query(connectionStr, expression, values);
-                return UniReturnUtil.success(result);
-//                更新或新增
-            } else if (Objects.equals("6", executionNumber)) {
-                Map<String, Object> map = args.get(0);
-                Map<String, Object> filter = ((Map<String, Object>) map.get("filter"));
-                filterNames = filter.keySet().stream().toList();
-
-                List<Map<String, Object>> insertValues = new ArrayList<>();
-                List<Map<String, Object>> updateValues = new ArrayList<>();
-
-                String sql = "select count(1) as existscount from %s where %s".formatted(expression, filterNames.stream().map("%s = ?"::formatted).collect(Collectors.joining(" and ")));
-                for (Map<String, Object> arg : args) {
-
-                    Map<String, Object> where = ((Map<String, Object>) arg.get("filter"));
-                    Object[] objects = filterNames.stream().map(where::get).toArray();
-                    if (exists(connectionStr, sql, objects)) {
-                        updateValues.add(arg);
-                    } else {
-                        insertValues.add(arg);
-                    }
-                }
-                Map<String, Object> insertResult = exec(connectionStr, expression, insertValues, "1", filterColumns, filterLines);
-                Map<String, Object> updateResult = exec(connectionStr, expression, updateValues, "2", filterColumns, filterLines);
-
-                return UniReturnUtil.success(new HashMap<>() {{
-                    put("insert", insertResult);
-                    put("update", updateResult);
-                }});
-
-            } else {
-
-//                新增
-                if (Objects.equals("1", executionNumber)) {
-                    Map<String, Object> map = args.get(0);
-                    Map<String, Object> value = ((Map<String, Object>) map.getOrDefault("value", map));
-                    valueNames = value.keySet().stream().toList();
-                    expression = "insert into %s ( %s) values(%s)".formatted(expression, String.join(",", valueNames), valueNames.stream().map(it -> "?").collect(Collectors.joining(",")));
-//                    更新
-                } else if (Objects.equals("2", executionNumber)) {
-                    Map<String, Object> map = args.get(0);
-                    Map<String, Object> value = ((Map<String, Object>) map.get("value"));
-                    valueNames = value.keySet().stream().toList();
-                    Map<String, Object> filter = ((Map<String, Object>) map.get("filter"));
-                    filterNames = filter.keySet().stream().toList();
-
-                    expression = "update %s set %s where %s and %s".formatted(expression, valueNames.stream().map("%s = ?"::formatted).collect(Collectors.joining(",")),
-                            filterNames.stream().map("%s = ?"::formatted).collect(Collectors.joining(" and ")),
-                            Objects.isNull(filterLineWhereStr)  ? " 1=1 " : filterLineWhereStr);
-//                    删除
-                } else if (Objects.equals("3", executionNumber)) {
-                    Map<String, Object> map = args.get(0);
-                    Map<String, Object> filter = ((Map<String, Object>) map.getOrDefault("filter", map));
-                    filterNames = filter.keySet().stream().toList();
-                    expression = "delete from %s where %s and  %s".formatted(expression,
-                            filterNames.stream().map("%s = ?"::formatted).collect(Collectors.joining(" and ")),
-                            Objects.isNull(filterLineWhereStr)  ? " 1=1 " : filterLineWhereStr);
-                }
-                List<Object[]> values = new ArrayList<>();
-//                按照名称 和过滤条件取值
-                final List<String> finalFilterColumns = filterColumns;
-                for (Map<String, Object> arg : args) {
-                    List<Object> objects = new ArrayList<>();
-                    if (Objects.nonNull(valueNames)) {
-                        Map<String, Object> o1 = ((Map<String, Object>) arg.getOrDefault("value", arg));
-                        objects.addAll(valueNames.stream().map(it -> {
-
-//                            新增 更新 对列过滤
-                            if (finalFilterColumns.contains(it) || finalFilterColumns.isEmpty()) {
-                                return o1.get(it);
-                            } else {
-                                return null;
-                            }
-                        }).toList());
-                    }
-                    if (Objects.nonNull(filterNames)) {
-                        Map<String, Object> o1 = ((Map<String, Object>) arg.getOrDefault("filter", arg));
-                        objects.addAll(filterNames.stream().map(o1::get).toList());
-                    }
-                    values.add(objects.toArray());
-                }
-                int[] ints = updateBatch(connectionStr, expression, values);
-                return UniReturnUtil.success(ints);
-            }
-
-//         目前只支持查询
-        } else if (expression.contains("《whereStr》")) {
-
-            String whereStr = " ";//初始化条件字符串
-            List<Object> dbFilter = new ArrayList<>();//初始化条件执行参数
-            Map<String, Object> map = args.get(0);
-            Object filter = map.get("filter");
-            if (filter instanceof List filterList && !filterList.isEmpty()) {//如果存在上传的条件参数或者存在行权限
-                Map<String, Object> filterMap = (Map<String, Object>) filterList.get(0);
-                if (filterMap.containsKey("column")) {
-                    for (Object f : filterList) {
-                        Map<String, Object> it = ((Map<String, Object>) f);
-                        whereStr = " %s %s %s %s %s %s %s".formatted(
-                                whereStr,
-                                it.getOrDefault("left", ""),
-                                it.get("column"),
-                                it.get("comparator"),
-                                Objects.equals(it.get("comparator"), " is null ") ? "" : "?",
-                                it.getOrDefault("right", ""),
-                                it.getOrDefault("connector", "")
-                        );
-                        if (!Objects.equals(it.get("comparator"), " is null ")) {
-                            dbFilter.add(it.get("value"));
-                        }
-                    }
-                } else {
-                    List<Map.Entry<String, Object>> list = filterMap.entrySet().stream().toList();
-                    whereStr += list.stream().map("%s = ?"::formatted).collect(Collectors.joining(" and "));
-                    dbFilter.addAll(list.stream().map(Map.Entry::getValue).toList());
-                }
-            }else if(filter instanceof Map<?,?> filterMap && !filterMap.isEmpty()){
-                    List<? extends Map.Entry<?, ?>> list = filterMap.entrySet().stream().toList();
-                    whereStr += list.stream().map(it->"%s = ?".formatted(it.getKey())).collect(Collectors.joining(" and "));
-                    dbFilter.addAll(list.stream().map(Map.Entry::getValue).toList());
-            }
-            whereStr = " %s and  %s".formatted(whereStr, Objects.isNull(filterLineWhereStr)  ? " 1=1 " : filterLineWhereStr);
-            String sql = expression.replaceAll("《whereStr》", " " + whereStr);
-
-            if( !filterColumns.isEmpty()){
-                sql= "select %s from (%s) as T".formatted(String.join(",", filterColumns),sql);
-            }
-
-            List<Map<String, Object>> queryResult = query(connectionStr, sql, Collections.singletonList(dbFilter.toArray()));
-            return UniReturnUtil.success(queryResult);
-
-        } else {
-            if (Objects.equals(executionNumber, "0")) {
-                List<Map<String, Object>> queryResult = query(connectionStr, expression, args, filterColumns, filterLines);
-                return UniReturnUtil.success(queryResult);
-            } else if (Objects.equals(executionNumber, "1")) {
-                if (sqlStrVarList.containsKey(expression)) {
-                    getSQLVarList(expression);
-                }
-                List<String> names = sqlStrVarList.get(expression);
-                String sql = sqlStrNewSQL.get(expression);
-                int[] updateResult = updateBatch(connectionStr, sql, args.stream().map(it -> names.stream().map(it::get).toArray()).toList());
-                return UniReturnUtil.success(updateResult);
-            } else {
-                if (sqlStrVarList.containsKey(expression)) {
-                    getSQLVarList(expression);
-                }
-                List<String> names = sqlStrVarList.get(expression);
-                String sql = " %s  and %s".formatted(sqlStrNewSQL.get(expression), Objects.isNull(filterLineWhereStr)  ? " 1=1 " : filterLineWhereStr);
-                int[] updateResult = updateBatch(connectionStr, sql, args.stream().map(it -> names.stream().map(it::get).toArray()).toList());
-                return UniReturnUtil.success(updateResult);
-            }
-        }
-    }
-
-    private static Pattern regExpression = Pattern.compile("(?<=《)([^》]+)?(?=》)");//提取书名号变量的正则表达式
-    private static Map<String, List<String>> sqlStrVarList = new HashMap<>();//SQL语句的书名号变量列表
-    private static Map<String, String> sqlStrNewSQL = new HashMap<>();//SQL语句更换书名号变量后的可执行SQL
-
-    private static List<String> getSQLVarList(String sqlStr) {
-        String newSqlStr = sqlStr;//不破坏之前SQL语句
-        List<String> sqlvarList = sqlStrVarList.containsKey(sqlStr) ? sqlStrVarList.get(sqlStr) : new ArrayList<>();//优先从缓存中取
-        if (!sqlStrNewSQL.containsKey(sqlStr)) {//缓存不存在则重新获取
-            Matcher matcher = regExpression.matcher(sqlStr);//正则提取
-            while (matcher.find()) {//循环提取到的所有书名号变量
-                String varName = matcher.group();
-                sqlvarList.add(varName.trim());
-                newSqlStr = newSqlStr.replaceFirst("《".concat(varName).concat("》"), " ? "); //修订SQL
-            }
-            sqlStrVarList.put(sqlStr, sqlvarList);//添加到缓存
-            sqlStrNewSQL.put(sqlStr, newSqlStr);//添加到缓存
-        }
-        return sqlvarList;
-    }
-
-    private static boolean exists(String connectionStr, String sql, Object[] args) throws Exception {
-        List<Map<String, Object>> mapList = query(connectionStr, sql, Collections.singletonList(args));
-        if (mapList.isEmpty()) return false;
-        return !Objects.equals(mapList.get(0).get("existscount").toString(), "0");
-    }
 
     public static List<Map<String, Object>> query(String connectionStr, String sql, List<Map<String, Object>> argsList, List<String> filterColumns, List<Map<String, Object>> filterLines) throws Exception {
 
@@ -389,18 +137,9 @@ public class DataBase {
         }
 
         List<List<Object>> result = new ArrayList<>();
-//        List<String> names = new ArrayList<>();
-//        Matcher matcher = regExpression.matcher(sql);
-//        if (matcher.find()) {
-//            int index = 0;
-//            while (matcher.find()) {
-//                String name = matcher.group(index);
-//                names.add(name);
-//            }
-//        }
-
-        List<String> names = getSQLVarList(sql);
-        String newSql = sqlStrNewSQL.get(sql);
+
+        List<String> names = DatabaseScriptUtil.getSQLVarList(sql);
+        String newSql = DatabaseScriptUtil.sqlStrNewSQL.get(sql);
 
         if (names.size() == 1 && names.contains("whereStr")) {
             List<Map<String, Object>> list = new ArrayList<>();

+ 2 - 2
src/main/java/com/scbfkj/uni/service/ControlService.java

@@ -36,9 +36,9 @@ public class ControlService {
         String serviceId = serviceidOpt.get();
         List<Map<String, Object>> serviceInfoList = null;
         if (serviceId.matches("^\\d+$")) {
-            serviceInfoList = DataBase.query(Config.centerConnectionStr, "select * from servideinfo where serviceid=?", Collections.singletonList(new Object[]{serviceId}));
+            serviceInfoList = DataBase.query(Config.centerConnectionStr, "select * from serviceinfo where serviceid=?", Collections.singletonList(new Object[]{serviceId}));
         } else {
-            serviceInfoList = DataBase.query(Config.localCenterConnectionStr, "select * from servideinfo where serviceid=?", Collections.singletonList(new Object[]{serviceId}));
+            serviceInfoList = DataBase.query(Config.localCenterConnectionStr, "select * from serviceinfo where serviceid=?", Collections.singletonList(new Object[]{serviceId}));
         }
         if (serviceInfoList.isEmpty()) {
             throw new RuntimeException("服务%s没有配置".formatted(serviceId));

+ 10 - 1
src/main/java/com/scbfkj/uni/service/DataProcessService.java

@@ -5,6 +5,7 @@ import com.jayway.jsonpath.JsonPath;
 import com.scbfkj.uni.library.DataAliasGetUtil;
 import com.scbfkj.uni.library.DataFormatUtil;
 import com.scbfkj.uni.library.UniReturnUtil;
+import com.scbfkj.uni.library.script.DatabaseScriptUtil;
 import com.scbfkj.uni.library.script.JavaScriptEngineUtil;
 import com.scbfkj.uni.library.script.JsScriptEngineUtil;
 import com.scbfkj.uni.process.DataBase;
@@ -176,7 +177,7 @@ public class DataProcessService {
             case "3" -> {
 //                下放到Database中处理数据
 //                参数表达式顺序是 数据源连接字符串(String.$.datasource.connectset),sql表达式(String.$.algorithm.computingexpression),需要操作的值(List.$.args[1].returnData),执行编号(String.$.algorithm.executionnumber)
-                return DataBase.exec(parameters.get(0).toString(), parameters.get(1).toString(), ((List<Map<String, Object>>) parameters.get(2)), parameters.get(3), (List<String>) parameters.get(4), (List<Map<String, Object>>) parameters.get(5));
+                return DatabaseScriptUtil.exec(parameters.get(0).toString(), parameters.get(1).toString(), ((List<Map<String, Object>>) parameters.get(2)), parameters.get(3), (List<String>) parameters.get(4), (List<Map<String, Object>>) parameters.get(5));
             }
         }
         return UniReturnUtil.fail("算法类型不支持");
@@ -197,6 +198,14 @@ public class DataProcessService {
         for (String it : paths) {
             it = it.trim();
             String type = it.split("\\.")[0];
+            if(!List.of().contains(type)){
+                if(Objects.equals("null",type)) {
+                    result.add(null);
+                }else{
+                    result.add(type);
+                }
+                    break;
+            }
             String path = it.replace(type + ".", "");
             Object value = null;
 //            $开头的使用标准的jsonPath

+ 31 - 14
src/main/java/com/scbfkj/uni/service/LoggerService.java

@@ -3,11 +3,11 @@ package com.scbfkj.uni.service;
 import com.jayway.jsonpath.JsonPath;
 import com.scbfkj.uni.library.DataFormatUtil;
 import com.scbfkj.uni.library.UniReturnUtil;
+import com.scbfkj.uni.library.script.DatabaseScriptUtil;
 import com.scbfkj.uni.process.DataBase;
 import com.scbfkj.uni.process.Elasticsearch;
 import com.scbfkj.uni.process.Kafka;
 import com.scbfkj.uni.system.Config;
-import com.zaxxer.hikari.pool.HikariPool;
 import org.springframework.stereotype.Component;
 
 import java.io.File;
@@ -71,9 +71,12 @@ public class LoggerService {
             if (!Objects.equals(returnCode, "0")) {
                 tableName = "serviceerrlog";
             }
-            insertLog(connectionStr, "insert into %s ('begintime','endtime','serviceid','resource','preresource','returncode','returnmessage','lifecycleid') values (?,?,?,?,?,?,?,?,?)".formatted(tableName), List.of(beginTime, endTime, serviceID, resource, preResource, returnCode, returnMessage, dataObjectID));
+//            insertLog(connectionStr,
+//                    "insert into %s ('begintime','endtime','serviceid','resource','preresource','returncode','returnmessage','lifecycleid') values (?,?,?,?,?,?,?,?,?)".formatted(tableName),
+//                    List.of(beginTime, endTime, serviceID, resource, preResource, returnCode, returnMessage, dataObjectID));
         } catch (Exception e) {
-            throw new RuntimeException(e);
+            e.printStackTrace();
+            System.out.println(UniReturnUtil.getMessage(e));
         }
     }
 
@@ -83,6 +86,16 @@ public class LoggerService {
         //调用工具类的获取雪花编号getUniqueNumber(时间戳+当前容器编号+0)
         //打开雪花编号对应的临时Sqlite(日志文件夹下)
         //写入数据
+
+        try {
+            String tableName = "systemerrlog";
+            String connectionStr = getCurrentThreadConnection(tableName);
+            insertLog(connectionStr,
+                    "insert into %s ('occurrenceTime','occurrenceAddress','detailedMessage') values (?,?,?)".formatted(tableName),
+                    List.of(occurrenceTime, occurrenceAddress, detailedMessage));
+        } catch (Exception e) {
+            System.out.println(UniReturnUtil.getMessage(e));
+        }
     }
 
     private static String getCurrentThreadConnection(String targetName) throws Exception {
@@ -102,7 +115,7 @@ public class LoggerService {
                         CREATE TABLE interfacelog (
                              
                             logid         Integer
-                                primary key auto_increment,
+                                primary key autoincrement,
                             requesttime DATETIME,
                             requestip TEXT,
                             requestpath TEXT,
@@ -121,7 +134,7 @@ public class LoggerService {
                         CREATE TABLE servicelog (
                              
                             logid         Integer
-                                primary key auto_increment,
+                                primary key autoincrement,
                              begintime DATETIME,
                              endtime DATETIME,
                              serviceid TEXT,
@@ -138,7 +151,7 @@ public class LoggerService {
                         CREATE TABLE serviceerrlog (
                              
                             logid         Integer
-                                primary key auto_increment,
+                                primary key autoincrement,
                              begintime DATETIME,
                              endtime DATETIME,
                              serviceid TEXT,
@@ -155,7 +168,7 @@ public class LoggerService {
                         create table systemerrlog
                          (
                              logid         Integer
-                                 primary key auto_increment,
+                                 primary key autoincrement,
                              occurrencetime DATETIME,
                              occurrenceaddress TEXT,
                              detailedmessage TEXT
@@ -168,7 +181,7 @@ public class LoggerService {
                         CREATE TABLE userlog (
                               
                             logid         Integer
-                                primary key auto_increment,
+                                primary key autoincrement,
                             requesttime DATETIME,
                             requestip TEXT,
                             requestpath TEXT,
@@ -202,7 +215,7 @@ public class LoggerService {
      * @param fileName
      * @return
      */
-    private static Map<String, Object> apply(String fileName) {
+    private static void apply(String fileName) {
         String newConnection = logConnection.replace("log_", fileName);
         String tableName = fileName.substring(fileName.lastIndexOf("_") + 1);
         try {
@@ -215,12 +228,17 @@ public class LoggerService {
                 if (value > 10) {
                     new File("logs" + File.separator + fileName).delete();
                     flag.remove(fileName);
-                    return UniReturnUtil.success(null);
+                    return;
                 } else {
                     flag.put(fileName, value);
 
                 }
 
+            } else {
+                if (!flag.containsKey(fileName)) {
+                    flag.put(fileName, 0);
+                }
+                flag.put(fileName, 0);
             }
 //           删除成功的日志
             if (!result.isEmpty()) {
@@ -229,7 +247,7 @@ public class LoggerService {
                     if (Objects.isNull(type)) throw new RuntimeException("日志输出目标类型没有配置");
                     switch (type.toString()) {
                         case "DB" -> {
-                            DataBase.exec(target, tableName, result, "1", null, null);
+                            DatabaseScriptUtil.exec(target, tableName, result, "1", null, null);
                         }
                         case "KAFKA" -> {
                             Kafka.sendMessage(target, tableName, result);
@@ -239,13 +257,12 @@ public class LoggerService {
                         }
                     }
                 }
-                DataBase.exec(newConnection, tableName, result.stream().map(it -> (Map<String, Object>) new HashMap<String, Object>() {{
+                DatabaseScriptUtil.exec(newConnection, tableName, result.stream().map(it -> (Map<String, Object>) new HashMap<String, Object>() {{
                     put("logid", it.get("logid"));
                 }}).toList(), "3", null, null);
             }
-            return UniReturnUtil.success(null);
         } catch (Exception e) {
-            throw new RuntimeException(e);
+            System.out.println(UniReturnUtil.getMessage(e));
         }
 
     }

+ 40 - 7
src/main/java/com/scbfkj/uni/service/SecurityService.java

@@ -1,6 +1,7 @@
 package com.scbfkj.uni.service;
 
 import com.scbfkj.uni.library.*;
+import com.scbfkj.uni.library.script.DatabaseScriptUtil;
 import com.scbfkj.uni.process.DataBase;
 import com.scbfkj.uni.system.Config;
 import org.springframework.beans.factory.annotation.Value;
@@ -29,7 +30,6 @@ public class SecurityService {
     private boolean debug;
 
 
-
     private static final SecureRandom RANDOM = new SecureRandom();
 
     private static String createCode(int size, String source) {
@@ -63,16 +63,35 @@ public class SecurityService {
             }
             Map<String, Object> application = applicationList.get(0);
 
+
             Object apptokeneffectiveObj = application.get("apptokeneffective");
             Long apptokeneffective = defaultAppTokenEffective;
             if (Objects.nonNull(apptokeneffectiveObj)) {
                 apptokeneffective = Long.parseLong(apptokeneffectiveObj.toString());
             }
             LocalDateTime expiresTime = LocalDateTime.now().plusSeconds(apptokeneffective);
-            String sessionId = RequestUtil.getSessionId();
-            String appToken = DataEncryptionUtil.signatureMD5("%s:%s".formatted(LocalDateTime.now(), sessionId));
-            RequestContextHolder.currentRequestAttributes().setAttribute("appid", appid, SCOPE_SESSION);
             Map<String, Object> data = new HashMap<>();
+            String ip = RequestUtil.getIpAddr();
+            List<Map<String, Object>> logs = DataBase.query(Config.securityConnectionStr, "select * from appconnectlog where requestip=? and appid = ?", Collections.singletonList(new Object[]{ip, appid.get()}));
+            String appToken;
+            if (!logs.isEmpty()) {
+                DataBase.updateBatch(Config.securityConnectionStr, """
+                                                update appconnectlog
+                        set expiretime = ?,lasttime=?
+                        where connid=?""", Collections.singletonList(new Object[]{expiresTime, LocalDateTime.now(), logs.get(0).get("connid")}));
+                Map<String, Object> map = logs.get(0);
+                RequestContextHolder.currentRequestAttributes().setAttribute("application", application, SCOPE_SESSION);
+                appToken = map.get("apptoken").toString();
+            } else {
+                String sessionId = RequestUtil.getSessionId();
+                appToken = DataEncryptionUtil.signatureMD5("%s:%s".formatted(LocalDateTime.now(), sessionId));
+                RequestContextHolder.currentRequestAttributes().setAttribute("appid", appid, SCOPE_SESSION);
+
+                DataBase.updateBatch(Config.securityConnectionStr, """
+                                                insert into appconnectlog (appid, requesttime, requestip, apptoken, expiretime, lasttime)
+                        values (?,?,?,?,?,?)""", Collections.singletonList(new Object[]{appid.get(), LocalDateTime.now(), ip, appToken, expiresTime, LocalDateTime.now()}));
+
+            }
             data.put("token", appToken);
             data.put("expirestime", DataFormatUtil.toString(expiresTime));
             data.put("appname", application.get("appname"));
@@ -229,7 +248,7 @@ public class SecurityService {
             }
         }
 
-        String query = "select * from userinfo where  username =? and userpassword=? ";
+        String query = "select * from userinfo where  account =? and userpassword=? ";
         List<Map<String, Object>> userInfoList = DataBase.query(Config.securityConnectionStr, query, new ArrayList<>() {{
             add(new Object[]{username.get(), DataEncryptionUtil.decryptRSAByPrivateKey(password.get())});
         }});
@@ -378,7 +397,21 @@ public class SecurityService {
     public Map<String, Object> permission() throws Exception {
 
         String userId = RequestUtil.getUserId();
-        String query = " select userpermissionsid, t2.userid,  t3.pagecode, t1.serviceid, insertcolumnlist, updatecolumnlist, selectcolumnlist, filterset from userinfo t2,userpermissions t1 left join pageconfiguration t3 on t3.pageconfigurationid=t1.pageconfigurationid where t1.userid=t2.userid and t1.userid = ?";
+        String query = """
+                                select userpermissionsid,
+                       t2.userid,
+                       t3.*,
+                       t1.serviceid,
+                       insetcolumnlist,
+                       updatecolumnlist,
+                       selectcolumnlist,
+                       filterset
+                from pageconfiguration t3,
+                     userpermissions t1,
+                          userinfo t2
+                where t1.userid = t2.userid
+                  and  t3.pageconfigurationid = t1.pageconfigurationid
+                  and t1.userid = ?""";
         List<Map<String, Object>> permission = DataBase.query(Config.securityConnectionStr, query, new ArrayList<>() {{
             add(new Object[]{userId});
         }});
@@ -419,7 +452,7 @@ public class SecurityService {
         if (userLoginLogList.isEmpty()) {
             return UniReturnUtil.fail("查询失败");
         } else {
-            return UniReturnUtil.success("查询失败");
+            return UniReturnUtil.success("查询成功");
         }
 
     }

+ 7 - 7
src/main/java/com/scbfkj/uni/system/SystemInit.java

@@ -49,13 +49,13 @@ public class SystemInit {
         initializeSystemEnvironment();
         ControlService.startServiceByContainerCode();
 //        日志任务
-        ScheduleUtil.start(() -> {
-            try {
-                LoggerService.sendLog();
-            } catch (FileNotFoundException exception) {
-                System.out.println(exception.getMessage());
-            }
-        }, "* * * * * *");
+//        ScheduleUtil.start(() -> {
+//            try {
+//                LoggerService.sendLog();
+//            } catch (FileNotFoundException exception) {
+//                System.out.println(exception.getMessage());
+//            }
+//        }, "* * * * * *");
 
     }
 

+ 2 - 2
src/main/resources/application.properties

@@ -1,6 +1,6 @@
 db.center.config=hLcDKcDr4MgqYdb8j0gF0nF806yUy1UdEp1nmztEdo5rNL8IZliDj7/feOp2Fc7j19m9jtiwFp5nPvClI1Ni4kxluI8MQepS8nBK3bEzRzsGSswNHa/Sjyw0GK9/ZnOaiD+lDQyI7+fVbmpdvkLy7QE07bpTIjdI1tcLx8Z9QWs=
 db.security.config=Jnj84d14EmSgKEXyAbSH+bratWGkpV89/VA5Er4yQOt7qlnKtGYJzBVJNNYMBdmSlW0G+nqDHMhJQcmHrwbjjChYuGeDcmKSRmvFQ9u7LwqmgEfazzKKoVawXmJ40dMsec2yaFyNnCM92xn1hzHvle5BL7x3kza2htGm+iOqO7Y=
 log.target=B7xSbq4imA5zapX8kEO42mU/5sA2TyF/Ba2Y/++F3z9Np7iT4ywDUkbRC4w/Xrxv1kMSR8PQMJ4dfYwc3mYj0SJJivN5A5/6hI+ZSQBabfZZrYwaIIRdM1XIk4wo1SIrSCXKzef8X6YUH70R2tnh+Uq6KNNp08KaZ2ZXM8vX5Ss=
-server.port=8085
-app.container.code=001
+server.port=9500
+app.container.code=dev
 #app.debug=true

+ 19 - 0
src/test/java/com/scbfkj/uni/ControllerBaseTest.java

@@ -0,0 +1,19 @@
+package com.scbfkj.uni;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+@SpringBootTest
+public class ControllerBaseTest {
+
+
+    protected MockMvc mockMvc;
+
+    @BeforeEach
+    public void before (WebApplicationContext webApplicationContext){
+        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
+    }
+}

+ 114 - 0
src/test/java/com/scbfkj/uni/api/SecurityApiTest.java

@@ -0,0 +1,114 @@
+package com.scbfkj.uni.api;
+
+import com.jayway.jsonpath.JsonPath;
+import com.scbfkj.uni.ControllerBaseTest;
+import jakarta.servlet.http.Cookie;
+import org.hamcrest.core.IsEqual;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.springframework.http.MediaType;
+import org.springframework.mock.web.MockCookie;
+import org.springframework.mock.web.MockHttpSession;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
+import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
+
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class SecurityApiTest extends ControllerBaseTest {
+    private Cookie cookie = MockCookie.parse("JSESSIONID=78C3FBDF21FFFBE46B8DD728D5C5DBF7");
+    private static String token;
+
+    public void testHello() throws Exception {
+
+        /*
+         * 1、mockMvc.perform执行一个请求。
+         * 2、MockMvcRequestBuilders.get("XXX")构造一个请求。
+         * 3、ResultActions.param添加请求传值
+         * 4、ResultActions.accept(MediaType.TEXT_HTML_VALUE))设置返回类型
+         * 5、ResultActions.andExpect添加执行完成后的断言。
+         * 6、ResultActions.andDo添加一个结果处理器,表示要对结果做点什么事情
+         *   比如此处使用MockMvcResultHandlers.print()输出整个响应结果信息。
+         * 7、ResultActions.andReturn表示执行完成后返回相应的结果。
+         */
+        mockMvc.perform(MockMvcRequestBuilders
+                        .get("/hello")
+                        // 设置返回值类型为utf-8,否则默认为ISO-8859-1
+                        .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
+                        .param("name", "Tom"))
+                .andExpect(MockMvcResultMatchers.status().isOk())
+                .andExpect(MockMvcResultMatchers.content().string("Hello Tom!"))
+                .andDo(MockMvcResultHandlers.print());
+    }
+
+
+    @Test
+    @Order(1)
+    void getToken() throws Exception {
+
+        mockMvc.perform(MockMvcRequestBuilders.post("/user/getToken")
+                        .contentType(MediaType.APPLICATION_JSON_VALUE)
+                        .content("""
+                                {"appid":"test","appsecret":"test"}
+                                """)
+                        .cookie(cookie))
+
+                .andExpect(MockMvcResultMatchers.status().isOk())
+                .andExpect(MockMvcResultMatchers.jsonPath("code", IsEqual.equalTo("0")))
+                .andDo(result -> {
+                    String content = result.getResponse().getContentAsString();
+                    SecurityApiTest.token = JsonPath.read(content, "$.returnData.token");
+                })
+                .andDo(MockMvcResultHandlers.print());
+    }
+
+    @Test
+    @Order(2)
+    void refreshToken() throws Exception {
+        mockMvc.perform(MockMvcRequestBuilders.post("/user/refreshToken")
+                        .contentType(MediaType.APPLICATION_JSON_VALUE)
+                        .header("token", token)
+                        .cookie(cookie))
+
+                .andExpect(MockMvcResultMatchers.status().isOk())
+                .andExpect(MockMvcResultMatchers.jsonPath("code", IsEqual.equalTo("0")))
+                .andDo(MockMvcResultHandlers.print());
+    }
+
+    @Test
+    void testToken() {
+    }
+
+    @Test
+    void getCode() {
+    }
+
+    @Test
+    void forceLogin() {
+    }
+
+    @Test
+    void login() {
+    }
+
+    @Test
+    void getPermissions() {
+    }
+
+    @Test
+    void changePwd() {
+    }
+
+    @Test
+    void logOut() {
+    }
+
+    @Test
+    void health() {
+    }
+
+    @Test
+    void getPubKey() {
+    }
+}

+ 1 - 1
src/test/java/com/scbfkj/uni/library/DataEncryptionUtilTest.java

@@ -75,7 +75,7 @@ class DataEncryptionUtilTest {
         System.out.println("private:  " + privateKeyString);
 
         String algorithm = "RSA/ECB/PKCS1Padding";
-        String password = "FIPlYkIL9R+AZ/KGhEjGguLpuBmUjgPNhnO9DbrTw+sJGXTDR5vGMQwLfli3QeJAES1pZCr/icDF5yhJa7Q3mSKpDgl7q1/X+NyuKna43h1rR617d55TLkOBx/h3nvVQGwoOLkQnQvZoYXZplNTyOkGuKRS2ze/iOZuKnhIlZDc=";
+        String password = "V/A7EMJGarEct13FipYK3vP/plaSTuTk7tsE5TnO2M8S5u80NEFGKTmaV2Rl/6G9/y6wpU9RpQUdU4Ri8Ss+/PbR0/LqtIIWQ85pgEpS9lCcfPt3b0pNeQwQnuRDFtg/6z7dGW6MDPAuQtRYgiFIh1YF7qOYcQqG++iYgWBtMu4=";
 
         String decryptedData = DataEncryptionUtil.decryptByPrivateKey(password, privateKeyString, type, algorithm);
         System.out.println(decryptedData);

+ 13 - 12
src/test/java/com/scbfkj/uni/process/DataBaseTest.java

@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
 import com.scbfkj.uni.library.DataFormatUtil;
 import org.junit.jupiter.api.Test;
 import org.springframework.boot.test.context.SpringBootTest;
+import static com.scbfkj.uni.library.script.DatabaseScriptUtil.exec;
 
 import java.util.*;
 
@@ -74,44 +75,44 @@ class DataBaseTest {
    }};
 
     @Test
-    void exec() throws Exception {
+    void testExec() throws Exception {
 
 
 
-        Map<String, Object> exec = DataBase.exec(connectionStr, tableName, insert, "3", filterColumns, filterLines);
+        Map<String, Object> exec = exec(connectionStr, tableName, insert, "3", filterColumns, filterLines);
         System.out.println(DataFormatUtil.toString(exec));
-        exec = DataBase.exec(connectionStr, tableName, insert, "1", filterColumns, filterLines);
+        exec = exec(connectionStr, tableName, insert, "1", filterColumns, filterLines);
         System.out.println(DataFormatUtil.toString(exec));
-        exec = DataBase.exec(connectionStr, tableName, insert, "0", filterColumns, filterLines);
+        exec = exec(connectionStr, tableName, insert, "0", filterColumns, filterLines);
         System.out.println(DataFormatUtil.toString(exec));
-        exec = DataBase.exec(connectionStr, tableName, update, "2", filterColumns, filterLines);
+        exec = exec(connectionStr, tableName, update, "2", filterColumns, filterLines);
         System.out.println(DataFormatUtil.toString(exec));
-        exec = DataBase.exec(connectionStr, tableName, update, "0", filterColumns, filterLines);
+        exec = exec(connectionStr, tableName, update, "0", filterColumns, filterLines);
         System.out.println(DataFormatUtil.toString(exec));
-        exec = DataBase.exec(connectionStr, tableName, insertOrupdate, "6", filterColumns, filterLines);
+        exec = exec(connectionStr, tableName, insertOrupdate, "6", filterColumns, filterLines);
         System.out.println(DataFormatUtil.toString(exec));
-        exec = DataBase.exec(connectionStr, tableName, insertOrupdate, "0", filterColumns, filterLines);
+        exec = exec(connectionStr, tableName, insertOrupdate, "0", filterColumns, filterLines);
         System.out.println(DataFormatUtil.toString(exec));
     }
 
     @Test
     public void testWhereStr() throws Exception {
-        Map<String, Object> exec = DataBase.exec(connectionStr, "select * from %s where 《whereStr》".formatted(tableName), insert, "0", filterColumns, filterLines);
+        Map<String, Object> exec = exec(connectionStr, "select * from %s where 《whereStr》".formatted(tableName), insert, "0", filterColumns, filterLines);
         System.out.println(DataFormatUtil.toString(exec));
     }
     @Test
     public void testBookTitleSymbol() throws Exception {
-        Map<String, Object> exec = DataBase.exec(connectionStr, "select * from %s where id=《id》".formatted(tableName), insert, "0", filterColumns, filterLines);
+        Map<String, Object> exec = exec(connectionStr, "select * from %s where id=《id》".formatted(tableName), insert, "0", filterColumns, filterLines);
         System.out.println(DataFormatUtil.toString(exec));
     }
     @Test
     public void testBookTitleSymbol2() throws Exception {
-        Map<String, Object> exec = DataBase.exec(connectionStr, "select * from %s where id=《id》".formatted(tableName), insert.stream().map(it-> ((Map<String,Object>) it.get("filter"))).toList(), "0", filterColumns, filterLines);
+        Map<String, Object> exec = exec(connectionStr, "select * from %s where id=《id》".formatted(tableName), insert.stream().map(it-> ((Map<String,Object>) it.get("filter"))).toList(), "0", filterColumns, filterLines);
         System.out.println(DataFormatUtil.toString(exec));
     }
     @Test
     public void testFilter() throws Exception {
-        Map<String, Object> exec = DataBase.exec(connectionStr, "select * from %s where 《whereStr》".formatted(tableName), List.of(new HashMap<>(){{
+        Map<String, Object> exec = exec(connectionStr, "select * from %s where 《whereStr》".formatted(tableName), List.of(new HashMap<>(){{
             put("filter",new ArrayList<Map<String,Object>>(){{
                 add(new HashMap<>(){{
                     put("left","(");