1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools.template_engine;
|
---|
3 |
|
---|
4 | import java.util.Collection;
|
---|
5 | import java.util.Locale;
|
---|
6 |
|
---|
7 | public class Variable implements TemplateEntry {
|
---|
8 |
|
---|
9 | private static final String SPECIAL_VARIABLE_PREFIX = "special:";
|
---|
10 | private static final String SPECIAL_VALUE_EVERYTHING = "everything";
|
---|
11 |
|
---|
12 |
|
---|
13 | private final String variableName;
|
---|
14 | private final boolean special;
|
---|
15 |
|
---|
16 | public Variable(String variableName) {
|
---|
17 | if (variableName.toLowerCase(Locale.ENGLISH).startsWith(SPECIAL_VARIABLE_PREFIX)) {
|
---|
18 | this.variableName = variableName.substring(SPECIAL_VARIABLE_PREFIX.length());
|
---|
19 | // special:special:key means that real key named special:key is needed, not special variable
|
---|
20 | this.special = !this.variableName.toLowerCase(Locale.ENGLISH).startsWith(SPECIAL_VARIABLE_PREFIX);
|
---|
21 | } else {
|
---|
22 | this.variableName = variableName;
|
---|
23 | this.special = false;
|
---|
24 | }
|
---|
25 | }
|
---|
26 |
|
---|
27 | @Override
|
---|
28 | public void appendText(StringBuilder result, TemplateEngineDataProvider dataProvider) {
|
---|
29 | if (special && SPECIAL_VALUE_EVERYTHING.equals(variableName)) {
|
---|
30 | Collection<String> keys = dataProvider.getTemplateKeys();
|
---|
31 | boolean first = true;
|
---|
32 | for (String key: keys) {
|
---|
33 | if (!first) {
|
---|
34 | result.append(", ");
|
---|
35 | } else {
|
---|
36 | first = false;
|
---|
37 | }
|
---|
38 | result.append(key).append('=').append(dataProvider.getTemplateValue(key, false));
|
---|
39 | }
|
---|
40 | } else {
|
---|
41 | Object value = dataProvider.getTemplateValue(variableName, special);
|
---|
42 | if (value != null) {
|
---|
43 | result.append(value);
|
---|
44 | }
|
---|
45 | }
|
---|
46 | }
|
---|
47 |
|
---|
48 | @Override
|
---|
49 | public boolean isValid(TemplateEngineDataProvider dataProvider) {
|
---|
50 | if (special && SPECIAL_VALUE_EVERYTHING.equals(variableName))
|
---|
51 | return true;
|
---|
52 | else
|
---|
53 | return dataProvider.getTemplateValue(variableName, special) != null;
|
---|
54 | }
|
---|
55 |
|
---|
56 | @Override
|
---|
57 | public String toString() {
|
---|
58 | return '{' + (special ? SPECIAL_VARIABLE_PREFIX : "") + variableName + '}';
|
---|
59 | }
|
---|
60 |
|
---|
61 | public boolean isSpecial() {
|
---|
62 | return special;
|
---|
63 | }
|
---|
64 | }
|
---|