refactor(report): 优化报告生成服务的安全性和文档处理

- 添加 FilePathSanitizer 工具类,防止路径穿越和非法字符问题
- 在报告目录路径构建中使用安全的文件名处理
- 为 BookmarkEnum 添加排序字段和注释说明
- 改进书签处理排序逻辑,使用 sort 字段而非依赖枚举声明顺序
- 添加批量处理的语义说明文档
- 优化数据处理流程中的哨兵标记机制
- 为 WordReportService 接口添加详细的资源管理契约文档
- 改进 dealDataLine 方法的职责分离和参数命名
- 修复测试结果详情书签键值引用错误
This commit is contained in:
2026-05-26 19:20:03 +08:00
parent 13677f21d9
commit 3cb4a46a16
6 changed files with 142 additions and 23 deletions

4
.gitignore vendored
View File

@@ -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/

View File

@@ -30,6 +30,7 @@ public enum BookmarkEnum {
private String desc;
/** 书签处理顺序1=数据项2=结果信息3=目录信息;由 dealDataModelScatteredByBookmark 排序时使用 */
private Integer sort;
BookmarkEnum(String key, String desc, Integer sort) {

View File

@@ -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<PqReportMapper, PqReport> implements IPqReportService {
/**
* resultMap 内部协议:当 dealDataLine 跑完一轮但未采集到任何有效合格性数据时,
* 在 resultMap 中塞入这个 key 作为"已尝试且无数据"的哨兵,避免后续 TEST_RESULT_*
* 分支的 fallback 重复调用 dealDataLine 浪费资源;同时 dealTestResultLine 检测到
* 此 key 存在时跳过结论表生成。
* <p>
* 故意使用明显非业务字符串,避免与任何 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<PqReportMapper, PqReport> i
/**
* 根据设备类型生成报告
* 注:该方法目前仅支持楼下出厂检测场景,属于模板占位符替换方式,后期可能会有调整
* <p>
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
* 而非待修复缺陷。
*
* @param devReportParam 被检设备信息
*/
@@ -783,6 +800,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
/**
* 需要支持批量生成,如果用户选择批量生成,则默认都采用测试数据的第一个合格,如果
* 比对模式下生成检测报告,实际后期需要根据用户选择的检测数据或者某次波形数据生成报告
* <p>
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
* 而非待修复缺陷。
*
* @param plan 计划信息
* @param devReportParam 设备信息
@@ -821,7 +843,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> 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<PqReportMapper, PqReport> i
/**
* 根据计划绑定的报告模板生成报告
* 注:该方法目前属于同用信息占位符替换,数据页为面向对象动态填充拼凑方式
* <p>
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
* 而非待修复缺陷。
*
* @param plan 计划信息
* @param devReportParam 设备信息
@@ -899,7 +926,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> 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<PqReportMapper, PqReport> i
* 1、数据项
* 2、结果信息
* 3、目录信息
* 所以要先先获取的书签进行操作排
* 按 BookmarkEnum.sort 字段排序,避免依赖枚举常量声明顺
* */
Collections.sort(bookmarkEnums);
bookmarkEnums.sort(Comparator.comparingInt(BookmarkEnum::getSort).thenComparingInt(Enum::ordinal));
List<Object> todoInsertList;
BookmarkUtil.BookmarkInfo bookmarkInfo;
Map<Integer/*回路号*/, List<ContrastTestResult>> resultMap = null;
@@ -1230,9 +1257,9 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
* 1、数据项
* 2、结果信息
* 3、目录信息
* 所以要先先获取的书签进行操作排
* 按 BookmarkEnum.sort 字段排序,避免依赖枚举常量声明顺
* */
Collections.sort(bookmarkEnums);
bookmarkEnums.sort(Comparator.comparingInt(BookmarkEnum::getSort).thenComparingInt(Enum::ordinal));
// 定义个结果,以便存在结果信息的书签
Map<String/*指标名称*/, List<Boolean/*以回路的顺序填充结果*/>> resultMap = new HashMap<>();
List<Object> todoInsertList;
@@ -1281,7 +1308,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> 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<PqReportMapper, PqReport> i
*/
private List<Object> dealTestResultLine(DevReportParam devReportParam, Map<String, List<Boolean>> resultMap, DocAnchorEnum docAnchorEnum) {
List<Object> 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<PqReportMapper, PqReport> i
/**
* 处理以回路维度数据项,书签占位符的方式
* 以回路维度处理数据项,并填充 resultMap指标合格性结论
* <p>
* 本方法承担双重职责:
* <ol>
* <li><b>返回值</b>:根据 modelPart 中的 H5 分组表格模板,灌入实测数据后生成可插入文档的元素列表;</li>
* <li><b>副作用</b>:把每个指标在各回路上的合格性写入 resultMap供后续 dealTestResultLine 构造结论表使用。</li>
* </ol>
* 调用约定(务必区分以下两条路径,避免误解形参用途):
* <ul>
* <li><b>常规路径</b>DATA_LINE 分支modelPart 传 detail 文档(数据页模板池),返回值会被插入 DATA_LINE 书签锚点。</li>
* <li><b>fallback 路径</b>TEST_RESULT_* 分支且 resultMap 为空时modelPart 允许传 base 文档(封面页);此时模板池为空,返回值无业务意义,调用方应丢弃,仅借此触发 resultMap 计算。</li>
* </ul>
* 因此 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<Object> dealDataLine(MainDocumentPart detailModelDocument, DevReportParam devReportParam, PqDevVO pqDevVO, Map<String, List<Boolean>> resultMap) {
private List<Object> dealDataLine(MainDocumentPart modelPart, DevReportParam devReportParam, PqDevVO pqDevVO, Map<String, List<Boolean>> resultMap) {
List<Object> todoInsertList = new ArrayList<>();
// 以回路维度处理数据项
Integer devChns = pqDevVO.getDevChns();
@@ -1410,8 +1451,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
// 读取该计划的检测大项组装数据内容
List<PqScriptDtlDataVO> pqScriptDtlsList = pqScriptDtlsService.getScriptDtlsDataList(devReportParam.getScriptId());
Map<String, List<PqScriptDtlDataVO>> scriptMap = pqScriptDtlsList.stream().collect(Collectors.groupingBy(PqScriptDtlDataVO::getScriptCode, LinkedHashMap::new, Collectors.toList()));
List<Object> allContent = detailModelDocument.getContent();
List<Docx4jUtil.HeadingContent> headingContents = Docx4jUtil.extractHeading5Contents(allContent, detailModelDocument);
List<Object> allContent = modelPart.getContent();
List<Docx4jUtil.HeadingContent> headingContents = Docx4jUtil.extractHeading5Contents(allContent, modelPart);
Map<String, List<Docx4jUtil.HeadingContent>> 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<PqReportMapper, PqReport> 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<PqReportMapper, PqReport> 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;
}

View File

@@ -14,10 +14,17 @@ public interface IWordReportService {
/**
* 替换Word文档中的占位符
*
*
* @param templateInputStream 模板文档输入流
* @param placeholderMap 占位符替换映射表key为占位符标识value为替换值
* @return 处理后的文档输入流,调用方可根据需要进行下载、上传等操作
* @return 处理后的文档输入流,调用方可根据需要进行下载、上传等操作
* <p>
* <b>资源管理契约:</b>当前实现返回 {@link java.io.ByteArrayInputStream}
* 其 {@code close()} 为空操作、内部仅持有 byte 数组、不占用文件句柄等 native 资源,
* 调用方<strong>不强制</strong>用 try-with-resources 包裹该返回流;
* 若未来该方法的实现改为返回底层依赖文件 / 网络 / 临时文件的真实流,
* 必须先改造所有调用方按 try-with-resources 关流后再合并实现,
* 以避免句柄泄漏。
* @throws Exception 处理异常
*/
InputStream replacePlaceholders(InputStream templateInputStream, Map<String, String> placeholderMap) throws Exception;

View File

@@ -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();

View File

@@ -0,0 +1,60 @@
package com.njcn.gather.tools.report.util;
import cn.hutool.core.util.StrUtil;
/**
* 文件路径片段净化工具。
* <p>
* 用于把外部输入(数据库中的设备型号名、计划名等)作为目录或文件名片段拼入磁盘路径前的兜底清洗,
* 防止 {@code /} {@code \} {@code ..} {@code :} 等路径敏感字符导致:
* <ul>
* <li>报告文件被写到预期目录之外(路径穿越)</li>
* <li>名字含 {@code /} 时被操作系统解释成多级子目录(即使无恶意,自然命名如"高/中压"也会触发)</li>
* <li>Windows 上 {@code :} 触发 NTFS 备用数据流</li>
* <li>文件创建失败抛 IO 异常</li>
* </ul>
*
* @author hongawen
*/
public final class FilePathSanitizer {
/**
* Windows + Linux 共同非法字符 + 控制字符:替换为下划线
*/
private static final String UNSAFE_CHAR_PATTERN = "[\\\\/:*?\"<>|\\x00-\\x1F]";
private FilePathSanitizer() {
}
/**
* 把一段字符串净化成可安全拼入磁盘路径的片段。
* <p>
* 规则:
* <ol>
* <li>{@code null} 或全空白 → 返回 {@code "_"}(保证拼出来的路径仍合法)</li>
* <li>{@code /} {@code \} {@code :} {@code *} {@code ?} {@code "} {@code <} {@code >} {@code |}
* 及 ASCII 控制字符替换为 {@code _}</li>
* <li>把 {@code ..} 折叠为 {@code _},防止路径穿越</li>
* <li>连续 {@code _} 合并为单个 {@code _}</li>
* <li>首尾空白与 {@code .} 去掉Windows 不允许文件名以 {@code .} 结尾)</li>
* </ol>
*
* @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;
}
}