提交 28f56f11 authored 作者: kxjia's avatar kxjia

提交新文件

上级 39357ace
...@@ -164,6 +164,16 @@ public class Result<T> implements Serializable { ...@@ -164,6 +164,16 @@ public class Result<T> implements Serializable {
return this; return this;
} }
public static<T> Result<T> ok(T data,String strMsg) {
Result<T> r = new Result<T>();
r.setSuccess(true);
r.setMessage(strMsg);
r.setCode(CommonConstant.SC_OK_200);
r.setResult(data);
return r;
}
/** /**
* 无权限访问返回结果 * 无权限访问返回结果
*/ */
......
...@@ -43,7 +43,7 @@ public class SsrfFileTypeFilter { ...@@ -43,7 +43,7 @@ public class SsrfFileTypeFilter {
FILE_TYPE_WHITE_LIST.add("docx"); FILE_TYPE_WHITE_LIST.add("docx");
FILE_TYPE_WHITE_LIST.add("pdf"); FILE_TYPE_WHITE_LIST.add("pdf");
FILE_TYPE_WHITE_LIST.add("csv"); FILE_TYPE_WHITE_LIST.add("csv");
// FILE_TYPE_WHITE_LIST.add("xml"); FILE_TYPE_WHITE_LIST.add("xml");
FILE_TYPE_WHITE_LIST.add("md"); FILE_TYPE_WHITE_LIST.add("md");
//音视频文件 //音视频文件
......
package org.jeecg.modules.demo.cloud.controller; package org.jeecg.modules.demo.cloud.controller;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.demo.cloud.service.JcloudDemoService; import org.jeecg.modules.demo.cloud.service.JcloudDemoService;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
......
...@@ -17,6 +17,7 @@ import javax.xml.transform.stream.StreamResult; ...@@ -17,6 +17,7 @@ import javax.xml.transform.stream.StreamResult;
import org.jeecg.common.api.vo.Result; import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator; import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.stm.baosong.entity.TaskRecordVo;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskAllocService; import org.jeecg.modules.stm.baosong.service.IBaosongTaskAllocService;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskReviewService; import org.jeecg.modules.stm.baosong.service.IBaosongTaskReviewService;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskService; import org.jeecg.modules.stm.baosong.service.IBaosongTaskService;
...@@ -191,42 +192,11 @@ public class BaosongTaskReviewController extends JeecgController<BaosongTaskRevi ...@@ -191,42 +192,11 @@ public class BaosongTaskReviewController extends JeecgController<BaosongTaskRevi
return super.importExcel(request, response, BaosongTaskReview.class); return super.importExcel(request, response, BaosongTaskReview.class);
} }
@RequestMapping(value = "/downLoadTaskXml2")
public Result<String> downLoadTaskXml2(HttpServletRequest request, BaosongTaskReview taskReview) {
Integer tplId = taskReview.getTplid();
List<Map<String,Object>> list = baosongTaskReviewService.queryTaskRecordForXml(taskReview);
BaosongTpl baosongTpl = baosongTplService.getById(tplId);
try {
String rootPath = uploadpath;
String newFileName = getReportFilePath(taskReview);
String templateFileName = getTempleFilePath(taskReview.getTplid());
String templetPath = rootPath+ templateFileName;
String reportPath = rootPath + newFileName;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File xmlFile = new File(templetPath);
Document document = builder.parse(xmlFile);
document.getDocumentElement().normalize();
for(Map<String,Object> item:list) {
String code = item.get("code").toString();
String value = item.get("content").toString();
setNodeValue(document, code, value);
}
saveDocumentToFile(document, reportPath);
return Result.OK(newFileName);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@RequestMapping(value = "/downLoadTaskXml") @RequestMapping(value = "/downLoadTaskXml")
public Result<String> downLoadTaskXml(HttpServletRequest request, BaosongTaskReview taskReview) { public Result<String> downLoadTaskXml(HttpServletRequest request, BaosongTaskReview taskReview) {
Integer tplId = taskReview.getTplid(); Integer tplId = taskReview.getTplid();
Integer taskId = taskReview.getTaskid(); Integer taskId = taskReview.getTaskid();
List<Map<String,Object>> list = baosongTaskReviewService.queryTaskRecordForXml(taskReview); List<TaskRecordVo> list = baosongTaskReviewService.queryTaskRecordForXml(taskReview);
BaosongTpl baosongTpl = baosongTplService.getById(tplId); BaosongTpl baosongTpl = baosongTplService.getById(tplId);
BaosongTask baosongTask = baosongTaskService.getById(taskId); BaosongTask baosongTask = baosongTaskService.getById(taskId);
try { try {
......
...@@ -3,12 +3,14 @@ package org.jeecg.modules.stm.baosong.controller; ...@@ -3,12 +3,14 @@ package org.jeecg.modules.stm.baosong.controller;
import org.jeecg.common.util.DateUtils; import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.stm.baosong.entity.BaosongTask; import org.jeecg.modules.stm.baosong.entity.BaosongTask;
import org.jeecg.modules.stm.baosong.entity.BaosongTpl; import org.jeecg.modules.stm.baosong.entity.BaosongTpl;
import org.jeecg.modules.stm.baosong.entity.TaskRecordVo;
import org.jeecg.modules.stm.utils.DirectoryUtil; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Comment; import org.w3c.dom.Comment;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys; import javax.xml.transform.OutputKeys;
...@@ -18,191 +20,380 @@ import javax.xml.transform.dom.DOMSource; ...@@ -18,191 +20,380 @@ import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamResult;
import java.io.File; import java.io.File;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.HashMap; import java.util.*;
import java.util.List;
import java.util.Map;
public class CreateXmlFile { public class CreateXmlFile {
private BaosongTpl baosongTpl = null; private static final Logger logger = LoggerFactory.getLogger(CreateXmlFile.class);
private BaosongTask baosongTask = null;
private String fillUserNames = ""; // 常量定义
public CreateXmlFile(BaosongTpl baosongTpl, BaosongTask baosongTask,String fillUserNames) { private static final String DEFAULT_ENCODING = "UTF-8";
this.baosongTpl = baosongTpl; private static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd";
this.baosongTask = baosongTask; private static final String INDENT_AMOUNT_KEY = "{http://xml.apache.org/xslt}indent-amount";
this.fillUserNames = fillUserNames; private static final int DEFAULT_RIND_VALUE = 1;
}
public void createXml (List<Map<String,Object>> dataList, String filePath) { private final BaosongTpl baosongTpl;
private final BaosongTask baosongTask;
private final String fillUserNames;
public CreateXmlFile(BaosongTpl baosongTpl, BaosongTask baosongTask, String fillUserNames) {
this.baosongTpl = Objects.requireNonNull(baosongTpl, "baosongTpl cannot be null");
this.baosongTask = Objects.requireNonNull(baosongTask, "baosongTask cannot be null");
this.fillUserNames = fillUserNames != null ? fillUserNames : "";
}
/**
* 创建XML文件
*/
public boolean createXml(List<TaskRecordVo> dataList, String filePath) {
if (dataList == null || dataList.isEmpty()) {
logger.warn("数据列表为空,无法生成XML文件");
return false;
}
if (filePath == null || filePath.trim().isEmpty()) {
logger.error("文件路径不能为空");
return false;
}
try { try {
// 创建Document
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument(); Document doc = docBuilder.newDocument();
// 用于存储已经创建的节点
Map<String, Map<Integer, Element>> pcodeRindGroupMap = new HashMap<>();
String root = this.baosongTpl.getCode();
Map<String,String> codeMapPcode = getParentCodeMap(dataList);
Map<String,Map<String,Object>> codeMapObject = getParentObjectMap(dataList);
// 创建根元素 // 创建根元素
Comment rootComment = doc.createComment(baosongTpl.getNm()); Comment rootComment = doc.createComment(baosongTpl.getNm());
doc.appendChild(rootComment); doc.appendChild(rootComment);
root = root.replace("-","_");
Element rootElement = doc.createElement(root); String rootElementName = normalizeElementName(this.baosongTpl.getCode());
Element rootElement = doc.createElement(rootElementName);
doc.appendChild(rootElement); doc.appendChild(rootElement);
createFillUser(doc,rootElement);
for (int i = 0; i < dataList.size(); i++) {
Map<String,Object> tmpMap = dataList.get(i);
String pcode = tmpMap.get("pcode").toString();
String code = tmpMap.get("code").toString();
String content = tmpMap.get("content")==null?"":tmpMap.get("content").toString();
String strComment = tmpMap.get("title")==null?null:tmpMap.get("title").toString();
int rind = 1;
if(tmpMap.get("rind")!=null) {
rind = Integer.valueOf(tmpMap.get("rind").toString());
}
String parentPcode = codeMapPcode.get(pcode);
String currentPcode = pcode;
Element parentElement = null;
if(parentPcode==null||parentPcode.equals("null")) {
continue;
}
if(!parentPcode.equals(root)){
Map<String,Object> pObject = codeMapObject.get(pcode);
String strTitle = pObject.get("title").toString();
parentElement = getOrCreateParentElement(doc, rootElement, parentPcode,strTitle);
} else { // 添加固定信息节点
parentElement = rootElement; createFixedInfoNodes(doc, rootElement);
}
// 获取或创建 pcode 对应的分组
Map<Integer, Element> rindGroupMap = pcodeRindGroupMap.get(currentPcode);
if (rindGroupMap == null) {
rindGroupMap = new HashMap<>();
pcodeRindGroupMap.put(currentPcode, rindGroupMap);
}
// 获取或创建 rind 分组节点
Element rindGroupElement = rindGroupMap.get(rind);
if (rindGroupElement == null) {
Map<String,Object> pObject = codeMapObject.get(pcode);
String strTitle = pObject.get("title").toString();
Comment comment = doc.createComment(strTitle);
rindGroupElement = doc.createElement(currentPcode);
parentElement.appendChild(comment);
parentElement.appendChild(rindGroupElement);
rindGroupMap.put(rind, rindGroupElement);
}
if(strComment!=null) { // 重新组织数据结构 - 按层级关系构建树形结构
Comment comment = doc.createComment(strComment); Map<String, TaskRecordVo> codeToItemMap = new HashMap<>();
rindGroupElement.appendChild(comment); Map<String, List<TaskRecordVo>> pcodeToChildrenMap = new HashMap<>();
Set<String> allCodes = new HashSet<>();
// 第一步:构建映射关系
for (TaskRecordVo item : dataList) {
String code = item.getCode();
String pcode = item.getPcode();
if (code != null) {
codeToItemMap.put(code, item);
allCodes.add(code);
} }
// 创建当前节点
Element currentElement = doc.createElement(code);
currentElement.setTextContent(content);
rindGroupElement.appendChild(currentElement); if (pcode != null && !pcode.trim().isEmpty()) {
pcodeToChildrenMap.computeIfAbsent(pcode, k -> new ArrayList<>()).add(item);
}
} }
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
String dirPath = filePath.substring(0,filePath.lastIndexOf("/")); // 第二步:找出顶级节点(根节点的直接子节点)
Boolean pathIsEsixt = DirectoryUtil.ensureDirectoryExists(dirPath); // 从目标XML可以看到,顶级节点是像TB1001、TB1012等
if(pathIsEsixt) { // 我们需要根据数据推断哪些是顶级节点
StreamResult result = new StreamResult(new File(filePath)); List<String> topLevelNodes = findTopLevelNodes(dataList, allCodes, codeToItemMap);
transformer.transform(source, result);
System.out.println("XML 文件生成成功!"); logger.debug("找到的顶级节点: {}", topLevelNodes);
} else {
System.out.println("XML 生成失败"); // 第三步:为每个顶级节点创建XML结构
for (String topNodeCode : topLevelNodes) {
createNodeStructure(doc, rootElement, topNodeCode,
codeToItemMap, pcodeToChildrenMap, new HashSet<>());
} }
// 保存XML
return saveXmlToFile(doc, filePath);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.error("创建XML文件时发生错误", e);
return false;
} }
} }
// 获取或创建父节点 /**
private static Element getOrCreateParentElement(Document doc, Element rootElement, String parentPcode,String strComment) { * 找出顶级节点
// 假设父节点是直接挂在根节点下的 */
Element parentElement = (Element) rootElement.getElementsByTagName(parentPcode).item(0); private List<String> findTopLevelNodes(List<TaskRecordVo> dataList, Set<String> allCodes,
if (parentElement == null) { Map<String, TaskRecordVo> codeToItemMap) {
try { List<String> topNodes = new ArrayList<>();
if(strComment!=null) {
Comment comment = doc.createComment(strComment); // 收集所有可能的节点代码
rootElement.appendChild(comment); Set<String> allPcodes = new HashSet<>();
for (TaskRecordVo item : dataList) {
String pcode = item.getPcode();
if (pcode != null && !pcode.trim().isEmpty()) {
allPcodes.add(pcode);
} }
parentElement = doc.createElement(parentPcode);
rootElement.appendChild(parentElement);
} catch (Exception e) {
System.out.println(parentPcode);
} }
// 顶级节点特征:
// 1. 是一个pcode(有数据以此pcode为父节点)
// 2. 但不是其他节点的子节点(即这个pcode不作为code出现在数据中)
// 3. 或者这个pcode虽然有对应的item,但它的pcode是T_B_1或空
for (String pcode : allPcodes) {
if (!allCodes.contains(pcode)) {
// 这个pcode没有对应的item,说明它是顶级节点
topNodes.add(pcode);
} else {
// 这个pcode有对应的item,检查它的父节点
TaskRecordVo item = codeToItemMap.get(pcode);
if (item != null) {
String parentPcode = item.getPcode();
if (parentPcode == null || parentPcode.trim().isEmpty() ||
"T_B_1".equals(parentPcode)) {
topNodes.add(pcode);
} }
return parentElement;
} }
}
}
return topNodes;
}
/**
* 创建节点结构
*/
/**
* 创建节点结构
*/
private void createNodeStructure(Document doc, Element parentElement, String nodeCode,
Map<String, TaskRecordVo> codeToItemMap,
Map<String, List<TaskRecordVo>> pcodeToChildrenMap,
Set<String> processedNodes) {
private static Map<String,String> getParentCodeMap(List<Map<String,Object>> dataList) { if (processedNodes.contains(nodeCode)) {
Map<String,String> retMap = new HashMap<>(); return; // 防止循环
for(Map<String,Object> tmpMap:dataList) {
String code = tmpMap.get("code").toString();
String pcode = tmpMap.get("pcode").toString();
retMap.put(code,pcode);
} }
return retMap; processedNodes.add(nodeCode);
// 检查是否有子节点
boolean hasChildren = pcodeToChildrenMap.containsKey(nodeCode);
if (hasChildren) {
// 创建外层节点
Element outerElement = doc.createElement(nodeCode);
parentElement.appendChild(outerElement);
// 获取子节点并按rind分组
List<TaskRecordVo> children = pcodeToChildrenMap.get(nodeCode);
Map<Integer, List<TaskRecordVo>> childrenByRind = groupByRind(children, nodeCode);
// 检查分组数量
if (childrenByRind.size() == 1) {
// 只有一个分组,直接将节点添加到outerElement
for (Map.Entry<Integer, List<TaskRecordVo>> rindEntry : childrenByRind.entrySet()) {
List<TaskRecordVo> rindGroup = rindEntry.getValue();
// 处理这个分组中的每个子项
for (TaskRecordVo child : rindGroup) {
// 检查这个子项是否本身还有子项
String childCode = child.getCode();
if (pcodeToChildrenMap.containsKey(childCode)) {
// 这个子项还有子项,递归处理
createNodeStructure(doc, outerElement, childCode,
codeToItemMap, pcodeToChildrenMap, processedNodes);
} else {
// 这个子项是叶子节点,直接添加到outerElement
addDataItem(doc, outerElement, child);
} }
private static Map<String,Map<String,Object>> getParentObjectMap(List<Map<String,Object>> dataList) {
Map<String,Map<String,Object>> retMap = new HashMap<>();
for(Map<String,Object> tmpMap:dataList) {
String code = tmpMap.get("code").toString();
retMap.put(code,tmpMap);
} }
return retMap;
} }
} else {
// 多个分组,创建内层节点
for (Map.Entry<Integer, List<TaskRecordVo>> rindEntry : childrenByRind.entrySet()) {
List<TaskRecordVo> rindGroup = rindEntry.getValue();
//创建填写用户、填报时间、填报电话等信息 // 创建内层节点
private void createFillUser(Document doc, Element parentElement) { Element innerElement = doc.createElement(nodeCode);
outerElement.appendChild(innerElement);
Element fillinDept = doc.createElement("FILLIN_DEPT"); // 处理这个分组中的每个子项
fillinDept.setTextContent(this.baosongTask.getRespDepart()); for (TaskRecordVo child : rindGroup) {
parentElement.appendChild(fillinDept); // 检查这个子项是否本身还有子项
String childCode = child.getCode();
Element fillinDate = doc.createElement("FILLIN_DATE"); if (pcodeToChildrenMap.containsKey(childCode)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 这个子项还有子项,递归处理
String strDate = DateUtils.date2Str(this.baosongTask.getEnterDate(),sdf); createNodeStructure(doc, innerElement, childCode,
fillinDate.setTextContent(strDate); codeToItemMap, pcodeToChildrenMap, processedNodes);
parentElement.appendChild(fillinDate); } else {
// 这个子项是叶子节点,直接添加
addDataItem(doc, innerElement, child);
}
}
}
}
} else {
// 没有子节点,可能是数据项或空节点
TaskRecordVo item = codeToItemMap.get(nodeCode);
if (item != null) {
addDataItem(doc, parentElement, item);
}
}
}
/**
* 按rind分组
*/
private Map<Integer, List<TaskRecordVo>> groupByRind(List<TaskRecordVo> items, String pcode) {
Map<Integer, List<TaskRecordVo>> groups = new HashMap<>();
for (TaskRecordVo item : items) {
if (pcode.equals(item.getPcode())) {
int rind = getIntValue(item, DEFAULT_RIND_VALUE);
groups.computeIfAbsent(rind, k -> new ArrayList<>()).add(item);
}
}
return groups;
}
/**
* 添加数据项(带注释)
*/
private void addDataItem(Document doc, Element parentElement, TaskRecordVo item) {
String title = item.getTitle();
String code = item.getCode();
String content = item.getContent();
// 添加注释
if (title != null && !title.trim().isEmpty()) {
Comment comment = doc.createComment(title);
parentElement.appendChild(comment);
}
// 创建元素
Element element = doc.createElement(code);
element.setTextContent(content != null ? content : "");
parentElement.appendChild(element);
}
/**
* 创建固定信息节点
*/
private void createFixedInfoNodes(Document doc, Element parentElement) {
try {
String respDepart = this.baosongTask.getRespDepart() != null ?
this.baosongTask.getRespDepart() : "";
String enterDate = formatDate(this.baosongTask.getEnterDate(), DATE_FORMAT_PATTERN);
String enterTel = this.baosongTask.getEnterTel() != null ?
this.baosongTask.getEnterTel() : "";
String respUser = this.baosongTask.getRespUser() != null ?
this.baosongTask.getRespUser() : "";
String version = this.baosongTpl.getVersion() != null ?
this.baosongTpl.getVersion() : "";
addFixedNode(doc, parentElement, "FILLIN_DEPT", respDepart, "填报部门");
addFixedNode(doc, parentElement, "FILLIN_DATE", enterDate, "填报日期");
addFixedNode(doc, parentElement, "FILLIN_PERSON", this.fillUserNames, "填报人");
addFixedNode(doc, parentElement, "TELEPHONE", enterTel, "联系电话");
addFixedNode(doc, parentElement, "RES_PERSON", respUser, "负责人");
addFixedNode(doc, parentElement, "jiaoyanwei", "0", "校验位");
addFixedNode(doc, parentElement, "isempty", "yes", "是否为空");
String title = this.baosongTpl.getCode() + " " + this.baosongTpl.getNm();
addFixedNode(doc, parentElement, "itTitle", title, "模板标题");
addFixedNode(doc, parentElement, "itVersion", version, "模板版本");
} catch (Exception e) {
logger.error("创建固定信息节点时发生错误", e);
}
}
Element fillinPerson = doc.createElement("FILLIN_PERSON"); /**
fillinPerson.setTextContent(this.fillUserNames); * 添加固定节点
parentElement.appendChild(fillinPerson); */
private void addFixedNode(Document doc, Element parentElement,
String tagName, String textContent, String comment) {
if (comment != null && !comment.trim().isEmpty()) {
Comment commentNode = doc.createComment(comment);
parentElement.appendChild(commentNode);
}
Element element = doc.createElement(tagName);
element.setTextContent(textContent != null ? textContent : "");
parentElement.appendChild(element);
}
/**
* 保存XML到文件
*/
private boolean saveXmlToFile(Document doc, String filePath) {
try {
File file = new File(filePath);
File parentDir = file.getParentFile();
if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs()) {
logger.error("创建目录失败: {}", parentDir.getAbsolutePath());
return false;
}
Element telephone = doc.createElement("TELEPHONE"); TransformerFactory transformerFactory = TransformerFactory.newInstance();
telephone.setTextContent(this.baosongTask.getEnterTel()); transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
parentElement.appendChild(telephone); Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, DEFAULT_ENCODING);
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
transformer.setOutputProperty(INDENT_AMOUNT_KEY, "4");
Element resPerson = doc.createElement("RES_PERSON"); DOMSource source = new DOMSource(doc);
resPerson.setTextContent(this.baosongTask.getRespUser()); StreamResult result = new StreamResult(file);
parentElement.appendChild(resPerson); transformer.transform(source, result);
Element jiaoyanwei = doc.createElement("jiaoyanwei"); logger.info("XML文件生成成功: {}", filePath);
jiaoyanwei.setTextContent("0"); return true;
parentElement.appendChild(jiaoyanwei);
Element isempty = doc.createElement("isempty"); } catch (Exception e) {
isempty.setTextContent("yes"); logger.error("保存XML文件时发生错误: {}", filePath, e);
parentElement.appendChild(isempty); return false;
}
}
Element itTitle = doc.createElement("itTitle"); /**
itTitle.setTextContent(this.baosongTpl.getCode()+" "+ this.baosongTpl.getNm()); * 规范化元素名称
parentElement.appendChild(itTitle); */
private String normalizeElementName(String name) {
return name != null ? name.replace("-", "_") : "";
}
Element itVersion = doc.createElement("itVersion"); /**
itVersion.setTextContent(this.baosongTpl.getVersion()); * 格式化日期
parentElement.appendChild(itVersion); */
private String formatDate(Date date, String pattern) {
if (date == null) {
return "";
}
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return DateUtils.date2Str(date, sdf);
} catch (Exception e) {
logger.warn("日期格式化失败", e);
return "";
}
}
/**
* 获取整数值
*/
private int getIntValue(TaskRecordVo taskRecordVo, int defaultValue) {
try {
Object value = taskRecordVo.getRind();
if (value == null) {
return defaultValue;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
logger.warn("解析rind值失败,使用默认值: {}", defaultValue);
return defaultValue;
}
} }
} }
\ No newline at end of file
package org.jeecg.modules.stm.baosong.entity;
import lombok.Data;
import java.io.Serializable;
/**
* @Description: 填报记录
* @Author: jeecg-boot
* @Date: 2024-12-17
* @Version: V1.0
*/
@Data
public class TaskRecordVo implements Serializable {
private static final long serialVersionUID = 1L;
private java.lang.Integer tplid;
private java.lang.Integer taskid;
private java.lang.Integer itemid;
private java.lang.Integer rind;
private java.lang.String content;
private java.lang.String pcode;
private java.lang.String code;
private java.lang.String title;
}
...@@ -6,6 +6,7 @@ import java.util.Map; ...@@ -6,6 +6,7 @@ import java.util.Map;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import org.jeecg.modules.stm.baosong.entity.BaosongTaskReview; import org.jeecg.modules.stm.baosong.entity.BaosongTaskReview;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.jeecg.modules.stm.baosong.entity.TaskRecordVo;
/** /**
* @Description: 内容检查 * @Description: 内容检查
...@@ -15,5 +16,5 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; ...@@ -15,5 +16,5 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
*/ */
public interface BaosongTaskReviewMapper extends BaseMapper<BaosongTaskReview> { public interface BaosongTaskReviewMapper extends BaseMapper<BaosongTaskReview> {
List<Map<String,Object>> queryTaskReview(@Param("query") BaosongTaskReview taskReview); List<Map<String,Object>> queryTaskReview(@Param("query") BaosongTaskReview taskReview);
List<Map<String,Object>> queryTaskRecordForXml(@Param("query") BaosongTaskReview taskReview); List<TaskRecordVo> queryTaskRecordForXml(@Param("query") BaosongTaskReview taskReview);
} }
...@@ -2,6 +2,7 @@ package org.jeecg.modules.stm.baosong.service; ...@@ -2,6 +2,7 @@ package org.jeecg.modules.stm.baosong.service;
import org.jeecg.modules.stm.baosong.entity.BaosongTaskReview; import org.jeecg.modules.stm.baosong.entity.BaosongTaskReview;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.modules.stm.baosong.entity.TaskRecordVo;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -14,5 +15,5 @@ import java.util.Map; ...@@ -14,5 +15,5 @@ import java.util.Map;
*/ */
public interface IBaosongTaskReviewService extends IService<BaosongTaskReview> { public interface IBaosongTaskReviewService extends IService<BaosongTaskReview> {
List<Map<String,Object>> queryTaskReview(BaosongTaskReview taskReview); List<Map<String,Object>> queryTaskReview(BaosongTaskReview taskReview);
List<Map<String,Object>> queryTaskRecordForXml(BaosongTaskReview taskReview); List<TaskRecordVo> queryTaskRecordForXml(BaosongTaskReview taskReview);
} }
package org.jeecg.modules.stm.baosong.service.impl; package org.jeecg.modules.stm.baosong.service.impl;
import org.jeecg.modules.stm.baosong.entity.BaosongTaskReview; import org.jeecg.modules.stm.baosong.entity.BaosongTaskReview;
import org.jeecg.modules.stm.baosong.entity.TaskRecordVo;
import org.jeecg.modules.stm.baosong.mapper.BaosongTaskReviewMapper; import org.jeecg.modules.stm.baosong.mapper.BaosongTaskReviewMapper;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskReviewService; import org.jeecg.modules.stm.baosong.service.IBaosongTaskReviewService;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -25,7 +26,7 @@ public class BaosongTaskReviewServiceImpl extends ServiceImpl<BaosongTaskReviewM ...@@ -25,7 +26,7 @@ public class BaosongTaskReviewServiceImpl extends ServiceImpl<BaosongTaskReviewM
} }
@Override @Override
public List<Map<String,Object>> queryTaskRecordForXml(BaosongTaskReview taskReview){ public List<TaskRecordVo> queryTaskRecordForXml(BaosongTaskReview taskReview){
return this.baseMapper.queryTaskRecordForXml(taskReview); return this.baseMapper.queryTaskRecordForXml(taskReview);
} }
} }
package org.jeecg.modules.stm.utils;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Set;
/**
* 目录工具类 - 提供目录检查、创建、管理等功能
* @author System
* @version 1.0
*/
public class DirectoryUtil {
/**
* 私有构造方法,防止实例化
*/
private DirectoryUtil() {
throw new IllegalStateException("工具类,无需实例化");
}
// 系统属性常量
private static final String OS_NAME = System.getProperty("os.name").toLowerCase();
private static final boolean IS_WINDOWS = OS_NAME.contains("win");
private static final String TEMP_DIR = System.getProperty("java.io.tmpdir");
private static final String USER_HOME = System.getProperty("user.home");
/**
* 检查目录是否存在,不存在则创建(基础方法)
* @param directoryPath 目录路径
* @return 如果目录存在或创建成功返回true,否则返回false
*/
public static boolean ensureDirectoryExists(String directoryPath) {
if (directoryPath == null || directoryPath.trim().isEmpty()) {
System.err.println("[DirectoryUtil] 目录路径为空!");
return false;
}
try {
// 规范化路径
String normalizedPath = normalizePath(directoryPath);
// 创建File对象
File directory = new File(normalizedPath);
// 检查是否是文件而不是目录
if (directory.exists() && !directory.isDirectory()) {
System.err.println("[DirectoryUtil] 路径已存在但不是目录:" + normalizedPath);
return false;
}
// 如果目录不存在,尝试创建
if (!directory.exists()) {
System.out.println("[DirectoryUtil] 目录不存在,尝试创建:" + normalizedPath);
// 使用mkdirs()创建所有不存在的父目录
boolean created = directory.mkdirs();
if (created) {
System.out.println("[DirectoryUtil] 目录创建成功:" + normalizedPath);
// 设置目录权限(非Windows系统)
if (!IS_WINDOWS) {
setDirectoryPermissions(Paths.get(normalizedPath));
}
return true;
} else {
System.err.println("[DirectoryUtil] 目录创建失败:" + normalizedPath);
return false;
}
} else {
// 目录已存在
System.out.println("[DirectoryUtil] 目录已存在:" + normalizedPath);
return true;
}
} catch (SecurityException e) {
System.err.println("[DirectoryUtil] 安全异常:没有创建目录的权限 - " + directoryPath);
e.printStackTrace();
return false;
} catch (Exception e) {
System.err.println("[DirectoryUtil] 创建目录时发生异常:" + directoryPath);
e.printStackTrace();
return false;
}
}
/**
* 检查文件所在的目录是否存在,不存在则创建
* @param filePath 文件完整路径
* @return 如果目录存在或创建成功返回true,否则返回false
*/
public static boolean ensureFileDirectoryExists(String filePath) {
if (filePath == null || filePath.trim().isEmpty()) {
System.err.println("[DirectoryUtil] 文件路径为空!");
return false;
}
try {
File file = new File(filePath);
File parentDir = file.getParentFile();
if (parentDir == null) {
System.err.println("[DirectoryUtil] 无法获取文件的父目录:" + filePath);
return false;
}
return ensureDirectoryExists(parentDir.getAbsolutePath());
} catch (Exception e) {
System.err.println("[DirectoryUtil] 检查文件目录时发生异常:" + filePath);
e.printStackTrace();
return false;
}
}
/**
* 创建目录(使用NIO API,支持更好的错误处理)
* @param path 目录路径
* @return 如果目录存在或创建成功返回true,否则返回false
*/
public static boolean createDirectory(String path) {
if (path == null || path.trim().isEmpty()) {
return false;
}
try {
// 规范化路径
String normalizedPath = normalizePath(path);
Path dirPath = Paths.get(normalizedPath);
// 如果目录已存在,直接返回true
if (Files.exists(dirPath)) {
if (Files.isDirectory(dirPath)) {
return true;
} else {
System.err.println("[DirectoryUtil] 路径已存在但不是目录:" + normalizedPath);
return false;
}
}
// 创建目录(包含所有父目录)
Files.createDirectories(dirPath);
// 在非Windows系统上设置目录权限
if (!IS_WINDOWS) {
setDirectoryPermissions(dirPath);
}
System.out.println("[DirectoryUtil] 目录创建成功:" + dirPath.toAbsolutePath());
return true;
} catch (Exception e) {
System.err.println("[DirectoryUtil] 创建目录失败:" + path + " - " + e.getMessage());
return false;
}
}
/**
* 设置目录权限(Unix/Linux系统)
* @param path 目录路径
* @throws Exception 设置权限异常
*/
private static void setDirectoryPermissions(Path path) throws Exception {
if (IS_WINDOWS) {
return; // Windows系统不需要设置POSIX权限
}
Set<PosixFilePermission> perms = new HashSet<>();
// 所有者权限
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OWNER_EXECUTE);
// 组权限
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_EXECUTE);
// 其他用户权限
perms.add(PosixFilePermission.OTHERS_READ);
perms.add(PosixFilePermission.OTHERS_EXECUTE);
Files.setPosixFilePermissions(path, perms);
}
/**
* 规范化路径(处理不同操作系统的路径分隔符)
* @param path 原始路径
* @return 规范化后的路径
*/
public static String normalizePath(String path) {
if (path == null) {
return "";
}
String normalized = path.trim();
// 统一使用正斜杠
normalized = normalized.replace("\\", "/");
// 移除多余的分隔符
normalized = normalized.replaceAll("/+", "/");
return normalized;
}
/**
* 获取有效的目录路径(确保以分隔符结尾)
* @param path 目录路径
* @return 有效的目录路径
*/
public static String getValidDirectoryPath(String path) {
if (path == null || path.trim().isEmpty()) {
return "";
}
String normalized = normalizePath(path);
// 确保以分隔符结尾
if (!normalized.endsWith("/")) {
normalized += "/";
}
return normalized;
}
/**
* 清理目录名称中的非法字符
* @param name 目录名称
* @return 清理后的目录名称
*/
public static String sanitizeDirectoryName(String name) {
if (name == null) {
return "";
}
// 移除Windows和Unix中的非法字符
String sanitized = name.replaceAll("[\\\\/:*?\"<>|]", "_");
// 移除首尾空格和点号
sanitized = sanitized.trim();
while (sanitized.endsWith(".")) {
sanitized = sanitized.substring(0, sanitized.length() - 1);
}
return sanitized;
}
/**
* 获取临时目录路径
* @return 临时目录路径
*/
public static String getTempDirectory() {
return getValidDirectoryPath(TEMP_DIR);
}
/**
* 获取用户主目录路径
* @return 用户主目录路径
*/
public static String getUserHomeDirectory() {
return getValidDirectoryPath(USER_HOME);
}
/**
* 检查并创建多个目录
* @param paths 目录路径数组
* @return 所有目录都创建成功返回true,否则返回false
*/
public static boolean ensureDirectoriesExist(String... paths) {
boolean allSuccess = true;
for (String path : paths) {
if (!ensureDirectoryExists(path)) {
allSuccess = false;
System.err.println("[DirectoryUtil] 目录创建失败:" + path);
}
}
return allSuccess;
}
/**
* 检查目录是否可写
* @param directoryPath 目录路径
* @return 如果目录可写返回true,否则返回false
*/
public static boolean isDirectoryWritable(String directoryPath) {
if (directoryPath == null || directoryPath.trim().isEmpty()) {
return false;
}
try {
File dir = new File(normalizePath(directoryPath));
if (!dir.exists() || !dir.isDirectory()) {
return false;
}
// 创建一个临时文件测试写入权限
File testFile = new File(dir, ".write_test_" + System.currentTimeMillis());
if (testFile.createNewFile()) {
testFile.delete();
return true;
}
return false;
} catch (Exception e) {
System.err.println("[DirectoryUtil] 检查目录可写性时发生异常:" + directoryPath);
return false;
}
}
/**
* 获取目录大小(递归计算)
* @param directoryPath 目录路径
* @return 目录大小(字节)
*/
public static long getDirectorySize(String directoryPath) {
long size = 0;
try {
File dir = new File(normalizePath(directoryPath));
if (!dir.exists() || !dir.isDirectory()) {
return 0;
}
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
size += file.length();
} else if (file.isDirectory()) {
size += getDirectorySize(file.getAbsolutePath());
}
}
}
} catch (SecurityException e) {
System.err.println("[DirectoryUtil] 没有访问目录的权限:" + directoryPath);
} catch (Exception e) {
System.err.println("[DirectoryUtil] 计算目录大小时发生异常:" + directoryPath);
}
return size;
}
/**
* 格式化目录大小
* @param size 字节数
* @return 格式化后的字符串
*/
public static String formatSize(long size) {
if (size < 1024) {
return size + " B";
} else if (size < 1024 * 1024) {
return String.format("%.2f KB", size / 1024.0);
} else if (size < 1024 * 1024 * 1024) {
return String.format("%.2f MB", size / (1024.0 * 1024));
} else {
return String.format("%.2f GB", size / (1024.0 * 1024 * 1024));
}
}
/**
* 检查目录是否为空
* @param directoryPath 目录路径
* @return 如果目录为空或不存在返回true,否则返回false
*/
public static boolean isDirectoryEmpty(String directoryPath) {
try {
File dir = new File(normalizePath(directoryPath));
if (!dir.exists() || !dir.isDirectory()) {
return true;
}
String[] files = dir.list();
return files == null || files.length == 0;
} catch (SecurityException e) {
System.err.println("[DirectoryUtil] 没有访问目录的权限:" + directoryPath);
return true;
} catch (Exception e) {
System.err.println("[DirectoryUtil] 检查目录是否为空时发生异常:" + directoryPath);
return true;
}
}
}
\ No newline at end of file
...@@ -16,16 +16,8 @@ ...@@ -16,16 +16,8 @@
ORDER BY A.id, B.code ORDER BY A.id, B.code
</select> </select>
<select id="queryTaskRecordForXml" resultType="java.util.Map"> <select id="queryTaskRecordForXml" resultType="org.jeecg.modules.stm.baosong.entity.TaskRecordVo">
SELECT SELECT A.content,A.taskid,A.itemid,A.rind, B.tplid,B.code,B.pcode,B.title
A.content,
A.taskid,
A.itemid,
A.rind,
B.tplid,
B.code,
B.pcode,
B.title
FROM baosong_task_record A FROM baosong_task_record A
RIGHT JOIN baosong_tpl_item B ON A.itemid = B.id RIGHT JOIN baosong_tpl_item B ON A.itemid = B.id
<where> <where>
...@@ -36,7 +28,8 @@ ...@@ -36,7 +28,8 @@
AND B.tplid = #{query.tplid} AND B.tplid = #{query.tplid}
</if> </if>
</where> </where>
ORDER BY B.id, B.pcode, B.code ORDER BY B.id,B.pcode,B.code
</select> </select>
</mapper> </mapper>
\ No newline at end of file
...@@ -155,7 +155,7 @@ spring: ...@@ -155,7 +155,7 @@ spring:
# username: root # username: root
# password: ZhongRunChangHong/123 # password: ZhongRunChangHong/123
url: jdbc:mysql://localhost:3306/zrch_stm_db_3.9?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai url: jdbc:mysql://localhost:3306/zrch_stm_db_3.9_new?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
username: root username: root
password: 123456 password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论