public static String replaceTokens(String template, Pattern pattern,
      Map<String, String> replacements) {
    StringBuffer sb = new StringBuffer();
    Matcher matcher = pattern.matcher(template);
    while (matcher.find()) {
      String replacement = replacements.get(matcher.group(1));
      if (replacement == null) {
        replacement = "";
      }
      matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
    }
    matcher.appendTail(sb);
    return sb.toString();
  }
@Test (timeout = 5000)
  public void testReplaceTokensWinEnvVars() {
    Pattern pattern = StringUtils.WIN_ENV_VAR_PATTERN;
    Map<String, String> replacements = new HashMap<String, String>();
    replacements.put("foo", "zoo");
    replacements.put("baz", "zaz");

    assertEquals("zoo", StringUtils.replaceTokens("%foo%", pattern,
      replacements));
    assertEquals("zaz", StringUtils.replaceTokens("%baz%", pattern,
      replacements));
    assertEquals("", StringUtils.replaceTokens("%bar%", pattern,
      replacements));
    assertEquals("", StringUtils.replaceTokens("", pattern, replacements));
    assertEquals("zoo__zaz", StringUtils.replaceTokens("%foo%_%bar%_%baz%",
      pattern, replacements));
    assertEquals("begin zoo__zaz end", StringUtils.replaceTokens(
      "begin %foo%_%bar%_%baz% end", pattern, replacements));
  }