From dca217fd4f5ab1b5f92dad3681b13bde7cce6607 Mon Sep 17 00:00:00 2001 From: kangli <1363539513@qq.com> Date: Thu, 15 Aug 2024 22:16:14 +0800 Subject: [PATCH] escape json --- .../impl/AbstractAlertNotifyHandlerImpl.java | 36 +++++++++++++++++++ .../impl/WebHookAlertNotifyHandlerImpl.java | 1 + 2 files changed, 37 insertions(+) diff --git a/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/AbstractAlertNotifyHandlerImpl.java b/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/AbstractAlertNotifyHandlerImpl.java index a44af67211f..79655123f80 100644 --- a/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/AbstractAlertNotifyHandlerImpl.java +++ b/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/AbstractAlertNotifyHandlerImpl.java @@ -118,6 +118,42 @@ protected String renderContent(NoticeTemplate noticeTemplate, Alert alert) throw return template.replaceAll("((\r\n)|\n)[\\s\t ]*(\\1)+", "$1"); } + protected String escapeJsonStr(String jsonStr){ + if (jsonStr == null) { + return null; + } + + StringBuilder sb = new StringBuilder(); + for (char c : jsonStr.toCharArray()) { + switch (c) { + case '"': + sb.append("\\\""); + break; + case '\\': + sb.append("\\\\"); + break; + case '\b': + sb.append("\\b"); + break; + case '\f': + sb.append("\\f"); + break; + case '\n': + sb.append("\\n"); + break; + case '\r': + sb.append("\\r"); + break; + case '\t': + sb.append("\\t"); + break; + default: + sb.append(c); + } + } + return sb.toString(); + } + @EventListener(SystemConfigChangeEvent.class) public void onEvent(SystemConfigChangeEvent event) { log.info("{} receive system config change event: {}.", this.getClass().getName(), event.getSource()); diff --git a/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/WebHookAlertNotifyHandlerImpl.java b/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/WebHookAlertNotifyHandlerImpl.java index b4db3b0773c..7f7b793cb25 100644 --- a/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/WebHookAlertNotifyHandlerImpl.java +++ b/manager/src/main/java/org/apache/hertzbeat/manager/component/alerter/impl/WebHookAlertNotifyHandlerImpl.java @@ -47,6 +47,7 @@ public void send(NoticeReceiver receiver, NoticeTemplate noticeTemplate, Alert a // fix null pointer exception filterInvalidTags(alert); + alert.setContent(escapeJsonStr(alert.getContent())); String webhookJson = renderContent(noticeTemplate, alert); webhookJson = webhookJson.replace(",\n }", "\n }");