Selaa lähdekoodia

更新查询的方法, 支持传入sql,

liu 3 viikkoa sitten
vanhempi
commit
c6ceee84d3

+ 68 - 15
src/main/java/com/bfkj/unidia/Core/DataServices.java

@@ -5,15 +5,16 @@ import com.bfkj.unidia.DataBaseUtils.DbExecutor;
 import com.bfkj.unidia.DataUtils.DataFormatConverter;
 import com.bfkj.unidia.DataUtils.ScriptExecutor;
 import com.bfkj.unidia.Result;
-import com.fasterxml.jackson.databind.JsonSerializable;
-import com.fasterxml.jackson.databind.util.JSONPObject;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+import org.springframework.util.StringUtils;
 
 import java.util.*;
 import java.util.concurrent.*;
+import java.util.stream.Collector;
 import java.util.stream.Collectors;
 
 /**
@@ -81,9 +82,9 @@ public class DataServices {
             return Result.fail("算法执行失败: " + executionResult.getError());
         }
         // 5. 构建返回结果
-        Map<String, Object> result = buildResult(context, serviceInfo);
+        Map<String, Object> result = buildResult(context, serviceInfo,algorithms);
         if(serviceInfo.logEnable()){//异步正常数据库日志
-            logger.info("服务执行完成: {},总耗时:{}",result, System.currentTimeMillis() - startTime);
+//            logger.info("服务执行完成: {},总耗时:{}",result, System.currentTimeMillis() - startTime);
         }
         return Result.success(result);
     }
@@ -268,14 +269,18 @@ public class DataServices {
     private Object resolveFromResults(String path, Map<String, Object> allResults) {
         // 分割路径以获取算法代码和键路径
         String[] parts = path.split("\\.");
+        if (path.equals("0000")){
+            Object object = allResults.get(path);
+            if (Objects.nonNull(object)){ // 直接返回可用的json给前端用
+                return DataFormatConverter.mapToJson((Map<?, ?>) object);
+            }
+            return  null;
+        }
         // 如果路径格式不正确(即没有算法代码或没有键路径),则返回null
         if (parts.length < 2) return null;
 
         // 获取算法代码
         String algorithmCode = parts[0];
-        if (algorithmCode.equals("5")){
-            logger.info("---------------------------");
-        }
         // 构造键路径,从路径中排除算法代码部分
         String keyPath = String.join(".", Arrays.asList(parts).subList(1, parts.length));
 
@@ -377,11 +382,6 @@ public class DataServices {
         try {
             // 检查是否提供了Java类和方法名,以决定使用Java反射还是JS脚本执行
             if (config.className() != null && config.methodName() != null) {
-
-                if (config.algorithmCode.equals("4")||config.algorithmCode.equals("5")){
-                    System.out.println("********************");
-                }
-
                 // 准备参数值数组,用于Java反射调用
                 Object[] paramValues = new Object[inputParams.size()];
                 int i = 0;
@@ -414,7 +414,7 @@ public class DataServices {
                 return Result.success(Collections.singletonMap("returnData", jsResult.getData()));
             }
         } catch (Exception e) {
-            logger.error("算法执行异常:1,{}2,{}3,{}", config.algorithmCode,config.methodName,config.inputDataTemplate);
+            logger.error("算法执行异常:\n编码,{}\n配置,{}\n输入参数,{}", config.algorithmCode,config.methodName,config.inputDataTemplate);
             return Result.fail("算法执行异常: " + e.getMessage());
         }
     }
@@ -527,11 +527,12 @@ public class DataServices {
      * 根据ServiceInfo中的resultType配置,决定返回结果的格式和内容
      * 不同的resultType对应不同的返回结果结构,旨在满足不同场景下对返回数据的需求
      *
-     * @param context ProcessContext对象,包含流程执行的上下文信息和结果
+     * @param context     ProcessContext对象,包含流程执行的上下文信息和结果
      * @param serviceInfo ServiceInfo对象,包含服务的相关信息,包括返回结果的类型
+     * @param algorithms
      * @return Map<String, Object> 返回一个Map对象,包含根据resultType构建的结果
      */
-    private Map<String, Object> buildResult(ProcessContext context, ServiceInfo serviceInfo) {
+    private Map<String, Object> buildResult(ProcessContext context, ServiceInfo serviceInfo, List<AlgorithmConfig> algorithms) {
         // 初始化结果Map
         Map<String, Object> result = new HashMap<>();
 
@@ -545,6 +546,27 @@ public class DataServices {
         } else if (serviceInfo.resultType() == 1) { // 只返回数据
             // 当结果类型为1时,仅返回所有结果数据,不包含状态码和消息
             result.put("returnData", context.getAllResults());
+        }else if (serviceInfo.resultType() == 2){ // 仅返回最后一个算法的数据
+            if (!CollectionUtils.isEmpty(algorithms)&&algorithms.size()>0){
+                List<String> filteredKeys = context.getAllResults().keySet().stream()
+                        .filter(key -> !key.isEmpty()) // 示例过滤条件
+                        .collect(Collectors.toList());
+                List<AlgorithmConfig> collect = algorithms.stream().filter(obj -> filteredKeys.contains(obj.algorithmCode)).collect(Collectors.toList());
+                Object aDefault = context.getAllResults().getOrDefault(collect.get(collect.size() - 1).algorithmCode(), null);
+                if (Objects.nonNull(aDefault)){
+                    Map<String, Object> aDefaultMap = (Map<String, Object>) aDefault;
+                    Object data = aDefaultMap.get("returnData");
+                    if (Objects.nonNull(data)&&data instanceof String&&((String) data).length()>0){
+                            return parseJson((String) data);
+                    }else if (Objects.nonNull(data)&&data instanceof Map){
+                        return (Map<String, Object>) data;
+                    } else if (Objects.nonNull(data)&&data instanceof Integer){
+                        return Map.of("data",data);
+                    }
+                }
+                return Map.of("data","");
+            }
+//            return context.getAllResults().getOrDefault(,null);
         } else { // 完整数据
             // 当结果类型为其他值时,返回完整的上下文信息
             result.put("context", context);
@@ -719,4 +741,35 @@ public class DataServices {
             return serviceCode;
         }
     }
+
+    public Result<String> getServiceInfoByPath(String path) {
+        try {
+            // 构建查询条件,查询启用的服务信息
+            Map<String, Object> conditions = Map.of("service_url", path, "is_enabled", 1,"run_state",1);
+
+            // 执行数据库查询操作
+            Result<List<Map<String, Object>>> result = dbExecutor.search(
+                    systemEnvCache.getDbInfo(),
+                    "service_info",
+                    Map.of("dataContent", Map.of("conditions", conditions),"event","SELECT"));
+
+            // 检查查询结果是否成功且不为空
+            if (!result.isSuccess() || result.getData().isEmpty()) {
+                // 如果查询失败或结果为空,记录日志并返回失败结果
+                logger.error("未找到服务[{}]配置", path);
+                return Result.fail("未找到服务配置");
+            }
+            List<Map<String, Object>> list = result.getData();
+            Map<String, Object> map = list.get(0);
+            if (Objects.nonNull( map)&& StringUtils.hasText(map.get("service_code").toString())){
+                return Result.success(map.get("service_code").toString());
+            }
+            return Result.fail("未找到服务配置");
+        } catch (Exception e) {
+            // 日志记录获取服务信息时的异常
+            logger.error("获取服务信息异常", e);
+            // 返回异常结果
+            return Result.fail("获取服务信息异常: " + e.getMessage());
+        }
+    }
 }

+ 14 - 1
src/main/java/com/bfkj/unidia/DataBaseUtils/ConnectionPoolManager.java

@@ -13,6 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
 
 import javax.annotation.PreDestroy;
 import java.io.File;
@@ -103,6 +104,7 @@ public class ConnectionPoolManager {
         }
     }
 
+//    decrypt(String algorithm, String encryptedData, String key, String iv)
     /**
      * 实际创建数据源
      *
@@ -141,6 +143,15 @@ public class ConnectionPoolManager {
         }
     }
 
+    public String getPwd(String password,String algorithm){
+        String iv = envCache.get("IV", String.class);
+        String key = getPasswordDecryptionKey(algorithm);
+        String encrypt = encryptionUtil.encrypt(algorithm, password, key, iv);
+        String a="ENC(AES:1234567890abcdef:"+encrypt+")";
+        return  a;
+    }
+
+
     /**
      * 解密加密的密码字符串。
      *
@@ -149,6 +160,9 @@ public class ConnectionPoolManager {
      */
     private String decryptPassword(String encryptedPassword) {
         try {
+            if (!StringUtils.hasText(encryptedPassword)){
+                return "";
+            }
             //提取加密密码的主体内容(去除ENC()包裹),用于后续结构校验
             //示例:对于"ENC(algorithm:iv:cipherText)",content为"algorithm:iv:cipherText"
             String content = encryptedPassword.substring(4, encryptedPassword.length() - 1);
@@ -159,7 +173,6 @@ public class ConnectionPoolManager {
              */
             int firstColon = content.indexOf(':');
             int secondColon = content.indexOf(':', firstColon + 1);
-
             // 验证参数分隔符完整性,如果是加密密码则直接进行解密
             if (firstColon > 0 && secondColon > firstColon) {
                 // 提取加密算法、IV和密文数据

+ 58 - 0
src/main/java/com/bfkj/unidia/DataBaseUtils/DbExecutor.java

@@ -7,6 +7,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+import org.springframework.util.StringUtils;
 
 import java.sql.ResultSet;
 import java.util.*;
@@ -387,6 +389,62 @@ public class DbExecutor {
 
     //----------------------------------------------------------------------------------------
 
+    public  Result<List<Map<String, Object>>> search(Map<String, String> dbConfig, String tableName, Map<String, Object> params) {
+        try {
+            //参数预处理为标准参数
+            Result<DbParamsService.ProcessedResult> processDataContextResult = dbParamsService.processExecutorParams(params, dbConfig, tableName);
+            if (!processDataContextResult.isSuccess()) {
+                return Result.fail(processDataContextResult.getError());
+            }
+            DbParamsService.ProcessedResult dbParams = processDataContextResult.getData();
+            String event = dbParams.getEvent();
+            if(!event.equalsIgnoreCase("SELECT")){
+                return Result.fail("event 不存在或为空");
+            }
+
+            //获取分页信息
+            int page = dbParams.getPage();
+            int pageSize = dbParams.getPageSize();
+
+            String selectColumns = dbParams.getSelectColumns();//查询语句
+
+            StringBuilder whereString = new StringBuilder();
+            List<Object> whereParam = new CopyOnWriteArrayList<>();
+
+            whereString.append(selectColumns).append(" WHERE ");
+            consolidateConditional(dbParams, whereString, whereParam);
+            return jdbcExecutor.jdbcSearch(dbConfig, whereString.toString(), whereParam, page, pageSize);
+
+        } catch (Exception e) {
+            logger.error("动态查询失败", e);
+            return Result.fail("动态查询失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * sql查询,用问号作为占位符,必须严格按照顺序执行查询
+     * @param dbConfig
+     * @param params
+     * @param sql
+     * @return
+     */
+    public  Result<List<Map<String, Object>>> searchBySql(Map<String, String> dbConfig, Map<String, Object> params,String sql){
+        //从 params 参数 获取
+        List<Object> whereParam = new CopyOnWriteArrayList<>();
+        String event = params.getOrDefault("event","").toString();
+        if(!StringUtils.hasText(event)||!event.equalsIgnoreCase("SELECT")){
+            return Result.fail("event 不存在或为空");
+        }
+        Map<String,Object> dataContent = (Map<String, Object>) params.get("dataContent");
+        if (Objects.nonNull(dataContent)){
+            List<Object> object = (List<Object>) dataContent.get("conditions");
+            if (!CollectionUtils.isEmpty(object)){
+                whereParam = object;
+            }
+        }
+        return jdbcExecutor.queryForSql(dbConfig,sql, whereParam);
+    }
+
     /**
      * 统一查询入口,自动判断数据格式类型并执行查询操作
      *

+ 5 - 1
src/main/java/com/bfkj/unidia/DataBaseUtils/DbParamsService.java

@@ -123,7 +123,8 @@ public class DbParamsService {
             }
             result.setSelectColumns("SELECT " + (authColumns.isEmpty()?"*":String.join(",", authColumns)) +
                     " FROM " + tableName);
-            result.setDeleteColumnss("DELETE FROM ".concat(tableName) + " WHEERE ");
+//            result.setDeleteColumnss("DELETE FROM ".concat(tableName) + " WHERE "); // 多加了where
+            result.setDeleteColumnss("DELETE FROM ".concat(tableName) + " ");
             // 分页参数
             Optional.ofNullable(params.get("page"))
                     .filter(obj -> obj instanceof Integer)
@@ -227,6 +228,9 @@ public class DbParamsService {
             if(key != null) {//空字段不处理
                 String keyStr = (String) key;
                 Object value = dataMap.get(key);
+                if(value == null){
+                    continue;//空值不处理
+                }
                 //权限为空时,表示无权限控制,直接添加到更新字段集合中
                 if (authColumns == null || authColumns.isEmpty() || authColumns.contains(keyStr)){
                     if(modifyColumns == null || modifyColumns.isEmpty() ||!modifyColumns.contains(keyStr)) {

+ 102 - 0
src/main/java/com/bfkj/unidia/DataBaseUtils/JdbcExecutor.java

@@ -124,6 +124,108 @@ public class JdbcExecutor {
             }
         });
     }
+
+
+    public Result<List<Map<String, Object>>> queryForSql(Map<String, String> dbConfig,
+                                                        String sql,
+                                                        List<Object> params ) {
+        return queryWithDatasource(dbConfig, sql, dataSource -> {
+            try(Connection connection = dataSource.getConnection()) {
+                try(PreparedStatement ps = connection.prepareStatement(sql)){
+                    // 设置参数
+                    if (params != null && !params.isEmpty()) {
+                        for (int i = 0; i < params.size(); i++) {
+                            ps.setObject(i + 1, params.get(i)); // 参数从 1 开始
+                        }
+                    }
+                    logger.info("ps.toString():{}", ps.toString());
+                    logger.info("Executing paginated SQL: {}", sql);
+                    List<Map<String, Object>> resultList = new ArrayList<>();
+                    try (ResultSet rs = ps.executeQuery()) {
+                        ResultSetMetaData metaData = rs.getMetaData();
+                        int columnCount = metaData.getColumnCount();
+                        // 获取所有列名
+                        List<String> columnNames = new ArrayList<>();
+                        for (int i = 1; i <= columnCount; i++) {
+                            columnNames.add(metaData.getColumnLabel(i));  // 使用别名
+                        }
+                        // 遍历结果集
+                        while (rs.next()) {
+                            Map<String, Object> row = new LinkedHashMap<>();
+                            for (int i = 0; i < columnCount; i++) {
+                                String columnName = columnNames.get(i);
+                                Object value = rs.getObject(i + 1);
+                                row.put(columnName, value);
+                            }
+                            resultList.add(row);
+                        }
+                    }
+                    logger.info("Query returned {} rows", resultList.size());
+                    return Result.success(resultList);
+                }catch (SQLException e){
+                    return Result.fail("查询失败: " + e.getMessage());
+                }
+            } catch (Exception e) {
+                logger.error("查询失败:{}; SQL: {}, params: {}", e.getMessage(), sql, params);
+                return Result.fail(e.getMessage());
+            }
+        });
+    }
+
+
+    public Result<List<Map<String, Object>>> jdbcSearch(Map<String, String> dbConfig,
+                                     String sql,
+                                     List<Object> params,
+                                     int page,
+                                     int pageSize ) {
+        String paginatedSql = applyPagination(sql, dbConfig.get("url"), page, pageSize);
+        return queryWithDatasource(dbConfig, paginatedSql, dataSource -> {
+            try(Connection connection = dataSource.getConnection()) {
+                try(PreparedStatement ps = connection.prepareStatement(paginatedSql)){
+                    // 设置参数
+                    if (params != null && !params.isEmpty()) {
+                        for (int i = 0; i < params.size(); i++) {
+                            ps.setObject(i + 1, params.get(i)); // 参数从 1 开始
+                        }
+                    }
+                    logger.info("ps.toString():{}", ps.toString());
+                    logger.info("Executing paginated SQL: {}", paginatedSql);
+                    List<Map<String, Object>> resultList = new ArrayList<>();
+
+                    try (ResultSet rs = ps.executeQuery()) {
+                        ResultSetMetaData metaData = rs.getMetaData();
+                        int columnCount = metaData.getColumnCount();
+
+                        // 获取所有列名
+                        List<String> columnNames = new ArrayList<>();
+                        for (int i = 1; i <= columnCount; i++) {
+                            columnNames.add(metaData.getColumnLabel(i));  // 使用别名
+                        }
+
+                        // 遍历结果集
+                        while (rs.next()) {
+                            Map<String, Object> row = new LinkedHashMap<>();
+                            for (int i = 0; i < columnCount; i++) {
+                                String columnName = columnNames.get(i);
+                                Object value = rs.getObject(i + 1);
+                                row.put(columnName, value);
+                            }
+
+                            resultList.add(row);
+                        }
+                    }
+
+                    logger.info("Query returned {} rows", resultList.size());
+                    return Result.success(resultList);
+                }catch (SQLException e){
+                    return Result.fail("查询失败: " + e.getMessage());
+                }
+            } catch (Exception e) {
+                logger.error("查询失败:{}; SQL: {}, params: {}", e.getMessage(), paginatedSql, params);
+                return Result.fail(e.getMessage());
+            }
+        });
+    }
     /**
      * 执行SQL查询并返回结果列表
      * 此方法重载了另一个queryForList方法,为查询数据库提供了便利

+ 1 - 0
src/main/java/com/bfkj/unidia/DataUtils/DataFormatConverter.java

@@ -274,6 +274,7 @@ public class DataFormatConverter {
             try {
                 return objectMapper.readValue(input, Map.class);
             } catch (JsonProcessingException e) {
+                logger.error("input输入参数:{}",input);
                 throw new RuntimeException("JSON解析失败", e);
             }
         } else if (firstChar == '<') {

+ 21 - 0
src/main/java/com/bfkj/unidia/DataUtils/ScriptExecutor.java

@@ -149,6 +149,7 @@ public class ScriptExecutor {
         }
         return context.eval(source);
     }
+
     /**
      * 转换脚本执行结果为Java对象
      *
@@ -157,6 +158,7 @@ public class ScriptExecutor {
      *         - null(当输入为null或空值时)
      *         - HostObject(当值为宿主对象时)
      *         - Boolean/Number/String(基础类型转换)
+     *         - List(当值为数组时转换为List结构)
      *         - Map(当值包含成员时转换为Map结构)
      *         - String(其他情况返回字符串表示)
      */
@@ -170,12 +172,31 @@ public class ScriptExecutor {
         if (resultValue.isBoolean() || resultValue.isNumber() || resultValue.isString()) {
             return resultValue.as(Object.class);// 处理基础数据类型(布尔/数字/字符串)
         }
+        // 处理数组类型(包括JavaScript数组)
+        if (resultValue.hasArrayElements()) {
+            return convertJsArrayToList(resultValue);
+        }
         // 复杂对象转换为Map结构
         if (resultValue.hasMembers()) {
             return convertJsObjectToMap(resultValue);
         }
         return resultValue.toString();
     }
+    /**
+     * 将JavaScript数组转换为Java List结构
+     *
+     * @param value 来自GraalJS的Value对象,表示需要转换的JavaScript数组
+     * @return 转换后的Java List结构,包含转换后的Java对象
+     */
+    private List<Object> convertJsArrayToList(Value value) {
+        List<Object> resultList = new ArrayList<>();
+        long arraySize = value.getArraySize();
+        for (long i = 0; i < arraySize; i++) {
+            Value element = value.getArrayElement(i);
+            resultList.add(convertResult(element));
+        }
+        return resultList;
+    }
     /**
      * 构建性能指标集合,包含执行时间、脚本长度、参数数量及内存使用情况。
      *

+ 133 - 0
src/main/java/com/bfkj/unidia/OpenApi/ApiController.java

@@ -0,0 +1,133 @@
+
+package com.bfkj.unidia.OpenApi;
+
+import com.bfkj.unidia.Core.DataServices;
+import com.bfkj.unidia.Result;
+import jakarta.servlet.http.HttpServletRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.ResponseEntity;
+import org.springframework.util.StringUtils;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * api对接
+ */
+@RestController
+//@Tag(name = "数据处理", description = "统一数据处理接收入口")
+public class ApiController {
+    private static final Logger logger = LoggerFactory.getLogger(ServiceControllerApi.class);
+    private final DataServices dataServices;
+
+    public ApiController(DataServices dataServices) {
+        this.dataServices = dataServices;
+    }
+    // 匹配所有路径 (/*)
+    @RequestMapping("/*/*")
+    public Map<String, Object> handleAllRequests(HttpServletRequest request) {
+        Map<String, Object> response = new HashMap<>();
+
+        // 5. 获取请求路径(不包括域名和参数)
+        String requestPath = request.getRequestURI();
+        logger.info("请求方法**********************************************");
+        logger.info(requestPath);
+        //打印日志,显示请求的路径
+        return new HashMap<>();
+    }
+
+//    @PostMapping("/syncApi/{path}")
+    public <T> T processData(@RequestBody Map<String,Object> request, @PathVariable String path) {
+        Map<String, String> map =  new HashMap<>();
+        map.put("SchemaService","1010");
+        map.put("UserCreateService","1011");
+        map.put("UserUpdateService","1012");
+        map.put("UserDeleteService","1013");
+        map.put("RoleCreateService","1014");
+        map.put("RoleUpdateService","1015");
+        map.put("RoleDeleteService","1016");
+        map.put("OrgCreateService","1017");
+        map.put("OrgUpdateService","1018");
+        map.put("OrgDeleteService","1019");
+        logger.info("接口对接开始>>>>>"+path);
+//        Result<String> result = dataServices.getServiceInfoByPath(path);
+        if (StringUtils.hasText(path)){
+            String s = map.getOrDefault(path, "").toString();
+            request.put("service_code",  s);
+            return (T) baseProcessData(request, "processData", null);
+        }else {
+            return (T)ResponseEntity.status(500).body("{\"code\":\"404\", \"message\":\"未知请求\"}");
+        }
+    }
+    /**
+     * 处理基础请求的私有方法
+     * 该方法主要用于处理来自客户端的请求,执行数据处理,并返回处理结果
+     *
+     * @param request 包含请求数据的Map对象,由请求体转换而来
+     * @param url 请求的URL,用于日志记录和特定处理
+     * @param event 请求的事件类型,如果存在,则添加到请求数据中
+     * @return 返回一个包含处理结果的ResponseEntity对象
+     */
+    private ResponseEntity<Result<Map<String,Object>>> baseProcess(@RequestBody Map<String,Object> request,
+                                                                   String url,
+                                                                   String event) {
+        try {
+            // 检查请求是否为空,如果为空,则记录日志并返回错误响应
+            if(request == null || request.isEmpty()){
+                logger.info("dataprocess/" + url + "收到空请求");
+                return ResponseEntity.ok(Result.fail("接收空数据"));
+            }
+            // 如果事件参数不为空,则将其添加到请求数据中
+            if(event != null){
+                request.put("event",event);
+            }
+            // 调用数据处理服务处理请求,并返回处理结果
+            Result<Map<String,Object>> result = dataServices.process(request);
+            return ResponseEntity.ok(result);
+        } catch (IllegalArgumentException e) {
+            // 捕获非法参数异常,并返回错误响应
+            logger.info("dataprocess/" + url + "参数错误: ",e);
+            return ResponseEntity.badRequest().body(Result.fail("参数错误: " + e.getMessage()));
+        } catch (Exception e) {
+            // 捕获其他异常,并返回内部服务器错误响应
+            logger.info("dataprocess/" + url + "服务失败: ",e);
+            return ResponseEntity.status(500).body(Result.fail("服务失败: " + e.getMessage()));
+        }
+    }
+
+    /**
+     * 无包装类,直接返回结果
+     * @param request
+     * @param url
+     * @param event
+     * @return
+     * @param <T>
+     */
+    private <T> T baseProcessData(Map<String,Object> request, String url, String event ){
+        try {
+            // 检查请求是否为空,如果为空,则记录日志并返回错误响应
+            if(request == null || request.isEmpty()){
+                logger.info("dataprocess/" + url + "收到空请求");
+                return (T) "";
+            }
+            // 如果事件参数不为空,则将其添加到请求数据中
+            if(event != null){
+                request.put("event",event);
+            }
+            // 调用数据处理服务处理请求,并返回处理结果
+            return (T) ResponseEntity.ok(dataServices.process(request).getData());
+        } catch (IllegalArgumentException e) {
+            // 捕获非法参数异常,并返回错误响应
+            logger.info("dataprocess/" + url + "参数错误: ",e);
+            return (T) ResponseEntity.status(500).body("服务器出错");
+        } catch (Exception e) {
+            // 捕获其他异常,并返回内部服务器错误响应
+            logger.info("dataprocess/" + url + "服务失败: ",e);
+            return (T) ResponseEntity.status(500).body("服务器出错");
+        }
+    }
+
+}
+

+ 44 - 4
src/main/java/com/bfkj/unidia/OpenApi/DataProcessApi.java

@@ -7,10 +7,8 @@ import com.bfkj.unidia.Core.DataServices;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.util.StringUtils;
+import org.springframework.web.bind.annotation.*;
 
 import java.util.Map;
 
@@ -31,6 +29,16 @@ public class DataProcessApi {
     public ResponseEntity<Result<Map<String,Object>>> process(@RequestBody Map<String,Object> request) {
         return baseProcess(request, "process", null);
     }
+    @PostMapping("/processData/{path}")
+    public <T> T processData(@RequestBody Map<String,Object> request, @PathVariable String path) {
+        Result<String> result = dataServices.getServiceInfoByPath(path);
+        if (StringUtils.hasText(result.getData())){
+            request.put("service_code", result.getData());
+            return (T) baseProcessData(request, "processData", null);
+        }else {
+            return (T)ResponseEntity.status(500).body("{\"code\":\"404\", \"message\":\"未知请求\"}");
+        }
+    }
     @PostMapping("/new")
     public ResponseEntity<Result<Map<String,Object>>> newData(@RequestBody Map<String,Object> request) {
         return baseProcess(request, "new", "INSERT");
@@ -83,5 +91,37 @@ public class DataProcessApi {
         }
     }
 
+    /**
+     * 无包装类,直接返回结果
+     * @param request
+     * @param url
+     * @param event
+     * @return
+     * @param <T>
+     */
+    private <T> T baseProcessData(Map<String,Object> request, String url, String event ){
+        try {
+            // 检查请求是否为空,如果为空,则记录日志并返回错误响应
+            if(request == null || request.isEmpty()){
+                logger.info("dataprocess/" + url + "收到空请求");
+                return (T) "";
+            }
+            // 如果事件参数不为空,则将其添加到请求数据中
+            if(event != null){
+                request.put("event",event);
+            }
+            // 调用数据处理服务处理请求,并返回处理结果
+            return (T) ResponseEntity.ok(dataServices.process(request).getData());
+        } catch (IllegalArgumentException e) {
+            // 捕获非法参数异常,并返回错误响应
+            logger.info("dataprocess/" + url + "参数错误: ",e);
+            return (T) ResponseEntity.status(500).body("服务器出错");
+        } catch (Exception e) {
+            // 捕获其他异常,并返回内部服务器错误响应
+            logger.info("dataprocess/" + url + "服务失败: ",e);
+            return (T) ResponseEntity.status(500).body("服务器出错");
+        }
+    }
+
 }
 

+ 1 - 0
src/main/java/com/bfkj/unidia/SystemEnvInitializer.java

@@ -203,6 +203,7 @@ public class SystemEnvInitializer implements ApplicationListener<ApplicationRead
         String containerCode = ipAddress + ":" + port;
         // 更新环境缓存中的容器编码
         envCache.put("container_code", containerCode);
+        envCache.put("CACHE_container_code", containerCode);
         logger.info("应用IP地址已缓存: {}", ipAddress);
         return containerCode;
     }

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 41 - 0
src/test/java/com/bfkj/unidia/UnidiaApplicationTests.java


Kaikkia tiedostoja ei voida näyttää, sillä liian monta tiedostoa muuttui tässä diffissä