3536d5f12efccf7da066ce4b1d140553c633e631
[nikiroo-utils.git] / library / Template.java
1 package be.nikiroo.fanfix.library;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.util.HashMap;
6 import java.util.List;
7 import java.util.Map;
8
9 import be.nikiroo.utils.IOUtils;
10 import be.nikiroo.utils.streams.ReplaceInputStream;
11
12 public class Template {
13 private Class<?> location;
14 private String name;
15
16 private Map<String, String> values = new HashMap<String, String>();
17 private Map<String, Template> valuesTemplate = new HashMap<String, Template>();
18 private Map<String, List<Template>> valuesTemplateList = new HashMap<String, List<Template>>();
19
20 public Template(Class<?> location, String name) {
21 this.location = location;
22 this.name = name;
23 }
24
25 public synchronized InputStream read() throws IOException {
26
27 String from[] = new String[values.size() + valuesTemplate.size()
28 + valuesTemplateList.size()];
29 String to[] = new String[from.length];
30
31 int i = 0;
32
33 for (String key : values.keySet()) {
34 from[i] = "${" + key + "}";
35 to[i] = values.get(key);
36
37 i++;
38 }
39 for (String key : valuesTemplate.keySet()) {
40 InputStream value = valuesTemplate.get(key).read();
41 try {
42 from[i] = "${" + key + "}";
43 to[i] = IOUtils.readSmallStream(value);
44 } finally {
45 value.close();
46 }
47
48 i++;
49 }
50 for (String key : valuesTemplateList.keySet()) {
51 List<Template> templates = valuesTemplateList.get(key);
52 StringBuilder value = new StringBuilder();
53 for (Template template : templates) {
54 InputStream valueOne = template.read();
55 try {
56 value.append(IOUtils.readSmallStream(valueOne));
57 } finally {
58 valueOne.close();
59 }
60 }
61
62 from[i] = "${" + key + "}";
63 to[i] = value.toString();
64
65 i++;
66 }
67
68 InputStream in = IOUtils.openResource(location, name);
69 return new ReplaceInputStream(in, from, to);
70 }
71
72 public synchronized Template set(String key, String value) {
73 values.put(key, value);
74 valuesTemplate.remove(key);
75 valuesTemplateList.remove(key);
76 return this;
77 }
78
79 public synchronized Template set(String key, Template value) {
80 values.remove(key);
81 valuesTemplate.put(key, value);
82 valuesTemplateList.remove(key);
83 return this;
84 }
85
86 public synchronized Template set(String key, List<Template> value) {
87 values.remove(key);
88 valuesTemplate.remove(key);
89 valuesTemplateList.put(key, value);
90 return this;
91 }
92
93 @Override
94 public String toString() {
95 return String.format(
96 "[Template for %s with (%d,%d,%d) value(s) to replace]", name,
97 values.size(), valuesTemplate.size(),
98 valuesTemplateList.size());
99 }
100 }