1 package be
.nikiroo
.fanfix
.library
;
3 import java
.io
.ByteArrayInputStream
;
4 import java
.io
.IOException
;
5 import java
.io
.InputStream
;
6 import java
.util
.HashMap
;
10 import be
.nikiroo
.utils
.IOUtils
;
11 import be
.nikiroo
.utils
.StringUtils
;
12 import be
.nikiroo
.utils
.streams
.ReplaceInputStream
;
14 public class Template
{
15 private Class
<?
> location
;
18 private Map
<String
, String
> values
= new HashMap
<String
, String
>();
19 private Map
<String
, Template
> valuesTemplate
= new HashMap
<String
, Template
>();
20 private Map
<String
, List
<Template
>> valuesTemplateList
= new HashMap
<String
, List
<Template
>>();
22 public Template(Class
<?
> location
, String name
) {
23 this.location
= location
;
27 public synchronized InputStream
read() throws IOException
{
29 String from
[] = new String
[values
.size() + valuesTemplate
.size()
30 + valuesTemplateList
.size()];
31 String to
[] = new String
[from
.length
];
35 for (String key
: values
.keySet()) {
36 from
[i
] = "${" + key
+ "}";
37 to
[i
] = values
.get(key
);
41 for (String key
: valuesTemplate
.keySet()) {
42 InputStream value
= valuesTemplate
.get(key
).read();
44 from
[i
] = "${" + key
+ "}";
45 to
[i
] = IOUtils
.readSmallStream(value
);
52 for (String key
: valuesTemplateList
.keySet()) {
53 List
<Template
> templates
= valuesTemplateList
.get(key
);
54 StringBuilder value
= new StringBuilder();
55 for (Template template
: templates
) {
56 InputStream valueOne
= template
.read();
58 value
.append(IOUtils
.readSmallStream(valueOne
));
63 from
[i
] = "${" + key
+ "}";
64 to
[i
] = value
.toString();
69 InputStream in
= IOUtils
.openResource(location
, name
);
71 //TODO: pending fix in replace stream
72 String data
= IOUtils
.readSmallStream(in
);
74 for(i
= 0 ; i
< from
.length
;i
++) {
75 data
=data
.replace(from
[i
], to
[i
]);
78 //in = new ReplaceInputStream(in, from, to);
79 in
= new ByteArrayInputStream(StringUtils
.getBytes(data
));
85 public synchronized Template
set(String key
, String value
) {
86 values
.put(key
, value
);
87 valuesTemplate
.remove(key
);
88 valuesTemplateList
.remove(key
);
92 public synchronized Template
set(String key
, Template value
) {
94 valuesTemplate
.put(key
, value
);
95 valuesTemplateList
.remove(key
);
99 public synchronized Template
set(String key
, List
<Template
> value
) {
101 valuesTemplate
.remove(key
);
102 valuesTemplateList
.put(key
, value
);
107 public String
toString() {
108 return String
.format(
109 "[Template for %s with (%d,%d,%d) value(s) to replace]", name
,
110 values
.size(), valuesTemplate
.size(),
111 valuesTemplateList
.size());