Alternative interpolateString implementation leveraging commons-lang3.

This commit is contained in:
Anthony Whitford
2015-10-28 00:08:12 -07:00
parent 92e7d9cf80
commit a92bdfe30d

View File

@@ -21,6 +21,9 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
import org.apache.commons.lang3.text.StrLookup;
import org.apache.commons.lang3.text.StrSubstitutor;
/** /**
* A simple pojo to hold data related to a Maven POM file. * A simple pojo to hold data related to a Maven POM file.
* *
@@ -307,33 +310,26 @@ public class Model {
* @return the interpolated text. * @return the interpolated text.
*/ */
public static String interpolateString(String text, Properties properties) { public static String interpolateString(String text, Properties properties) {
final Properties props = properties; if (null == text || null == properties) {
if (text == null) {
return text; return text;
} }
if (props == null) { final StrSubstitutor substitutor = new StrSubstitutor(new PropertyLookup(properties));
return text; return substitutor.replace(text);
} }
final int pos = text.indexOf("${"); /**
if (pos < 0) { * Utility class that can provide values from a Properties object to a StrSubstitutor.
return text; */
} private static class PropertyLookup extends StrLookup {
final int end = text.indexOf("}"); private final Properties props;
if (end < pos) {
return text; public PropertyLookup (Properties props) {
this.props = props;
} }
final String propName = text.substring(pos + 2, end); @Override
String propValue = interpolateString(props.getProperty(propName), props); public String lookup (String key) {
if (propValue == null) { return props.getProperty(key);
propValue = "";
} }
final StringBuilder sb = new StringBuilder(propValue.length() + text.length());
sb.append(text.subSequence(0, pos));
sb.append(propValue);
sb.append(text.substring(end + 1));
return interpolateString(sb.toString(), props); //yes yes, this should be a loop...
} }
} }