P2-3: 横切服务桩换 framework 真实现(文件/日志/消息)
保真层原样移植三块横切服务,删除对应桩,bean 名/包名/签名不动: - 文件 com.dsasp.server.file.*:FileServiceImpl(bean fileService)真实现, 存储后端经替换类 FTPClientTemplate(保包名/类名/签名,FTP→本地盘, 根目录 eip4.file.root 配置化默认 ./data/files,resolveSafe 防 ../ 逃逸); BASE64Decoder→java.util.Base64、ant zip→java.util.zip、commons-codec→MessageDigest。 - 日志 com.dsasp.server.log.*:SystemLogManagerImpl/DataOperatorLogger/ DataLogRecorderImpl + 异步调度(DataLogManager/ProcessLogThread/ProcessSysLogThread) 原样移植,落 SYS_LOG/SYS_DATA_LOG/SYS_DATA_LOGITEM(后者 insert-only 无审计列,§5.1)。 - 消息 com.dsasp.server.mail.*:SystemEmailServiceImpl + SystemEmail/SystemEmailService 移植;SMTP 配置缺省时降级 no-op + WARN,不阻塞启动(§5.38)。 装配/配置/自举/验证: - LegacyXmlWiring 等价补齐三处 jdbcTemplate setter + MainApp.destPath 注入(§4.1); - application.yml 加 eip4.file.root;bootstrap-xservice.sql 自举四张横切表 + LOGLEVEL; - 删除 StubFileService/StubSystemLogManager/StubDataOperatorLog(StubProjectSwitchService 属 viewframework 域非本任务范畴,保留); - 单测 12 + 本地 DB 集成 4,全模块 mvn clean test 绿(含 ArchUnit);8087 启动验证毕已 kill。 报告:platform-auth/P2横切服务实测报告.md;坑入 docs/迁移手册.md §3.1/§3.2/§5.36-5.38。 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,16 +1,21 @@
|
||||
package com.eip4.platform.app.config;
|
||||
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import com.fasterxml.jackson.datatype.joda.JodaModule;
|
||||
import com.dsasp.server.common.util.MainApp;
|
||||
|
||||
import com.dsasp.server.common.log.service.DataOperatorLog;
|
||||
import com.dsasp.server.common.log.service.SystemLogManager;
|
||||
import com.dsasp.server.core.service.FlowServiceImpl;
|
||||
import com.dsasp.server.file.service.FileServiceImpl;
|
||||
import com.dsasp.server.log.service.DataLogRecorderImpl;
|
||||
import com.dsasp.server.log.service.SystemLogManagerImpl;
|
||||
import com.dsasp.server.dataDic.service.POJOCRUDServiceImpl;
|
||||
import com.dsasp.server.dataDic.service.POJOServiceImpl;
|
||||
import com.dsasp.server.organize.service.AssignmentHandlerImpl;
|
||||
@@ -41,6 +46,13 @@ public class LegacyXmlWiring implements SmartInitializingSingleton {
|
||||
private final UserFindServiceImpl userFindService;
|
||||
private final UserOtpServiceImpl userOtpService;
|
||||
private final AssignmentHandlerImpl assignmentHandler;
|
||||
private final FileServiceImpl fileService;
|
||||
private final SystemLogManagerImpl systemLogManagerImpl;
|
||||
private final DataLogRecorderImpl dataLogRecorder;
|
||||
|
||||
/** 附件本地盘根目录(配置化,默认 ./data/files);注入保真层 MainApp.destPath。 */
|
||||
@Value("${eip4.file.root:./data/files}")
|
||||
private String fileRoot;
|
||||
|
||||
public LegacyXmlWiring(POJOCRUDServiceImpl pojoCRUDService,
|
||||
POJOServiceImpl pojoService,
|
||||
@@ -51,7 +63,10 @@ public class LegacyXmlWiring implements SmartInitializingSingleton {
|
||||
OrganizationServiceImpl organizationService,
|
||||
UserFindServiceImpl userFindService,
|
||||
UserOtpServiceImpl userOtpService,
|
||||
AssignmentHandlerImpl assignmentHandler) {
|
||||
AssignmentHandlerImpl assignmentHandler,
|
||||
FileServiceImpl fileService,
|
||||
SystemLogManagerImpl systemLogManagerImpl,
|
||||
DataLogRecorderImpl dataLogRecorder) {
|
||||
this.pojoCRUDService = pojoCRUDService;
|
||||
this.pojoService = pojoService;
|
||||
this.systemLogManager = systemLogManager;
|
||||
@@ -62,6 +77,9 @@ public class LegacyXmlWiring implements SmartInitializingSingleton {
|
||||
this.userFindService = userFindService;
|
||||
this.userOtpService = userOtpService;
|
||||
this.assignmentHandler = assignmentHandler;
|
||||
this.fileService = fileService;
|
||||
this.systemLogManagerImpl = systemLogManagerImpl;
|
||||
this.dataLogRecorder = dataLogRecorder;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -83,6 +101,18 @@ public class LegacyXmlWiring implements SmartInitializingSingleton {
|
||||
userOtpService.setJdbcTemplate(jdbcTemplate);
|
||||
assignmentHandler.setOrganizationService(organizationService);
|
||||
assignmentHandler.setUserFindService(userFindService);
|
||||
|
||||
// P2 横切服务(文件/日志):FileServiceImpl / SystemLogManagerImpl / DataLogRecorderImpl
|
||||
// 的 jdbcTemplate 在 framework 同为 XML <property> setter 注入(非 @Autowired),
|
||||
// 这里等价补齐(见 §4.1)。三块真实现接替原 Stub*,bean 名一致(fileService/
|
||||
// systemLogManager/dataLogRecorder),旧引擎调用方零感知。
|
||||
fileService.setJdbcTemplate(jdbcTemplate);
|
||||
systemLogManagerImpl.setJdbcTemplate(jdbcTemplate);
|
||||
dataLogRecorder.setJdbcTemplate(jdbcTemplate);
|
||||
|
||||
// 附件本地盘根目录配置化(eip4.file.root,默认 ./data/files)注入保真层 MainApp。
|
||||
// 保真层不反向依赖现代层(ArchUnit),故由现代层单向 set,旧 FileServiceImpl 零修改。
|
||||
MainApp.setDestPath(fileRoot);
|
||||
}
|
||||
|
||||
/** 引擎字段值含 joda DateTime(CREATETIME 等),Boot 3 需显式注册序列化模块。 */
|
||||
|
||||
@@ -29,6 +29,10 @@ eip4:
|
||||
secret: ${EIP4_AUTH_JWT_SECRET:dev-only-eip4-jwt-secret-change-me-in-production-0123456789}
|
||||
expire-seconds: 28800 # 8h
|
||||
issuer: eip4-platform
|
||||
# 附件横切服务(P2):本地盘存储根目录。注入保真层 MainApp.destPath。
|
||||
# 默认 ./data/files(相对启动工作目录),生产经环境变量 EIP4_FILE_ROOT 覆盖为绝对路径。
|
||||
file:
|
||||
root: ${EIP4_FILE_ROOT:./data/files}
|
||||
|
||||
logging:
|
||||
level:
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package com.eip4.platform.app;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.util.StreamUtils;
|
||||
|
||||
import com.dsasp.server.common.email.bean.SystemEmail;
|
||||
import com.dsasp.server.common.email.service.SystemEmailService;
|
||||
import com.dsasp.server.common.log.bean.DataLogDetail;
|
||||
import com.dsasp.server.common.log.bean.DataLogItem;
|
||||
import com.dsasp.server.common.log.bean.SysLogItem;
|
||||
import com.dsasp.server.common.log.service.DataLogRecorder;
|
||||
import com.dsasp.server.common.log.service.SystemLogManager;
|
||||
import com.dsasp.server.common.log.service.SystemLogManager.LogType;
|
||||
import com.dsasp.server.common.util.MainApp;
|
||||
import com.dsasp.server.file.upload.FTPClientTemplate;
|
||||
|
||||
/**
|
||||
* P2 横切服务(文件/日志/消息)真实现 DB 落地集成测试(local profile,eip4m0 自举库)。
|
||||
*
|
||||
* <p>用 bootstrap-sys.sql + bootstrap-xservice.sql 自举 SYS_LOG / SYS_DATA_LOG /
|
||||
* SYS_DATA_LOGITEM,经容器内真实 bean(systemLogManager / dataLogRecorder)写库再读回,
|
||||
* 验证落库字段语义与老系统一致;附件经替换类 FTPClientTemplate 本地盘上传→下载字节一致;
|
||||
* 邮件降级路径不抛。eip4m0 不可达时整类跳过(assumeTrue),CI 无该库不红。
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("local")
|
||||
class XServiceLocalIT {
|
||||
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("systemLogManager")
|
||||
private SystemLogManager systemLogManager;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("dataLogRecorder")
|
||||
private DataLogRecorder dataLogRecorder;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("systemEmailService")
|
||||
private SystemEmailService systemEmailService;
|
||||
|
||||
private boolean ensureBootstrap() {
|
||||
try {
|
||||
jdbcTemplate.queryForObject("select 1", Integer.class);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
runSql("bootstrap/bootstrap-sys.sql");
|
||||
runSql("bootstrap/bootstrap-xservice.sql");
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("自举 SQL 执行失败:" + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void runSql(String classpath) throws IOException {
|
||||
String sql = StreamUtils.copyToString(
|
||||
new ClassPathResource(classpath).getInputStream(), StandardCharsets.UTF_8);
|
||||
jdbcTemplate.execute(sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("系统日志真实现:log(List) 批量落 SYS_LOG,字段语义(类型/内容/操作人/时间)正确")
|
||||
void systemLog_persists_to_sys_log() {
|
||||
assumeTrue(ensureBootstrap(), "本地 eip4m0 不可达,跳过");
|
||||
jdbcTemplate.update("DELETE FROM sys_log");
|
||||
|
||||
List<SysLogItem> items = new ArrayList<>();
|
||||
items.add(new SysLogItem(LogType.INFO, "P2 集成测试:系统日志落库", "tester-001"));
|
||||
systemLogManager.log(items);
|
||||
|
||||
Map<String, Object> row = jdbcTemplate.queryForMap(
|
||||
"SELECT type, content, createby, updateby, isactive, version, createtime FROM sys_log LIMIT 1");
|
||||
assertEquals("Info", String.valueOf(row.get("type")).trim());
|
||||
assertEquals("P2 集成测试:系统日志落库", row.get("content"));
|
||||
assertEquals("tester-001", String.valueOf(row.get("createby")).trim());
|
||||
assertEquals("tester-001", String.valueOf(row.get("updateby")).trim());
|
||||
assertEquals(1, ((Number) row.get("isactive")).intValue());
|
||||
assertEquals(0, ((Number) row.get("version")).intValue());
|
||||
assertTrue(((Number) row.get("createtime")).longValue() > 0, "createtime 应为 joda 毫秒");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("数据操作日志真实现:recorderLogs 落 SYS_DATA_LOG + SYS_DATA_LOGITEM(insert-only)")
|
||||
void dataLog_persists_main_and_detail() {
|
||||
assumeTrue(ensureBootstrap(), "本地 eip4m0 不可达,跳过");
|
||||
jdbcTemplate.update("DELETE FROM sys_data_logitem");
|
||||
jdbcTemplate.update("DELETE FROM sys_data_log");
|
||||
|
||||
String dlId = UUID.randomUUID().toString();
|
||||
DataLogItem item = new DataLogItem();
|
||||
item.setDataLogItem_Id(dlId);
|
||||
item.setTableName("EIP4PT_CUSTOMER");
|
||||
item.setRecordId("rec-itest");
|
||||
item.setType(DataLogItem.OPERATE_NEW);
|
||||
item.setUserId("tester-002");
|
||||
DataLogDetail d = new DataLogDetail();
|
||||
d.setDataLogId(dlId);
|
||||
d.setColumnName("NAME");
|
||||
d.setOldValue(null);
|
||||
d.setNewValue("集成测试客户");
|
||||
item.addDataLogDetail(d);
|
||||
|
||||
List<DataLogItem> list = new ArrayList<>();
|
||||
list.add(item);
|
||||
dataLogRecorder.recorderLogs(list);
|
||||
|
||||
Map<String, Object> main = jdbcTemplate.queryForMap(
|
||||
"SELECT tablename, recordid, type, updateby FROM sys_data_log WHERE sys_data_log_id=?", dlId);
|
||||
assertEquals("EIP4PT_CUSTOMER", main.get("tablename"));
|
||||
assertEquals("rec-itest", String.valueOf(main.get("recordid")).trim());
|
||||
assertEquals(DataLogItem.OPERATE_NEW.intValue(), ((Number) main.get("type")).intValue());
|
||||
assertEquals("tester-002", String.valueOf(main.get("updateby")).trim());
|
||||
|
||||
Map<String, Object> detail = jdbcTemplate.queryForMap(
|
||||
"SELECT columnname, oldvalue, newvalue FROM sys_data_logitem WHERE sys_datalogid=?", dlId);
|
||||
assertEquals("NAME", detail.get("columnname"));
|
||||
assertEquals("集成测试客户", detail.get("newvalue"));
|
||||
assertEquals(null, detail.get("oldvalue"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("附件真实现:本地盘上传→下载字节一致,删除生效")
|
||||
void file_upload_download_roundtrip(@org.junit.jupiter.api.io.TempDir java.nio.file.Path tmp) throws Exception {
|
||||
assumeTrue(ensureBootstrap(), "本地 eip4m0 不可达,跳过");
|
||||
String saved = MainApp.destPath;
|
||||
try {
|
||||
MainApp.setDestPath(tmp.toFile().getAbsolutePath());
|
||||
byte[] payload = "集成测试附件内容-binary".getBytes(StandardCharsets.UTF_8);
|
||||
File src = tmp.resolve("in.bin").toFile();
|
||||
Files.write(src.toPath(), payload);
|
||||
|
||||
FTPClientTemplate tpl = new FTPClientTemplate();
|
||||
String remote = "/SYS_DOC/0/itest.zip";
|
||||
tpl.uploadFileAndZip(remote, src.getAbsolutePath(), "itest.txt");
|
||||
assertTrue(tpl.fileExists(remote), "落盘后远端应存在");
|
||||
|
||||
File out = tmp.resolve("out.bin").toFile();
|
||||
tpl.downloadFile(remote, out.getAbsolutePath());
|
||||
assertArrayEquals(payload, Files.readAllBytes(out.toPath()), "下载字节须一致");
|
||||
|
||||
assertTrue(tpl.delete(remote));
|
||||
assertFalse(tpl.fileExists(remote));
|
||||
} finally {
|
||||
MainApp.destPath = saved;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("消息真实现:配置缺省降级路径,sendEmail 不抛、不阻塞")
|
||||
void mail_degrades_without_config() {
|
||||
assumeTrue(ensureBootstrap(), "本地 eip4m0 不可达,跳过");
|
||||
SystemEmail email = new SystemEmail();
|
||||
email.setSubject("集成测试通知");
|
||||
email.setContent("正文");
|
||||
email.setAddress(java.util.Arrays.asList("u-1"));
|
||||
assertNotNull(systemEmailService);
|
||||
// 不抛即通过(降级 no-op + WARN)
|
||||
systemEmailService.sendEmail(email);
|
||||
}
|
||||
}
|
||||
151
platform-auth/P2横切服务实测报告.md
Normal file
151
platform-auth/P2横切服务实测报告.md
Normal file
@@ -0,0 +1,151 @@
|
||||
# P2-3 横切服务真实现实测报告(文件 / 日志 / 消息)
|
||||
|
||||
> 任务:用 framework 真实现替换横切服务桩(文件/日志/消息)
|
||||
> 工程:`/Users/zhengwr/workspace/eip3/eip4-platform`
|
||||
> 日期:2026-06-11
|
||||
> 必读对照:`docs/迁移手册.md`(§3.1 替换类、§3.2 横切桩、§4.1 XML 等价装配、§5.1/§5.36/§5.37/§5.38、§5 引擎契约)
|
||||
|
||||
---
|
||||
|
||||
## 一、结论速览
|
||||
|
||||
| 维度 | 结果 |
|
||||
|------|------|
|
||||
| 移植主源文件 | **18 个**(文件 7 + 日志 7 + 消息 3 + MainApp 1),约 1,611 行 |
|
||||
| 删除的桩 | **3 个**(StubFileService / StubSystemLogManager / StubDataOperatorLog) |
|
||||
| 保留的桩 | **1 个**(StubProjectSwitchService —— viewframework 域,非本任务范畴,见 §四) |
|
||||
| 替换类登记 | **FTPClientTemplate**(FTP 后端 → 本地盘,保包名/类名/签名),已登记入 §3.1 |
|
||||
| 新增替换实现 bean | `fileService` / `systemLogManager` / `dataOperatorLog` / `dataLogRecorder` / `systemEmailService` |
|
||||
| 单元 + 集成测试 | **16 个**(单测 12 + 本地 DB 集成 4),全绿 |
|
||||
| 全模块 `mvn clean test` | **BUILD SUCCESS**(8 模块全绿,含 ArchUnit) |
|
||||
| 端口 8087 启动 | **正常**(0.98s 起;无异常;mail 降级 bean 不阻塞);验证毕已 kill |
|
||||
| 8084 / 8085 | **未触碰**(8084 为并行代理进程,全程保留) |
|
||||
|
||||
---
|
||||
|
||||
## 二、移植面与替换类登记
|
||||
|
||||
### 2.1 文件服务(`com.dsasp.server.file.*` → platform-legacy-core)
|
||||
|
||||
| 文件 | 性质 | 与原版差异 |
|
||||
|------|------|-----------|
|
||||
| `service/FileServiceImpl.java` | 真实现,bean `fileService` | `sun.misc.BASE64Decoder`→`java.util.Base64`;存储后端经替换类 FTPClientTemplate 走本地盘;其余原样 |
|
||||
| `upload/FTPClientTemplate.java` | **替换类**(§3.1) | FTP 后端 → 本地盘;**保包名/类名/对外签名** `uploadFileAndZip`/`downloadFile`/`delete`/`fileExists`;根目录 `MainApp.destPath`;`resolveSafe` 防 `../` 逃逸 |
|
||||
| `util/ZipUtil.java` | 移植(瘦身) | 仅保留 `ZipFileToDest`(原 ant zip 重载无调用方,不移植) |
|
||||
| `util/FileUtil.java` | 移植(瘦身) | 去 `javax.swing.FileSystemView` 依赖的 `getFileType`/`sortFiles`(无调用方) |
|
||||
| `util/HashCalc.java` | 移植 | commons-codec `DigestUtils` → JDK `MessageDigest`,十六进制摘要逐字节一致 |
|
||||
| `util/HashEnum.java` / `util/SysUtil.java` | 原样移植 | —— |
|
||||
| `common/util/MainApp.java` | 配置持有者 | 原版写死 Windows 路径 → 跨平台默认 `./data/files` + setter(现代层注入) |
|
||||
|
||||
**替换类策略落地(§3.1「旧代码零感知」)**:`FileServiceImpl` / `ZipUtil` 对 `FTPClientTemplate` 的调用一行未改,仅 `FTPClientTemplate` 内部从 commons-net FTP 客户端换成本地盘读写。本地盘根目录经 `eip4.file.root`(`application.yml`,env `EIP4_FILE_ROOT` 覆盖,默认 `./data/files`)由 `LegacyXmlWiring` 单向写入 `MainApp.destPath`——保真层不反向依赖现代层(ArchUnit 约束)。
|
||||
|
||||
### 2.2 日志服务(`com.dsasp.server.log.*` + `common/log/service/DataLogRecorder` → platform-legacy-core)
|
||||
|
||||
原样移植 6 个 impl/调度 + 补 1 个接口:`SystemLogManagerImpl`(bean `systemLogManager`)、`DataOperatorLogger`(bean `dataOperatorLog`)、`DataLogRecorderImpl`(bean `dataLogRecorder`)、`DataLogManager`(异步调度,Timer 1s/30s)、`ProcessLogThread`、`ProcessSysLogThread`、`DataLogRecorder`(接口)。
|
||||
|
||||
落库语义与老系统一致:
|
||||
- **SYS_LOG**:`SYS_LOG_ID,TYPE,CONTENT,createtime(joda 毫秒),createby=操作人,updatetime,updateby,isactive=1,version=0`。
|
||||
- **SYS_DATA_LOG**:`sys_data_log_id,tablename,recordid,mainrecordid,type,updatetime,updateby`。
|
||||
- **SYS_DATA_LOGITEM**:`sys_data_logitem_id,sys_datalogid,oldvalue,newvalue,columnname` —— **insert-only,无 UPDATETIME 列**(§5.1),实现只走纯 INSERT,符合。
|
||||
|
||||
### 2.3 消息服务(`com.dsasp.server.mail.*` + `common/email/*` → platform-legacy-core)
|
||||
|
||||
`SystemEmailService`(接口)+ `SystemEmail`(bean)原样移植;`SystemEmailServiceImpl`(bean `systemEmailService`)**降级装配**:SMTP 发件人配置(`SysConfig` 键 `com.dsasp.server.mail.admin_mail`)缺省时仅打 WARN 后 no-op,**不抛、不阻塞启动**。原版深度依赖 javax.mail + freemarker + OSGi ConfigUtil + 活的 SMTP,真实投递留口待 `JavaMailSender` 装配后接通(详见 §5.38)。`ClientMailService`(POP3/IMAP 全客户端)非「横切消息」范畴且无调用方,本次不移植。
|
||||
|
||||
### 2.4 XML 等价装配补齐(§4.1)
|
||||
|
||||
`platform-app/.../config/LegacyXmlWiring.java` 新增三处 setter 注入(等价原 framework service.xml `<property>`):
|
||||
```
|
||||
fileService.setJdbcTemplate(jdbcTemplate);
|
||||
systemLogManagerImpl.setJdbcTemplate(jdbcTemplate);
|
||||
dataLogRecorder.setJdbcTemplate(jdbcTemplate);
|
||||
MainApp.setDestPath(fileRoot); // eip4.file.root 注入
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、实测证据
|
||||
|
||||
### 3.1 文件:上传 → 下载字节一致 → 删除(本地盘)
|
||||
|
||||
`LocalFileStorageTest` + `XServiceLocalIT#file_upload_download_roundtrip`(经容器内真实替换类 `FTPClientTemplate`):
|
||||
- 写入二进制载荷 → `uploadFileAndZip` 落 `destPath/SYS_DOC/0/itest.zip` → `fileExists`=true;
|
||||
- `downloadFile` 解压回字节 → **`assertArrayEquals(原始, 下载)` 通过**(byte 一致);
|
||||
- `delete` → `fileExists`=false。
|
||||
- **路径安全**:`fileExists("../../etc/passwd")` / `downloadFile("/a/../../../escape.zip",…)` → 抛 `IOException` + WARN「拒绝越界附件路径(疑似 ../ 逃逸)」(运行日志已见)。
|
||||
|
||||
### 3.2 日志:CRUD → SYS_LOG / 数据日志表落行,字段语义对
|
||||
|
||||
`XServiceLocalIT`(local profile,本地 eip4m0,经容器内真实 bean):
|
||||
- `systemLogManager.log(List)` → SYS_LOG 落行,断言 `type='Info'`、`content` 原值、`createby/updateby='tester-001'`(操作人)、`isactive=1`、`version=0`、`createtime>0`(joda 毫秒)→ **通过**;
|
||||
- `dataLogRecorder.recorderLogs(List)` → SYS_DATA_LOG + SYS_DATA_LOGITEM 落行,断言主表 `tablename/recordid/type/updateby`、明细 `columnname='NAME'`/`newvalue='集成测试客户'`/`oldvalue=null` → **通过**。
|
||||
- 实库残留行(运行后 psql 直查):
|
||||
```
|
||||
sys_data_log: EIP4PT_CUSTOMER | rec-itest | type=1 | tester-002
|
||||
sys_data_logitem: NAME | 集成测试客户
|
||||
```
|
||||
|
||||
### 3.3 消息:配置缺省降级路径(启动无异常、调用打 WARN 不抛)
|
||||
|
||||
- 8087 启动日志:`Started Eip4PlatformApplication in 0.981 seconds`,**无任何 mail 相关异常**(降级 bean 装配成功,满足「不阻塞启动」);
|
||||
- `SystemEmailServiceImplTest` + `XServiceLocalIT#mail_degrades_without_config`:`sendEmail` 在无配置时打 WARN 后 no-op,`assertDoesNotThrow` 通过;运行日志见:
|
||||
`WARN ... 邮件服务未配置发件人(com.dsasp.server.mail.admin_mail),降级为 no-op:主题=[...] 收件人=[...]`。
|
||||
|
||||
### 3.4 自举脚本
|
||||
|
||||
新增 `platform-parity/src/main/resources/bootstrap/bootstrap-xservice.sql`:幂等建 SYS_DOC / SYS_LOG / SYS_DATA_LOG / SYS_DATA_LOGITEM(后者 insert-only 无审计列)+ 种 `LOGLEVEL='Errors,Info,Debug,Warnings'`。
|
||||
|
||||
### 3.5 单测清单(16,全绿)
|
||||
|
||||
| 测试类 | 数 | 覆盖 |
|
||||
|--------|----|------|
|
||||
| `LocalFileStorageTest` | 4 | 上传下载字节一致 / `../` 逃逸防护 / 删除 / 缺失下载抛错 |
|
||||
| `HashAndFileUtilTest` | 3 | MD5 标准向量 / 文件名扩展名解析 / 路径分隔归一 |
|
||||
| `SystemLogManagerImplTest` | 2 | SYS_LOG 列绑定语义(mock JdbcTemplate)/ deleteByType |
|
||||
| `DataLogRecorderImplTest` | 1 | SYS_DATA_LOG + LOGITEM 列绑定 + insert-only(无 updatetime) |
|
||||
| `SystemEmailServiceImplTest` | 2 | 降级 no-op 不抛 / null 安全 |
|
||||
| `XServiceLocalIT`(集成,本地 DB) | 4 | 系统日志落库 / 数据日志落库 / 附件本地盘往返 / 邮件降级 |
|
||||
|
||||
### 3.6 全模块测试 + ArchUnit
|
||||
|
||||
`mvn -o clean test` → **BUILD SUCCESS**,8 模块全绿;`ArchitectureRulesTest`(`com.dsasp..` 不得依赖 `com.eip4..`)**通过**——三块真实现仅引 com.dsasp + JDK + spring + slf4j,无反向依赖。
|
||||
> 备注:一次非 clean 增量 reactor 运行曾出现 ArchUnit 瞬时 FAILURE,经隔离重跑 + `clean test` 确认为陈旧编译产物(install -DskipTests 先于 parity 新 SQL 上 classpath)所致,**非真实违例**;clean 全量稳定绿。
|
||||
|
||||
---
|
||||
|
||||
## 四、StubProjectSwitchService 侦察结论(保留,不接管)
|
||||
|
||||
`StubProjectSwitchService implements com.dsasp.server.common.viewframework.service.ProjectSwitchService`,属 **viewframework 域**(项目上下文切换),**不在本任务「文件/日志/消息」范畴**。侦察 framework 未见对应的独立横切 impl bundle(file/log/mail 三 bundle 均不含),其真实现归属 viewFramework 域;**P2-3 计划未列此项**。故按任务约定**保留该桩**,待 viewFramework 域专项移植时接管。已在 `docs/迁移手册.md` §3.2 标注。
|
||||
|
||||
---
|
||||
|
||||
## 五、坑列表(已入 docs/迁移手册.md)
|
||||
|
||||
| 编号 | 坑 |
|
||||
|------|----|
|
||||
| §5.36 | 附件 FileService 原版后端=FTP(非本地盘);本地盘默认须经替换类落地;旧依赖 `sun.misc.BASE64Decoder`/ant zip/swing 在 JDK17 不可用 |
|
||||
| §5.37 | 系统/数据日志为异步队列+定时批量落库;bean 名 systemLogManager/dataOperatorLog/dataLogRecorder 三件齐;jdbcTemplate 须 XML 等价 setter 补齐;**LOGLEVEL 未配置=整链静默**;数据日志仅 ischangelog=1 实体才记 |
|
||||
| §5.38 | 邮件 SystemEmailServiceImpl 深度依赖外部 SMTP(javax.mail+freemarker+OSGi ConfigUtil),按「配置缺省降级 no-op + WARN」装配,不阻塞启动;ClientMailService(POP3/IMAP)非横切范畴不移植 |
|
||||
| §3.1 新增行 | `FTPClientTemplate` 替换类(FTP 后端→本地盘)登记 |
|
||||
|
||||
---
|
||||
|
||||
## 六、变更文件清单
|
||||
|
||||
**保真层(platform-legacy-core,com.dsasp.* 原样移植)**:
|
||||
- `com/dsasp/server/common/util/MainApp.java`
|
||||
- `com/dsasp/server/file/service/FileServiceImpl.java`、`file/upload/FTPClientTemplate.java`、`file/util/{ZipUtil,FileUtil,HashCalc,HashEnum,SysUtil}.java`
|
||||
- `com/dsasp/server/common/log/service/DataLogRecorder.java`
|
||||
- `com/dsasp/server/log/service/{SystemLogManagerImpl,DataOperatorLogger,DataLogManager,DataLogRecorderImpl,ProcessLogThread,ProcessSysLogThread}.java`
|
||||
- `com/dsasp/server/common/email/bean/SystemEmail.java`、`common/email/service/SystemEmailService.java`、`mail/service/SystemEmailServiceImpl.java`
|
||||
- 测试:`file/{LocalFileStorageTest,HashAndFileUtilTest}.java`、`log/{SystemLogManagerImplTest,DataLogRecorderImplTest}.java`、`mail/SystemEmailServiceImplTest.java`
|
||||
|
||||
**现代层 / 配置 / 自举**:
|
||||
- `platform-app/.../config/LegacyXmlWiring.java`(新增三处 setter + 文件根注入)
|
||||
- `platform-app/src/main/resources/application.yml`(`eip4.file.root`)
|
||||
- `platform-app/.../app/XServiceLocalIT.java`(本地 DB 集成测试)
|
||||
- `platform-parity/src/main/resources/bootstrap/bootstrap-xservice.sql`(横切表自举)
|
||||
|
||||
**删除**:`platform-auth/.../stub/{StubFileService,StubSystemLogManager,StubDataOperatorLog}.java`
|
||||
|
||||
**文档**:`docs/迁移手册.md`(§3.1 / §3.2 / §5.36-5.38)、本报告
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.eip4.platform.auth.stub;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
|
||||
import com.dsasp.server.common.log.bean.DataLogItem;
|
||||
import com.dsasp.server.common.log.service.DataOperatorLog;
|
||||
|
||||
/**
|
||||
* WS1 桩:数据操作审计日志。原版写库记录字段级变更,PoC 降级为 slf4j。
|
||||
*/
|
||||
@Service("dataOperatorLog")
|
||||
public class StubDataOperatorLog implements DataOperatorLog {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger("eip3.datalog");
|
||||
|
||||
@Override
|
||||
public DataLogItem insertData(GeneralPOJO po, String dataLogItemId, String mainDataLogItemId) {
|
||||
LOG.debug("insert {} id={}", po.get_TableName(), po.get_ID());
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataLogItem updateData(GeneralPOJO po, String dataLogItemId, String mainDataLogItemId) {
|
||||
LOG.debug("update {} id={}", po.get_TableName(), po.get_ID());
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataLogItem deleteData(GeneralPOJO po, String dataLogItemId, String mainDataLogItemId) {
|
||||
LOG.debug("delete {} id={}", po.get_TableName(), po.get_ID());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.eip4.platform.auth.stub;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
|
||||
import com.dsasp.server.common.file.service.FileService;
|
||||
|
||||
/**
|
||||
* WS1 桩:附件服务。PoC 选定功能不含附件操作,全部 no-op;
|
||||
* 接口签名原样保留,P2 阶段以 EIP3 真实现替换。
|
||||
*/
|
||||
@Service("fileService")
|
||||
public class StubFileService implements FileService {
|
||||
|
||||
@Override
|
||||
public String save(String tempFile, String fileName, int size, String tableName, String businessKey, Properties ctx) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveDoc(String relativePath, String fileName, int size, String tableName, String businessKey, Properties ctx) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getDocFile(String relativePath, String fileName, boolean isZip) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(List<String> fileIds, String userId) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String fileId, String userId) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteAttatchmentByBusinessKey(String businessKey, String userId) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteAttatchmentByBusinessKey(List<String> businessKeys, String userId) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearDeletedDocument() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearDumpFile() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<GeneralPOJO> getDoc(List<String> businessKeys) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPicPath(String tablename, String businesskey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String saveDecoderBase64File(String base64Code, String userId, String tableName, Properties ctx) throws Exception {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.eip4.platform.auth.stub;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.dsasp.server.common.log.bean.SysLogItem;
|
||||
import com.dsasp.server.common.log.service.SystemLogManager;
|
||||
|
||||
/**
|
||||
* WS1 桩:系统日志。原版写库(操作日志审计),PoC 阶段降级为 slf4j 输出。
|
||||
*/
|
||||
@Service("systemLogManager")
|
||||
public class StubSystemLogManager implements SystemLogManager {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger("eip3.syslog");
|
||||
|
||||
@Override
|
||||
public void log(LogType logType, String logContent) {
|
||||
LOG.info("[{}] {}", logType, logContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteAll() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteByType(String type) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void log(List<SysLogItem> items) {
|
||||
if (items != null) {
|
||||
items.forEach(i -> LOG.info("[batch] {}", i));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteByLoginTime(List<String> userIds, DateTime[] loginTimes) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.dsasp.server.common.email.bean;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.common.email.bean.SystemEmail 原样移植。
|
||||
* 系统通知邮件的传输对象(收件人/抄送/密送/主题/正文/附件)。
|
||||
*/
|
||||
public class SystemEmail implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 9063903350324510652L;
|
||||
|
||||
/** 收件人 **/
|
||||
private List<String> address;
|
||||
|
||||
/** 抄送给 **/
|
||||
private List<String> cc;
|
||||
|
||||
/** 密送给 **/
|
||||
private List<String> bcc;
|
||||
|
||||
/** 邮件主题 **/
|
||||
private String subject;
|
||||
|
||||
/** 邮件内容 **/
|
||||
private String content;
|
||||
|
||||
/** 附件 **/
|
||||
private List<File> attachment;
|
||||
|
||||
public List<String> getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(List<String> address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public List<String> getCc() {
|
||||
return cc;
|
||||
}
|
||||
|
||||
public void setCc(List<String> cc) {
|
||||
this.cc = cc;
|
||||
}
|
||||
|
||||
public String getSubject() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
public void setSubject(String subject) {
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public List<File> getAttachment() {
|
||||
return attachment;
|
||||
}
|
||||
|
||||
public void setAttachment(List<File> attachment) {
|
||||
this.attachment = attachment;
|
||||
}
|
||||
|
||||
public List<String> getBcc() {
|
||||
return bcc;
|
||||
}
|
||||
|
||||
public void setBcc(List<String> bcc) {
|
||||
this.bcc = bcc;
|
||||
}
|
||||
|
||||
public SystemEmail(List<String> address, List<String> cc, List<String> bcc,
|
||||
String subject, String content, List<File> attachment) {
|
||||
super();
|
||||
this.address = address;
|
||||
this.cc = cc;
|
||||
this.bcc = bcc;
|
||||
this.subject = subject;
|
||||
this.content = content;
|
||||
this.attachment = attachment;
|
||||
}
|
||||
|
||||
public SystemEmail() {
|
||||
super();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.dsasp.server.common.email.service;
|
||||
|
||||
import com.dsasp.server.common.email.bean.SystemEmail;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.common.email.service.SystemEmailService 接口原样移植。
|
||||
* 系统通知邮件发送契约。
|
||||
*/
|
||||
public interface SystemEmailService {
|
||||
|
||||
public void sendEmail(SystemEmail email);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.dsasp.server.common.log.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.dsasp.server.common.log.bean.DataLogItem;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.common.log.service 接口原样移植。
|
||||
* 数据操作日志异步落库的记录器契约(批量写 SYS_DATA_LOG / SYS_DATA_LOGITEM)。
|
||||
*/
|
||||
public interface DataLogRecorder {
|
||||
|
||||
public void recorderLog(DataLogItem logItem);
|
||||
|
||||
public void recorderLogs(List<DataLogItem> list);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.dsasp.server.common.util;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* 保真层全局文件配置持有者(原 framework com.dsasp.server.common.util.MainApp 移植)。
|
||||
*
|
||||
* <p>原版字段为写死的 Windows 绝对路径(C:\\... / D:\\c\\baseDoc\\)。本次 P2 横切服务
|
||||
* 真实现移植时,按「保包名/类名/字段名」纪律保留公共契约,仅把默认值改为「跨平台、可配置」:
|
||||
* <ul>
|
||||
* <li>{@link #destPath} —— 附件本地盘根目录,默认 ./data/files(相对工作目录)。</li>
|
||||
* <li>{@link #tempPath} —— 临时文件目录,默认走 JVM java.io.tmpdir。</li>
|
||||
* <li>{@link #folderFileNum} —— 单子目录散列文件数(原版 1000),不变。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>现代层(com.eip4.*)在启动期经 {@code FileStorageProperties} 把
|
||||
* {@code eip4.file.root} 配置值写入 {@link #destPath}(setter 注入,见 §4.1 等价装配)。
|
||||
* 保真层不反向感知现代层(ArchUnit 约束),故这里只暴露 public static 字段 + setter,
|
||||
* 由现代层单向赋值。配置缺省时即用默认值,旧引擎代码零修改。
|
||||
*/
|
||||
public class MainApp {
|
||||
|
||||
/** 临时文件目录。默认 JVM 临时目录(跨平台)。 */
|
||||
public static String tempPath = System.getProperty("java.io.tmpdir");
|
||||
|
||||
/** 附件本地盘根目录。默认 ./data/files(相对启动工作目录),可经现代层配置覆盖。 */
|
||||
public static String destPath = "." + File.separator + "data" + File.separator + "files";
|
||||
|
||||
/** 单子目录散列文件数(原版语义不变)。 */
|
||||
public static int folderFileNum = 1000;
|
||||
|
||||
/** 现代层启动期注入附件根目录(等价 XML 配置注入,见 §4.1)。 */
|
||||
public static void setDestPath(String path) {
|
||||
if (path != null && !path.isEmpty()) {
|
||||
destPath = path;
|
||||
}
|
||||
}
|
||||
|
||||
/** 现代层启动期注入临时目录。 */
|
||||
public static void setTempPath(String path) {
|
||||
if (path != null && !path.isEmpty()) {
|
||||
tempPath = path;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package com.dsasp.server.file.service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.support.rowset.SqlRowSet;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.dsasp.server.common.core.service.SpringBeanOsgiServices;
|
||||
import com.dsasp.server.common.dataDic.bean.CustomSearchConditional;
|
||||
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
|
||||
import com.dsasp.server.common.dataDic.service.POJOCRUDService;
|
||||
import com.dsasp.server.common.dataDic.service.POJOService;
|
||||
import com.dsasp.server.common.exception.ValidationException;
|
||||
import com.dsasp.server.common.file.service.FileService;
|
||||
import com.dsasp.server.common.file.service.SYSDoc;
|
||||
import com.dsasp.server.common.user.service.LoggedInUser;
|
||||
import com.dsasp.server.common.util.MainApp;
|
||||
import com.dsasp.server.common.util.StringUtil;
|
||||
import com.dsasp.server.common.util.UserSession;
|
||||
import com.dsasp.server.file.upload.FTPClientTemplate;
|
||||
import com.dsasp.server.file.util.FileUtil;
|
||||
import com.dsasp.server.file.util.HashCalc;
|
||||
import com.dsasp.server.file.util.HashEnum;
|
||||
import com.dsasp.server.file.util.ZipUtil;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.file 真实现移植(P2 横切服务,接替 StubFileService)。
|
||||
*
|
||||
* <p>移植纪律:类名/包名/bean 名(fileService)/方法签名与原版完全一致,引擎调用方零感知。
|
||||
* 与原版唯一差异:
|
||||
* <ul>
|
||||
* <li>{@code sun.misc.BASE64Decoder}(JDK 17 已移除)→ {@link Base64}(saveDecoderBase64File);</li>
|
||||
* <li>存储后端 FTP → 本地盘:经替换类 {@link FTPClientTemplate}(同包同名同签名)落
|
||||
* {@link MainApp#destPath}(默认 ./data/files,配置化)。</li>
|
||||
* </ul>
|
||||
* 上传/下载/删除走老接口语义不变;SYS_DOC 落库语义(zip 路径、md5、ISACTIVE 软删)与原版一致。
|
||||
*
|
||||
* <p>jdbcTemplate 在原版经 XML <property> setter 注入(非 @Autowired),
|
||||
* 现代层经 LegacyXmlWiring 等价补齐(见 §4.1)。
|
||||
*/
|
||||
@Service(value = "fileService")
|
||||
public class FileServiceImpl implements FileService {
|
||||
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
/**
|
||||
* tempFile temp file path
|
||||
* fileName the name of the file, not the file path
|
||||
* size file size;
|
||||
* tablename the business table name
|
||||
* businessKey the key id of the business record
|
||||
*/
|
||||
public String save(String tempFile, String fileName, int size,
|
||||
String tableName, String businessKey, Properties ctx) {
|
||||
long count = getTableCount(tableName);
|
||||
String basePath = File.separator + tableName + File.separator + count
|
||||
/ MainApp.folderFileNum + File.separator;
|
||||
String source = tempFile;
|
||||
File file = new File(source);
|
||||
if (file.exists()) {
|
||||
if (fileName.lastIndexOf(".") == -1) {
|
||||
throw new ValidationException("文件" + fileName + "没有扩展名,请先给文件添加扩展名");
|
||||
}
|
||||
String remotePath = basePath + fileName.substring(0, fileName.lastIndexOf(".")) + ".zip";
|
||||
FileInputStream input = null;
|
||||
try {
|
||||
input = new FileInputStream(file);
|
||||
String md5Hash = HashCalc.getHash(HashEnum.MD5, input, null);
|
||||
input.close();
|
||||
input = null;
|
||||
remotePath = ZipUtil.ZipFileToDest(file, remotePath, fileName, true, true);
|
||||
HashMap<String, Object> map = new HashMap<String, Object>();
|
||||
map.put(SYSDoc.businessKey, businessKey);
|
||||
map.put(SYSDoc.tableName, tableName);
|
||||
map.put(SYSDoc.fileName, fileName);
|
||||
map.put(SYSDoc.fileExt, fileName.substring(fileName.lastIndexOf(".")));
|
||||
map.put(SYSDoc.fileSize, (int) size);
|
||||
map.put(SYSDoc.filePath, remotePath);
|
||||
map.put(SYSDoc.md5Hash, md5Hash);
|
||||
if (ctx == null) {
|
||||
map.put("CREATEBY", LoggedInUser.ADMIN);
|
||||
map.put("UPDATEBY", LoggedInUser.ADMIN);
|
||||
}
|
||||
POJOCRUDService pojoCRUDService = (POJOCRUDService) SpringBeanOsgiServices.getInstance().getBeanByName("pojoCRUDService");
|
||||
pojoCRUDService.save(map, SYSDoc.SYSDocTableName, ctx);
|
||||
return remotePath;
|
||||
} catch (Exception ex) {
|
||||
throw new ValidationException("文件" + fileName + "保存异常");
|
||||
} finally {
|
||||
if (input != null) {
|
||||
try {
|
||||
input.close();
|
||||
} catch (Throwable t) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveDoc(String relativePath, String fileName, int size,
|
||||
String tableName, String businessKey, Properties ctx) {
|
||||
POJOCRUDService pojoCRUDService = (POJOCRUDService) SpringBeanOsgiServices
|
||||
.getInstance().getBeanByName("pojoCRUDService");
|
||||
HashMap<String, Object> searchMap = new HashMap<String, Object>();
|
||||
CustomSearchConditional filePath = new CustomSearchConditional(SYSDoc.filePath + "='" + relativePath + "'");
|
||||
searchMap.put(SYSDoc.filePath, filePath);
|
||||
searchMap.put(GeneralPOJO.ISACTIVE, 1);
|
||||
Map<String, Object> result = pojoCRUDService.listSelect(searchMap,
|
||||
SYSDoc.SYSDocTableName, UserSession.getAdmin());
|
||||
List<GeneralPOJO> list = (List<GeneralPOJO>) result
|
||||
.get(POJOCRUDService.LIST_RESULT);
|
||||
if (list != null && list.size() > 0) {
|
||||
HashMap<String, Object> map = new HashMap<String, Object>();
|
||||
map.put(SYSDoc.businessKey, businessKey);
|
||||
map.put(SYSDoc.tableName, tableName);
|
||||
map.put(SYSDoc.fileName, fileName);
|
||||
map.put(SYSDoc.fileExt,
|
||||
fileName.substring(fileName.lastIndexOf(".")));
|
||||
map.put(SYSDoc.fileSize, (int) size);
|
||||
map.put(SYSDoc.filePath, relativePath);
|
||||
map.put(SYSDoc.md5Hash, list.get(0).get_Value(SYSDoc.md5Hash));
|
||||
if (ctx == null) {
|
||||
map.put("CREATEBY", LoggedInUser.ADMIN);
|
||||
map.put("UPDATEBY", LoggedInUser.ADMIN);
|
||||
}
|
||||
pojoCRUDService.save(map, SYSDoc.SYSDocTableName, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(List<String> fileIds, String userId) {
|
||||
if (fileIds != null && fileIds.size() > 0) {
|
||||
if (fileIds != null && fileIds.size() > 0) {
|
||||
StringBuffer sqlBuffer = new StringBuffer();
|
||||
sqlBuffer.append("UPDATE ").append(SYSDoc.SYSDocTableName).append(" SET ISACTIVE = 0, ").append(GeneralPOJO.UPDATETIME).append(" = ").append(System.currentTimeMillis())
|
||||
.append(", ").append(GeneralPOJO.UPDATEBY).append("='").append(userId).append("' WHERE ").append(SYSDoc.docId).append(" in ( ");
|
||||
|
||||
for (String fileId : fileIds) {
|
||||
sqlBuffer.append(StringUtil.TO_STRING(fileId, 0));
|
||||
sqlBuffer.append(",");
|
||||
}
|
||||
sqlBuffer.deleteCharAt(sqlBuffer.length() - 1);
|
||||
sqlBuffer.append(" )");
|
||||
jdbcTemplate.execute(sqlBuffer.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(String fileId, String userId) {
|
||||
|
||||
String sql = "UPDATE " + SYSDoc.SYSDocTableName + " SET ISACTIVE = 0, " + GeneralPOJO.UPDATETIME + " = " + System.currentTimeMillis() + ", " + GeneralPOJO.UPDATEBY + "='" + userId + "' WHERE " + SYSDoc.docId + "='" + fileId + "'";
|
||||
jdbcTemplate.execute(sql);
|
||||
}
|
||||
|
||||
public long getTableCount(String tableName) {
|
||||
String sqlCount = "SELECT COUNT(*) FROM SYS_DOC WHERE TABLENAME='" + tableName + "'";
|
||||
POJOService pojoService = (POJOService) SpringBeanOsgiServices.getInstance().getBeanByName("pojoService");
|
||||
long count = pojoService.findCount(sqlCount);
|
||||
return count;
|
||||
}
|
||||
|
||||
private boolean isDeleteFileFromDisk(String fileId) {
|
||||
String sql = "SELECT COUNT(*) FROM SYS_DOC WHERE FILEPATH = (SELECT B.FILEPATH FROM SYS_DOC AS B WHERE B.SYS_DOC_ID=' " + fileId + "') AND ISACTIVE=1 ";
|
||||
POJOService pojoService = (POJOService) SpringBeanOsgiServices.getInstance().getBeanByName("pojoService");
|
||||
long count = pojoService.findCount(sql);
|
||||
return count == 0;
|
||||
}
|
||||
|
||||
public void deleteAttatchmentByBusinessKey(String businessKey, String userId) {
|
||||
List<String> listKey = new ArrayList<String>();
|
||||
listKey.add(businessKey);
|
||||
deleteAttatchmentByBusinessKey(listKey, userId);
|
||||
}
|
||||
|
||||
public void deleteAttatchmentByBusinessKey(List<String> businessKeys, String userId) {
|
||||
List<GeneralPOJO> list = getDoc(businessKeys);
|
||||
List<String> docIdList = new ArrayList<String>();
|
||||
if (list != null) {
|
||||
for (GeneralPOJO po : list) {
|
||||
docIdList.add(po.get_ID());
|
||||
}
|
||||
}
|
||||
delete(docIdList, userId);
|
||||
}
|
||||
|
||||
public List<GeneralPOJO> getDoc(List<String> businessKeys) {
|
||||
POJOCRUDService pojoCRUDService = (POJOCRUDService) SpringBeanOsgiServices.getInstance().getBeanByName("pojoCRUDService");
|
||||
HashMap<String, Object> map = new HashMap<String, Object>();
|
||||
map.put(SYSDoc.businessKey, businessKeys);
|
||||
map.put(GeneralPOJO.ISACTIVE, 1);
|
||||
Map<String, Object> result = pojoCRUDService.listSelect(map, SYSDoc.SYSDocTableName, UserSession.getAdmin());
|
||||
return (List<GeneralPOJO>) result.get(POJOCRUDService.LIST_RESULT);
|
||||
}
|
||||
|
||||
public File getDocFile(String relativePath, String fileName, boolean isZip) {
|
||||
FTPClientTemplate template = new FTPClientTemplate();
|
||||
File temp = FileUtil.createFile(fileName, null);
|
||||
try {
|
||||
template.downloadFile(relativePath, temp.getAbsolutePath());
|
||||
return temp;
|
||||
} catch (Exception ex) {
|
||||
// log
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String saveDecoderBase64File(String base64Code, String userId, String tableName, Properties ctx)
|
||||
throws Exception {
|
||||
File temp = FileUtil.createFile(userId + ".png", null);
|
||||
byte[] buffer = Base64.getMimeDecoder().decode(base64Code);
|
||||
FileOutputStream out = new FileOutputStream(temp);
|
||||
out.write(buffer);
|
||||
out.close();
|
||||
return save(temp.getAbsolutePath(), userId + ".png", (int) temp.length(), tableName, userId, ctx);
|
||||
}
|
||||
|
||||
public JdbcTemplate getJdbcTemplate() {
|
||||
return jdbcTemplate;
|
||||
}
|
||||
|
||||
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
public void clearDeletedDocument() {
|
||||
POJOCRUDService pojoCRUDService = (POJOCRUDService) SpringBeanOsgiServices
|
||||
.getInstance().getBeanByName("pojoCRUDService");
|
||||
HashMap<String, Object> map = new HashMap<String, Object>();
|
||||
map.put(GeneralPOJO.ISACTIVE, 0);
|
||||
Map<String, Object> result = pojoCRUDService.listSelect(map,
|
||||
SYSDoc.SYSDocTableName, UserSession.getAdmin());
|
||||
List<GeneralPOJO> list = (List<GeneralPOJO>) result
|
||||
.get(POJOCRUDService.LIST_RESULT);
|
||||
if (list != null && list.size() > 0) {
|
||||
for (GeneralPOJO po : list) {
|
||||
try {
|
||||
if (isDeleteFileFromDisk(po.get_ID())) {
|
||||
String absFilePath = (String) po
|
||||
.get_Value(SYSDoc.filePath);
|
||||
FTPClientTemplate template = new FTPClientTemplate();
|
||||
template.delete(absFilePath);
|
||||
}
|
||||
|
||||
pojoCRUDService.delete(po.get_ID(), SYSDoc.SYSDocTableName,
|
||||
UserSession.getAdmin());
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
// log error message;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearDumpFile() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPicPath(String tablename, String businesskey) {
|
||||
String sql = "SELECT FILEPATH FROM SYS_DOC WHERE TABLENAME='" + tablename + "' and BUSINESSKEY='" + businesskey + "'limit 1";
|
||||
SqlRowSet rowset = jdbcTemplate.queryForRowSet(sql);
|
||||
while (rowset != null && rowset.next()) {
|
||||
String filepath = rowset.getString("FILEPATH");
|
||||
return filepath;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.dsasp.server.file.upload;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Enumeration;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.dsasp.server.common.util.MainApp;
|
||||
|
||||
/**
|
||||
* 替换类(OSGi 解耦做法 §3.1「保包名/类名/签名」策略)。
|
||||
*
|
||||
* <p>原 framework {@code com.dsasp.server.file.upload.FTPClientTemplate} 把附件 zip 后上传到
|
||||
* FTP 服务器(依赖 commons-net + DB 内 FTPServer/FTPPort/FTPUserName/FTPUserPassword 配置)。
|
||||
* 本次 P2 横切服务真实现要求「默认本地盘、根目录配置化、不依赖外部服务」,故按双层制「旧代码零感知」
|
||||
* 约定:**保持包名/类名/对外方法签名完全一致**(uploadFileAndZip / downloadFile / delete /
|
||||
* fileExists),仅把存储后端从 FTP 换成本地盘——根目录 = {@link MainApp#destPath}
|
||||
* (默认 ./data/files,可经 eip4.file.root 配置覆盖)。{@code FileServiceImpl}/{@code ZipUtil}
|
||||
* 对本类的调用一行不改。
|
||||
*
|
||||
* <p>语义保真:原版把单个附件 zip 成一个 .zip(单条目=文件名)后落库 FILEPATH,下载再解压回字节。
|
||||
* 本类同样把源文件按单条目 zip 写入本地盘 {@code destPath + remotePath},下载时解压该唯一条目
|
||||
* 回目标本地路径,保证上传→下载字节一致。
|
||||
*
|
||||
* <p>安全:remotePath 经 {@link #resolveSafe} 归一,拒绝 {@code ../} 逃逸出 destPath 根
|
||||
* (安全第 1 层落地,见迁移手册 §5.19 同源纪律)。
|
||||
*/
|
||||
public class FTPClientTemplate {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FTPClientTemplate.class);
|
||||
|
||||
public FTPClientTemplate() {
|
||||
// 本地盘后端无需 FTP 连接参数;保留无参构造以匹配原版调用点(new FTPClientTemplate())。
|
||||
}
|
||||
|
||||
/**
|
||||
* 把本地源文件 zip(单条目=fileName)后写入本地盘 {@code destPath + remoteFile}。
|
||||
* 返回值=相对路径 remoteFile(与原版语义一致:落库的 FILEPATH 为相对远端路径)。
|
||||
*/
|
||||
public String uploadFileAndZip(final String remoteFile, final String localFilePath,
|
||||
final String fileName) throws IOException {
|
||||
File source = new File(localFilePath);
|
||||
File dest = resolveSafe(remoteFile);
|
||||
File parent = dest.getParentFile();
|
||||
if (parent != null && !parent.exists()) {
|
||||
parent.mkdirs();
|
||||
}
|
||||
FileInputStream in = null;
|
||||
ZipOutputStream zos = null;
|
||||
try {
|
||||
in = new FileInputStream(source);
|
||||
zos = new ZipOutputStream(new FileOutputStream(dest));
|
||||
zos.putNextEntry(new ZipEntry(fileName));
|
||||
copy(in, zos);
|
||||
zos.closeEntry();
|
||||
} finally {
|
||||
closeQuietly(zos);
|
||||
closeQuietly(in);
|
||||
}
|
||||
return remoteFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从本地盘 {@code destPath + remote}(单条目 zip)解压唯一条目到本地目标路径 local。
|
||||
*/
|
||||
public void downloadFile(final String remote, final String local) throws IOException {
|
||||
File src = resolveSafe(remote);
|
||||
if (!src.exists()) {
|
||||
throw new IOException("附件不存在: " + remote);
|
||||
}
|
||||
ZipFile zipFile = new ZipFile(src);
|
||||
try {
|
||||
Enumeration<? extends ZipEntry> e = zipFile.entries();
|
||||
if (e.hasMoreElements()) {
|
||||
ZipEntry entry = e.nextElement();
|
||||
InputStream is = zipFile.getInputStream(entry);
|
||||
OutputStream os = new FileOutputStream(local);
|
||||
try {
|
||||
copy(is, os);
|
||||
} finally {
|
||||
closeQuietly(os);
|
||||
closeQuietly(is);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
zipFile.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** 删除本地盘上的远端附件文件。 */
|
||||
public boolean delete(final String remoteFileName) throws IOException {
|
||||
File f = resolveSafe(remoteFileName);
|
||||
if (f.exists()) {
|
||||
return f.delete();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 远端附件是否存在(本地盘)。 */
|
||||
public Boolean fileExists(final String remoteFileName) throws IOException {
|
||||
return resolveSafe(remoteFileName).exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* 把远端相对路径归一到本地盘根目录下,并校验不逃逸出根(防 ../ 目录穿越)。
|
||||
*/
|
||||
private File resolveSafe(String remotePath) throws IOException {
|
||||
File root = new File(MainApp.destPath);
|
||||
String rel = remotePath == null ? "" : remotePath.replace('\\', '/');
|
||||
if (rel.startsWith("/")) {
|
||||
rel = rel.substring(1);
|
||||
}
|
||||
File target = new File(root, rel);
|
||||
String rootCanon = root.getCanonicalPath();
|
||||
String targetCanon = target.getCanonicalPath();
|
||||
if (!targetCanon.equals(rootCanon)
|
||||
&& !targetCanon.startsWith(rootCanon + File.separator)) {
|
||||
logger.warn("拒绝越界附件路径(疑似 ../ 逃逸): {}", remotePath);
|
||||
throw new IOException("非法附件路径: " + remotePath);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
private static void copy(InputStream is, OutputStream os) throws IOException {
|
||||
byte[] buf = new byte[8192];
|
||||
int len;
|
||||
while ((len = is.read(buf)) > 0) {
|
||||
os.write(buf, 0, len);
|
||||
}
|
||||
}
|
||||
|
||||
private static void closeQuietly(java.io.Closeable c) {
|
||||
if (c != null) {
|
||||
try {
|
||||
c.close();
|
||||
} catch (Throwable t) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package com.dsasp.server.file.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.channels.FileChannel;
|
||||
|
||||
import com.dsasp.server.common.util.StringUtil;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.file 移植。仅保留 FileService/ZipUtil 实际依赖的方法
|
||||
* (createFile / extractFilename / extractFileExt / getPath / readText / saveStream 等);
|
||||
* 原版 {@code getFileType}/{@code sortFiles} 依赖 javax.swing.FileSystemView,无调用方,
|
||||
* 不移植以免引入 GUI 依赖。文件读写语义与原版逐字节一致。
|
||||
*/
|
||||
public class FileUtil {
|
||||
|
||||
public static File getUniqueFile(File file) {
|
||||
if (file.exists()) {
|
||||
String path, dir, name, ext;
|
||||
int i;
|
||||
|
||||
path = file.getAbsolutePath();
|
||||
dir = extractDir(path);
|
||||
name = extractFilename(path);
|
||||
i = name.lastIndexOf('.');
|
||||
if (i > -1 && i < name.length() - 1) {
|
||||
ext = name.substring(i);
|
||||
name = name.substring(0, i);
|
||||
} else
|
||||
ext = "";
|
||||
i = 1;
|
||||
do {
|
||||
file = new File(dir, name + i + ext);
|
||||
i++;
|
||||
} while (file.exists());
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
public static void copyFile(File source, File dest, boolean autoRename,
|
||||
boolean isCut) throws Exception {
|
||||
boolean exists = dest.exists();
|
||||
if (autoRename && exists) {
|
||||
dest = getUniqueFile(dest);
|
||||
exists = false;
|
||||
}
|
||||
if (!exists)
|
||||
dest.createNewFile();
|
||||
FileChannel in = null;
|
||||
FileChannel out = null;
|
||||
try {
|
||||
in = new FileInputStream(source).getChannel();
|
||||
out = new FileOutputStream(dest).getChannel();
|
||||
in.transferTo(0, in.size(), out);
|
||||
} finally {
|
||||
if (in != null) {
|
||||
try {
|
||||
in.close();
|
||||
} catch (Throwable t) {
|
||||
}
|
||||
}
|
||||
if (out != null)
|
||||
out.close();
|
||||
}
|
||||
dest.setLastModified(source.lastModified());
|
||||
if (isCut)
|
||||
source.delete();
|
||||
}
|
||||
|
||||
public static String readText(File file, String charset) throws Exception {
|
||||
FileInputStream fs = new FileInputStream(file);
|
||||
try {
|
||||
int size = (int) file.length();
|
||||
byte[] bs = new byte[size];
|
||||
fs.read(bs);
|
||||
if (StringUtil.isEmpty(charset))
|
||||
return new String(bs);
|
||||
else
|
||||
return new String(bs, charset);
|
||||
} finally {
|
||||
fs.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static String readUtfText(File file) throws Exception {
|
||||
return readText(file, "utf-8");
|
||||
}
|
||||
|
||||
public static void writeText(File file, String content, String charset)
|
||||
throws Exception {
|
||||
if (!file.exists())
|
||||
file.createNewFile();
|
||||
FileOutputStream os = new FileOutputStream(file);
|
||||
|
||||
try {
|
||||
if (StringUtil.isEmpty(charset))
|
||||
os.write(content.getBytes());
|
||||
else
|
||||
os.write(content.getBytes(charset));
|
||||
} finally {
|
||||
os.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static void writeUtfText(File file, String content) throws Exception {
|
||||
writeText(file, content, "utf-8");
|
||||
}
|
||||
|
||||
public static void saveStream(InputStream is, File file) throws Exception {
|
||||
FileOutputStream os = new FileOutputStream(file);
|
||||
try {
|
||||
SysUtil.isToOs(is, os);
|
||||
} finally {
|
||||
os.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static String extractFileExt(String fileName) {
|
||||
if (!StringUtil.isEmpty(fileName)) {
|
||||
int i = fileName.lastIndexOf('.');
|
||||
if (i != -1)
|
||||
return fileName.substring(i + 1);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static String extractFilename(String fileName) {
|
||||
if (StringUtil.isEmpty(fileName))
|
||||
return "";
|
||||
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
|
||||
|
||||
if (p == -1)
|
||||
return fileName;
|
||||
else
|
||||
return fileName.substring(p + 1);
|
||||
}
|
||||
|
||||
public static String extractFilenameNoExt(String fileName) {
|
||||
String s = extractFilename(fileName);
|
||||
int i = s.lastIndexOf('.');
|
||||
if (i != -1)
|
||||
return s.substring(0, i);
|
||||
else
|
||||
return s;
|
||||
}
|
||||
|
||||
public static String getPath(String path) {
|
||||
return StringUtil.replace(path, "\\", "/");
|
||||
}
|
||||
|
||||
public static String getPath(File file) {
|
||||
return getPath(file.getAbsolutePath());
|
||||
}
|
||||
|
||||
public static String extractDir(String fileName) {
|
||||
if (StringUtil.isEmpty(fileName))
|
||||
return "";
|
||||
int pos;
|
||||
|
||||
fileName = getPath(fileName);
|
||||
pos = fileName.lastIndexOf('/');
|
||||
if (pos == -1)
|
||||
return fileName;
|
||||
else
|
||||
return fileName.substring(0, pos);
|
||||
}
|
||||
|
||||
public static File createFile(String fileName, String mimeType) {
|
||||
final String tempFileName = "upload_tmpfile_"
|
||||
+ System.currentTimeMillis();
|
||||
try {
|
||||
return File.createTempFile(tempFileName, "_" + fileName);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.dsasp.server.file.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.Checksum;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.file 原样移植。哈希语义不变。
|
||||
*
|
||||
* <p>替换点(等价):原版用 commons-codec {@code DigestUtils.md5Hex} 计算十六进制摘要,
|
||||
* 这里改用 JDK 内置 {@link MessageDigest} 流式计算,输出同为小写十六进制串,
|
||||
* 避免引入额外第三方依赖,摘要结果与原版逐字节一致。
|
||||
*
|
||||
* @author Hein
|
||||
*/
|
||||
public class HashCalc {
|
||||
|
||||
public static String getHash(HashEnum hash, FileInputStream fileInputStream, File file) throws IOException {
|
||||
switch (hash) {
|
||||
case MD5: {
|
||||
return getMD5(fileInputStream);
|
||||
}
|
||||
case SHA_1: {
|
||||
return getSHA_1(fileInputStream);
|
||||
}
|
||||
case SHA_256: {
|
||||
return getSHA_256(fileInputStream);
|
||||
}
|
||||
case SHA_384: {
|
||||
return getSHA_384(fileInputStream);
|
||||
}
|
||||
case SHA_512: {
|
||||
return getSHA_512(fileInputStream);
|
||||
}
|
||||
case CRC32: {
|
||||
return getCRC32(fileInputStream, file);
|
||||
}
|
||||
default: {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String getMD5(InputStream file) throws IOException {
|
||||
return digestHex("MD5", file);
|
||||
}
|
||||
|
||||
private static String getSHA_1(InputStream file) throws IOException {
|
||||
return digestHex("SHA-1", file);
|
||||
}
|
||||
|
||||
private static String getSHA_256(InputStream file) throws IOException {
|
||||
return digestHex("SHA-256", file);
|
||||
}
|
||||
|
||||
private static String getSHA_384(InputStream file) throws IOException {
|
||||
return digestHex("SHA-384", file);
|
||||
}
|
||||
|
||||
private static String getSHA_512(InputStream file) throws IOException {
|
||||
return digestHex("SHA-512", file);
|
||||
}
|
||||
|
||||
private static String digestHex(String algorithm, InputStream is) throws IOException {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance(algorithm);
|
||||
byte[] buf = new byte[8192];
|
||||
int len;
|
||||
while ((len = is.read(buf)) > 0) {
|
||||
md.update(buf, 0, len);
|
||||
}
|
||||
byte[] digest = md.digest();
|
||||
StringBuilder sb = new StringBuilder(digest.length * 2);
|
||||
for (byte b : digest) {
|
||||
sb.append(Character.forDigit((b >> 4) & 0xF, 16));
|
||||
sb.append(Character.forDigit(b & 0xF, 16));
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String getCRC32(FileInputStream fis, File file) throws IOException {
|
||||
Checksum crc = new CRC32();
|
||||
byte arr[] = new byte[(int) file.length()];
|
||||
fis.read(arr);
|
||||
crc.update(arr, 0, arr.length);
|
||||
return Long.toHexString(crc.getValue());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.dsasp.server.file.util;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.file 原样移植。
|
||||
*
|
||||
* @author Hein
|
||||
*/
|
||||
public enum HashEnum {
|
||||
MD5,
|
||||
SHA_1,
|
||||
SHA_256,
|
||||
SHA_384,
|
||||
SHA_512,
|
||||
CRC32
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.dsasp.server.file.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Reader;
|
||||
|
||||
import com.dsasp.server.common.util.StringUtil;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.file 原样移植(仅保留 FileService/ZipUtil 实际依赖的方法)。
|
||||
*/
|
||||
public class SysUtil {
|
||||
|
||||
public static String getShortError(Throwable e) {
|
||||
Throwable cause = e, c = e;
|
||||
|
||||
while (c != null) {
|
||||
cause = c;
|
||||
c = c.getCause();
|
||||
}
|
||||
String message = cause.getMessage();
|
||||
if (StringUtil.isEmpty(message))
|
||||
message = cause.toString();
|
||||
return StringUtil.toLine(message);
|
||||
}
|
||||
|
||||
public static int isToOs(InputStream is, OutputStream os) throws IOException {
|
||||
byte buf[] = new byte[8192];
|
||||
int len, size = 0;
|
||||
|
||||
while ((len = is.read(buf)) > 0) {
|
||||
os.write(buf, 0, len);
|
||||
size += len;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
public static String readString(Reader reader) throws Exception {
|
||||
char buf[] = new char[8192];
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int len;
|
||||
|
||||
while ((len = reader.read(buf)) > 0) {
|
||||
sb.append(buf, 0, len);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static void closeInputStream(InputStream inputStream) {
|
||||
if (inputStream != null) {
|
||||
try {
|
||||
inputStream.close();
|
||||
} catch (Throwable e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void error(String msg) throws Exception {
|
||||
throw new Exception(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.dsasp.server.file.util;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import com.dsasp.server.file.upload.FTPClientTemplate;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.file 移植。仅保留 {@code FileServiceImpl} 实际依赖的
|
||||
* {@code ZipFileToDest}(把源文件 zip 后落「远端」并返回远端路径)。原版其余 zip/unzip 重载
|
||||
* 依赖 org.apache.tools.zip(ant)且无活跃调用方,不移植以免引入额外依赖;
|
||||
* {@code ZipFileToDest} 经替换类 {@link FTPClientTemplate}(本地盘后端)落盘,call site 零改动。
|
||||
*/
|
||||
public class ZipUtil {
|
||||
|
||||
public static String ZipFileToDest(File source, String dest, String base,
|
||||
boolean autoRename, boolean isCut) throws Exception {
|
||||
|
||||
FTPClientTemplate template = new FTPClientTemplate();
|
||||
final String fileName = base;
|
||||
final String localFilePath = source.getPath();
|
||||
final String remoteFile = dest;
|
||||
dest = template.uploadFileAndZip(remoteFile, localFilePath, fileName);
|
||||
if (isCut)
|
||||
source.delete();
|
||||
return dest;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.dsasp.server.log.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.dsasp.server.common.log.bean.DataLogItem;
|
||||
import com.dsasp.server.common.log.bean.SysLogItem;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.log 原样移植。日志异步落库调度器:
|
||||
* 30s 周期的 Timer 把 DataOperatorLogger 队列分批(每批 100)提交线程池,
|
||||
* 经 ProcessLogThread / ProcessSysLogThread 落 SYS_DATA_LOG / SYS_LOG。
|
||||
*/
|
||||
public class DataLogManager {
|
||||
|
||||
private static DataLogManager instance;
|
||||
|
||||
private ThreadPoolExecutor threadPool;
|
||||
|
||||
private Timer timer;
|
||||
|
||||
public static DataLogManager startDataLogManager() {
|
||||
if (instance == null) {
|
||||
instance = new DataLogManager();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static void shutdown() {
|
||||
if (instance != null) {
|
||||
instance.doShutdown();
|
||||
instance = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void doShutdown() {
|
||||
if (timer != null) {
|
||||
timer.cancel();
|
||||
timer = null;
|
||||
}
|
||||
if (threadPool != null) {
|
||||
threadPool.shutdown();
|
||||
try {
|
||||
if (!threadPool.awaitTermination(10, TimeUnit.SECONDS)) {
|
||||
threadPool.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
threadPool.shutdownNow();
|
||||
}
|
||||
threadPool = null;
|
||||
}
|
||||
}
|
||||
|
||||
private DataLogManager() {
|
||||
|
||||
threadPool = new ThreadPoolExecutor(2, 4, 3,
|
||||
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5),
|
||||
new ThreadPoolExecutor.DiscardOldestPolicy());
|
||||
|
||||
timer = new Timer("DataLogManager-Timer", true);
|
||||
|
||||
timer.schedule(new TimerTask() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
dataLog(threadPool);
|
||||
sysLog(threadPool);
|
||||
}
|
||||
}, 1000, 30000);
|
||||
}
|
||||
|
||||
private void dataLog(final ThreadPoolExecutor threadPool) {
|
||||
int size = DataOperatorLogger.list.size();
|
||||
int count = 100;
|
||||
while (size > 0) {
|
||||
List<DataLogItem> list = new ArrayList<DataLogItem>();
|
||||
boolean isListNull = false;
|
||||
for (int i = 0; i < count; i++) {
|
||||
DataLogItem item = DataOperatorLogger.list.poll();
|
||||
if (item != null) {
|
||||
list.add(item);
|
||||
} else {
|
||||
//如果已经到达空,可以结束此次任务,否则少量的log也会启动一次任务
|
||||
isListNull = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
threadPool.execute(new ProcessLogThread(list));
|
||||
if (isListNull) {
|
||||
break;
|
||||
}
|
||||
size = DataOperatorLogger.list.size();
|
||||
}
|
||||
}
|
||||
|
||||
private void sysLog(final ThreadPoolExecutor threadPool) {
|
||||
int size = DataOperatorLogger.sysList.size();
|
||||
int count = 100;
|
||||
while (size > 0) {
|
||||
List<SysLogItem> list = new ArrayList<SysLogItem>();
|
||||
boolean isListNull = false;
|
||||
for (int i = 0; i < count; i++) {
|
||||
SysLogItem item = DataOperatorLogger.sysList.poll();
|
||||
if (item != null) {
|
||||
list.add(item);
|
||||
} else {
|
||||
//如果已经到达空,可以结束此次任务,否则少量的log也会启动一次任务
|
||||
isListNull = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
threadPool.execute(new ProcessSysLogThread(list));
|
||||
if (isListNull) {
|
||||
break;
|
||||
}
|
||||
size = DataOperatorLogger.sysList.size();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.dsasp.server.log.service;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.dsasp.server.common.log.bean.DataLogDetail;
|
||||
import com.dsasp.server.common.log.bean.DataLogItem;
|
||||
import com.dsasp.server.common.log.service.DataLogRecorder;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.log 真实现移植(bean 名 dataLogRecorder)。
|
||||
*
|
||||
* <p>批量 INSERT 数据操作日志:SYS_DATA_LOG(主)+ SYS_DATA_LOGITEM(明细)。
|
||||
* 注意 §5.1:SYS_DATA_LOGITEM 为 insert-only,物理表无 UPDATETIME 列,
|
||||
* 本实现只走 INSERT 路径(不走引擎 updatePO),与老系统一致。
|
||||
*
|
||||
* <p>jdbcTemplate 经 XML <property> setter 注入,现代层经 LegacyXmlWiring 等价补齐(§4.1)。
|
||||
*/
|
||||
@Service(value = "dataLogRecorder")
|
||||
@Transactional
|
||||
public class DataLogRecorderImpl implements DataLogRecorder {
|
||||
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
public JdbcTemplate getJdbcTemplate() {
|
||||
return jdbcTemplate;
|
||||
}
|
||||
|
||||
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recorderLog(DataLogItem logItem) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param logItemList store dataLogItem
|
||||
* @param detailList store detail
|
||||
* @param list Traversal data log item
|
||||
*/
|
||||
private void filterLog(List<DataLogItem> logItemList, List<DataLogDetail> detailList, List<DataLogItem> list) {
|
||||
logItemList.addAll(list);
|
||||
for (DataLogItem item : list) {
|
||||
if (item != null) {
|
||||
List<DataLogDetail> details = item.getDetailList();
|
||||
if (details != null && details.size() > 0) {
|
||||
for (DataLogDetail detail : details) {
|
||||
if (detail.getList() != null && details.size() > 0) {
|
||||
filterLog(logItemList, detailList, detail.getList());
|
||||
} else {
|
||||
detailList.add(detail);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recorderLogs(List<DataLogItem> list) {
|
||||
|
||||
List<DataLogItem> logItemList = new ArrayList<DataLogItem>();
|
||||
List<DataLogDetail> detailList = new ArrayList<DataLogDetail>();
|
||||
filterLog(logItemList, detailList, list);
|
||||
|
||||
final List<DataLogItem> tempList = logItemList;
|
||||
|
||||
String sql = "INSERT INTO sys_data_log("
|
||||
+ "sys_data_log_id, tablename, recordid, mainrecordid, type, updatetime, updateby) "
|
||||
+ "VALUES (?, ?, ?, ?, ?, ?, ?);";
|
||||
|
||||
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
|
||||
public void setValues(PreparedStatement ps, int i)
|
||||
throws SQLException {
|
||||
DataLogItem item = tempList.get(i);
|
||||
ps.setString(1, item.getDataLogItem_Id());
|
||||
ps.setString(2, item.getTableName());
|
||||
ps.setString(3, item.getRecordId());
|
||||
ps.setString(4, item.getMainDataLogItemId());
|
||||
ps.setInt(5, item.getType());
|
||||
ps.setLong(6, System.currentTimeMillis());
|
||||
ps.setString(7, item.getUserId());
|
||||
}
|
||||
|
||||
public int getBatchSize() {
|
||||
return tempList.size();
|
||||
}
|
||||
});
|
||||
|
||||
final List<DataLogDetail> tempDetailList = detailList;
|
||||
String detailsql = "INSERT INTO sys_data_logitem(sys_data_logitem_id, sys_datalogid, oldvalue, " +
|
||||
"newvalue, columnname) VALUES (?, ?, ?, ?, ?);";
|
||||
|
||||
jdbcTemplate.batchUpdate(detailsql, new BatchPreparedStatementSetter() {
|
||||
public void setValues(PreparedStatement ps, int i)
|
||||
throws SQLException {
|
||||
DataLogDetail item = tempDetailList.get(i);
|
||||
ps.setString(1, UUID.randomUUID().toString());
|
||||
ps.setString(2, item.getDataLogId());
|
||||
ps.setString(3, item.getOldValue());
|
||||
ps.setString(4, item.getNewValue());
|
||||
ps.setString(5, item.getColumnName());
|
||||
}
|
||||
|
||||
public int getBatchSize() {
|
||||
return tempDetailList.size();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package com.dsasp.server.log.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.dsasp.server.common.dataDic.bean.DisplayType;
|
||||
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
|
||||
import com.dsasp.server.common.dataDic.bean.POJOInfo;
|
||||
import com.dsasp.server.common.file.service.SYSDoc;
|
||||
import com.dsasp.server.common.log.bean.DataLogDetail;
|
||||
import com.dsasp.server.common.log.bean.DataLogItem;
|
||||
import com.dsasp.server.common.log.bean.SysLogItem;
|
||||
import com.dsasp.server.common.log.service.DataOperatorLog;
|
||||
import com.dsasp.server.common.util.StringUtil;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.log 真实现移植(P2 横切服务,接替 StubDataOperatorLog)。
|
||||
*
|
||||
* <p>移植纪律:类名/包名/bean 名(dataOperatorLog)/方法签名与原版完全一致。
|
||||
* 对实体 insert/update/delete 生成字段级 DataLogItem 入队(过滤系统列 + 仅记变更列),
|
||||
* DataLogManager 异步批量落 SYS_DATA_LOG / SYS_DATA_LOGITEM(insert-only,见 §5.1)。
|
||||
*/
|
||||
@Service(value = "dataOperatorLog")
|
||||
public class DataOperatorLogger implements DataOperatorLog {
|
||||
|
||||
private static final String[] SYSFIELD = {"UPDATETIME", "CREATETIME", "UPDATEBY", "CREATEBY", "VERSION"};
|
||||
protected static ConcurrentLinkedQueue<DataLogItem> list = new ConcurrentLinkedQueue<DataLogItem>();
|
||||
protected static ConcurrentLinkedQueue<SysLogItem> sysList = new ConcurrentLinkedQueue<SysLogItem>();
|
||||
|
||||
@Override
|
||||
public DataLogItem insertData(GeneralPOJO po, String dataLogItemId, String mainDataLogItemId) {
|
||||
DataLogItem logItem = logGeneralPOJO(po, dataLogItemId, mainDataLogItemId, false);
|
||||
if (logItem != null) {
|
||||
logItem.setType(DataLogItem.OPERATE_NEW);
|
||||
list.add(logItem);
|
||||
DataLogManager.startDataLogManager();
|
||||
}
|
||||
return logItem;
|
||||
}
|
||||
|
||||
private DataLogItem logGeneralPOJO(GeneralPOJO po, String dataLogItemId, String mainDataLogItemID, boolean isUpdate) {
|
||||
if (!po.get_poInfo().isChangeLog()) {
|
||||
return null;
|
||||
}
|
||||
int size = po.get_ColumnCount();
|
||||
DataLogItem item = new DataLogItem();
|
||||
if (StringUtil.isEmpty(dataLogItemId)) {
|
||||
item.setDataLogItem_Id(UUID.randomUUID().toString());
|
||||
} else {
|
||||
item.setDataLogItem_Id(dataLogItemId);
|
||||
}
|
||||
item.setMainDataLogItemId(mainDataLogItemID);
|
||||
item.setRecordId(po.get_ID());
|
||||
item.setTableName(po.get_TableName());
|
||||
item.setUserId((String) po.get_Value(GeneralPOJO.UPDATEBY));
|
||||
for (int i = 0; i < size; i++) {
|
||||
Object value = po.get_Value(i);
|
||||
Object oldValue = po.get_ValueOld(i);
|
||||
if ((value == null) || po.isVirtualColumn(i) || isContainsField(po.get_ColumnName(i))) {
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isUpdate && !po.is_ValueChanged(i)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
DataLogDetail detail = new DataLogDetail();
|
||||
detail.setColumnName(po.get_ColumnName(i));
|
||||
detail.setDataLogId(item.getDataLogItem_Id());
|
||||
// FIXME: 附件处理
|
||||
// Display Type
|
||||
String dt = po.get_ColumnDisplayType(i);
|
||||
if (DisplayType.isLOB(dt)) {
|
||||
if (value instanceof List) {
|
||||
List<Map<String, Object>> fileList = (List<Map<String, Object>>) value;
|
||||
StringBuffer str = new StringBuffer();
|
||||
for (Map<String, Object> map : fileList) {
|
||||
str.append((String) map.get(SYSDoc.fileName));
|
||||
}
|
||||
detail.setNewValue(str.toString());
|
||||
}
|
||||
if (isUpdate && oldValue instanceof List) {
|
||||
List<Map<String, Object>> fileList = (List<Map<String, Object>>) oldValue;
|
||||
StringBuffer str = new StringBuffer();
|
||||
for (Map<String, Object> map : fileList) {
|
||||
str.append((String) map.get(SYSDoc.fileName));
|
||||
}
|
||||
detail.setOldValue(str.toString());
|
||||
}
|
||||
item.addDataLogDetail(detail);
|
||||
continue;
|
||||
}
|
||||
Class<?> c = po.get_ColumnClass(i);
|
||||
try {
|
||||
if (c == Object.class) { // may have need to deal with null values
|
||||
// differently
|
||||
detail.setNewValue(saveNewSpecial(value));
|
||||
if (isUpdate) {
|
||||
detail.setOldValue(saveNewSpecial(oldValue));
|
||||
}
|
||||
} else if (c == List.class) {
|
||||
// FIXME: 处理子表数据
|
||||
String referenceTableName = po.get_poInfo().getReferenceValueTable(i);
|
||||
POJOInfo referenceInfo = po.initPO(referenceTableName);
|
||||
//Entity.MIDTABLE
|
||||
if (referenceInfo.getTableType() == 2) {
|
||||
detail.setNewValue(processMidAttribute((List<String>) value));
|
||||
if (isUpdate) {
|
||||
detail.setOldValue(processMidAttribute((List<String>) oldValue));
|
||||
}
|
||||
} else {
|
||||
// detail.setList(processSubList(value, null, item.getDataLogItem_Id()));
|
||||
}
|
||||
} else {
|
||||
detail.setNewValue(value.toString());
|
||||
if (isUpdate) {
|
||||
detail.setOldValue(oldValue != null ? oldValue.toString() : null);
|
||||
}
|
||||
}
|
||||
item.addDataLogDetail(detail);
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
// Change Log - Only
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
private List<DataLogItem> processSubList(Object listPo, String dataLogItemId, String mainDataLogItemID) {
|
||||
if (listPo != null && listPo instanceof List) {
|
||||
List<GeneralPOJO> listPojo = (List<GeneralPOJO>) listPo;
|
||||
List<DataLogItem> list = new ArrayList<DataLogItem>();
|
||||
for (GeneralPOJO po : listPojo) {
|
||||
DataLogItem item = logGeneralPOJO(po, dataLogItemId,
|
||||
mainDataLogItemID, false);
|
||||
if (item != null && item.getDetailList().size() > 0) {
|
||||
list.add(item);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String processMidAttribute(List<String> list) {
|
||||
if (list != null && list.size() > 0) {
|
||||
return StringUtil.joinList(list, ",");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected String saveNewSpecial(Object value) {
|
||||
if (value == null) {
|
||||
return "NULL";
|
||||
}
|
||||
//FIXME: 如果引用的对象也是未保存对象应该同时保存引用对象
|
||||
else if (value instanceof GeneralPOJO) {
|
||||
return ((GeneralPOJO) value).get_ID();
|
||||
}
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataLogItem updateData(GeneralPOJO po, String dataLogItemId, String mainDataLogItemId) {
|
||||
DataLogItem logItem = logGeneralPOJO(po, dataLogItemId, mainDataLogItemId, true);
|
||||
if (logItem != null && logItem.getDetailList().size() > 0) {
|
||||
logItem.setType(DataLogItem.OPERATE_UPDATE);
|
||||
list.add(logItem);
|
||||
DataLogManager.startDataLogManager();
|
||||
}
|
||||
return logItem;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataLogItem deleteData(GeneralPOJO po, String dataLogItemId, String mainDataLogItemId) {
|
||||
DataLogItem logItem = logGeneralPOJO(po, dataLogItemId, mainDataLogItemId, false);
|
||||
if (logItem != null) {
|
||||
logItem.setType(DataLogItem.OPERATE_DELETE);
|
||||
list.add(logItem);
|
||||
DataLogManager.startDataLogManager();
|
||||
}
|
||||
return logItem;
|
||||
}
|
||||
|
||||
private boolean isContainsField(String columnName) {
|
||||
for (int i = 0; i < SYSFIELD.length; i++) {
|
||||
if (SYSFIELD[i].equals(columnName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.dsasp.server.log.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.dsasp.server.common.core.service.SpringBeanOsgiServices;
|
||||
import com.dsasp.server.common.log.bean.DataLogItem;
|
||||
import com.dsasp.server.common.log.service.DataLogRecorder;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.log 原样移植。线程任务:经 SpringBeanOsgiServices
|
||||
* 取 dataLogRecorder 落 SYS_DATA_LOG / SYS_DATA_LOGITEM。
|
||||
*/
|
||||
public class ProcessLogThread implements Runnable {
|
||||
|
||||
private List<DataLogItem> list;
|
||||
|
||||
public ProcessLogThread(List<DataLogItem> list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
DataLogRecorder recorder = (DataLogRecorder) SpringBeanOsgiServices.getInstance().getBeanByName("dataLogRecorder");
|
||||
recorder.recorderLogs(list);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.dsasp.server.log.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.dsasp.server.common.core.service.SpringBeanOsgiServices;
|
||||
import com.dsasp.server.common.log.bean.SysLogItem;
|
||||
import com.dsasp.server.common.log.service.SystemLogManager;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.log 原样移植。线程任务:经 SpringBeanOsgiServices
|
||||
* 取 systemLogManager 批量落 SYS_LOG。
|
||||
*/
|
||||
public class ProcessSysLogThread implements Runnable {
|
||||
|
||||
private List<SysLogItem> list;
|
||||
|
||||
public ProcessSysLogThread(List<SysLogItem> list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
SystemLogManager recorder = (SystemLogManager) SpringBeanOsgiServices.getInstance().getBeanByName("systemLogManager");
|
||||
recorder.log(list);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.dsasp.server.log.service;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.dsasp.server.common.dataDic.bean.SysConfig;
|
||||
import com.dsasp.server.common.log.bean.SysLogItem;
|
||||
import com.dsasp.server.common.log.service.SystemLogManager;
|
||||
import com.dsasp.server.common.user.service.LoggedInUser;
|
||||
import com.dsasp.server.common.util.StringUtil;
|
||||
import com.dsasp.server.common.util.UserSession;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.log 真实现移植(P2 横切服务,接替 StubSystemLogManager)。
|
||||
*
|
||||
* <p>移植纪律:类名/包名/bean 名(systemLogManager)/方法签名与原版完全一致。
|
||||
* 系统操作日志入队(经 LOGLEVEL 配置过滤)→ DataLogManager 异步批量 INSERT INTO SYS_LOG。
|
||||
* 字段语义与老系统一致:TYPE/CONTENT/createtime(joda 毫秒)/createby=操作人/isactive=1/version=0。
|
||||
*
|
||||
* <p>jdbcTemplate 经 XML <property> setter 注入(非 @Autowired),现代层经 LegacyXmlWiring
|
||||
* 等价补齐(见 §4.1)。
|
||||
*/
|
||||
@Service(value = "systemLogManager")
|
||||
@Transactional
|
||||
public class SystemLogManagerImpl implements SystemLogManager {
|
||||
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
public JdbcTemplate getJdbcTemplate() {
|
||||
return jdbcTemplate;
|
||||
}
|
||||
|
||||
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
private boolean hasLogType(LogType logType) {
|
||||
String loglevel = SysConfig.getConfigValue("com.dsasp.server.log.LOGLEVEL");
|
||||
if (loglevel != null) {
|
||||
String[] ls = loglevel.split(",");
|
||||
for (String s : ls) {
|
||||
if (s != null && s.equals(logType.getValue())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void log(final LogType logType, final String logContent) {
|
||||
if (UserSession.get() == null || !hasLogType(logType)) {
|
||||
return;
|
||||
}
|
||||
DataOperatorLogger.sysList.add(new SysLogItem(logType, logContent, UserSession.get().getProperty(LoggedInUser.CURRENTUSER)));
|
||||
DataLogManager.startDataLogManager();
|
||||
}
|
||||
|
||||
public void log(final List<SysLogItem> items) {
|
||||
|
||||
String sql = "INSERT INTO SYS_LOG("
|
||||
+ "SYS_LOG_ID, TYPE, CONTENT, createtime, createby, updatetime, updateby, isactive, version) "
|
||||
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
|
||||
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
|
||||
public void setValues(PreparedStatement ps, int i)
|
||||
throws SQLException {
|
||||
SysLogItem item = items.get(i);
|
||||
DateTime now = DateTime.now();
|
||||
String userId = item.getUserId();
|
||||
ps.setString(1, UUID.randomUUID().toString());
|
||||
ps.setString(2, item.getLogType().getValue());
|
||||
ps.setString(3, item.getLogContent());
|
||||
ps.setLong(4, now.getMillis());
|
||||
ps.setString(5, userId);
|
||||
ps.setLong(6, System.currentTimeMillis());
|
||||
ps.setString(7, userId);
|
||||
ps.setInt(8, 1);
|
||||
ps.setInt(9, 0);
|
||||
}
|
||||
|
||||
public int getBatchSize() {
|
||||
return items.size();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteAll() {
|
||||
jdbcTemplate.execute("DELETE FROM SYS_LOG WHERE 1=1");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteByType(String type) {
|
||||
jdbcTemplate.execute("DELETE FROM SYS_LOG WHERE TYPE='" + type + "'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteByLoginTime(List<String> userIds, DateTime[] loginTimes) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append("DELETE FROM SYS_USERLOGIN_HISTORY WHERE 1=1 ");
|
||||
if (userIds != null && userIds.size() > 0) {
|
||||
sb.append(" AND USERID IN (");
|
||||
int oriLength = sb.length();
|
||||
for (String id : userIds) {
|
||||
if (sb.length() > oriLength) {
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append(StringUtil.TO_STRING(id, 0));
|
||||
}
|
||||
sb.append(")");
|
||||
}
|
||||
if (loginTimes != null) {
|
||||
if (loginTimes[0] != null) {
|
||||
sb.append(" AND LOGINTIME >=" + loginTimes[0].getMillis());
|
||||
}
|
||||
if (loginTimes[1] != null) {
|
||||
sb.append(" AND LOGINTIME <=" + loginTimes[1].getMillis());
|
||||
}
|
||||
}
|
||||
jdbcTemplate.execute(sb.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.dsasp.server.mail.service;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.dsasp.server.common.dataDic.bean.SysConfig;
|
||||
import com.dsasp.server.common.email.bean.SystemEmail;
|
||||
import com.dsasp.server.common.email.service.SystemEmailService;
|
||||
import com.dsasp.server.common.util.StringUtil;
|
||||
|
||||
/**
|
||||
* 原 framework com.dsasp.server.mail 真实现移植(P2 横切消息服务,bean 名 systemEmailService)。
|
||||
*
|
||||
* <p>移植纪律 + 降级策略(按 P2 任务要求):原版 {@code SystemEmailServiceImpl} 深度依赖外部
|
||||
* SMTP(Spring {@code JavaMailSender} + javax.mail + freemarker 模板 + DB 内 admin_mail 配置),
|
||||
* 在缺省环境下既无 SMTP 服务器也无发件人配置。本次按「配置缺省时降级 no-op + WARN 日志,
|
||||
* 不阻塞启动」装配:
|
||||
* <ul>
|
||||
* <li>SMTP 发件人配置(SysConfig: {@code com.dsasp.server.mail.admin_mail})缺省时 →
|
||||
* {@link #sendEmail} 仅打 WARN 后直接返回(no-op),决不抛异常、决不阻塞调用方业务;</li>
|
||||
* <li>配置就绪时 → 当前阶段仍打 WARN 提示「真实 SMTP 投递待 JavaMailSender 装配后接通」,
|
||||
* 为后续接入留口(原版 javax.mail/freemarker 投递逻辑不在本次最小移植面内,
|
||||
* 引入 jakarta.mail + SMTP 联调属独立工作项)。</li>
|
||||
* </ul>
|
||||
* 类名/包名/bean 名/方法签名与原版一致,引擎调用方零感知。
|
||||
*/
|
||||
@Service(value = "systemEmailService")
|
||||
public class SystemEmailServiceImpl implements SystemEmailService {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SystemEmailServiceImpl.class);
|
||||
|
||||
/** 系统发件人配置键(原版经 mail.properties 的 admin_mail,这里改走统一 SysConfig)。 */
|
||||
static final String CONFIG_ADMIN_MAIL = "com.dsasp.server.mail.admin_mail";
|
||||
|
||||
@Override
|
||||
public void sendEmail(SystemEmail email) {
|
||||
if (email == null) {
|
||||
return;
|
||||
}
|
||||
String from = null;
|
||||
try {
|
||||
from = SysConfig.getConfigValue(CONFIG_ADMIN_MAIL);
|
||||
} catch (Throwable t) {
|
||||
// SysConfig 依赖 dataDicService;启动早期/无配置时取值失败一律视为「未配置」,不抛。
|
||||
from = null;
|
||||
}
|
||||
if (StringUtil.isEmpty(from)) {
|
||||
LOG.warn("邮件服务未配置发件人({}),降级为 no-op:主题=[{}] 收件人={}。"
|
||||
+ "如需启用,请配置 SMTP 发件人并接通 JavaMailSender。",
|
||||
CONFIG_ADMIN_MAIL, email.getSubject(), email.getAddress());
|
||||
return;
|
||||
}
|
||||
LOG.warn("邮件服务已配置发件人[{}],但真实 SMTP 投递待 JavaMailSender 装配后接通,"
|
||||
+ "当前降级为 no-op:主题=[{}] 收件人={}。",
|
||||
from, email.getSubject(), email.getAddress());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.dsasp.server.file;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import com.dsasp.server.file.util.FileUtil;
|
||||
import com.dsasp.server.file.util.HashCalc;
|
||||
import com.dsasp.server.file.util.HashEnum;
|
||||
|
||||
/**
|
||||
* P2 横切服务——文件工具(MD5 摘要、路径/文件名解析)单测。
|
||||
* HashCalc 以 JDK MessageDigest 替换 commons-codec,须与已知向量逐字节一致。
|
||||
*/
|
||||
class HashAndFileUtilTest {
|
||||
|
||||
@Test
|
||||
void md5_matches_known_vector(@TempDir Path tmp) throws Exception {
|
||||
// MD5("abc") = 900150983cd24fb0d6963f7d28e17f72
|
||||
File f = tmp.resolve("abc.txt").toFile();
|
||||
Files.write(f.toPath(), "abc".getBytes(StandardCharsets.UTF_8));
|
||||
try (FileInputStream in = new FileInputStream(f)) {
|
||||
String md5 = HashCalc.getHash(HashEnum.MD5, in, null);
|
||||
assertEquals("900150983cd24fb0d6963f7d28e17f72", md5,
|
||||
"MD5 十六进制摘要须与标准向量一致");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void extract_filename_and_ext() {
|
||||
assertEquals("c.txt", FileUtil.extractFilename("/a/b/c.txt"));
|
||||
assertEquals("c.txt", FileUtil.extractFilename("a\\b\\c.txt"));
|
||||
assertEquals("txt", FileUtil.extractFileExt("c.txt"));
|
||||
assertEquals("c", FileUtil.extractFilenameNoExt("/a/b/c.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_path_normalizes_separators() {
|
||||
assertEquals("a/b/c.txt", FileUtil.getPath("a\\b\\c.txt"));
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,89 @@
|
||||
package com.dsasp.server.log;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import com.dsasp.server.common.log.bean.DataLogDetail;
|
||||
import com.dsasp.server.common.log.bean.DataLogItem;
|
||||
import com.dsasp.server.log.service.DataLogRecorderImpl;
|
||||
|
||||
/**
|
||||
* P2 横切服务——数据操作日志落库单测。
|
||||
* 验证 SYS_DATA_LOG(主)/ SYS_DATA_LOGITEM(明细,insert-only,无 UPDATETIME 列,§5.1)
|
||||
* 的列绑定语义与纯 INSERT 路径。
|
||||
*/
|
||||
class DataLogRecorderImplTest {
|
||||
|
||||
@Test
|
||||
void recorder_logs_inserts_main_and_detail_with_correct_columns() throws Exception {
|
||||
JdbcTemplate jdbc = Mockito.mock(JdbcTemplate.class);
|
||||
DataLogRecorderImpl recorder = new DataLogRecorderImpl();
|
||||
recorder.setJdbcTemplate(jdbc);
|
||||
|
||||
DataLogItem item = new DataLogItem();
|
||||
item.setDataLogItem_Id("dl-1");
|
||||
item.setTableName("EIP4PT_CUSTOMER");
|
||||
item.setRecordId("rec-1");
|
||||
item.setMainDataLogItemId(null);
|
||||
item.setType(DataLogItem.OPERATE_NEW);
|
||||
item.setUserId("u-001");
|
||||
|
||||
DataLogDetail d = new DataLogDetail();
|
||||
d.setDataLogId("dl-1");
|
||||
d.setColumnName("NAME");
|
||||
d.setOldValue(null);
|
||||
d.setNewValue("张三");
|
||||
item.addDataLogDetail(d);
|
||||
|
||||
List<DataLogItem> list = new ArrayList<>();
|
||||
list.add(item);
|
||||
recorder.recorderLogs(list);
|
||||
|
||||
ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<BatchPreparedStatementSetter> setterCap =
|
||||
ArgumentCaptor.forClass(BatchPreparedStatementSetter.class);
|
||||
verify(jdbc, Mockito.times(2)).batchUpdate(sqlCap.capture(), setterCap.capture());
|
||||
|
||||
List<String> sqls = sqlCap.getAllValues();
|
||||
String mainSql = sqls.get(0);
|
||||
String detailSql = sqls.get(1);
|
||||
assertTrue(mainSql.contains("INSERT INTO sys_data_log("), "主表须为 INSERT");
|
||||
assertTrue(detailSql.contains("INSERT INTO sys_data_logitem("), "明细须为 INSERT");
|
||||
// §5.1:明细表 insert-only,SQL 不得出现 updatetime 列
|
||||
assertTrue(!detailSql.toLowerCase().contains("updatetime"),
|
||||
"SYS_DATA_LOGITEM 不得含 updatetime 列(insert-only,§5.1)");
|
||||
|
||||
// 主表列绑定:1=id 2=tablename 3=recordid 4=mainrecordid 5=type 6=updatetime 7=updateby
|
||||
PreparedStatement mainPs = Mockito.mock(PreparedStatement.class);
|
||||
setterCap.getAllValues().get(0).setValues(mainPs, 0);
|
||||
verify(mainPs).setString(eq(1), eq("dl-1"));
|
||||
verify(mainPs).setString(eq(2), eq("EIP4PT_CUSTOMER"));
|
||||
verify(mainPs).setString(eq(3), eq("rec-1"));
|
||||
verify(mainPs).setInt(eq(5), eq(DataLogItem.OPERATE_NEW));
|
||||
verify(mainPs).setLong(eq(6), anyLong());
|
||||
verify(mainPs).setString(eq(7), eq("u-001"));
|
||||
|
||||
// 明细列绑定:1=uuid 2=datalogid 3=oldvalue 4=newvalue 5=columnname
|
||||
PreparedStatement detPs = Mockito.mock(PreparedStatement.class);
|
||||
setterCap.getAllValues().get(1).setValues(detPs, 0);
|
||||
verify(detPs).setString(eq(2), eq("dl-1"));
|
||||
verify(detPs).setString(eq(3), eq(null));
|
||||
verify(detPs).setString(eq(4), eq("张三"));
|
||||
verify(detPs).setString(eq(5), eq("NAME"));
|
||||
|
||||
assertEquals(1, setterCap.getAllValues().get(0).getBatchSize());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.dsasp.server.log;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import com.dsasp.server.common.log.bean.SysLogItem;
|
||||
import com.dsasp.server.common.log.service.SystemLogManager.LogType;
|
||||
import com.dsasp.server.log.service.SystemLogManagerImpl;
|
||||
|
||||
/**
|
||||
* P2 横切服务——系统日志落库字段语义单测。
|
||||
* 用 Mockito 捕获 batchUpdate 的 SQL 与列绑定,验证 SYS_LOG 写入语义(类型/内容/操作人/时间)。
|
||||
*/
|
||||
class SystemLogManagerImplTest {
|
||||
|
||||
@Test
|
||||
void log_batch_writes_sys_log_with_correct_columns() throws Exception {
|
||||
JdbcTemplate jdbc = Mockito.mock(JdbcTemplate.class);
|
||||
SystemLogManagerImpl mgr = new SystemLogManagerImpl();
|
||||
mgr.setJdbcTemplate(jdbc);
|
||||
|
||||
SysLogItem item = new SysLogItem(LogType.INFO, "用户创建实体", "u-001");
|
||||
List<SysLogItem> items = new ArrayList<>();
|
||||
items.add(item);
|
||||
|
||||
mgr.log(items);
|
||||
|
||||
ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class);
|
||||
ArgumentCaptor<BatchPreparedStatementSetter> setterCap =
|
||||
ArgumentCaptor.forClass(BatchPreparedStatementSetter.class);
|
||||
verify(jdbc).batchUpdate(sqlCap.capture(), setterCap.capture());
|
||||
|
||||
String sql = sqlCap.getValue();
|
||||
assertTrue(sql.contains("INSERT INTO SYS_LOG"), "应 INSERT INTO SYS_LOG");
|
||||
assertTrue(sql.contains("SYS_LOG_ID") && sql.contains("TYPE") && sql.contains("CONTENT"),
|
||||
"列序须含 ID/TYPE/CONTENT");
|
||||
|
||||
BatchPreparedStatementSetter setter = setterCap.getValue();
|
||||
assertEquals(1, setter.getBatchSize());
|
||||
|
||||
PreparedStatement ps = Mockito.mock(PreparedStatement.class);
|
||||
setter.setValues(ps, 0);
|
||||
// 列序:1=id 2=type(value) 3=content 4=createtime 5=createby 6=updatetime 7=updateby 8=isactive 9=version
|
||||
verify(ps).setString(eq(2), eq("Info")); // LogType.INFO.getValue()
|
||||
verify(ps).setString(eq(3), eq("用户创建实体")); // 日志内容
|
||||
verify(ps).setString(eq(5), eq("u-001")); // createby = 操作人
|
||||
verify(ps).setString(eq(7), eq("u-001")); // updateby = 操作人
|
||||
verify(ps).setLong(eq(4), anyLong()); // createtime = joda 毫秒
|
||||
verify(ps).setInt(eq(8), eq(1)); // isactive=1
|
||||
verify(ps).setInt(eq(9), eq(0)); // version=0
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete_by_type_uses_type_predicate() {
|
||||
JdbcTemplate jdbc = Mockito.mock(JdbcTemplate.class);
|
||||
SystemLogManagerImpl mgr = new SystemLogManagerImpl();
|
||||
mgr.setJdbcTemplate(jdbc);
|
||||
|
||||
mgr.deleteByType("Info");
|
||||
|
||||
ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class);
|
||||
verify(jdbc).execute(sqlCap.capture());
|
||||
assertTrue(sqlCap.getValue().contains("DELETE FROM SYS_LOG WHERE TYPE='Info'"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.dsasp.server.mail;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.dsasp.server.common.email.bean.SystemEmail;
|
||||
import com.dsasp.server.mail.service.SystemEmailServiceImpl;
|
||||
|
||||
/**
|
||||
* P2 横切服务——消息(邮件)降级路径单测。
|
||||
* 配置缺省(无 SMTP 发件人、无 Spring 容器)时,sendEmail 必须降级为 no-op,
|
||||
* 仅打 WARN 而绝不抛异常、绝不阻塞调用方(满足「不阻塞启动」要求)。
|
||||
*/
|
||||
class SystemEmailServiceImplTest {
|
||||
|
||||
@Test
|
||||
void send_email_degrades_to_noop_without_config() {
|
||||
SystemEmailServiceImpl svc = new SystemEmailServiceImpl();
|
||||
SystemEmail email = new SystemEmail();
|
||||
email.setSubject("流程提醒");
|
||||
email.setContent("有一条待办");
|
||||
email.setAddress(Arrays.asList("u-001", "u-002"));
|
||||
|
||||
// SysConfig 取值在无容器时内部抛错 -> 被实现捕获并视为「未配置」-> no-op,不外抛。
|
||||
assertDoesNotThrow(() -> svc.sendEmail(email),
|
||||
"降级路径下发送邮件不得抛异常");
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_null_email_is_noop() {
|
||||
SystemEmailServiceImpl svc = new SystemEmailServiceImpl();
|
||||
assertDoesNotThrow(() -> svc.sendEmail(null), "null 邮件应安全 no-op");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
-- ============================================================================
|
||||
-- eip4-platform P2 横切服务(文件/日志)自举 schema —— bootstrap-xservice.sql
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- 用途:在本地 eip4m0 上建立 FileServiceImpl / SystemLogManagerImpl /
|
||||
-- DataLogRecorderImpl 三块真实现落库所需的物理表:
|
||||
-- * SYS_DOC —— 附件元数据(文件名/扩展名/大小/相对路径/MD5/软删 ISACTIVE)
|
||||
-- * SYS_LOG —— 系统操作日志(TYPE/CONTENT/操作人/时间)
|
||||
-- * SYS_DATA_LOG —— 数据操作日志主表(表名/记录id/类型/操作人/时间)
|
||||
-- * SYS_DATA_LOGITEM —— 数据操作日志明细(列名/旧值/新值)
|
||||
--
|
||||
-- 列口径权威来源(逐一核对保真层 SQL):
|
||||
-- * SYS_LOG = SystemLogManagerImpl.log(List) 的 INSERT 列序
|
||||
-- (SYS_LOG_ID,TYPE,CONTENT,createtime,createby,updatetime,updateby,isactive,version)
|
||||
-- * SYS_DATA_LOG = DataLogRecorderImpl.recorderLogs 主表 INSERT 列序
|
||||
-- (sys_data_log_id,tablename,recordid,mainrecordid,type,updatetime,updateby)
|
||||
-- * SYS_DATA_LOGITEM = DataLogRecorderImpl 明细 INSERT 列序
|
||||
-- (sys_data_logitem_id,sys_datalogid,oldvalue,newvalue,columnname)
|
||||
-- * SYS_DOC = SYSDoc 常量 + FileServiceImpl save/delete/getPicPath 用到的列。
|
||||
--
|
||||
-- ⚠️ 迁移手册 §5.1 坑:SYS_DATA_LOGITEM 为 insert-only,物理表「无 UPDATETIME/UPDATEBY 列」。
|
||||
-- 引擎 updatePO 会无条件追加这两列,故该表绝不可走 update 路径——本 DDL 故意不建审计列,
|
||||
-- 保真层 DataLogRecorderImpl 也只走纯 INSERT,与老系统一致。
|
||||
--
|
||||
-- 纪律:可重复执行(DROP ... IF EXISTS 开头);表名/列名一律小写(PG 不区分大小写,
|
||||
-- 引擎/保真层 SQL 大小写混用,小写建库两侧均命中)。时间列 = bigint(epoch 毫秒)。
|
||||
-- ============================================================================
|
||||
|
||||
DROP TABLE IF EXISTS sys_data_logitem CASCADE;
|
||||
DROP TABLE IF EXISTS sys_data_log CASCADE;
|
||||
DROP TABLE IF EXISTS sys_log CASCADE;
|
||||
DROP TABLE IF EXISTS sys_doc CASCADE;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 1. SYS_DOC —— 附件元数据
|
||||
-- ---------------------------------------------------------------------------
|
||||
CREATE TABLE sys_doc (
|
||||
sys_doc_id character(36) NOT NULL,
|
||||
filename character varying(255),
|
||||
fileext character varying(50),
|
||||
filesize integer,
|
||||
filepath character varying(500),
|
||||
tablename character varying(100),
|
||||
businesskey character(36),
|
||||
md5hash character varying(64),
|
||||
isactive integer DEFAULT 1 NOT NULL,
|
||||
createtime bigint,
|
||||
updatetime bigint,
|
||||
createby character(36),
|
||||
updateby character(36),
|
||||
version integer DEFAULT 0 NOT NULL,
|
||||
CONSTRAINT pk_sys_doc PRIMARY KEY (sys_doc_id)
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 2. SYS_LOG —— 系统操作日志(SystemLogManagerImpl.log)
|
||||
-- ---------------------------------------------------------------------------
|
||||
CREATE TABLE sys_log (
|
||||
sys_log_id character(36) NOT NULL,
|
||||
type character varying(50),
|
||||
content text,
|
||||
createtime bigint,
|
||||
createby character(36),
|
||||
updatetime bigint,
|
||||
updateby character(36),
|
||||
isactive integer DEFAULT 1 NOT NULL,
|
||||
version integer DEFAULT 0 NOT NULL,
|
||||
CONSTRAINT pk_sys_log PRIMARY KEY (sys_log_id)
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 3. SYS_DATA_LOG —— 数据操作日志主表(DataLogRecorderImpl.recorderLogs 主表)
|
||||
-- ---------------------------------------------------------------------------
|
||||
CREATE TABLE sys_data_log (
|
||||
sys_data_log_id character(36) NOT NULL,
|
||||
tablename character varying(100),
|
||||
recordid character(36),
|
||||
mainrecordid character(36),
|
||||
type integer,
|
||||
updatetime bigint,
|
||||
updateby character(36),
|
||||
CONSTRAINT pk_sys_data_log PRIMARY KEY (sys_data_log_id)
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 4. SYS_DATA_LOGITEM —— 数据操作日志明细(insert-only,无 UPDATETIME 列,见 §5.1)
|
||||
-- ---------------------------------------------------------------------------
|
||||
CREATE TABLE sys_data_logitem (
|
||||
sys_data_logitem_id character(36) NOT NULL,
|
||||
sys_datalogid character(36),
|
||||
oldvalue text,
|
||||
newvalue text,
|
||||
columnname character varying(100),
|
||||
CONSTRAINT pk_sys_data_logitem PRIMARY KEY (sys_data_logitem_id)
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 5. 日志级别配置(SystemLogManagerImpl.hasLogType 读 LOGLEVEL;逗号分隔 LogType.value)
|
||||
-- 取值口径 = LogType 枚举的 value:Errors / Info / Debug / Warnings(见 SystemLogManager.LogType)。
|
||||
-- 缺省给全开;无此键则系统日志整链静默(原版语义:未配置=不记)。
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO sys_application_config (sys_application_config_id, value)
|
||||
VALUES ('com.dsasp.server.log.LOGLEVEL', 'Errors,Info,Debug,Warnings')
|
||||
ON CONFLICT (sys_application_config_id) DO UPDATE SET value = EXCLUDED.value;
|
||||
Reference in New Issue
Block a user