1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.parsing;
17
18 import java.util.Properties;
19
20
21
22
23
24 public class PropertyParser {
25
26 private static final String KEY_PREFIX = "org.apache.ibatis.parsing.PropertyParser.";
27
28
29
30
31
32
33
34
35
36 public static final String KEY_ENABLE_DEFAULT_VALUE = KEY_PREFIX + "enable-default-value";
37
38
39
40
41
42
43
44
45
46 public static final String KEY_DEFAULT_VALUE_SEPARATOR = KEY_PREFIX + "default-value-separator";
47
48 private static final String ENABLE_DEFAULT_VALUE = "false";
49 private static final String DEFAULT_VALUE_SEPARATOR = ":";
50
51 private PropertyParser() {
52
53 }
54
55 public static String parse(String string, Properties variables) {
56 VariableTokenHandler handler = new VariableTokenHandler(variables);
57 GenericTokenParser parser = new GenericTokenParser("${", "}", handler);
58 return parser.parse(string);
59 }
60
61 private static class VariableTokenHandler implements TokenHandler {
62 private final Properties variables;
63 private final boolean enableDefaultValue;
64 private final String defaultValueSeparator;
65
66 private VariableTokenHandler(Properties variables) {
67 this.variables = variables;
68 this.enableDefaultValue = Boolean.parseBoolean(getPropertyValue(KEY_ENABLE_DEFAULT_VALUE, ENABLE_DEFAULT_VALUE));
69 this.defaultValueSeparator = getPropertyValue(KEY_DEFAULT_VALUE_SEPARATOR, DEFAULT_VALUE_SEPARATOR);
70 }
71
72 private String getPropertyValue(String key, String defaultValue) {
73 return variables == null ? defaultValue : variables.getProperty(key, defaultValue);
74 }
75
76 @Override
77 public String handleToken(String content) {
78 if (variables != null) {
79 String key = content;
80 if (enableDefaultValue) {
81 final int separatorIndex = content.indexOf(defaultValueSeparator);
82 String defaultValue = null;
83 if (separatorIndex >= 0) {
84 key = content.substring(0, separatorIndex);
85 defaultValue = content.substring(separatorIndex + defaultValueSeparator.length());
86 }
87 if (defaultValue != null) {
88 return variables.getProperty(key, defaultValue);
89 }
90 }
91 if (variables.containsKey(key)) {
92 return variables.getProperty(key);
93 }
94 }
95 return "${" + content + "}";
96 }
97 }
98
99 }