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 public static final String KEY_ENABLE_DEFAULT_VALUE = KEY_PREFIX + "enable-default-value";
36
37
38
39
40
41
42
43
44 public static final String KEY_DEFAULT_VALUE_SEPARATOR = KEY_PREFIX + "default-value-separator";
45
46 private static final String ENABLE_DEFAULT_VALUE = "false";
47 private static final String DEFAULT_VALUE_SEPARATOR = ":";
48
49 private PropertyParser() {
50
51 }
52
53 public static String parse(String string, Properties variables) {
54 VariableTokenHandler handler = new VariableTokenHandler(variables);
55 GenericTokenParserrser.html#GenericTokenParser">GenericTokenParser parser = new GenericTokenParser("${", "}", handler);
56 return parser.parse(string);
57 }
58
59 private static class VariableTokenHandler implements TokenHandler {
60 private final Properties variables;
61 private final boolean enableDefaultValue;
62 private final String defaultValueSeparator;
63
64 private VariableTokenHandler(Properties variables) {
65 this.variables = variables;
66 this.enableDefaultValue = Boolean.parseBoolean(getPropertyValue(KEY_ENABLE_DEFAULT_VALUE, ENABLE_DEFAULT_VALUE));
67 this.defaultValueSeparator = getPropertyValue(KEY_DEFAULT_VALUE_SEPARATOR, DEFAULT_VALUE_SEPARATOR);
68 }
69
70 private String getPropertyValue(String key, String defaultValue) {
71 return (variables == null) ? defaultValue : variables.getProperty(key, defaultValue);
72 }
73
74 @Override
75 public String handleToken(String content) {
76 if (variables != null) {
77 String key = content;
78 if (enableDefaultValue) {
79 final int separatorIndex = content.indexOf(defaultValueSeparator);
80 String defaultValue = null;
81 if (separatorIndex >= 0) {
82 key = content.substring(0, separatorIndex);
83 defaultValue = content.substring(separatorIndex + defaultValueSeparator.length());
84 }
85 if (defaultValue != null) {
86 return variables.getProperty(key, defaultValue);
87 }
88 }
89 if (variables.containsKey(key)) {
90 return variables.getProperty(key);
91 }
92 }
93 return "${" + content + "}";
94 }
95 }
96
97 }