diff --git a/.gitignore b/.gitignore index 15cc7a6c..4c12dd82 100644 --- a/.gitignore +++ b/.gitignore @@ -48,3 +48,7 @@ rebel.xml /.fastRequest/collections/Root/Default Group/directory.json /.fastRequest/collections/Root/directory.json /.fastRequest/config/fastRequestCurrentProjectConfig.json + +# 个人工作文档,不与团队共享 +CLAUDE.md +docs/ diff --git a/detection/src/main/java/com/njcn/gather/report/pojo/enums/BookmarkEnum.java b/detection/src/main/java/com/njcn/gather/report/pojo/enums/BookmarkEnum.java index 3c41b291..3ebb6da0 100644 --- a/detection/src/main/java/com/njcn/gather/report/pojo/enums/BookmarkEnum.java +++ b/detection/src/main/java/com/njcn/gather/report/pojo/enums/BookmarkEnum.java @@ -30,6 +30,7 @@ public enum BookmarkEnum { private String desc; + /** 书签处理顺序:1=数据项,2=结果信息,3=目录信息;由 dealDataModelScatteredByBookmark 排序时使用 */ private Integer sort; BookmarkEnum(String key, String desc, Integer sort) { diff --git a/detection/src/main/java/com/njcn/gather/report/service/impl/PqReportServiceImpl.java b/detection/src/main/java/com/njcn/gather/report/service/impl/PqReportServiceImpl.java index acb83abb..89bac02a 100644 --- a/detection/src/main/java/com/njcn/gather/report/service/impl/PqReportServiceImpl.java +++ b/detection/src/main/java/com/njcn/gather/report/service/impl/PqReportServiceImpl.java @@ -76,6 +76,7 @@ import com.njcn.gather.tools.report.service.IWordReportService; import com.njcn.gather.tools.report.util.BookmarkUtil; import com.njcn.gather.tools.report.util.Docx4jUtil; import com.njcn.gather.tools.report.util.DocxMergeUtil; +import com.njcn.gather.tools.report.util.FilePathSanitizer; import com.njcn.gather.tools.report.util.WordDocumentUtil; import com.njcn.gather.type.pojo.po.DevType; import com.njcn.gather.type.service.IDevTypeService; @@ -133,6 +134,17 @@ import java.util.stream.Collectors; @RequiredArgsConstructor public class PqReportServiceImpl extends ServiceImpl implements IPqReportService { + /** + * resultMap 内部协议:当 dealDataLine 跑完一轮但未采集到任何有效合格性数据时, + * 在 resultMap 中塞入这个 key 作为"已尝试且无数据"的哨兵,避免后续 TEST_RESULT_* + * 分支的 fallback 重复调用 dealDataLine 浪费资源;同时 dealTestResultLine 检测到 + * 此 key 存在时跳过结论表生成。 + *

+ * 故意使用明显非业务字符串,避免与任何 PqScriptDtls.scriptCode / PowerIndexEnum + * 的真实业务取值撞车。 + */ + private static final String RESULT_MAP_NO_DATA_FLAG = "__internal_no_data__"; + @Value("${report.template:D:\\template}") private String templatePath; @@ -583,6 +595,11 @@ public class PqReportServiceImpl extends ServiceImpl i /** * 根据设备类型生成报告 * 注:该方法目前仅支持楼下出厂检测场景,属于模板占位符替换方式,后期可能会有调整 + *

+ * 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException + * 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给 + * 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义, + * 而非待修复缺陷。 * * @param devReportParam 被检设备信息 */ @@ -783,6 +800,11 @@ public class PqReportServiceImpl extends ServiceImpl i /** * 需要支持批量生成,如果用户选择批量生成,则默认都采用测试数据的第一个合格,如果 * 比对模式下生成检测报告,实际后期需要根据用户选择的检测数据或者某次波形数据生成报告 + *

+ * 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException + * 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给 + * 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义, + * 而非待修复缺陷。 * * @param plan 计划信息 * @param devReportParam 设备信息 @@ -821,7 +843,7 @@ public class PqReportServiceImpl extends ServiceImpl i MainDocumentPart detailDocumentPart = detailModelDocument.getMainDocumentPart(); dealDataModelScatteredByBookmarkByPlanContrast(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO); // 保存新的文档 - String dirPath = reportPath.concat(File.separator).concat(plan.getName()); + String dirPath = reportPath.concat(File.separator).concat(FilePathSanitizer.toSafeFileName(plan.getName())); // 确保目录存在 ensureDirectoryExists(dirPath); // 构建文件名:cityName_gdName_subName_name.docx @@ -861,6 +883,11 @@ public class PqReportServiceImpl extends ServiceImpl i /** * 根据计划绑定的报告模板生成报告 * 注:该方法目前属于同用信息占位符替换,数据页为面向对象动态填充拼凑方式 + *

+ * 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException + * 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给 + * 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义, + * 而非待修复缺陷。 * * @param plan 计划信息 * @param devReportParam 设备信息 @@ -899,7 +926,7 @@ public class PqReportServiceImpl extends ServiceImpl i dealDataModelScatteredByBookmark(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO); // 保存新的文档 - String dirPath = reportPath.concat(File.separator).concat(devType.getName()); + String dirPath = reportPath.concat(File.separator).concat(FilePathSanitizer.toSafeFileName(devType.getName())); // 确保目录存在 ensureDirectoryExists(dirPath); baseModelDocument.save(new File(dirPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX))); @@ -950,9 +977,9 @@ public class PqReportServiceImpl extends ServiceImpl i * 1、数据项 * 2、结果信息 * 3、目录信息 - * 所以要先先获取的书签进行操作排序 + * 按 BookmarkEnum.sort 字段排序,避免依赖枚举常量声明顺序 * */ - Collections.sort(bookmarkEnums); + bookmarkEnums.sort(Comparator.comparingInt(BookmarkEnum::getSort).thenComparingInt(Enum::ordinal)); List todoInsertList; BookmarkUtil.BookmarkInfo bookmarkInfo; Map> resultMap = null; @@ -1230,9 +1257,9 @@ public class PqReportServiceImpl extends ServiceImpl i * 1、数据项 * 2、结果信息 * 3、目录信息 - * 所以要先先获取的书签进行操作排序 + * 按 BookmarkEnum.sort 字段排序,避免依赖枚举常量声明顺序 * */ - Collections.sort(bookmarkEnums); + bookmarkEnums.sort(Comparator.comparingInt(BookmarkEnum::getSort).thenComparingInt(Enum::ordinal)); // 定义个结果,以便存在结果信息的书签 Map> resultMap = new HashMap<>(); List todoInsertList; @@ -1281,7 +1308,7 @@ public class PqReportServiceImpl extends ServiceImpl i if (CollUtil.isEmpty(resultMap)) { dealDataLine(baseDocumentPart, devReportParam, pqDevVO, resultMap); } - bookmarkInfo = BookmarkUtil.getBookmarkInfo(BookmarkEnum.TEST_RESULT_LINE.getKey(), bookmarks); + bookmarkInfo = BookmarkUtil.getBookmarkInfo(BookmarkEnum.TEST_RESULT_DETAIL.getKey(), bookmarks); todoInsertList = dealTestResultLine(devReportParam, resultMap, DocAnchorEnum.TEST_RESULT_DETAIL); if (Objects.nonNull(bookmarkInfo) && CollectionUtil.isNotEmpty(todoInsertList)) { BookmarkUtil.insertElement(bookmarkInfo, todoInsertList); @@ -1306,8 +1333,8 @@ public class PqReportServiceImpl extends ServiceImpl i */ private List dealTestResultLine(DevReportParam devReportParam, Map> resultMap, DocAnchorEnum docAnchorEnum) { List todoInsertList = new ArrayList<>(); - // 先判断数据有没有,如果没有,则不处理 - if (CollUtil.isEmpty(resultMap.get(PowerIndexEnum.UNKNOWN.getKey()))) { + // 先判断数据有没有,如果没有,则不处理(哨兵协议详见 RESULT_MAP_NO_DATA_FLAG 注释) + if (!resultMap.containsKey(RESULT_MAP_NO_DATA_FLAG)) { ObjectFactory factory = Context.getWmlObjectFactory(); // 源文档的内容 // 创建表格(示例为3列,列数可任意调整) @@ -1396,13 +1423,27 @@ public class PqReportServiceImpl extends ServiceImpl i /** - * 处理以回路为维度的数据项,书签占位符的方式 + * 以回路维度处理数据项,并填充 resultMap(指标合格性结论)。 + *

+ * 本方法承担双重职责: + *

    + *
  1. 返回值:根据 modelPart 中的 H5 分组表格模板,灌入实测数据后生成可插入文档的元素列表;
  2. + *
  3. 副作用:把每个指标在各回路上的合格性写入 resultMap,供后续 dealTestResultLine 构造结论表使用。
  4. + *
+ * 调用约定(务必区分以下两条路径,避免误解形参用途): + *
    + *
  • 常规路径(DATA_LINE 分支):modelPart 传 detail 文档(数据页模板池),返回值会被插入 DATA_LINE 书签锚点。
  • + *
  • fallback 路径(TEST_RESULT_* 分支且 resultMap 为空时):modelPart 允许传 base 文档(封面页);此时模板池为空,返回值无业务意义,调用方应丢弃,仅借此触发 resultMap 计算。
  • + *
+ * 因此 modelPart 命名保持中性,不要改回 detailXxx 等带语义偏向的名字。 * - * @param detailModelDocument 数据项模板 - * @param devReportParam 测试报告参数 - * @param pqDevVO 被检设备 + * @param modelPart 文档模板部分;常规传 detail 文档,fallback 仅需算 resultMap 时可传 base 文档 + * @param devReportParam 测试报告参数 + * @param pqDevVO 被检设备 + * @param resultMap 结果性数据集合(被本方法写入;fallback 路径正是借此计算) + * @return 待插入文档的元素列表;fallback 路径下应被调用方丢弃 */ - private List dealDataLine(MainDocumentPart detailModelDocument, DevReportParam devReportParam, PqDevVO pqDevVO, Map> resultMap) { + private List dealDataLine(MainDocumentPart modelPart, DevReportParam devReportParam, PqDevVO pqDevVO, Map> resultMap) { List todoInsertList = new ArrayList<>(); // 以回路维度处理数据项 Integer devChns = pqDevVO.getDevChns(); @@ -1410,8 +1451,8 @@ public class PqReportServiceImpl extends ServiceImpl i // 读取该计划的检测大项组装数据内容 List pqScriptDtlsList = pqScriptDtlsService.getScriptDtlsDataList(devReportParam.getScriptId()); Map> scriptMap = pqScriptDtlsList.stream().collect(Collectors.groupingBy(PqScriptDtlDataVO::getScriptCode, LinkedHashMap::new, Collectors.toList())); - List allContent = detailModelDocument.getContent(); - List headingContents = Docx4jUtil.extractHeading5Contents(allContent, detailModelDocument); + List allContent = modelPart.getContent(); + List headingContents = Docx4jUtil.extractHeading5Contents(allContent, modelPart); Map> contentMap = headingContents.stream().collect(Collectors.groupingBy(Docx4jUtil.HeadingContent::getHeadingText, Collectors.toList())); for (int i = 0; i < devChns; i++) { // 回路标题 @@ -1479,9 +1520,11 @@ public class PqReportServiceImpl extends ServiceImpl i } } } - // 如果经过一顿处理后,结果性数据集合还是空,塞个特殊数据进去,避免嵌套循环 + // 经过一轮处理仍未采集到任何合格性数据时,塞入哨兵: + // 一是让后续 TEST_RESULT_* 分支的 fallback 看到 resultMap 非空而跳过重复调用本方法, + // 二是供 dealTestResultLine 据此跳过结论表生成(哨兵协议详见 RESULT_MAP_NO_DATA_FLAG 注释)。 if (CollUtil.isEmpty(resultMap)) { - resultMap.put(PowerIndexEnum.UNKNOWN.getKey(), Collections.singletonList(false)); + resultMap.put(RESULT_MAP_NO_DATA_FLAG, Collections.singletonList(false)); } return todoInsertList; } @@ -1906,16 +1949,16 @@ public class PqReportServiceImpl extends ServiceImpl i pqDevVO.getGdName() != null ? pqDevVO.getGdName() : "未知供电公司", pqDevVO.getSubName() != null ? pqDevVO.getSubName() : "未知电站", pqDevVO.getName() != null ? pqDevVO.getName() : "未知设备"); - filePath = reportPath.concat(File.separator).concat(plan.getName()).concat(File.separator).concat(fileName); + filePath = reportPath.concat(File.separator).concat(FilePathSanitizer.toSafeFileName(plan.getName())).concat(File.separator).concat(fileName); downloadFileName = fileName; } else { // 数字/模拟模式:使用原来的路径结构 - filePath = reportPath.concat(File.separator).concat(devType.getName()).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX); + filePath = reportPath.concat(File.separator).concat(FilePathSanitizer.toSafeFileName(devType.getName())).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX); downloadFileName = pqDevVO.getCreateId() + ReportConstant.DOCX; } } else { // 兜底:使用旧的路径结构 - filePath = reportPath.concat(File.separator).concat(devType.getName()).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX); + filePath = reportPath.concat(File.separator).concat(FilePathSanitizer.toSafeFileName(devType.getName())).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX); downloadFileName = pqDevVO.getCreateId() + ReportConstant.DOCX; } diff --git a/tools/report-generator/src/main/java/com/njcn/gather/tools/report/service/IWordReportService.java b/tools/report-generator/src/main/java/com/njcn/gather/tools/report/service/IWordReportService.java index 20889a67..ffe07e6e 100644 --- a/tools/report-generator/src/main/java/com/njcn/gather/tools/report/service/IWordReportService.java +++ b/tools/report-generator/src/main/java/com/njcn/gather/tools/report/service/IWordReportService.java @@ -14,10 +14,17 @@ public interface IWordReportService { /** * 替换Word文档中的占位符 - * + * * @param templateInputStream 模板文档输入流 * @param placeholderMap 占位符替换映射表,key为占位符标识,value为替换值 - * @return 处理后的文档输入流,调用方可根据需要进行下载、上传等操作 + * @return 处理后的文档输入流,调用方可根据需要进行下载、上传等操作。 + *

+ * 资源管理契约:当前实现返回 {@link java.io.ByteArrayInputStream}, + * 其 {@code close()} 为空操作、内部仅持有 byte 数组、不占用文件句柄等 native 资源, + * 调用方不强制用 try-with-resources 包裹该返回流; + * 若未来该方法的实现改为返回底层依赖文件 / 网络 / 临时文件的真实流, + * 必须先改造所有调用方按 try-with-resources 关流后再合并实现, + * 以避免句柄泄漏。 * @throws Exception 处理异常 */ InputStream replacePlaceholders(InputStream templateInputStream, Map placeholderMap) throws Exception; diff --git a/tools/report-generator/src/main/java/com/njcn/gather/tools/report/service/impl/WordReportServiceImpl.java b/tools/report-generator/src/main/java/com/njcn/gather/tools/report/service/impl/WordReportServiceImpl.java index 4efd8d8a..f616981a 100644 --- a/tools/report-generator/src/main/java/com/njcn/gather/tools/report/service/impl/WordReportServiceImpl.java +++ b/tools/report-generator/src/main/java/com/njcn/gather/tools/report/service/impl/WordReportServiceImpl.java @@ -40,6 +40,10 @@ public class WordReportServiceImpl implements IWordReportService { PlaceholderUtil.replaceAllPlaceholders(mainDocumentPart, placeholderMap); // 将处理后的文档转换为字节数组输入流 + // 注:返回类型必须是 ByteArrayInputStream 或 close() 为空操作的等价流, + // 以满足 IWordReportService.replacePlaceholders 接口契约 + // (多个调用方未对返回流做 try-with-resources 兜底)。 + // 若需改为依赖文件 / 网络 / 临时文件的真实流,必须先改造所有调用方再合并。 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { wordPackage.save(outputStream); byte[] documentBytes = outputStream.toByteArray(); diff --git a/tools/report-generator/src/main/java/com/njcn/gather/tools/report/util/FilePathSanitizer.java b/tools/report-generator/src/main/java/com/njcn/gather/tools/report/util/FilePathSanitizer.java new file mode 100644 index 00000000..f93f50d4 --- /dev/null +++ b/tools/report-generator/src/main/java/com/njcn/gather/tools/report/util/FilePathSanitizer.java @@ -0,0 +1,60 @@ +package com.njcn.gather.tools.report.util; + +import cn.hutool.core.util.StrUtil; + +/** + * 文件路径片段净化工具。 + *

+ * 用于把外部输入(数据库中的设备型号名、计划名等)作为目录或文件名片段拼入磁盘路径前的兜底清洗, + * 防止 {@code /} {@code \} {@code ..} {@code :} 等路径敏感字符导致: + *

    + *
  • 报告文件被写到预期目录之外(路径穿越)
  • + *
  • 名字含 {@code /} 时被操作系统解释成多级子目录(即使无恶意,自然命名如"高/中压"也会触发)
  • + *
  • Windows 上 {@code :} 触发 NTFS 备用数据流
  • + *
  • 文件创建失败抛 IO 异常
  • + *
+ * + * @author hongawen + */ +public final class FilePathSanitizer { + + /** + * Windows + Linux 共同非法字符 + 控制字符:替换为下划线 + */ + private static final String UNSAFE_CHAR_PATTERN = "[\\\\/:*?\"<>|\\x00-\\x1F]"; + + private FilePathSanitizer() { + } + + /** + * 把一段字符串净化成可安全拼入磁盘路径的片段。 + *

+ * 规则: + *

    + *
  1. {@code null} 或全空白 → 返回 {@code "_"}(保证拼出来的路径仍合法)
  2. + *
  3. {@code /} {@code \} {@code :} {@code *} {@code ?} {@code "} {@code <} {@code >} {@code |} + * 及 ASCII 控制字符替换为 {@code _}
  4. + *
  5. 把 {@code ..} 折叠为 {@code _},防止路径穿越
  6. + *
  7. 连续 {@code _} 合并为单个 {@code _}
  8. + *
  9. 首尾空白与 {@code .} 去掉(Windows 不允许文件名以 {@code .} 结尾)
  10. + *
+ * + * @param raw 原始字符串 + * @return 净化后的片段;当输入合法且无危险字符时与原值一致 + */ + public static String toSafeFileName(String raw) { + if (StrUtil.isBlank(raw)) { + return "_"; + } + String result = raw.replaceAll(UNSAFE_CHAR_PATTERN, "_"); + // 折叠路径穿越序列 + while (result.contains("..")) { + result = result.replace("..", "_"); + } + // 合并连续下划线 + result = result.replaceAll("_+", "_"); + // 去掉首尾空白和点 + result = result.replaceAll("^[\\s.]+|[\\s.]+$", ""); + return result.isEmpty() ? "_" : result; + } +}