1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.devzendo.xplp;
21
22 import java.util.HashSet;
23 import java.util.Properties;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
26
27
28
29
30
31
32
33
34 public final class PropertiesInterpolator {
35 private final Properties mProps;
36 private final Matcher variableReferenceMatcher =
37 Pattern.compile("^(.*?)\\$\\{([^}]+?)\\}(.*?)$", Pattern.DOTALL).matcher("");
38 private final HashSet<String> verbatimVariables = new HashSet<>();
39
40
41
42
43
44
45
46 public PropertiesInterpolator(final Properties props) {
47 mProps = props;
48 }
49
50
51
52
53
54
55 public String interpolate(final String input) {
56
57 if (input == null || input.length() == 0) {
58 return input;
59 }
60 if (input.matches("^\\s*#.*$")) {
61 return input;
62 }
63 String s = input;
64 final StringBuilder sb = new StringBuilder();
65 while (true) {
66 variableReferenceMatcher.reset(s);
67
68 if (variableReferenceMatcher.find()) {
69
70 final String before = variableReferenceMatcher.group(1);
71 final String variableName = variableReferenceMatcher.group(2);
72 final String after = variableReferenceMatcher.group(3);
73
74 if (verbatimVariables.contains(variableName)) {
75
76 sb.append(before);
77 sb.append("${");
78 sb.append(variableName);
79 sb.append("}");
80 } else {
81 if (mProps.containsKey(variableName)) {
82 final String variableValue = mProps.getProperty(variableName);
83
84 sb.append(before);
85 sb.append(variableValue);
86 } else {
87
88 throw new IllegalStateException("The name '" + variableName + "' is not defined");
89 }
90 }
91 s = after;
92 } else {
93
94 sb.append(s);
95 break;
96 }
97 }
98
99 return sb.toString();
100 }
101
102
103
104
105
106 public void doNotInterpolate(final String verbatimVariable) {
107 verbatimVariables.add(verbatimVariable);
108 }
109 }