ConfigBuilder.java
3.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package com.viontech.fanxing.task.model;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.util.List;
/**
* .
*
* @author 谢明辉
* @date 2021/9/26
*/
public class ConfigBuilder {
private static final Logger log = LoggerFactory.getLogger(ConfigBuilder.class);
private Document document;
private String build;
private boolean vChanInfoBuilt;
private boolean defaultConfigBuilt;
public ConfigBuilder() {
document = DocumentHelper.createDocument();
document.setRootElement(DocumentHelper.createElement("root"));
}
private void setText(Element element, String name, String text) {
Element e = element.element(name);
if (e == null) {
e = element.addElement(name);
}
e.clearContent();
e.setText(text);
}
public String build() {
try {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
XMLWriter xmlWriter = new XMLWriter(byteArrayOutputStream, format);
xmlWriter.write(document);
build = new String(byteArrayOutputStream.toByteArray(), Charset.forName("GBK"));
} catch (Exception e) {
log.error("", e);
}
log.debug("xmh:构建默认配置完成:{}", build);
return build;
}
public ConfigBuilder buildDefaultConfig(String defaultConfig) {
if (defaultConfigBuilt) {
return this;
}
try {
SAXReader saxReader = new SAXReader();
Document defaultDoc = saxReader.read(new ByteArrayInputStream(defaultConfig.getBytes(Charset.forName("GBK"))));
Element defaultRoot = defaultDoc.getRootElement();
Element root = document.getRootElement();
List<Element> defE = defaultRoot.elements();
for (Element element : defE) {
Element copy = element.createCopy();
root.add(copy);
}
defaultConfigBuilt = true;
} catch (Exception e) {
log.error("", e);
}
return this;
}
public ConfigBuilder buildVchanInfo(String name, String channelUnid) {
if (vChanInfoBuilt) {
return this;
}
try {
// 构建默认配置
Element rootElement = document.getRootElement();
Element deviceConfig = rootElement.element("设备配置");
if (deviceConfig == null) {
deviceConfig = rootElement.addElement("设备配置");
}
setText(deviceConfig, "设备名称", name);
setText(deviceConfig, "设备编号", channelUnid);
setText(deviceConfig, "地点名称", name);
setText(deviceConfig, "地点编号", channelUnid);
this.vChanInfoBuilt = true;
} catch (Exception e) {
log.error("", e);
}
return this;
}
}