-
Notifications
You must be signed in to change notification settings - Fork 350
Expand file tree
/
Copy pathTemplateBulider.java
More file actions
58 lines (48 loc) · 1.69 KB
/
TemplateBulider.java
File metadata and controls
58 lines (48 loc) · 1.69 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
package strman;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TemplateBulider {
private static final String REGEX = "<=(.*?)\\>";
private final String template;
private final Map<String, String> properties;
public TemplateBulider(String template) {
this.template = template;
this.properties = buildProperties(template);
}
public String execute() {
String result = template;
for (Map.Entry<String, String> entry : properties.entrySet()) {
if (null == entry.getValue())
continue;
String key = "<=" + entry.getKey() + ">";
result = result.replace(key, entry.getValue());
}
return result;
}
public void add(String key, String value) {
if (!properties.containsKey(key))
throw new RuntimeException("No veriable definitation \"" + key + "\"");
properties.replace(key, value);
}
public void add(String key, Number value) {
add(key, value.toString());
}
protected static Map<String, String> buildProperties(String template) {
Map<String, String> valueMap = new HashMap<>();
Pattern patten = Pattern.compile(REGEX);
Matcher m = patten.matcher(template);
while (m.find()) {
String key = m.group().substring(2, m.group().length() - 1);
if (valueMap.containsKey(key))
throw new RuntimeException("Duplicate value definition \"" + key + "\"");
valueMap.put(key, null);
}
return valueMap;
}
@Override
public String toString() {
return template;
}
}