Created
November 15, 2011 00:10
-
-
Save stevenschlansker/1365649 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ElLikeSubstitutionUtils { | |
private static final Pattern MATCH_PATTERN = Pattern.compile("\\$\\{([^}]+)\\}"); | |
/** | |
* Replace ${name} with the appropriate template value retrieved from the map. | |
* Does not gracefully handle nested or mismatched brace patterns | |
*/ | |
public static Verified<String> substitute(String string, Map<String, String> parameters) { | |
List<SyndicationVerificationError> errors = Lists.newArrayList(); | |
Matcher m = MATCH_PATTERN.matcher(string); | |
StringBuffer result = new StringBuffer(); | |
while (m.find()) { | |
String parameterName = m.group(1); | |
String replacement = parameters.get(parameterName); | |
if (replacement == null) { | |
replacement = ""; | |
errors.add(new SyndicationVerificationError("Parameter " + parameterName + " not present in map")); | |
} | |
m.appendReplacement(result, replacement); | |
} | |
m.appendTail(result); | |
if (!errors.isEmpty()) { | |
return new VerifiedFailure<String>(errors); | |
} | |
return new VerifiedSuccess<String>(result.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment