From b9f36bf305200aa1729eed2780cab22b9a50d5de Mon Sep 17 00:00:00 2001 From: Carpe-Wang <78642589+Carpe-Wang@users.noreply.github.com> Date: Tue, 5 Dec 2023 13:41:08 +0800 Subject: [PATCH] fix exception when sending email has special chars (#1383) Co-authored-by: Carpe-Wang --- .../hertzbeat/alert/util/AlertTemplateUtil.java | 8 ++++---- .../hertzbeat/alert/util/AlertTemplateUtilTest.java | 13 +++++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/alerter/src/main/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtil.java b/alerter/src/main/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtil.java index fc9ea8f054d..ba1c64eae3d 100644 --- a/alerter/src/main/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtil.java +++ b/alerter/src/main/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtil.java @@ -44,14 +44,14 @@ public static String render(String template, Map replaceData) { } try { Matcher matcher = PATTERN.matcher(template); - StringBuilder buffer = new StringBuilder(); + StringBuilder builder = new StringBuilder(); while (matcher.find()) { Object objectValue = replaceData.getOrDefault(matcher.group(1), "NullValue"); String value = objectValue.toString(); - matcher.appendReplacement(buffer, value); + matcher.appendReplacement(builder, Matcher.quoteReplacement(value)); } - matcher.appendTail(buffer); - return buffer.toString(); + matcher.appendTail(builder); + return builder.toString(); } catch (Exception e) { log.error(e.getMessage(), e); return template; diff --git a/alerter/src/test/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtilTest.java b/alerter/src/test/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtilTest.java index 76c5627934e..6a2cf642391 100644 --- a/alerter/src/test/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtilTest.java +++ b/alerter/src/test/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtilTest.java @@ -62,4 +62,17 @@ void render() { template = "${key1} ${key2} ${key3}"; assertEquals(AlertTemplateUtil.render(template, param), "Just for testing"); } + + @Test + void renderSpecialCharacters() { + Map param = new HashMap<>(); + param.put("valueWithDollar", "$100"); + param.put("valueWithBackslash", "C:\\Users"); + + String template = "The price is ${valueWithDollar} and the path is ${valueWithBackslash}"; + + // Expected to handle the dollar sign and backslash correctly without throwing an exception + String expectedResult = "The price is $100 and the path is C:\\Users"; + assertEquals(expectedResult, AlertTemplateUtil.render(template, param)); + } } \ No newline at end of file