1 16 package scriptella.expression; 17 18 import scriptella.spi.ParametersCallback; 19 20 import java.util.regex.Matcher ; 21 import java.util.regex.Pattern ; 22 23 24 46 public class PropertiesSubstitutor { 47 50 public static final Pattern PROP_PTR = Pattern.compile("([a-zA-Z_0-9\\.]+)"); 51 52 55 public static final Pattern EXPR_PTR = Pattern.compile("\\{([^\\}]+)\\}"); 56 57 final Matcher m1 = PROP_PTR.matcher(""); 58 final Matcher m2 = EXPR_PTR.matcher(""); 59 60 67 public PropertiesSubstitutor() { 68 } 69 70 75 public PropertiesSubstitutor(ParametersCallback parameters) { 76 this.parameters = parameters; 77 } 78 79 private ParametersCallback parameters; 80 81 89 public String substitute(final String s) { 90 if (s == null) { 91 return null; 92 } 93 if (parameters == null) { 94 throw new IllegalStateException ("setParameters must be called before calling substitute"); 95 } 96 97 final int len = s.length() - 1; if (len <= 0 || s.indexOf('$') < 0) { return s; 100 } 101 StringBuilder res = null; 102 final char[] sChars = s.toCharArray(); 103 int lastPos = 0; 104 m1.reset(s); 105 m2.reset(s); 106 for (int i = 0; i < len; i++) { 107 if (sChars[i]=='$') { 108 Matcher m; 110 if (m1.find(i + 1) && m1.start() == i + 1) { 111 m = m1; 112 } else if (m2.find(i + 1) && m2.start() == i + 1) { 113 m = m2; 114 } else { m = null; 116 } 117 if (m != null) { 118 if (res == null) { 119 res = new StringBuilder (s.length()); 120 } 121 if (i > lastPos) { res.append(sChars, lastPos, i - lastPos); 123 } 124 final String name = m.group(1); 125 String v; 126 127 if (m == m1) { 128 v = toString(parameters.getParameter(name)); 129 } else { 130 v = toString(Expression.compile(name).evaluate(parameters)); 131 } 132 133 lastPos = m.end(); 134 if (v != null) { 135 res.append(v); 136 } else { res.append(sChars, i, lastPos - i); 138 } 139 140 } 141 } 142 } 143 if (res == null) { 144 return s; 145 } 146 if (lastPos <= len) { 147 res.append(sChars, lastPos, s.length() - lastPos); 148 } 149 150 151 return res.toString(); 152 } 153 154 157 public ParametersCallback getParameters() { 158 return parameters; 159 } 160 161 166 public void setParameters(ParametersCallback parameters) { 167 this.parameters = parameters; 168 } 169 170 177 protected String toString(final Object o) { 178 return o == null ? null : o.toString(); 179 } 180 181 } 182 | Popular Tags |