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:
@@ -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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user