3 Commits 2432607536 ... 8207a9cb8d

Tác giả SHA1 Thông báo Ngày
  andy 8207a9cb8d 添加验证码使用后置空,用户登录错误次数限制 10 tháng trước cách đây
  andy cb1666659b 更新测试和新增配置 11 tháng trước cách đây
  andy 953791421c 新增本地日志 11 tháng trước cách đây

+ 3 - 13
mainFactory/pom.xml

@@ -30,12 +30,6 @@
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
-<!--            <exclusions>-->
-<!--                <exclusion>-->
-<!--                    <groupId>org.springframework.boot</groupId>-->
-<!--                    <artifactId>spring-boot-starter-logging</artifactId>-->
-<!--                </exclusion>-->
-<!--            </exclusions>-->
         </dependency>
 
         <dependency>
@@ -61,8 +55,8 @@
         </dependency>
 
         <dependency>
-            <groupId>junit</groupId>
-            <artifactId>junit</artifactId>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
         </dependency>
         <dependency>
@@ -85,6 +79,7 @@
         <dependency>
             <groupId>com.mysql</groupId>
             <artifactId>mysql-connector-j</artifactId>
+            <scope>runtime</scope>
         </dependency>
 
         <dependency>
@@ -151,11 +146,6 @@
             <artifactId>com.ibm.mq.jakarta.client</artifactId>
             <version>9.3.4.1</version>
         </dependency>
-<!--        <dependency>-->
-<!--            <groupId>cn.hutool</groupId>-->
-<!--            <artifactId>hutool-all</artifactId>-->
-<!--            <version>5.8.18</version>-->
-<!--        </dependency>-->
         <dependency>
             <groupId>cn.com.kingbase</groupId>
             <artifactId>kingbase8</artifactId>

+ 177 - 109
mainFactory/src/main/java/org/bfkj/application/AuthApplicationImpl.java

@@ -1,21 +1,35 @@
 package org.bfkj.application;
 
-
-import com.fasterxml.jackson.databind.ObjectMapper;
 import org.bfkj.config.AppConfig;
 import org.bfkj.config.ObjectMap;
-import org.bfkj.utils.*;
+import org.bfkj.utils.LogUtils;
+import org.bfkj.utils.MapTools;
+import org.bfkj.utils.MyDbHelper;
+import org.bfkj.utils.RandomGraphic;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
+import com.fasterxml.jackson.databind.ObjectMapper;
+
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 @Service
 public class AuthApplicationImpl {
-
+    @Value(value = "${app.user.login.retry:5}")
+    private Integer maxErrorCount = 5;
+    
+    private static final Map<String, Integer> userErrorCountMap = new ConcurrentHashMap<>();
+    
     //统一成功信息处理
     public Map<String, Object> processSuccess(Object returnData) {
         Map<String, Object> returnMap = new HashMap<>();//用于当前方法统一返回参数,不存在深拷贝问题
@@ -23,7 +37,7 @@ public class AuthApplicationImpl {
         returnMap.put("returnData", returnData);
         return returnMap;
     }
-
+    
     //统一错误信息处理
     public Map<String, Object> processFail(String errorMessage) {
         Map<String, Object> returnMap = new HashMap<>();//用于当前方法统一返回参数,不存在深拷贝问题
@@ -31,14 +45,9 @@ public class AuthApplicationImpl {
         returnMap.put("message", errorMessage);
         return returnMap;
     }
-
-
+    
     /**
      * 获取应用令牌
-     *
-     * @param params
-     * @param sessionID
-     * @return
      */
     public Object getToken(Map<String, String> params, String sessionID) {
         String appid = params.get("appid");
@@ -47,15 +56,17 @@ public class AuthApplicationImpl {
         if (Objects.nonNull(myDbHelper.getErrorMessage())) {
             return processFail("获取数据库连接失败");
         }
-        Map<String, Object> appInfoResult = myDbHelper.queryByParamsReturnList("select app_code_rule,app_id,app_name,app_log, app_token_effective,active_duration from t_application where  app_show_id =? AND  app_show_secret=?", appid, appSecret);
-        if (!appInfoResult.get("code").equals("0")) {
+        Map<String, Object> appInfoResult = myDbHelper.queryByParamsReturnList(
+                "select app_code_rule,app_id,app_name,app_log, app_token_effective,active_duration from t_application" +
+                        " where  app_show_id =? AND  app_show_secret=?", appid, appSecret);
+        if (! appInfoResult.get("code").equals("0")) {
             return processFail("查询异常" + appInfoResult.get("message"));
         }
         List<Map<String, Object>> appData = (List<Map<String, Object>>) appInfoResult.get("returnData");
         if (appData.isEmpty()) {
             return processFail("错误的appid或appSecret");
         }
-//        无条件删除已经过期的令牌delete from 应用验证表 where app_effective > NOW()
+        //        无条件删除已经过期的令牌delete from 应用验证表 where app_effective > NOW()
         myDbHelper.updateByCondition("delete from t_application_login where app_effective > NOW()", null);
         // 生成全局唯一的应用令牌
         String appTokenOnly = createLifeCycleCol(9999L, 9999);
@@ -65,72 +76,83 @@ public class AuthApplicationImpl {
         Map<String, Object> appInfoData = appData.get(0); //apptoken 有效时长,用户有效存活时长
         String app_id = appInfoData.get("app_id").toString();
         String app_effective_str = null;
-        if(Objects.nonNull(appInfoData.get("app_token_effective"))){
-            app_effective_str=  LocalDateTime.now().plusHours(Long.parseLong(appInfoData.get("app_token_effective").toString())).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
-        }
-        Map<String, Object> insertReturnKeyValues = myDbHelper.updateByCondition("insert into t_application_login(app_id,app_token,app_effective,session_id,request_time) values(?,?,?,?,?)", null, app_id, appTokenOnly,app_effective_str, serviceOnlyID, MapTools.dateTostr(new Date()));
+        if (Objects.nonNull(appInfoData.get("app_token_effective"))) {
+            app_effective_str =
+                    LocalDateTime.now().plusHours(Long.parseLong(appInfoData.get("app_token_effective").toString()))
+                                 .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+        }
+        Map<String, Object> insertReturnKeyValues = myDbHelper.updateByCondition(
+                "insert into t_application_login(app_id,app_token,app_effective,session_id,request_time) values(?,?," +
+                        "?,?,?)", null, app_id, appTokenOnly, app_effective_str, serviceOnlyID,
+                MapTools.dateTostr(new Date()));
         if (Objects.isNull(insertReturnKeyValues) || insertReturnKeyValues.get("code").equals("-1")) {
             return processFail("创建应用Token异常");
         }
-        Map<String, Object> listResult = myDbHelper.queryByParamsReturnList("select * from t_application_login where  app_token=?  ", appTokenOnly);
+        Map<String, Object> listResult =
+                myDbHelper.queryByParamsReturnList("select * from t_application_login where  app_token=?  ",
+                                                   appTokenOnly);
         HashMap<String, Object> returnData = new HashMap<>();
         returnData.put("app_token", appTokenOnly);
-        returnData.put("app_effective", ((List<Map<String, Object>>) listResult.get("returnData")).get(0).get("app_effective")); //令牌有效期
+        returnData.put("app_effective",
+                       ((List<Map<String, Object>>) listResult.get("returnData")).get(0).get("app_effective")); //令牌有效期
         returnData.put("active_duration", appInfoData.get("active_duration"));
         returnData.put("app_name", appInfoData.get("app_name"));
         returnData.put("app_log", appInfoData.get("app_log"));
         returnData.put("app_code_rule", appInfoData.get("app_code_rule"));
         return processSuccess(returnData);
     }
-
+    
     /**
      * 校验应用令牌的逻辑(app_token) 返回字符串----令牌唯一性确保无需其它信息进行判断
-     *
-     * @param appToken
-     * @return
      */
     public String verificationToken(String appToken) {
         MyDbHelper myDbHelper = ObjectMap.getordropMyDbHelper(AppConfig.REMOTE_DB_CONNECT);
         if (Objects.nonNull(myDbHelper.getErrorMessage())) {
             return "验证令牌获取远程数据库连接失败" + myDbHelper.getErrorMessage();
         }
-        Map<String, Object> verificationTokenResult = myDbHelper.queryByParamsReturnList("select app_id from t_application_login where app_token=? and  ( app_effective > NOW() or  app_effective is NULL )", appToken);
+        Map<String, Object> verificationTokenResult = myDbHelper.queryByParamsReturnList(
+                "select app_id from t_application_login where app_token=? and  ( app_effective > NOW() or  " +
+                        "app_effective is NULL )", appToken);
         List<Map<String, Object>> returnData = MapTools.getMapList(verificationTokenResult);
-        return (!verificationTokenResult.get("code").equals("0") || Objects.isNull(returnData) || returnData.isEmpty()) ? "查询错误或令牌验证不通过" : returnData.get(0).get("app_id").toString();
+        return (! verificationTokenResult.get("code").equals("0") || Objects.isNull(returnData) ||
+                returnData.isEmpty()) ? "查询错误或令牌验证不通过" : returnData.get(0).get("app_id").toString();
     }
-
+    
     /**
      * 刷新应用令牌的逻辑:
-     *
-     * @param params
-     * @return
      */
     public Object refreshToken(Map<String, String> params) {
         String app_token = params.get("app_token");
         if (Objects.isNull(app_token)) {
             return processFail("app_token为空,刷新失败");
-
         }
         MyDbHelper myDbHelper = ObjectMap.getordropMyDbHelper(AppConfig.REMOTE_DB_CONNECT);
         if (Objects.nonNull(myDbHelper.getErrorMessage())) {
             return processFail("刷新应用app_token获取远程数据库连接失败" + myDbHelper.getErrorMessage());
         }
         String appid = verificationToken(app_token);
-        if (!MapTools.isNumber(appid)) {
+        if (! MapTools.isNumber(appid)) {
             return processFail("校验token失败: " + appid);
         }
         // 获取令牌有效时长
-        Map<String, Object> appTokenEffectiveResult = myDbHelper.queryByParamsReturnList("select app_token_effective from t_application where  app_id = ?", appid);
+        Map<String, Object> appTokenEffectiveResult =
+                myDbHelper.queryByParamsReturnList("select app_token_effective from t_application where  app_id = ?",
+                                                   appid);
         List<Map<String, Object>> returnData = MapTools.getMapList(appTokenEffectiveResult);
         if (null == returnData || returnData.isEmpty()) {
             return appTokenEffectiveResult;
         }
-
         Object app_token_effective = returnData.get(0).get("app_token_effective");
-        String app_effective = Objects.nonNull(app_token_effective) ? "DATE_ADD(NOW(),INTERVAL  " + app_token_effective + " HOUR)" : null;
+        String app_effective =
+                Objects.nonNull(app_token_effective) ? "DATE_ADD(NOW(),INTERVAL  " + app_token_effective + " HOUR)" :
+                        null;
         try {
-            myDbHelper.updateByCondition("update t_application_login set app_effective=" + app_effective + "  where app_token=?", null, app_token);
-            Map<String, Object> listResult = myDbHelper.queryByParamsReturnList("select * from t_application_login where  app_token=?  ", app_token);
+            myDbHelper.updateByCondition(
+                    "update t_application_login set app_effective=" + app_effective + "  where app_token=?", null,
+                    app_token);
+            Map<String, Object> listResult =
+                    myDbHelper.queryByParamsReturnList("select * from t_application_login where  app_token=?  ",
+                                                       app_token);
             List<Map<String, Object>> returnD = MapTools.getMapList(listResult);
             if (null == returnD || returnD.isEmpty()) {
                 return listResult;
@@ -141,14 +163,14 @@ public class AuthApplicationImpl {
             return processSuccess(returnMap);
         } catch (Exception e) {
             return processFail("app_token 刷新失败");
-
         }
     }
-
+    
     /**
      * 获取验证码
      *
      * @param params {appId:"",token:""}
+     *
      * @return 验证码执行结果信息
      */
     public Object getVCode(Map<String, Object> params) {
@@ -157,14 +179,15 @@ public class AuthApplicationImpl {
             return processFail("app_token为空");
         }
         String appid = verificationToken(app_token.toString());
-        if (!MapTools.isNumber(appid)) {
+        if (! MapTools.isNumber(appid)) {
             return processFail("tokan校验失败:" + appid);
         }
         MyDbHelper myDbHelper = ObjectMap.getordropMyDbHelper(AppConfig.REMOTE_DB_CONNECT);
         if (Objects.nonNull(myDbHelper.getErrorMessage())) {
             return processFail("获取验证码,获取数据库连接失败");
         }
-        Map<String, Object> appCodeRuleResult = myDbHelper.queryByParamsReturnList("SELECT  app_code_rule ,app_code_effective   FROM t_application WHERE app_id =?", appid);
+        Map<String, Object> appCodeRuleResult = myDbHelper.queryByParamsReturnList(
+                "SELECT  app_code_rule ,app_code_effective   FROM t_application WHERE app_id =?", appid);
         List<Map<String, Object>> returnD = MapTools.getMapList(appCodeRuleResult);
         if (appCodeRuleResult.get("code").equals("-1")) {
             return processFail("获取验证规则失败");
@@ -174,12 +197,12 @@ public class AuthApplicationImpl {
         int appCodeEffective = 0;
         if (Objects.nonNull(returnD) && returnD.size() > 0) {
             appRule = returnD.get(0).get("app_code_rule");
-            appCodeEffective = Objects.isNull(returnD.get(0).get("app_code_effective")) ? 300 : Integer.parseInt(returnD.get(0).get("app_code_effective").toString());
+            appCodeEffective = Objects.isNull(returnD.get(0).get("app_code_effective")) ? 300 :
+                    Integer.parseInt(returnD.get(0).get("app_code_effective").toString());
         }
         if (Objects.isNull(appRule)) {
             return processFail("无需验证码");
         }
-
         String codeFormat = "";
         //codeType == 1 ? "0123456789" : "0123456789ACDEFGHJKLMNPQRSTWXY"
         if (appRule.toString().contains("A")) {
@@ -188,36 +211,39 @@ public class AuthApplicationImpl {
             codeFormat = codeFormat + "0123456789";
         } else {
             return processFail("验证码规则不存在");
-
         }
         // 生成验证码
         String appRuleStr = appRule.toString();  //A2N4
-        Map<String, Object> map = RandomGraphic.generateVerifyCode(Integer.parseInt(appRuleStr.substring(appRuleStr.length() - 1)), codeFormat);
+        Map<String, Object> map =
+                RandomGraphic.generateVerifyCode(Integer.parseInt(appRuleStr.substring(appRuleStr.length() - 1)),
+                                                 codeFormat);
         if (null == map) {
             return processFail("生成验证码失败");
         }
         try {
-            myDbHelper.updateByCondition("update t_application_login set app_code = ?,app_code_expire = DATE_ADD(NOW(),INTERVAL  " + appCodeEffective + " SECOND )  where app_token=?", null, map.get("verifyCode").toString(), app_token);
-            Map<String, Object> listResult = myDbHelper.queryByParamsReturnList("select * from t_application_login where  app_token=?  ", app_token);
+            myDbHelper.updateByCondition(
+                    "update t_application_login set app_code = ?,app_code_expire = DATE_ADD(NOW(),INTERVAL  " +
+                            appCodeEffective + " SECOND )  where app_token=?", null, map.get("verifyCode").toString(),
+                    app_token);
+            Map<String, Object> listResult =
+                    myDbHelper.queryByParamsReturnList("select * from t_application_login where  app_token=?  ",
+                                                       app_token);
             List<Map<String, Object>> applicationInfo = MapTools.getMapList(listResult);
             if (listResult.get("code").equals("-1") || null == applicationInfo) {
                 return processFail("获取验证规则失败");
-
             }
             return processSuccess(new HashMap<String, Object>() {{
                 put("verifyCode", map.get("verifyCodeImage"));
                 put("app_code_expire", applicationInfo.get(0).get("app_code_expire"));
-
             }});
         } catch (Exception e) {
             return processFail("验证码异常:" + LogUtils.getException(e));
         }
     }
-
+    
     /**
      * 用户登录并获取用户权限信息
      *
-     * @param data{”token“:”“,”appid“:”“,”username“:”“,”password“:”“}
      * @return 获取用户权限信息
      */
     public Map<String, Object> signIn(Map<String, String> data) {
@@ -226,7 +252,7 @@ public class AuthApplicationImpl {
         String verificationCode = data.get("verifyCode");
         String app_token = data.get("app_token");
         String app_id = verificationToken(app_token);
-        if (!MapTools.isNumber(app_id)) {
+        if (! MapTools.isNumber(app_id)) {
             return processFail("登陆token校验失败:" + app_id);
         }
         //校验验证码
@@ -234,33 +260,58 @@ public class AuthApplicationImpl {
         if (Objects.nonNull(myDbHelper.getErrorMessage())) {
             return processFail("用户登陆,获取数据库连接失败");
         }
-        Map<String, Object> applicationLogin = myDbHelper.queryByParamsReturnList("select 1 from t_application_login where app_token=? and if(app_code is null,true,app_code = ? and app_code_expire > NOW())", app_token, verificationCode);
+        Map<String, Object> applicationLogin = myDbHelper.queryByParamsReturnList(
+                "select 1 from t_application_login where app_token=? and if(app_code is null,true,app_code = ? and " +
+                        "app_code_expire > NOW())", app_token, verificationCode);
         List<Map<String, Object>> applicationList = MapTools.getMapList(applicationLogin);
-
-
-        if (!applicationLogin.get("code").equals("0")) {
+        if (! applicationLogin.get("code").equals("0")) {
             return processFail("校验验证码,执行错误");
+        }else{
+            myDbHelper.updateByCondition("update t_application_login set app_code = null where app_token=?", null,
+                                         app_token);
         }
         if (applicationList == null || applicationList.isEmpty()) {
             return processFail("验证码错误或过期");
         }
-        Map<String, Object> userInfoResult = myDbHelper.queryByParamsReturnList("select user_id,token_valid_duration,user_status from t_user where user_name = ?  and user_pwd =?", username, password);
-        if (!userInfoResult.get("code").equals("0")) {
+        Map<String, Object> userInfoResult = myDbHelper.queryByParamsReturnList(
+                "select user_id,token_valid_duration,user_status from t_user where user_name = ?  ", username);
+        if (! userInfoResult.get("code").equals("0")) {
             return processFail("校验用户信息,执行异常");
         }
         List<Map<String, Object>> userInfoList = MapTools.getMapList(userInfoResult);
         if (null == userInfoList || userInfoList.isEmpty()) {
             return processFail("用户名或密码错误");
-        }
-        String userStatus = userInfoList.get(0).get("user_status").toString();
-        if (Objects.equals(userStatus,"0")) {
-            return processFail("用户名被禁用");
+        } else {
+            String userStatus = userInfoList.get(0).get("user_status").toString();
+            if (Objects.equals(userStatus, "0")) {
+                return processFail("用户名被禁用");
+            } else {
+                String userPassword = userInfoList.get(0).get("user_pwd").toString();
+                if (! Objects.equals(userPassword, password)) {
+                    Integer errorCount = userErrorCountMap.getOrDefault(username, 0);
+                    errorCount++;
+                    userErrorCountMap.put(username, errorCount);
+                    if (errorCount >= maxErrorCount) {
+                        myDbHelper.updateByCondition("update t_user set user_status = 0 where user_name= ? ", null,
+                                                     username);
+                        userErrorCountMap.remove(username);
+                    }
+                    return processFail("用户名或密码错误");
+                } else {
+                    userErrorCountMap.remove(username);
+                }
+            }
         }
         String userID = userInfoList.get(0).get("user_id").toString();
         String userToken = MapTools.getMD5Str(String.valueOf(new Date().getTime()));
         try {
             Object token_valid_duration = userInfoList.get(0).get("token_valid_duration");
-            myDbHelper.updateByCondition("update t_user set user_token = ?,user_status = 1,signInTime = NOW(),token_valid_time = if(" + Objects.isNull(token_valid_duration) + ",null, DATE_ADD(NOW(),INTERVAL   " + (Objects.isNull(token_valid_duration) ? 0 : Integer.parseInt(token_valid_duration.toString())) + " SECOND) )  where user_id= ? ", null, userToken, userID);
+            myDbHelper.updateByCondition(
+                    "update t_user set user_token = ?,user_status = 1,LogoutTime = null," + "signInTime = NOW()," +
+                            "token_valid_time = if(" + Objects.isNull(token_valid_duration) +
+                            ",null, DATE_ADD(NOW(),INTERVAL   " + (Objects.isNull(token_valid_duration) ? 0 :
+                            Integer.parseInt(token_valid_duration.toString())) + " SECOND) )  where user_id= ? ", null,
+                    userToken, userID);
             return processSuccess(new HashMap<String, Object>() {{
                 put("user_token", userToken);
                 put("user_id", userID);
@@ -270,27 +321,29 @@ public class AuthApplicationImpl {
             return processFail("更新用户Token失败");
         }
     }
-
+    
     public String verificationUserToken(Map<String, String> params) {
         String user_token = params.get("user_token");
         String user_id = params.get("user_id");
-        if (Objects.isNull(user_token) || Objects.isNull(user_id)) return "user_token 或则 user_id为空";
+        if (Objects.isNull(user_token) || Objects.isNull(user_id)) {
+            return "user_token 或则 user_id为空";
+        }
         MyDbHelper myDbHelper = ObjectMap.getordropMyDbHelper(AppConfig.REMOTE_DB_CONNECT);
         if (Objects.nonNull(myDbHelper.getErrorMessage())) {
             return "验证user_token获取远程数据库连接失败" + myDbHelper.getErrorMessage();
         }
-        Map<String, String> userCountMap = myDbHelper.queryForObject("select count(1) as count from t_user where user_id=? and user_token = ? and (token_valid_time > NOW() or  token_valid_time is null )", user_id, user_token);
-        if ((!userCountMap.get("code").equals("0") || Objects.isNull(userCountMap.get("returnData")) || "0".equals(userCountMap.get("returnData")))) {
+        Map<String, String> userCountMap = myDbHelper.queryForObject(
+                "select count(1) as count from t_user where user_id=? and user_token = ? and (token_valid_time > NOW" +
+                        "() or  token_valid_time is null )", user_id, user_token);
+        if ((! userCountMap.get("code").equals("0") || Objects.isNull(userCountMap.get("returnData")) ||
+                "0".equals(userCountMap.get("returnData")))) {
             return "查询错误或令牌验证不通过";
         }
         return null;
     }
-
+    
     /**
      * 用户登出
-     *
-     * @param params
-     * @return
      */
     public Map<String, Object> loginOut(Map<String, String> params) {
         String errorInfo = verificationUserToken(params);
@@ -303,13 +356,14 @@ public class AuthApplicationImpl {
         }
         try {
             String user_id = params.get("user_id");
-            myDbHelper.updateByCondition("update t_user set user_token = null,LogoutTime = NOW() where user_id=?", null, user_id);
+            myDbHelper.updateByCondition("update t_user set user_token = null,LogoutTime = NOW() where user_id=?", null,
+                                         user_id);
             return processSuccess("用户登出成功");
         } catch (Exception e) {
             return processFail("用户登出失败: ");
         }
     }
-
+    
     public Map<String, Object> getAuth(Map<String, String> params) {
         String errorInfo = verificationUserToken(params); //user_toke,user_id
         if (Objects.nonNull(errorInfo)) {
@@ -325,11 +379,12 @@ public class AuthApplicationImpl {
         }
         return myDbHelper.queryByParamsReturnList(" select * from t_auth");
         // 从user_auth表中获取导航栏权限: select auth_id from t_user_auth  where user_id = ?
-//        return myDbHelper.queryByParamsReturnList(" select TA.* from t_user_auth  TUA LEFT JOIN t_auth TA  ON TA.auth_id = TUA.auth_id where TUA.user_id = ?",user_id);
+        //        return myDbHelper.queryByParamsReturnList(" select TA.* from t_user_auth  TUA LEFT JOIN t_auth TA
+        //        ON TA.auth_id = TUA.auth_id where TUA.user_id = ?",user_id);
     }
-
+    
     public Map<String, Object> initColumnSet(Map<String, Object> data) {
-        if (!data.containsKey("auth_id")) {
+        if (! data.containsKey("auth_id")) {
             return processFail("权限编号为空");
         }
         String auth_id = data.get("auth_id").toString();
@@ -337,22 +392,26 @@ public class AuthApplicationImpl {
         if (Objects.nonNull(myDbHelper.getErrorMessage())) {
             return processFail("初始化列设置:权限编号:" + auth_id + " 获取数据库对象异常");
         }
-
-        Map<String, Object> serviceInfoResult = myDbHelper.queryByParamsReturnList("select serviceID,serviceType from serviceinfo where serviceID = (select max(serviceID) as serviceID from t_auth where auth_id = ?) and serviceType ='1'", auth_id);
+        Map<String, Object> serviceInfoResult = myDbHelper.queryByParamsReturnList(
+                "select serviceID,serviceType from serviceinfo where serviceID = (select max(serviceID) as serviceID " +
+                        "from t_auth where auth_id = ?) and serviceType ='1'", auth_id);
         List<Map<String, Object>> serviceInfoList = MapTools.getMapList(serviceInfoResult);
-
-        if (!"0".equals(serviceInfoResult.get("code"))) {
+        if (! "0".equals(serviceInfoResult.get("code"))) {
             return processFail("初始化列设置:权限编号:" + auth_id + " 获取服务列表异常");
         }
         if (Objects.isNull(serviceInfoList) || serviceInfoList.isEmpty()) {
-            return processFail("初始化列设置:权限编号:" + auth_id + " 未找到对应的服务或者服务为采集类,不可进行列设置初始化");
+            return processFail(
+                    "初始化列设置:权限编号:" + auth_id + " 未找到对应的服务或者服务为采集类,不可进行列设置初始化");
         }
         String serviceID = serviceInfoList.get(0).get("serviceID").toString();
         // 通过服务获取列设置
         List<Map<String, Object>> columnList;
         Object tableName = null;
         try {
-            Map<String, Object> queryByParamsReturnMap = myDbHelper.queryByParamsReturnList("select calculation_library.*,datasourceinfo.connectConfig  from calculation_library INNER JOIN datasourceinfo on datasourceinfo.dataSourceID = calculation_library.datasource_id  where service_id=? and library_type =3 order by library_sort, library_id limit 1", serviceID);
+            Map<String, Object> queryByParamsReturnMap = myDbHelper.queryByParamsReturnList(
+                    "select calculation_library.*,datasourceinfo.connectConfig  from calculation_library INNER JOIN " +
+                            "datasourceinfo on datasourceinfo.dataSourceID = calculation_library.datasource_id  where" +
+                            " service_id=? and library_type =3 order by library_sort, library_id limit 1", serviceID);
             if (queryByParamsReturnMap.get("code").equals("-1")) {
                 return processFail("通过服务获取列设置:SQL执行异常");
             }
@@ -377,7 +436,9 @@ public class AuthApplicationImpl {
                 //todo 获取对应的数据源 获取mydb对象
                 // 替换SQL中的符号
                 String expression = "(?<=《)([^》]+)?(?=》)";
-                Pattern regExpression = Pattern.compile(expression);  // select * from user where userid = 《userID》 select * from user where userid is null
+                Pattern regExpression = Pattern.compile(
+                        expression);  // select * from user where userid = 《userID》 select * from user where userid
+                // is null
                 Matcher parameterNames = regExpression.matcher(tempSQL);
                 while (parameterNames.find()) {
                     String tempColumn = parameterNames.group(); //
@@ -387,8 +448,9 @@ public class AuthApplicationImpl {
             } else {
                 specialSearchDataResult = remoteMyDbHelper.getAllColumnTableSet(tableName.toString());
             }
-            if (!"0".equals(specialSearchDataResult.get("code"))) {
-                return processFail("初始化列设置:权限编号:" + auth_id + " 模拟查询异常:" + specialSearchDataResult.get("message"));
+            if (! "0".equals(specialSearchDataResult.get("code"))) {
+                return processFail(
+                        "初始化列设置:权限编号:" + auth_id + " 模拟查询异常:" + specialSearchDataResult.get("message"));
             }
             columnList = MapTools.getMapList(specialSearchDataResult);
             if (Objects.isNull(columnList) || columnList.isEmpty()) {
@@ -397,12 +459,14 @@ public class AuthApplicationImpl {
         } catch (Exception e) {
             return processFail("获取服务对应算法执行异常" + LogUtils.getException(e));
         }
-        Map<String, Object> columnSetListResult = myDbHelper.queryByParamsReturnList("select  * from querytemplatecolumnset where serviceOutPutId=?", auth_id);
+        Map<String, Object> columnSetListResult =
+                myDbHelper.queryByParamsReturnList("select  * from querytemplatecolumnset where serviceOutPutId=?",
+                                                   auth_id);
         List<Map<String, Object>> columnSetList = MapTools.getMapList(columnSetListResult);
-        if (!"0".equals(columnSetListResult.get("code")) || null == columnSetList) {
-            return processFail("初始化列设置:权限编号:" + auth_id + " 获取权限列标志异常" + columnSetListResult.get("message"));
+        if (! "0".equals(columnSetListResult.get("code")) || null == columnSetList) {
+            return processFail(
+                    "初始化列设置:权限编号:" + auth_id + " 获取权限列标志异常" + columnSetListResult.get("message"));
         }
-
         //初始化一个List<string> OLDColumnList--- > user(userPWD)-- 数据库元数据
         List<String> OLDColumnList = new ArrayList<>();
         HashMap<Object, Map<String, Object>> tempColumnSet = new HashMap<>();
@@ -424,7 +488,6 @@ public class AuthApplicationImpl {
             // 通过columnName与权限ID获取到此行的数据
             deleteList.add(tempColumnSet.get(columnName));
         }
-
         if (deleteList.size() > 0) {
             String sql = " delete from querytemplatecolumnset where serviceOutPutId= ? and columnName=?";
             List<Object[]> selectParams = new ArrayList<>();
@@ -439,27 +502,28 @@ public class AuthApplicationImpl {
         String sql = "";
         if (insertList.size() > 0) {
             if (Objects.nonNull(tableName)) {
-                sql = " insert into  querytemplatecolumnset(serviceOutPutId,columnName,columnLabel,columnDescribe) values(?,?,?,?)";
+                sql = " insert into  querytemplatecolumnset(serviceOutPutId,columnName,columnLabel,columnDescribe) " +
+                        "values(?,?,?,?)";
             } else {
                 sql = " insert into  querytemplatecolumnset(serviceOutPutId,columnName,columnLabel) values(?,?,?)";
             }
-
             List<Object[]> insertParams = new ArrayList<>();
             for (Map<String, Object> insertMap : insertList) {
                 List<Object> inList = new ArrayList<>();
                 inList.add(auth_id);
                 inList.add(insertMap.get("columnName").toString());
                 inList.add(insertMap.get("columnLable").toString());
-                if (Objects.nonNull(tableName)){
+                if (Objects.nonNull(tableName)) {
                     inList.add(insertMap.get("columnDescribe"));
                 }
                 insertParams.add(inList.toArray());
             }
             myDbHelper.updateByCondition(sql, insertParams);
         }
-        return myDbHelper.queryByParamsReturnList("select * from querytemplatecolumnset where serviceOutPutId=?", auth_id);
+        return myDbHelper.queryByParamsReturnList("select * from querytemplatecolumnset where serviceOutPutId=?",
+                                                  auth_id);
     }
-
+    
     //todo 目前采集实际是定时器,真正的采集是算法库中的算法,如果从头开始计算,代表是采集到的新数据,而不是旧数据的恢复
     // 如果需要真正的旧数据恢复,则必须从指定的算法开始,而不是从头开始
     // 需要将dataprocess对象中的算法循环,单独抽离出来,成为一个方法,此方法默认从第一个算法开始,也可以指定从第几个算法开始
@@ -485,9 +549,8 @@ public class AuthApplicationImpl {
             return processFail("异常数据恢复:获取远程数据库连接失败" + myDbHelper.getErrorMessage());
         }
         try {
-
             Map<String, Object> queryByParamsReturnListMap = myDbHelper.queryByParamsReturnList(sql, pmList.toArray());
-            if (!queryByParamsReturnListMap.get("code").equals("0")) {
+            if (! queryByParamsReturnListMap.get("code").equals("0")) {
                 return processFail("获远程日志错误: " + queryByParamsReturnListMap.get("message"));
             }
             List<Map<String, Object>> queryByParamsList = MapTools.getMapList(queryByParamsReturnListMap);
@@ -496,7 +559,7 @@ public class AuthApplicationImpl {
             }
             serviceId = queryByParamsList.get(0).get("serviceId").toString();
             DataProcess dataProcessObj = ObjectMap.getordropInput(serviceId);//获取数据输出处理对象
-            if (null == dataProcessObj || !MapTools.isBlank(dataProcessObj.getErrorMessage())) {
+            if (null == dataProcessObj || ! MapTools.isBlank(dataProcessObj.getErrorMessage())) {
                 return processFail("服务不可用:" + (null == dataProcessObj ? "" : dataProcessObj.getErrorMessage()));
             }
             List<Object[]> deleteIds = new ArrayList<>();
@@ -508,8 +571,11 @@ public class AuthApplicationImpl {
                 Object event = queryMap.get("event");
                 if (Objects.nonNull(iNDataContent)) {
                     ObjectMapper objectMapper = new ObjectMapper();
-                    List<Map<String, Object>> abnormalData = objectMapper.readValue(iNDataContent.toString(), List.class);
-//                    dataProcessObj.execCalultion(abnormalData, queryMap.get("calculationLocation").toString(), event.toString(), queryMap.get("dataObjectId").toString(), null, null);
+                    List<Map<String, Object>> abnormalData =
+                            objectMapper.readValue(iNDataContent.toString(), List.class);
+                    //                    dataProcessObj.execCalultion(abnormalData, queryMap.get
+                    //                    ("calculationLocation").toString(), event.toString(), queryMap.get
+                    //                    ("dataObjectId").toString(), null, null);
                 }
             }
             myDbHelper.updateByCondition("delete  from log_error_a where dataObjectId = ?", deleteIds);
@@ -518,29 +584,29 @@ public class AuthApplicationImpl {
             return processFail("异常数据恢复出现错误:" + LogUtils.getException(e));
         }
     }
-
-
+    
     /**
      * 支持的最大机器id,结果是31 (这个移位算法可以很快计算出几位二进制数所能表示的最大十进制数)
      */
     private final String maxWorkerId = "4";
+    
     /**
      * 支持的最大数据标识id,结果是31
      */
     private final String maxServiceId = "4";
+    
     /**
      * 毫秒内序列(0~4095)
      */
     private final Long maxSequence = 999L;
-
+    
     private long sequence = 0L;
-
+    
     /**
      * 上次生成ID的时间截
      */
-    private long lastTimestamp = -1L;
-
-
+    private long lastTimestamp = - 1L;
+    
     public synchronized String createLifeCycleCol(Long workerId, Integer serviceId) {
         long timestamp = System.currentTimeMillis();
         //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
@@ -563,6 +629,8 @@ public class AuthApplicationImpl {
         //上次生成ID的时间截
         lastTimestamp = timestamp;
         //移位并通过或运算拼到一起组成64位的ID
-        return timestamp + "" + (String.format("%0" + (maxSequence.toString().length()) + "d", sequence)) + (String.format("%0" + maxWorkerId + "d", workerId)) + (String.format("%0" + maxServiceId + "d", serviceId));
+        return timestamp + "" + (String.format("%0" + (maxSequence.toString().length()) + "d", sequence)) +
+                (String.format("%0" + maxWorkerId + "d", workerId)) +
+                (String.format("%0" + maxServiceId + "d", serviceId));
     }
 }

+ 17 - 0
mainFactory/src/main/java/org/bfkj/utils/LogUtils.java

@@ -5,6 +5,8 @@ import org.bfkj.config.AppConfig;
 import org.bfkj.config.ElasticsearchConfig;
 import org.bfkj.config.SpringContextApplication;
 import org.bfkj.protocol.ElasticHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
 import java.text.SimpleDateFormat;
@@ -15,11 +17,26 @@ public class LogUtils { // 依据服务编号ID获取服务类型,如果是异
     public static Map<String, List<Object>> logErrorMapList = new HashMap<>();
     public static Map<String, List<Object>> logSuccessMapList = new HashMap<>();
     public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+    
+    private static final Logger logger = LoggerFactory.getLogger(LogUtils.class);
     public static  void log(String location, String success, Object calculationLocation, String logContent, String serviceId,  Object iNDataContent, String dataObjectId, Object OutDataContent, Object event) {
         ThreadPoolTaskExecutor threadPoolTaskExecutor = SpringContextApplication.getBean("ThreadPoolTaskExecutor");
         threadPoolTaskExecutor.submit(() ->
                 logWrite(location, success, calculationLocation, logContent, serviceId, iNDataContent, dataObjectId, OutDataContent, event)
         );
+        threadPoolTaskExecutor.submit(() ->
+                logger.info("""
+                                    location: {};
+                                    result: {};
+                                    calculation location: {};
+                                    content: {};
+                                    service id: {};
+                                    input data content: {};
+                                    data object id: {};
+                                    output data content: {};
+                                    event: {}
+                                    """,location,success,calculationLocation,logContent,serviceId,iNDataContent,dataObjectId,OutDataContent,event)
+        );
     }
 
     public static void logWrite(String location, String success, Object calculationLocation, String logContent, String serviceId, Object iNDataContent, String dataObjectId, Object OutDataContent, Object event) {

+ 71 - 0
mainFactory/src/main/resources/application-jf.yml

@@ -0,0 +1,71 @@
+server:
+  port: 8043
+  #  ssl:
+  #    key-store: file:/app/database2.0/ssl/shiyq.xyz.jks
+  #    enable: true
+  #    key-store-password: dr41d2jn58c2b88
+  #    key-store-type: JKS
+  servlet:
+    encoding:
+      charset: UTF-8
+      force: true
+      enabled: true
+  codec:
+    max-in-memory-size: -1
+  application:
+    name: mainFactory
+spring:
+  web:
+    resources:
+      static-locations: file:/app/module/dist
+  mvc:
+    view:
+      prefix: /
+      suffix: .html
+    pathmatch:
+      matching-strategy: ant_path_matcher
+
+
+log:
+  url: jdbc:mysql://192.168.243.11:3306/DPFBLOG
+  title: bigdata
+  cipher: ml9*pO4866
+  type: com.mysql.cj.jdbc.Driver
+
+mydb:
+  url: jdbc:mysql://192.168.243.11:3306/DISACenter_2
+  title: bigdata
+  cipher: ml9*pO4866
+  type: com.mysql.cj.jdbc.Driver
+  serviceURL: 192.168.243.11:8043
+#isEs:
+#  open: true
+#  scheme: http
+#  hostname: 120.26.64.82
+#  port: 9200
+#  auth: false
+#  username: ""
+#  password: ""
+#  successIndexName: "success_log_center2"
+#  errorIndexName: "error_log_center2"
+
+isEs:
+  open: false
+  scheme: http
+  hostname: 10.211.67.175
+  port: 9201
+  auth: true
+  username: "elastic"
+  password: "TUihk5^a0J+GkI4!4"
+  successIndexName: "success_log_center2"
+  errorIndexName: "error_log_center2"
+
+
+service:
+  pool:
+    maxPoolSize: 512
+    corePoolSize: 6
+    queueCapacity: 1024
+    keepAliveSeconds: 60
+    threadNamePrefix: logthreadpool
+    waitForTasksToCompleteOnShutdown: true

+ 6 - 3
mainFactory/src/main/resources/application.yml

@@ -19,8 +19,6 @@ spring:
     additional-location: file:/app/config/
   application:
     name: mainFactory
-  profiles:
-    active:
 log:
   url: ${LOG_DB_URL:jdbc:mysql://localhost:3306/DPFBLOG}
   title: ${LOG_DB_USER:root}
@@ -64,4 +62,9 @@ service:
     queueCapacity: 1024
     keepAliveSeconds: 60
     threadNamePrefix: logthreadpool
-    waitForTasksToCompleteOnShutdown: true
+    waitForTasksToCompleteOnShutdown: true
+
+app:
+  user:
+    login:
+      retry: 5

+ 40 - 0
mainFactory/src/main/resources/logback-spring.xml

@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration scan="true" scanPeriod="1 minute" debug="false">
+
+    <!-- 定义日志文件的目录 -->
+    <property name="LOGS" value="./logs" />
+    <property name="LOG_PATTERN" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" />
+
+    <!-- 控制台输出配置 -->
+    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+        <encoder>
+            <pattern>${LOG_PATTERN}</pattern>
+        </encoder>
+    </appender>
+
+    <!-- 日志文件滚动策略,结合时间和大小 -->
+    <appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <file>${LOGS}/app.log</file>
+        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+            <!-- 日志文件按天滚动 -->
+            <fileNamePattern>${LOGS}/app.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
+            <!-- 每个日志文件的最大大小,例如10MB -->
+            <maxFileSize>10MB</maxFileSize>
+            <!-- 保留最近30天的日志文件 -->
+            <maxHistory>30</maxHistory>
+        </rollingPolicy>
+        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+            <!-- 触发滚动的文件大小 -->
+            <MaxFileSize>10MB</MaxFileSize>
+        </triggeringPolicy>
+        <encoder>
+            <pattern>${LOG_PATTERN}</pattern>
+        </encoder>
+    </appender>
+
+    <!-- 设置日志级别 -->
+    <root level="info">
+        <appender-ref ref="STDOUT" />
+        <appender-ref ref="ROLLING_FILE" />
+    </root>
+</configuration>

+ 1 - 1
mainFactory/src/test/java/org/bfkj/protocol/MyRabbitMQTest.java

@@ -1,6 +1,6 @@
 package org.bfkj.protocol;
 
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class MyRabbitMQTest {
 

+ 3 - 1
mainFactory/src/test/java/org/bfkj/protocol/WebAPITest.java

@@ -1,6 +1,8 @@
 package org.bfkj.protocol;
 
-import org.junit.Test;
+
+
+import org.junit.jupiter.api.Test;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;

+ 25 - 0
mainFactory/src/test/java/org/bfkj/utils/MyDbHelperTest.java

@@ -0,0 +1,25 @@
+package org.bfkj.utils;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Map;
+
+@SpringBootTest
+@ActiveProfiles("jf")
+public class MyDbHelperTest  {
+    @Test
+    public void testJdbcDriver() throws SQLException {
+       MyDbHelper myDbHelper = new MyDbHelper("{\"username\":\"system\",  \"password\":\"ml9*pO4866\",  \"url\":\"jdbc:kingbase8://192.168.243.13:54321/baggagebusiness\",  \"driver-class-name\":\"com.kingbase8.Driver\"}");
+        JdbcTemplate theJdbcTemplate = myDbHelper.getTheJdbcTemplate();
+        List<Map<String, Object>> maps = theJdbcTemplate.queryForList("""
+                                                                              select * from baggagebusiness.flight_schedule t1
+                                                                                       where carrierFlightsDate = '2024-04-01'
+                                                                                       """);
+        System.out.println(maps);
+    }
+}

+ 1 - 1
mainFactory/src/test/java/org/bfkj/utils/ScriptEngineProTest.java

@@ -1,7 +1,7 @@
 package org.bfkj.utils;
 
 import org.bfkj.protocol.WebAPI;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
 import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;