Просмотр исходного кода

fix(eds): 修复 BCP 索引字段错位并补真实包入库测试

- DataInfo 对索引字段名 trim,兼容 ' FILE_SIZE' 这类带空格字段

- DataProcess 保留未匹配字段的 null 占位,避免后续列整体错位

- 修复 WA_MFORENSICS_* 到 eds_mforensics_* 表名归一化

- 修复 Z7 路径/OS 选择,恢复真实 7-Zip 解压

- 修复 file_info.pid NOT NULL、聊天正文误当文件路径

- 新增 DemoBcpImportTest:真实解压 + Appender 主表 + MyBatis 辅助表入库校验
cc 3 недель назад
Родитель
Сommit
9a433b8a76

+ 2 - 2
ai-server/src/main/java/com/zsjz/ai/common/constants/PathConst.java

@@ -136,8 +136,8 @@ public class PathConst {
      * 专案 视频活音频的资源目录
      */
     public static final String EDS_VD = EDS_PATH + File.separator + "vd";
-    public static final String Z7_L = ROOT_PATH + "/7Zip/7zz";
-    public static final String Z7_W = ROOT_PATH + "/7Zip/7z.exe";
+    public static final String Z7_L = RUN_QINGJIAN_PATH + "/7Zip/7zz";
+    public static final String Z7_W = RUN_QINGJIAN_PATH + "/7Zip/7z.exe";
 
 
     /**

+ 2 - 1
ai-server/src/main/java/com/zsjz/ai/common/utils/Z7.java

@@ -86,6 +86,7 @@ public class Z7 {
     }
 
     private static String z7Path() {
-        return true ? PathConst.Z7_L : PathConst.Z7_W;
+        String osName = System.getProperty("os.name", "").toLowerCase();
+        return osName.contains("win") ? PathConst.Z7_W : PathConst.Z7_L;
     }
 }

+ 20 - 0
ai-server/src/main/java/com/zsjz/ai/module/eds/utils/Eds.java

@@ -259,6 +259,26 @@ public class Eds {
         return REMOVE_INVALID_CHAR_REG.matcher(ctId).replaceAll(StrUtil.EMPTY);
     }
 
+    /**
+     * 归一化 BCP 索引中的表名。
+     *
+     * <p>GAB 包索引使用 {@code WA_MFORENSICS_*},当前实体/DuckDB 表使用
+     * {@code eds_mforensics_*},入库前统一转换。</p>
+     *
+     * @param tableName 原始表名
+     * @return 归一化后的表名
+     */
+    public static String normalizeTableName(String tableName) {
+        if (tableName == null) {
+            return null;
+        }
+        String normalized = tableName.trim().toLowerCase();
+        if (normalized.startsWith("wa_mforensics_")) {
+            return "eds_mforensics_" + normalized.substring("wa_mforensics_".length());
+        }
+        return normalized;
+    }
+
 
     /**
      * 解压数据压缩包。

+ 32 - 2
ai-server/src/main/java/com/zsjz/ai/module/eds/xml/BcpMediaUploader.java

@@ -17,6 +17,7 @@ import lombok.extern.slf4j.Slf4j;
 
 import java.io.File;
 import java.lang.reflect.Field;
+import java.nio.file.InvalidPathException;
 import java.nio.file.Path;
 import java.time.LocalDateTime;
 import java.util.ArrayList;
@@ -139,12 +140,21 @@ final class BcpMediaUploader {
                 if (StrUtil.isEmpty(filePathStr)) {
                     return null;
                 }
+                //聊天/社交内容字段可能保存的是正文(含 http: 等),不是文件路径
+                if (!isPotentialMediaPath(filePathStr)) {
+                    return null;
+                }
                 String newFilePathStr = StrUtil.replace(filePathStr, "\\", "//");
                 List<String> listPath = StrUtil.split(newFilePathStr, "//");
 
                 Path filePath = bcpDir;
-                for (String s : listPath) {
-                    filePath = filePath.resolve(s);
+                try {
+                    for (String s : listPath) {
+                        filePath = filePath.resolve(s);
+                    }
+                } catch (InvalidPathException e) {
+                    log.debug("跳过非文件路径内容: table={}", tableName);
+                    return null;
                 }
                 File file = filePath.toFile();
                 //确认文件存在
@@ -186,4 +196,24 @@ final class BcpMediaUploader {
         }
         return null;
     }
+
+    /**
+     * 判断字段值是否可能是 BCP 包内的相对文件路径。
+     *
+     * <p>聊天/社交内容字段也可能是正文,正文中常含 {@code http:}、问号、书名号等,
+     * 直接 Path.resolve 会抛 InvalidPathException。这里先做轻量过滤。</p>
+     */
+    private static boolean isPotentialMediaPath(String value) {
+        if (StrUtil.isBlank(value) || value.length() > 1024) {
+            return false;
+        }
+        //Windows 文件名非法字符与 URL 协议分隔符
+        for (char c : new char[]{':', '*', '?', '"', '<', '>', '|', '\n', '\r'}) {
+            if (value.indexOf(c) >= 0) {
+                return false;
+            }
+        }
+        //绝对路径/UNC 不允许作为包内相对路径
+        return !value.startsWith("/") && !value.startsWith("\\");
+    }
 }

+ 1 - 1
ai-server/src/main/java/com/zsjz/ai/module/eds/xml/DataInfo.java

@@ -200,7 +200,7 @@ public class DataInfo {
             return new String[0];
         }
         return bcpFieldList.stream()
-                .map(item -> StrUtil.blankToDefault(item.getEng(), "").toLowerCase())
+                .map(item -> StrUtil.blankToDefault(StrUtil.trim(item.getEng()), "").toLowerCase())
                 .toArray(String[]::new);
     }
 

+ 0 - 1
ai-server/src/main/java/com/zsjz/ai/module/eds/xml/DataProcess.java

@@ -143,7 +143,6 @@ public class DataProcess implements AutoCloseable {
         this.startingLine = dataInfo.getStartingLine();
         this.charset = dataInfo.getCharset();
         this.bcpFiledArr = Arrays.stream(dataInfo.getBcpFieldNameArr())
-                .filter(bcpFieldName -> ObjUtil.isNotNull(fieldMap.get(bcpFieldName)))
                 .map(fieldMap::get).toArray(Field[]::new);
         this.createTime = LocalDateTime.now();
 

+ 3 - 2
ai-server/src/main/java/com/zsjz/ai/module/eds/xml/EdsExtra.java

@@ -223,8 +223,8 @@ public class EdsExtra {
      * @param dataCountInfo 数据统计
      */
     public void exec(DataInfo dataInfo, Message message, DataCountInfo dataCountInfo) {
-        //确定表名与实体信息
-        String tableName = dataInfo.getValByIk(Eds.TABLE_NAME_IK).toLowerCase();
+        //确定表名与实体信息(BCP 索引的 WA_MFORENSICS_* 归一化为 eds_mforensics_*)
+        String tableName = Eds.normalizeTableName(dataInfo.getValByIk(Eds.TABLE_NAME_IK));
         Class<?> cls = EdsEntityEnum.findClsByTableName(tableName);
         //校验表是否有对应实体
         if (cls == null) {
@@ -288,6 +288,7 @@ public class EdsExtra {
         stringRedisTemplate.delete(List.of(dataCntKey, dataSetKey));
 
         FileInfo fileInfo = new FileInfo();
+        fileInfo.setPid(0L);
         fileInfo.setFileName(dto.getFileName());
         fileInfo.setFileType(FILE_TYPE_DATA_PACKAGE);
         fileInfo.setFilePath(dto.getPath().toString());

+ 5 - 5
ai-server/src/main/java/com/zsjz/ai/module/eds/xml/Message.java

@@ -84,10 +84,10 @@ public class Message {
         if (indexAnno == null) {
             return null;
         }
-        String tableName = indexAnno.value();
+        String tableName = Eds.normalizeTableName(indexAnno.value());
         for (DataInfo dataInfo : getDataInfoList()) {
-            String bcpTableName = dataInfo.getValByIk(Eds.TABLE_NAME_IK);
-            if (StrUtil.equalsIgnoreCase(tableName, bcpTableName)) {
+            String bcpTableName = Eds.normalizeTableName(dataInfo.getValByIk(Eds.TABLE_NAME_IK));
+            if (StrUtil.equals(tableName, bcpTableName)) {
                 return dataInfo;
             }
         }
@@ -112,8 +112,8 @@ public class Message {
      * 按映射信息反查实体类
      */
     public Class<?> getClsByDataInfo(DataInfo dataInfo) {
-        String tableName = dataInfo.getValByIk(Eds.TABLE_NAME_IK);
-        return tableName == null ? null : EdsEntityEnum.findClsByTableName(tableName.toLowerCase());
+        String tableName = Eds.normalizeTableName(dataInfo.getValByIk(Eds.TABLE_NAME_IK));
+        return tableName == null ? null : EdsEntityEnum.findClsByTableName(tableName);
     }
 
 

+ 23 - 4
ai-server/src/test/java/com/zsjz/ai/module/eds/xml/BcpRowMapperTest.java

@@ -27,11 +27,12 @@ class BcpRowMapperTest {
         DataProcess process = new DataProcess(buildDataInfo(), TestRow.class, null);
 
         DataProcess.Result result = process.getResult(
-                List.of("abcdef\t42\t2026-01-02 03:04:05"));
+                List.of("abcdef\t64\t42\t2026-01-02 03:04:05"));
 
         assertNotNull(result);
         TestRow row = (TestRow) result.getDataList().getFirst();
         assertEquals("abc", row.getName());
+        assertEquals("64", row.getFileSize());
         assertEquals(42, row.getCountValue());
         assertEquals(LocalDateTime.of(2026, 1, 2, 3, 4, 5), row.getEventTime());
         assertEquals(Eds.TIME_DEFAULT_VALUE, row.getMailSendTime());
@@ -44,17 +45,32 @@ class BcpRowMapperTest {
         DataProcess process = DataProcess.forImport(buildDataInfo(), TestRow.class, null,
                 "CTID", null, "test_bcp", null, null, null, null);
 
-        DataProcess.Result result = process.getResult(List.of("x\t1\t"));
+        DataProcess.Result result = process.getResult(List.of("x\t64\t1"));
 
         TestRow row = (TestRow) result.getDataList().getFirst();
         assertEquals("CTID", row.getCollectTargetId());
         assertEquals(Eds.TIME_DEFAULT_VALUE, row.getMailSendTime());
     }
 
+    @Test
+    void unknownIndexFieldKeepsColumnAlignment() {
+        DataInfo dataInfo = buildDataInfo(List.of("name", " unknown_field", "count_value"));
+        DataProcess process = new DataProcess(dataInfo, TestRow.class, null);
+
+        DataProcess.Result result = process.getResult(List.of("abc\tIGNORED\t42"));
+
+        TestRow row = (TestRow) result.getDataList().getFirst();
+        assertEquals("abc", row.getName());
+        assertEquals(42, row.getCountValue());
+    }
+
     private DataInfo buildDataInfo() {
+        return buildDataInfo(List.of("name", " file_size", "count_value", "event_time", "mail_send_time"));
+    }
+
+    private DataInfo buildDataInfo(List<String> fieldNames) {
         DataInfo fieldData = new DataInfo();
-        fieldData.setItemList(List.of(
-                field("name"), field("count_value"), field("event_time"), field("mail_send_time")));
+        fieldData.setItemList(fieldNames.stream().map(BcpRowMapperTest::field).toList());
         Dataset fieldDataset = new Dataset();
         fieldDataset.setName(Eds.BCP_FIELD_DN);
         fieldDataset.setDataInfoList(List.of(fieldData));
@@ -89,6 +105,9 @@ class BcpRowMapperTest {
         @EdsFields(len = 3)
         private String name;
 
+        @TableField("file_size")
+        private String fileSize;
+
         @TableField("count_value")
         private Integer countValue;
 

+ 261 - 0
ai-server/src/test/java/com/zsjz/ai/module/eds/xml/DemoBcpImportTest.java

@@ -0,0 +1,261 @@
+package com.zsjz.ai.module.eds.xml;
+
+import cn.hutool.extra.spring.SpringUtil;
+import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
+import com.baomidou.mybatisplus.core.config.GlobalConfig;
+import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
+import com.thoughtworks.xstream.XStream;
+import com.thoughtworks.xstream.security.WildcardTypePermission;
+import com.zsjz.ai.common.config.DuckdbUnpooledDataSource;
+import com.zsjz.ai.module.dm.mapper.FileInfoMapper;
+import com.zsjz.ai.module.eds.duckdb.EdsImportActivityProbe;
+import com.zsjz.ai.module.eds.mapper.EdsImportMaterialMapper;
+import com.zsjz.ai.module.eds.mapper.EdsMediaFileMapper;
+import com.zsjz.ai.module.eds.mapper.EdsTreeCountMapper;
+import com.zsjz.ai.module.eds.utils.Eds;
+import org.apache.ibatis.mapping.Environment;
+import org.apache.ibatis.session.SqlSession;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.context.support.GenericApplicationContext;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyCollection;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 真实 BCP 演示包入库测试(需要显式指定包路径)。
+ *
+ * <p>走真实 {@link EdsExtra#extraZipData}:真实 7-Zip 解压、真实 BCP 解析、
+ * 真实 DuckDB Appender 写主表、真实 MyBatis 写 file_info/eds_tree_count/eds_media_file。
+ * 只有 Redis 和动态数据源路由用 mock 隔离。</p>
+ *
+ * <pre>
+ * mvn -pl ai-server -Dtest=DemoBcpImportTest \
+ *     -Deds.demo.zip="C:/Users/cc/Desktop/test/演示bcp包/李如云演示数据.zip" test
+ * </pre>
+ *
+ * @author zsjz
+ */
+@EnabledIfSystemProperty(named = "eds.demo.zip", matches = ".+")
+class DemoBcpImportTest {
+
+    @TempDir
+    Path tempDir;
+
+    @Test
+    @SuppressWarnings("unchecked")
+    void importsDemoPackageIntoCaseDuckDb() throws Exception {
+        Path zipSource = Path.of(System.getProperty("eds.demo.zip"));
+        assertTrue(Files.isRegularFile(zipSource), "演示包不存在: " + zipSource);
+
+        Path workDir = tempDir.resolve("work");
+        Files.createDirectories(workDir);
+        String zipName = zipSource.getFileName().toString();
+        Path zipCopy = workDir.resolve(zipName);
+        Files.copy(zipSource, zipCopy, StandardCopyOption.REPLACE_EXISTING);
+
+        Path caseDbSource = findRepoFile("QingJian/workspace/9/ylzkBGZJ9");
+        Path caseDb = tempDir.resolve("case.duckdb");
+        Files.copy(caseDbSource, caseDb, StandardCopyOption.REPLACE_EXISTING);
+        String jdbcUrl = "jdbc:duckdb:" + caseDb;
+
+        DuckdbUnpooledDataSource caseDataSource = new DuckdbUnpooledDataSource(jdbcUrl, "org.duckdb.DuckDBDriver");
+        DynamicRoutingDataSource routingDataSource = mock(DynamicRoutingDataSource.class);
+        when(routingDataSource.getDataSource("slave")).thenReturn(caseDataSource);
+
+        StringRedisTemplate redisTemplate = mock(StringRedisTemplate.class);
+        ValueOperations<String, String> valueOperations = mock(ValueOperations.class);
+        when(redisTemplate.opsForValue()).thenReturn(valueOperations);
+        AtomicLong remaining = new AtomicLong();
+        doAnswer(invocation -> {
+            remaining.set(Long.parseLong(invocation.getArgument(1)));
+            return null;
+        }).when(valueOperations).set(anyString(), anyString());
+        when(valueOperations.decrement(anyString())).thenAnswer(invocation -> remaining.decrementAndGet());
+        when(valueOperations.increment(anyString(), anyLong())).thenReturn(1L);
+        when(redisTemplate.delete(anyCollection())).thenReturn(1L);
+
+        MybatisConfiguration configuration = new MybatisConfiguration(
+                new Environment("demo-case", new JdbcTransactionFactory(), caseDataSource));
+        GlobalConfigUtils.setGlobalConfig(configuration, GlobalConfigUtils.defaults());
+        configuration.addMapper(EdsImportMaterialMapper.class);
+        configuration.addMapper(FileInfoMapper.class);
+        configuration.addMapper(EdsTreeCountMapper.class);
+        configuration.addMapper(EdsMediaFileMapper.class);
+        SqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(configuration);
+
+        XStream xStream = new XStream();
+        xStream.processAnnotations(Message.class);
+        xStream.addPermission(new WildcardTypePermission(new String[]{"com.zsjz.ai.module.eds.**"}));
+
+        ExtraFileDTO dto = new ExtraFileDTO(zipName, null, zipCopy, "test", 999L);
+
+        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
+            EdsImportMaterialMapper importMapper = sqlSession.getMapper(EdsImportMaterialMapper.class);
+            FileInfoMapper fileInfoMapper = sqlSession.getMapper(FileInfoMapper.class);
+            EdsTreeCountMapper treeCountMapper = sqlSession.getMapper(EdsTreeCountMapper.class);
+            EdsMediaFileMapper mediaFileMapper = sqlSession.getMapper(EdsMediaFileMapper.class);
+
+            GenericApplicationContext springContext = new GenericApplicationContext();
+            springContext.getBeanFactory().registerSingleton("edsMediaFileMapper", mediaFileMapper);
+            springContext.refresh();
+            new SpringUtil().setApplicationContext(springContext);
+
+            EdsExtra edsExtra = new EdsExtra(xStream, redisTemplate, importMapper, fileInfoMapper,
+                    treeCountMapper, routingDataSource, new EdsImportActivityProbe());
+            try {
+                // 真实入口:真实 7-Zip 解压 -> 索引解析 -> BCP 解析 -> Appender/MyBatis 入库
+                edsExtra.extraZipData(dto);
+            } finally {
+                springContext.close();
+            }
+        } finally {
+            caseDataSource.close();
+        }
+
+        assertNotNull(dto.getCti(), "采集编号为空,说明基础信息没有解析成功");
+        assertEquals("李如云", dto.getUserName());
+
+        List<String> nonEmptyTables = new ArrayList<>();
+        long totalRows = 0;
+        try (Connection connection = DriverManager.getConnection(jdbcUrl)) {
+            assertEquals(1L, count(connection, "select count(*) from eds_mforensics_010100"));
+            assertEquals(dto.getCti(), queryString(connection,
+                    "select collect_target_id from eds_mforensics_010100 limit 1"));
+            assertEquals(1L, count(connection, "select count(*) from eds_mforensics_020100"));
+            assertTrue(count(connection, "select count(*) from eds_mforensics_020500") > 0);
+            assertEquals(1L, countByFileName(connection, zipName));
+            assertEquals(0L, fileInfoPid(connection, zipName));
+            assertTrue(countByCid(connection, "eds_tree_count", dto.getCti()) > 0);
+            assertTrue(countByCid(connection, "eds_media_file", dto.getCti()) > 0);
+
+            // 校验 160100 的字段错位修复:索引里是 " FILE_SIZE"(带前导空格)
+            try (Statement st = connection.createStatement();
+                 ResultSet rs = st.executeQuery("""
+                         select file_size, brand, model, material_status
+                           from eds_mforensics_160100 limit 1
+                         """)) {
+                assertTrue(rs.next());
+                assertEquals("64", rs.getString("file_size"));
+                assertEquals("vivo", rs.getString("brand"));
+                assertEquals("Xplay6", rs.getString("model"));
+                assertNull(rs.getObject("material_status"));
+            }
+
+            List<String> tables = new ArrayList<>();
+            try (Statement st = connection.createStatement();
+                 ResultSet rs = st.executeQuery("""
+                         select table_name from information_schema.tables
+                          where table_schema = 'main' and table_name like 'eds_mforensics%'
+                          order by table_name
+                         """)) {
+                while (rs.next()) {
+                    tables.add(rs.getString(1));
+                }
+            }
+            for (String table : tables) {
+                long rows = count(connection, "select count(*) from " + table);
+                if (rows > 0) {
+                    nonEmptyTables.add(table + "=" + rows);
+                    totalRows += rows;
+                }
+            }
+            System.out.println("采集编号: " + dto.getCti());
+            System.out.println("有数据的表: " + nonEmptyTables);
+            System.out.println("主表总行数: " + totalRows);
+            System.out.println("file_info 行数: " + countByFileName(connection, zipName));
+            System.out.println("eds_tree_count 行数: " + countByCid(connection, "eds_tree_count", dto.getCti()));
+            System.out.println("eds_media_file 行数: " + countByCid(connection, "eds_media_file", dto.getCti()));
+        }
+        assertTrue(totalRows > 0, "没有任何主表数据入库");
+        verify(redisTemplate, atLeastOnce()).delete(anyCollection());
+    }
+
+    private static long count(Connection connection, String sql) throws Exception {
+        try (Statement st = connection.createStatement();
+             ResultSet rs = st.executeQuery(sql)) {
+            rs.next();
+            return rs.getLong(1);
+        }
+    }
+
+    private static long countByFileName(Connection connection, String fileName) throws Exception {
+        try (PreparedStatement ps = connection.prepareStatement(
+                "select count(*) from file_info where fileName = ?")) {
+            ps.setString(1, fileName);
+            try (ResultSet rs = ps.executeQuery()) {
+                rs.next();
+                return rs.getLong(1);
+            }
+        }
+    }
+
+    private static long fileInfoPid(Connection connection, String fileName) throws Exception {
+        try (PreparedStatement ps = connection.prepareStatement(
+                "select pid from file_info where fileName = ? limit 1")) {
+            ps.setString(1, fileName);
+            try (ResultSet rs = ps.executeQuery()) {
+                return rs.next() ? rs.getLong(1) : -1L;
+            }
+        }
+    }
+
+    private static long countByCid(Connection connection, String table, String cid) throws Exception {
+        try (PreparedStatement ps = connection.prepareStatement(
+                "select count(*) from " + table + " where collect_target_id = ?")) {
+            ps.setString(1, cid);
+            try (ResultSet rs = ps.executeQuery()) {
+                rs.next();
+                return rs.getLong(1);
+            }
+        }
+    }
+
+    private static String queryString(Connection connection, String sql) throws Exception {
+        try (Statement st = connection.createStatement();
+             ResultSet rs = st.executeQuery(sql)) {
+            return rs.next() ? rs.getString(1) : null;
+        }
+    }
+
+    private static Path findRepoFile(String relative) {
+        Path current = Path.of(System.getProperty("user.dir")).toAbsolutePath();
+        while (current != null) {
+            Path candidate = current.resolve(relative);
+            if (Files.isRegularFile(candidate)) {
+                return candidate;
+            }
+            current = current.getParent();
+        }
+        throw new IllegalStateException("找不到文件: " + relative);
+    }
+}