From d8dd44b24f78e83e64e304929532624f7ffcd0a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=84=E9=B8=BF?= Date: Fri, 26 Apr 2024 11:46:20 +0800 Subject: [PATCH] refactor(home): optimize common moudle of home-alert --- server/common/common/pom.xml | 5 + .../server}/common/CommonUtil.java | 2 +- .../io/holoinsight/server}/common/Fmt.java | 2 +- .../java/io/holoinsight/server/common/J.java | 20 + .../server}/common/http/ByteUtil.java | 2 +- .../server}/common/http/HttpAsync.java | 2 +- .../server}/common/http/HttpException.java | 2 +- .../server}/common/http/HttpProxy.java | 2 +- .../holoinsight/server}/common/http/Util.java | 2 +- .../server}/common/http/XHttpRequest.java | 2 +- .../server}/common/http/XHttpResponse.java | 2 +- .../server/home/alert/common/G.java | 94 ---- .../home/alert/common/ObjectToMapUtil.java | 4 +- .../server/home/alert/common/PeriodUtil.java | 4 +- .../common/{webhook => }/WebhookUtil.java | 33 +- .../home/alert/common/http/ByteUtil.java | 197 -------- .../home/alert/common/http/HttpAsync.java | 435 ------------------ .../home/alert/common/http/HttpException.java | 18 - .../home/alert/common/http/HttpProxy.java | 176 ------- .../server/home/alert/common/http/Util.java | 123 ----- .../home/alert/common/http/XHttpRequest.java | 237 ---------- .../home/alert/common/http/XHttpResponse.java | 46 -- .../alert/plugin/AlertSaveHistoryHandler.java | 33 +- .../alert/plugin/GetSubscriptionHandler.java | 46 +- .../home/alert/service/AlertService.java | 4 +- .../service/calculate/AlertTaskCompute.java | 13 +- .../service/calculate/AlgorithmHttp.java | 6 +- .../calculate/AnomalyDownAbnormalDetect.java | 15 +- .../calculate/AnomalyUpAbnormalDetect.java | 15 +- .../calculate/ValueDownAbnormalDetect.java | 21 +- .../calculate/ValueUpAbnormalDetect.java | 21 +- .../alert/service/converter/DoConvert.java | 17 +- .../service/data/load/AIAlarmLoadData.java | 18 +- .../service/data/load/RuleAlarmLoadData.java | 16 +- .../AlertManagerBuildMsgHandler.java | 7 +- .../AlertManagerSaveHistoryHandler.java | 8 +- .../AlertManagerSendMsgHandler.java | 12 +- server/home/home-common/pom.xml | 31 +- .../home/biz/service/gpt/GptService.java | 6 +- 39 files changed, 192 insertions(+), 1507 deletions(-) rename server/{home/home-alert/src/main/java/io/holoinsight/server/home/alert => common/common/src/main/java/io/holoinsight/server}/common/CommonUtil.java (99%) rename server/{home/home-alert/src/main/java/io/holoinsight/server/home/alert => common/common/src/main/java/io/holoinsight/server}/common/Fmt.java (97%) rename server/{home/home-common/src/main/java/io/holoinsight/server/home => common/common/src/main/java/io/holoinsight/server}/common/http/ByteUtil.java (99%) rename server/{home/home-common/src/main/java/io/holoinsight/server/home => common/common/src/main/java/io/holoinsight/server}/common/http/HttpAsync.java (99%) rename server/{home/home-common/src/main/java/io/holoinsight/server/home => common/common/src/main/java/io/holoinsight/server}/common/http/HttpException.java (87%) rename server/{home/home-common/src/main/java/io/holoinsight/server/home => common/common/src/main/java/io/holoinsight/server}/common/http/HttpProxy.java (99%) rename server/{home/home-common/src/main/java/io/holoinsight/server/home => common/common/src/main/java/io/holoinsight/server}/common/http/Util.java (98%) rename server/{home/home-common/src/main/java/io/holoinsight/server/home => common/common/src/main/java/io/holoinsight/server}/common/http/XHttpRequest.java (99%) rename server/{home/home-common/src/main/java/io/holoinsight/server/home => common/common/src/main/java/io/holoinsight/server}/common/http/XHttpResponse.java (96%) delete mode 100644 server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/G.java rename server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/{webhook => }/WebhookUtil.java (64%) delete mode 100644 server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/ByteUtil.java delete mode 100644 server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpAsync.java delete mode 100644 server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpException.java delete mode 100644 server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpProxy.java delete mode 100644 server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/Util.java delete mode 100644 server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/XHttpRequest.java delete mode 100644 server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/XHttpResponse.java diff --git a/server/common/common/pom.xml b/server/common/common/pom.xml index e2162d67c..914bff074 100644 --- a/server/common/common/pom.xml +++ b/server/common/common/pom.xml @@ -90,5 +90,10 @@ org.apache.logging.log4j log4j-api + + + org.apache.httpcomponents + httpasyncclient + \ No newline at end of file diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/CommonUtil.java b/server/common/common/src/main/java/io/holoinsight/server/common/CommonUtil.java similarity index 99% rename from server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/CommonUtil.java rename to server/common/common/src/main/java/io/holoinsight/server/common/CommonUtil.java index 6a7e15265..f44f472ae 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/CommonUtil.java +++ b/server/common/common/src/main/java/io/holoinsight/server/common/CommonUtil.java @@ -1,7 +1,7 @@ /* * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. */ -package io.holoinsight.server.home.alert.common; +package io.holoinsight.server.common; import java.text.DecimalFormat; diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/Fmt.java b/server/common/common/src/main/java/io/holoinsight/server/common/Fmt.java similarity index 97% rename from server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/Fmt.java rename to server/common/common/src/main/java/io/holoinsight/server/common/Fmt.java index 6b0469404..de14eb762 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/Fmt.java +++ b/server/common/common/src/main/java/io/holoinsight/server/common/Fmt.java @@ -1,7 +1,7 @@ /* * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. */ -package io.holoinsight.server.home.alert.common; +package io.holoinsight.server.common; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.time.DateUtils; diff --git a/server/common/common/src/main/java/io/holoinsight/server/common/J.java b/server/common/common/src/main/java/io/holoinsight/server/common/J.java index 2f3564022..487ed0196 100644 --- a/server/common/common/src/main/java/io/holoinsight/server/common/J.java +++ b/server/common/common/src/main/java/io/holoinsight/server/common/J.java @@ -5,10 +5,13 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import java.util.Map; @@ -57,6 +60,23 @@ public static T fromJson(String json, Type type) { return get().fromJson(json, type); } + public static T fromJson(String json, Class classOfT) { + return get().fromJson(json, classOfT); + } + + + public static List parseList(String json, Class elementType) { + JsonElement element = new JsonParser().parse(json); + JsonArray jsonArray = element.getAsJsonArray(); + List list = new ArrayList<>(); + Iterator it = jsonArray.iterator(); + while (it.hasNext()) { + T object = get().fromJson(it.next(), elementType); + list.add(object); + } + return list; + } + /** *

* jsonFormatter. diff --git a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/ByteUtil.java b/server/common/common/src/main/java/io/holoinsight/server/common/http/ByteUtil.java similarity index 99% rename from server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/ByteUtil.java rename to server/common/common/src/main/java/io/holoinsight/server/common/http/ByteUtil.java index 239013761..19af4d962 100644 --- a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/ByteUtil.java +++ b/server/common/common/src/main/java/io/holoinsight/server/common/http/ByteUtil.java @@ -1,7 +1,7 @@ /* * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. */ -package io.holoinsight.server.home.common.http; +package io.holoinsight.server.common.http; import java.io.ByteArrayOutputStream; import java.io.InputStream; diff --git a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/HttpAsync.java b/server/common/common/src/main/java/io/holoinsight/server/common/http/HttpAsync.java similarity index 99% rename from server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/HttpAsync.java rename to server/common/common/src/main/java/io/holoinsight/server/common/http/HttpAsync.java index f60a456cb..20e5e16b8 100644 --- a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/HttpAsync.java +++ b/server/common/common/src/main/java/io/holoinsight/server/common/http/HttpAsync.java @@ -1,7 +1,7 @@ /* * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. */ -package io.holoinsight.server.home.common.http; +package io.holoinsight.server.common.http; import lombok.Getter; import org.apache.http.Consts; diff --git a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/HttpException.java b/server/common/common/src/main/java/io/holoinsight/server/common/http/HttpException.java similarity index 87% rename from server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/HttpException.java rename to server/common/common/src/main/java/io/holoinsight/server/common/http/HttpException.java index d350d388f..8b57ba7a0 100644 --- a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/HttpException.java +++ b/server/common/common/src/main/java/io/holoinsight/server/common/http/HttpException.java @@ -1,7 +1,7 @@ /* * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. */ -package io.holoinsight.server.home.common.http; +package io.holoinsight.server.common.http; public class HttpException extends Exception { diff --git a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/HttpProxy.java b/server/common/common/src/main/java/io/holoinsight/server/common/http/HttpProxy.java similarity index 99% rename from server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/HttpProxy.java rename to server/common/common/src/main/java/io/holoinsight/server/common/http/HttpProxy.java index ba040875a..18b9c7484 100644 --- a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/HttpProxy.java +++ b/server/common/common/src/main/java/io/holoinsight/server/common/http/HttpProxy.java @@ -1,7 +1,7 @@ /* * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. */ -package io.holoinsight.server.home.common.http; +package io.holoinsight.server.common.http; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/Util.java b/server/common/common/src/main/java/io/holoinsight/server/common/http/Util.java similarity index 98% rename from server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/Util.java rename to server/common/common/src/main/java/io/holoinsight/server/common/http/Util.java index 64a22b4e1..c59819320 100644 --- a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/Util.java +++ b/server/common/common/src/main/java/io/holoinsight/server/common/http/Util.java @@ -1,7 +1,7 @@ /* * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. */ -package io.holoinsight.server.home.common.http; +package io.holoinsight.server.common.http; import org.apache.commons.lang3.StringUtils; import org.apache.http.Header; diff --git a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/XHttpRequest.java b/server/common/common/src/main/java/io/holoinsight/server/common/http/XHttpRequest.java similarity index 99% rename from server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/XHttpRequest.java rename to server/common/common/src/main/java/io/holoinsight/server/common/http/XHttpRequest.java index 735ea5fa1..730a3b820 100644 --- a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/XHttpRequest.java +++ b/server/common/common/src/main/java/io/holoinsight/server/common/http/XHttpRequest.java @@ -1,7 +1,7 @@ /* * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. */ -package io.holoinsight.server.home.common.http; +package io.holoinsight.server.common.http; import java.io.Serializable; import java.util.Map; diff --git a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/XHttpResponse.java b/server/common/common/src/main/java/io/holoinsight/server/common/http/XHttpResponse.java similarity index 96% rename from server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/XHttpResponse.java rename to server/common/common/src/main/java/io/holoinsight/server/common/http/XHttpResponse.java index 15551aacc..cdb26b9fd 100644 --- a/server/home/home-common/src/main/java/io/holoinsight/server/home/common/http/XHttpResponse.java +++ b/server/common/common/src/main/java/io/holoinsight/server/common/http/XHttpResponse.java @@ -1,7 +1,7 @@ /* * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. */ -package io.holoinsight.server.home.common.http; +package io.holoinsight.server.common.http; import java.io.Serializable; diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/G.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/G.java deleted file mode 100644 index 3c9ad520f..000000000 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/G.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. - */ -package io.holoinsight.server.home.alert.common; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * @author wangsiyuan - * @date 2022/3/21 7:45 下午 - */ -public class G { - private static final ThreadLocal DEFAULT_GSON = new ThreadLocal() { - @Override - protected Gson initialValue() { - return new Gson(); - } - }; - private static final ThreadLocal PRETTY_GSON = new ThreadLocal() { - @Override - protected Gson initialValue() { - return new GsonBuilder().setPrettyPrinting().create(); - } - }; - - public static Gson get() { - return DEFAULT_GSON.get(); - } - - public static Gson getPretty() { - return PRETTY_GSON.get(); - } - - public static List parseList(String json, Class elementType) { - JsonElement element = new JsonParser().parse(json); - JsonArray jsonArray = element.getAsJsonArray(); - List list = new ArrayList<>(); - Iterator it = jsonArray.iterator(); - while (it.hasNext()) { - T object = get().fromJson(it.next(), elementType); - list.add(object); - } - return list; - } - - public static Set parseSet(String json, Class elementType) { - JsonElement element = new JsonParser().parse(json); - JsonArray jsonArray = element.getAsJsonArray(); - Set set = new HashSet<>(); - Iterator it = jsonArray.iterator(); - while (it.hasNext()) { - T object = get().fromJson(it.next(), elementType); - set.add(object); - } - return set; - } - - public static Map parseMap(String json, Class keyType, Class valueType) { - JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); - Map map = new LinkedHashMap<>(); - for (Map.Entry entry : jsonObject.entrySet()) { - String keyStr = entry.getKey(); - Object key = keyStr; - if (keyType == Long.class) { - key = Long.valueOf(keyStr); - } else if (keyType == Integer.class) { - key = Integer.valueOf(keyStr); - } else if (keyType == Double.class) { - key = Double.valueOf(keyStr); - } else if (keyType == Float.class) { - key = Float.valueOf(keyStr); - } else if (keyType == Short.class) { - key = Short.valueOf(keyStr); - } - V value = get().fromJson(entry.getValue(), valueType); - map.putIfAbsent((K) key, value); - } - return map; - } - -} diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/ObjectToMapUtil.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/ObjectToMapUtil.java index b6ac4abd3..3618e31f7 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/ObjectToMapUtil.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/ObjectToMapUtil.java @@ -32,8 +32,8 @@ public static Map generateObjectToStringMap(Object o) throws Exc return map; } - private static String getMethodName(String fildeName) throws Exception { - byte[] items = fildeName.getBytes(); + private static String getMethodName(String fieldName) throws Exception { + byte[] items = fieldName.getBytes(); items[0] = (byte) ((char) items[0] - 'a' + 'A'); return new String(items); } diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/PeriodUtil.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/PeriodUtil.java index 739a1a5be..4dabcc3b1 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/PeriodUtil.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/PeriodUtil.java @@ -20,7 +20,7 @@ public class PeriodUtil implements Serializable { public static List toRanges(PeriodType periodType, List periods) { - if (periods.size() == 0) { + if (periods.isEmpty()) { return Collections.emptyList(); } // 排序 @@ -45,7 +45,7 @@ public static List toRanges(PeriodType periodType, List periods) { } public static List toRanges(PeriodType periodType, List periods, int tagsSize) { - if (periods.size() == 0) { + if (periods.isEmpty()) { return Collections.emptyList(); } if (periods.size() * tagsSize < 86400) { diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/webhook/WebhookUtil.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/WebhookUtil.java similarity index 64% rename from server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/webhook/WebhookUtil.java rename to server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/WebhookUtil.java index 1e40aa581..43cb01da1 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/webhook/WebhookUtil.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/WebhookUtil.java @@ -1,13 +1,12 @@ /* * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. */ -package io.holoinsight.server.home.alert.common.webhook; +package io.holoinsight.server.home.alert.common; - -import io.holoinsight.server.home.alert.common.G; -import io.holoinsight.server.home.alert.common.http.HttpProxy; -import io.holoinsight.server.home.alert.common.http.XHttpRequest; -import io.holoinsight.server.home.alert.common.http.XHttpResponse; +import io.holoinsight.server.common.J; +import io.holoinsight.server.common.http.HttpProxy; +import io.holoinsight.server.common.http.XHttpRequest; +import io.holoinsight.server.common.http.XHttpResponse; import io.holoinsight.server.home.alert.model.event.WebhookInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,29 +37,29 @@ public static XHttpResponse sendWebhook(WebhookInfo webhookInfo) { switch (webhookInfo.getRequestType().toUpperCase()) { case "POST": xHttpRequest = XHttpRequest.post(webhookInfo.getRequestUrl(), - G.get().fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000, + J.fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000, webhookInfo.getWebhookMsg().getBytes(UTF_8), CONTENT_TYPE_UTF_8); break; case "GET": xHttpRequest = XHttpRequest.get(webhookInfo.getRequestUrl(), null, - G.get().fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); + J.fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); break; case "PUT": xHttpRequest = XHttpRequest.put(webhookInfo.getRequestUrl(), - G.get().fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), null, + J.fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), null, CONTENT_TYPE_UTF_8, 60000); break; case "DELETE": xHttpRequest = XHttpRequest.delete(webhookInfo.getRequestUrl(), - G.get().fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); + J.fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); break; default: xHttpRequest = XHttpRequest.get(webhookInfo.getRequestUrl(), null, - G.get().fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); + J.fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); } return HttpProxy.request(xHttpRequest); } catch (Exception e) { - LOGGER.error("SendWebhook Exception WebhookInfo:{}", G.get().toJson(webhookInfo), e); + LOGGER.error("SendWebhook Exception WebhookInfo:{}", J.toJson(webhookInfo), e); return null; } } @@ -70,25 +69,25 @@ public static XHttpResponse sendWebhookWithException(WebhookInfo webhookInfo) th switch (webhookInfo.getRequestType().toUpperCase()) { case "POST": xHttpRequest = XHttpRequest.post(webhookInfo.getRequestUrl(), - G.get().fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000, + J.fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000, webhookInfo.getWebhookMsg().getBytes(UTF_8), CONTENT_TYPE_UTF_8); break; case "GET": xHttpRequest = XHttpRequest.get(webhookInfo.getRequestUrl(), null, - G.get().fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); + J.fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); break; case "PUT": xHttpRequest = XHttpRequest.put(webhookInfo.getRequestUrl(), - G.get().fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), null, + J.fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), null, CONTENT_TYPE_UTF_8, 60000); break; case "DELETE": xHttpRequest = XHttpRequest.delete(webhookInfo.getRequestUrl(), - G.get().fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); + J.fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); break; default: xHttpRequest = XHttpRequest.get(webhookInfo.getRequestUrl(), null, - G.get().fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); + J.fromJson(webhookInfo.getRequestHeaders(), Map.class), UTF_8.name(), 60000); } return HttpProxy.request(xHttpRequest); } diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/ByteUtil.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/ByteUtil.java deleted file mode 100644 index 8f2019095..000000000 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/ByteUtil.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. - */ -package io.holoinsight.server.home.alert.common.http; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.nio.charset.Charset; - -public class ByteUtil { - - public static byte[] getBytes(short data) { - byte[] bytes = new byte[2]; - bytes[0] = (byte) (data & 0xff); - bytes[1] = (byte) ((data & 0xff00) >> 8); - return bytes; - } - - public static byte[] getBytes(char data) { - byte[] bytes = new byte[2]; - bytes[0] = (byte) (data); - bytes[1] = (byte) (data >> 8); - return bytes; - } - - public static byte[] getBytes(int data) { - byte[] bytes = new byte[4]; - getBytes(data, bytes, 0); - return bytes; - } - - public static byte[] getBytes(long data) { - byte[] bytes = new byte[8]; - bytes[0] = (byte) (data & 0xff); - bytes[1] = (byte) ((data >> 8) & 0xff); - bytes[2] = (byte) ((data >> 16) & 0xff); - bytes[3] = (byte) ((data >> 24) & 0xff); - bytes[4] = (byte) ((data >> 32) & 0xff); - bytes[5] = (byte) ((data >> 40) & 0xff); - bytes[6] = (byte) ((data >> 48) & 0xff); - bytes[7] = (byte) ((data >> 56) & 0xff); - return bytes; - } - - public static byte[] getBytes(byte[] bytes, int offset, int length) { - byte[] ret = new byte[length]; - System.arraycopy(bytes, offset, ret, 0, length); - return ret; - } - - public static void getBytes(long data, byte[] bytes, int offset) { - bytes[0 + offset] = (byte) (data & 0xff); - bytes[1 + offset] = (byte) ((data >> 8) & 0xff); - bytes[2 + offset] = (byte) ((data >> 16) & 0xff); - bytes[3 + offset] = (byte) ((data >> 24) & 0xff); - bytes[4 + offset] = (byte) ((data >> 32) & 0xff); - bytes[5 + offset] = (byte) ((data >> 40) & 0xff); - bytes[6 + offset] = (byte) ((data >> 48) & 0xff); - bytes[7 + offset] = (byte) ((data >> 56) & 0xff); - } - - public static void getBytes(int data, byte[] bytes, int offset) { - bytes[0 + offset] = (byte) (data & 0xff); - bytes[1 + offset] = (byte) ((data >> 8) & 0xff); - bytes[2 + offset] = (byte) ((data >> 16) & 0xff); - bytes[3 + offset] = (byte) ((data >> 24) & 0xff); - } - - public static byte[] getBytes(float data) { - int intBits = Float.floatToIntBits(data); - return getBytes(intBits); - } - - public static void getBytes(float data, byte[] bytes, int offset) { - int intBits = Float.floatToIntBits(data); - getBytes(intBits, bytes, offset); - } - - public static byte[] getBytes(double data) { - long intBits = Double.doubleToLongBits(data); - return getBytes(intBits); - } - - public static void main(String[] args) { - // System.err.println(getDouble(new byte[] {0, 0, 0, 0, 0, -32, 127, 64}, 0)); - // System.err.println(getDouble(new byte[] {0, 0, 0, 0, 0, 48, 112, 64}, 0)); - } - - public static void getBytes(double data, byte[] bs, int offset) { - long intBits = Double.doubleToLongBits(data); - getBytes(intBits, bs, offset); - } - - public static void getBytes(byte[] from, byte[] bs, int offset) { - System.arraycopy(from, 0, bs, offset, from.length); - } - - public static void copyBytes(byte[] from, int fromOffset, int fromLength, byte[] to, - int toOffset) { - // for (int k = 0; k < fromLength; k++) { - // to[toOffset + k] = from[fromOffset + k]; - // } - System.arraycopy(from, fromOffset, to, toOffset, fromLength); - } - - public static byte[] getBytes(String data, String charsetName) { - Charset charset = Charset.forName(charsetName); - return data.getBytes(charset); - } - - public static byte[] getBytes(String data) { - return getBytes(data, "GBK"); - } - - public static short getShort(byte[] bytes, int offset) { - return (short) ((0xff & bytes[offset + 0]) | (0xff00 & (bytes[offset + 1] << 8))); - } - - public static char getChar(byte[] bytes) { - return (char) ((0xff & bytes[0]) | (0xff00 & (bytes[1] << 8))); - } - - public static int getInt(byte[] bytes, int offset) { - return (0xff & bytes[offset + 0]) | (0xff00 & (bytes[offset + 1] << 8)) - | (0xff0000 & (bytes[offset + 2] << 16)) | (0xff000000 & (bytes[offset + 3] << 24)); - } - - public static long getLong(byte[] bytes, int offset) { - return (0xffL & (long) bytes[offset + 0]) | (0xff00L & ((long) bytes[offset + 1] << 8)) - | (0xff0000L & ((long) bytes[offset + 2] << 16)) - | (0xff000000L & ((long) bytes[offset + 3] << 24)) - | (0xff00000000L & ((long) bytes[offset + 4] << 32)) - | (0xff0000000000L & ((long) bytes[offset + 5] << 40)) - | (0xff000000000000L & ((long) bytes[offset + 6] << 48)) - | (0xff00000000000000L & ((long) bytes[offset + 7] << 56)); - } - - public static float getFloat(byte[] bytes, int offset) { - return Float.intBitsToFloat(getInt(bytes, offset)); - } - - public static double getDouble(byte[] bytes, int offset) { - long l = getLong(bytes, offset); - return Double.longBitsToDouble(l); - } - - public static String getString(byte[] bytes, int offset, int len) { - return new String(bytes, offset, len); - } - - public static byte[] cloneBytes(byte[] bytes) { - if (bytes == null) { - return null; - } - byte[] ret = new byte[bytes.length]; - System.arraycopy(bytes, 0, ret, 0, bytes.length); - return ret; - } - - // 鎵惧埌绗竴娆″嚭鐜扮殑浣嶇疆 - public static int findIndex(byte[] bs, byte b) { - int index = 0; - for (byte by : bs) { - if (by == b) { - return index; - } - index++; - } - return -1; - } - - public static boolean equals(byte[] b1, byte[] b2) { - if (b1 == b2) - return true; - if (b1 == null) - return false; - - if (b1.length != b2.length) - return false; - for (int i = 0; i < b1.length; i++) { - if (b1[i] != b2[i]) - return false; - } - return true; - } - - public static byte[] readStream(InputStream inStream) throws Exception { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int len = -1; - while ((len = inStream.read(buffer)) != -1) { - outStream.write(buffer, 0, len); - } - outStream.close(); - return outStream.toByteArray(); - } -} diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpAsync.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpAsync.java deleted file mode 100644 index 48bcd7a42..000000000 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpAsync.java +++ /dev/null @@ -1,435 +0,0 @@ -/* - * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. - */ -package io.holoinsight.server.home.alert.common.http; - -import lombok.Getter; -import org.apache.http.Consts; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.auth.AuthSchemeProvider; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.config.AuthSchemes; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.config.RequestConfig.Builder; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.concurrent.FutureCallback; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.config.Lookup; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.DnsResolver; -import org.apache.http.entity.AbstractHttpEntity; -import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.auth.BasicSchemeFactory; -import org.apache.http.impl.auth.DigestSchemeFactory; -import org.apache.http.impl.auth.KerberosSchemeFactory; -import org.apache.http.impl.auth.NTLMSchemeFactory; -import org.apache.http.impl.auth.SPNegoSchemeFactory; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.LaxRedirectStrategy; -import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; -import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; -import org.apache.http.impl.nio.client.HttpAsyncClients; -import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; -import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; -import org.apache.http.impl.nio.reactor.IOReactorConfig; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.nio.conn.NoopIOSessionStrategy; -import org.apache.http.nio.conn.SchemeIOSessionStrategy; -import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy; -import org.apache.http.nio.entity.NFileEntity; -import org.apache.http.nio.reactor.ConnectingIOReactor; -import org.apache.http.nio.reactor.IOReactorException; -import org.apache.http.ssl.SSLContexts; -import org.apache.http.util.EntityUtils; - -import javax.net.ssl.SSLContext; -import java.io.File; -import java.io.InputStream; -import java.net.URI; -import java.nio.charset.CodingErrorAction; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.util.LinkedList; -import java.util.List; - -/** - * 异步的HTTP请求对象,可设置代理 - */ -public class HttpAsync { - - @Getter - public static class HttpConfig { - - public static int DEFALUT_CONNECTION_TIMEOUT = 2000; - - public static int DEFALUT_SOCKET_TIMEOUT = 5000; - - private int socketTimeout = DEFALUT_SOCKET_TIMEOUT; // 两个报文之间的间隔时间 - - private int connectTimeout = DEFALUT_CONNECTION_TIMEOUT; // 连接超时 - - private int connectRequestTimeout = DEFALUT_CONNECTION_TIMEOUT; // 连接池获取连接的时间 - - private int poolSize = 3000; // 连接池最大连接数 - - private int maxPerRoute = 1500; // 每个主机的并发最多只有1500 - - private String username; - - private String password; - - private boolean auth = false; - - private String proxyHost; - - private int proxyPort; - - private boolean proxy = false; - - public void proxy(String host, int port) { - proxy = true; - this.proxyHost = host; - this.proxyPort = port; - } - - public void auth(String username, String password) { - auth = true; - this.username = username; - this.password = password; - } - - public void connectionRequestTimeout(int timeout) { - this.connectRequestTimeout = timeout; - } - - public void socketTimeout(int socketTimeout) { - this.socketTimeout = socketTimeout; - } - - public void connectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - } - - public void poolSize(int poolSize) { - this.poolSize = poolSize; - } - - public void maxPerRoute(int maxPerRoute) { - this.maxPerRoute = maxPerRoute; - } - - public HttpAsyncClient build() throws Exception { - return new HttpAsyncClient(this, createAsyncClient()); - } - - private CloseableHttpAsyncClient createAsyncClient() - throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, - KeyStoreException, MalformedChallengeException, IOReactorException { - RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout) - .setSocketTimeout(socketTimeout).build(); - SSLContext sslcontext = SSLContexts.createDefault(); - // 设置协议http和https对应的处理socket链接工厂的对象 - Registry sessionStrategyRegistry = RegistryBuilder - .create().register("http", NoopIOSessionStrategy.INSTANCE) - .register("https", new SSLIOSessionStrategy(sslcontext)).build(); - - // 配置io线程 - IOReactorConfig ioReactorConfig = IOReactorConfig.custom() - .setIoThreadCount(Runtime.getRuntime().availableProcessors()).build(); - // 设置连接池大小 - ConnectingIOReactor ioReactor; - ioReactor = new DefaultConnectingIOReactor(ioReactorConfig); - PoolingNHttpClientConnectionManager conMgr = new PoolingNHttpClientConnectionManager( - ioReactor, null, sessionStrategyRegistry, (DnsResolver) null); - if (poolSize > 0) { - conMgr.setMaxTotal(poolSize); - } - if (maxPerRoute > 0) { - conMgr.setDefaultMaxPerRoute(maxPerRoute); - } else { - conMgr.setDefaultMaxPerRoute(10); - } - ConnectionConfig connectionConfig = - ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE) - .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).build(); - - Lookup authSchemeRegistry = RegistryBuilder.create() - .register(AuthSchemes.BASIC, new BasicSchemeFactory()) - .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) - .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) - .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) - .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build(); - conMgr.setDefaultConnectionConfig(connectionConfig); - HttpAsyncClientBuilder builder = HttpAsyncClients.custom().setConnectionManager(conMgr) - .setDefaultAuthSchemeRegistry(authSchemeRegistry) - .setDefaultCookieStore(new BasicCookieStore()).setDefaultRequestConfig(requestConfig) - .setRedirectStrategy(new LaxRedirectStrategy()); - - if (auth) { - UsernamePasswordCredentials credentials = - new UsernamePasswordCredentials(username, password); - CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(AuthScope.ANY, credentials); - builder.setDefaultCredentialsProvider(credentialsProvider); - } - if (proxy) { - builder.setProxy(new HttpHost(proxyHost, proxyPort)); - } - return builder.build(); - } - } - - public static interface HttpAsyncHandler { - - public void handle(XHttpResponse rep); - - public void onFail(String msg, Exception e); - - } - - public static interface HttpAsyncRetryHandler { - - public void handle(XHttpResponse rep); - - public void onFail(String msg, Exception e, int retryCnt, int maxRetryTimes); - } - - public static class HttpAsyncClient { - private HttpAsyncClient(HttpConfig httpConfig, CloseableHttpAsyncClient asyncHttpClient) { - this.config = httpConfig; - this.asyncHttpClient = asyncHttpClient; - this.asyncHttpClient.start(); - } - - private CloseableHttpAsyncClient asyncHttpClient; - @Getter - private HttpConfig config; - - public void request(XHttpRequest req, HttpAsyncHandler handler) { - try { - HttpRequestBase requestBase = buildHttpRequestBase(req); - HttpClientContext localContext = HttpClientContext.create(); - BasicCookieStore cookieStore = new BasicCookieStore(); - localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); - asyncHttpClient.execute(requestBase, localContext, new FutureCallback() { - @Override - public void failed(Exception ex) { - try { - handler.onFail(req.toString(), ex); - } finally { - requestBase.releaseConnection(); - } - } - - @Override - public void completed(HttpResponse response) { - try { - HttpEntity entity = response.getEntity(); - String headerEtag = null; - if (response.containsHeader("ETag")) { - Header etagHeader = response.getFirstHeader("ETag"); - if (etagHeader != null) { - headerEtag = etagHeader.getValue(); - } - } - String headerLastModify = null; - if (response.containsHeader("Last-Modified")) { - Header lastModifyHeader = response.getFirstHeader("Last-Modified"); - if (lastModifyHeader != null) { - headerLastModify = lastModifyHeader.getValue(); - } - } - byte[] byteResponse = EntityUtils.toByteArray(entity); - XHttpResponse rep = new XHttpResponse(response.getStatusLine().getStatusCode(), - byteResponse == null ? EntityUtils.toString(entity) : null, headerEtag, - headerLastModify); - rep.byteResponse = byteResponse; - handler.handle(rep); - } catch (Exception e) { - failed(e); - } finally { - requestBase.releaseConnection(); - } - } - - @Override - public void cancelled() { - failed(new RuntimeException("The reques is cancelled.")); - } - }); - - } catch (Exception e) { - handler.onFail(e.getMessage(), e); - } - } - - public void request(XHttpRequest req, HttpAsyncRetryHandler handler, int retryCnt, - int maxRetryTimes) { - try { - HttpRequestBase requestBase = buildHttpRequestBase(req); - HttpClientContext localContext = HttpClientContext.create(); - BasicCookieStore cookieStore = new BasicCookieStore(); - localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); - asyncHttpClient.execute(requestBase, localContext, new FutureCallback() { - @Override - public void failed(Exception ex) { - try { - handler.onFail(req.toString(), ex, retryCnt, maxRetryTimes); - } finally { - requestBase.releaseConnection(); - } - } - - @Override - public void completed(HttpResponse response) { - try { - HttpEntity entity = response.getEntity(); - String headerEtag = null; - if (response.containsHeader("ETag")) { - Header etagHeader = response.getFirstHeader("ETag"); - if (etagHeader != null) { - headerEtag = etagHeader.getValue(); - } - } - String headerLastModify = null; - if (response.containsHeader("Last-Modified")) { - Header lastModifyHeader = response.getFirstHeader("Last-Modified"); - if (lastModifyHeader != null) { - headerLastModify = lastModifyHeader.getValue(); - } - } - byte[] byteResponse = EntityUtils.toByteArray(entity); - XHttpResponse rep = new XHttpResponse(response.getStatusLine().getStatusCode(), - byteResponse == null ? EntityUtils.toString(entity) : null, headerEtag, - headerLastModify); - rep.byteResponse = byteResponse; - handler.handle(rep); - } catch (Exception e) { - failed(e); - } finally { - requestBase.releaseConnection(); - } - } - - @Override - public void cancelled() { - failed(new RuntimeException("The reques is cancelled.")); - } - }); - - } catch (Exception e) { - handler.onFail(e.getMessage(), e, retryCnt, maxRetryTimes); - } - } - - private byte[] download(HttpEntity entity) throws Exception { - long length = entity.getContentLength(); - if (length <= 0) { - return null; - } - InputStream in = entity.getContent(); - return ByteUtil.readStream(in); - } - - private HttpRequestBase buildHttpRequestBase(XHttpRequest req) throws Exception { - HttpRequestBase base = doBuildHttpRequestBase(req); - base.setConfig(buildTimeOutConfig(req.timeoutMillisecond)); - if (req.inHeaders != null) { - base.setHeaders(Util.buildHeaders(req.inHeaders)); - } - return base; - } - - /** - * 构建一个自定义的超时参数 - */ - private RequestConfig buildTimeOutConfig(int timeoutMillisecond) { - Builder builder = RequestConfig.custom(); - if (timeoutMillisecond <= 0) { - timeoutMillisecond = config.getSocketTimeout(); - } - builder.setConnectionRequestTimeout(config.getConnectRequestTimeout()); - builder.setConnectTimeout(timeoutMillisecond); - builder.setSocketTimeout(timeoutMillisecond); - RequestConfig requestConfig = builder.build(); - return requestConfig; - } - - private static HttpRequestBase doBuildHttpRequestBase(XHttpRequest req) throws Exception { - String method = req.method.toLowerCase(); - URI uri = URI.create(req.url); - if (req.params != null && !req.params.isEmpty()) { - List pairs = new LinkedList<>(); - req.params.forEach((k, v) -> { - pairs.add(new BasicNameValuePair(k, v + "")); - }); - uri = new URIBuilder(uri).addParameters(pairs).build(); - } - if (method.equals("get")) { - HttpGet get = new HttpGet(uri); - return get; - } else if (method.equals("post")) { - HttpPost post = new HttpPost(uri); - AbstractHttpEntity httpEntity = null; - if (req.postBody != null) { - httpEntity = new ByteArrayEntity(req.postBody); - } else if (req.postForm != null) { - httpEntity = new UrlEncodedFormEntity(Util.buildFormPostBody(req.postForm)); - } else if (req.raw != null) { - httpEntity = new StringEntity(req.raw); - } - if (httpEntity != null) { - if (req.contentType != null) { - httpEntity.setContentType(req.contentType); - } - post.setEntity(httpEntity); - } - return post; - } else if (method.equals("put")) { - HttpPut put = new HttpPut(uri); - AbstractHttpEntity httpEntity = null; - if (req.raw != null) { - httpEntity = new StringEntity(req.raw); - } - if (req.file != null) { - File file = new File(req.file); - httpEntity = new NFileEntity(file); - } - if (httpEntity != null) { - if (req.contentType != null) { - httpEntity.setContentType(req.contentType); - } - if (req.charset != null) { - httpEntity.setContentEncoding(req.charset); - } - put.setEntity(httpEntity); - } - return put; - } else if (method.equals("delete")) { - HttpDelete delete = new HttpDelete(uri); - return delete; - } else { - throw new HttpException("unsupport method"); - } - } - } -} diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpException.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpException.java deleted file mode 100644 index 6a7c32d79..000000000 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpException.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. - */ -package io.holoinsight.server.home.alert.common.http; - -public class HttpException extends Exception { - - /** */ - private static final long serialVersionUID = -7086098942444546040L; - - public HttpException(String msg) { - super(msg); - } - - public HttpException(String msg, Throwable e) { - super(msg, e); - } -} diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpProxy.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpProxy.java deleted file mode 100644 index af617fa22..000000000 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/HttpProxy.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. - */ -package io.holoinsight.server.home.alert.common.http; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * http DataCollection proxy - */ -public class HttpProxy { - - private static final Logger logger = LoggerFactory.getLogger(HttpProxy.class); - - public static final String HEADER_SEND_TIME = "http_proxy_send_time"; - public static final String HEADER_TRACE = "http_proxy_trace"; - - private static HttpAsync.HttpAsyncClient httpAsyncClient; - - private static synchronized void start() { - if (httpAsyncClient == null) { - try { - httpAsyncClient = new HttpAsync.HttpConfig().build(); - } catch (Exception e) { - logger.error("init http async client error:", e); - throw new RuntimeException("init http async client error:", e); - } - } - } - - public static void request(XHttpRequest request, HttpAsync.HttpAsyncHandler handler) { - if (httpAsyncClient == null) { - start(); - } - // 确保header中有请求发送时间 - if (request.inHeaders == null) { - request.inHeaders = new HashMap<>(); - } - long start = System.currentTimeMillis(); - String traceId = UUID.randomUUID().toString(); - - request.inHeaders.put(HEADER_SEND_TIME, String.format("%d", start)); - request.inHeaders.put(HEADER_TRACE, traceId); - httpAsyncClient.request(request, new HttpAsync.HttpAsyncHandler() { - - @Override - public void onFail(String msg, Exception e) { - logger.error("http request[" + request + "] fail, error: " + msg, e); - handler.onFail(msg, e); - } - - @Override - public void handle(XHttpResponse rep) { - logger.info("http request[" + request + "], trace = [" + traceId + "], cost " - + (System.currentTimeMillis() - start) + "ms, code[" + rep.code + "]."); - handler.handle(rep); - } - }); - } - - public static void requestWithRetry(XHttpRequest request, HttpAsync.HttpAsyncRetryHandler handler, - int retryCnt, int maxRetryTimes) { - if (httpAsyncClient == null) { - start(); - } - // 确保header中有请求发送时间 - if (request.inHeaders == null) { - request.inHeaders = new HashMap<>(); - } - long start = System.currentTimeMillis(); - String traceId = UUID.randomUUID().toString(); - - request.inHeaders.put(HEADER_SEND_TIME, String.format("%d", start)); - request.inHeaders.put(HEADER_TRACE, traceId); - httpAsyncClient.request(request, new HttpAsync.HttpAsyncRetryHandler() { - - @Override - public void onFail(String msg, Exception e, int retryCnt, int maxRetryTimes) { - retryCnt++; - logger.error("http request[" + request + "] fail, error: " + msg, e); - if (retryCnt <= maxRetryTimes) { - requestWithRetry(request, handler, retryCnt, maxRetryTimes); - } - handler.onFail(msg, e, retryCnt, maxRetryTimes); - - } - - @Override - public void handle(XHttpResponse rep) { - logger.info("http request[" + request + "], trace = [" + traceId + "], cost " - + (System.currentTimeMillis() - start) + "ms, code[" + rep.code + "]."); - handler.handle(rep); - } - }, retryCnt, maxRetryTimes); - } - - private static class Optional { - boolean sucess; - XHttpResponse response; - String error; - Exception exception; - } - - public static XHttpResponse requestWithRetry(XHttpRequest request, int retryCnt, - int maxRetryTimes) throws Exception { - XHttpResponse response; - try { - response = request(request); - return response; - } catch (Exception e) { - retryCnt++; - if (retryCnt >= maxRetryTimes) { - throw new RuntimeException( - String.format("request fail and reach the max retry times[%s], %s. ", maxRetryTimes, - e.getMessage()), - e); - } else { - return requestWithRetry(request, retryCnt, maxRetryTimes); - } - } - } - - public static XHttpResponse request(XHttpRequest request) throws Exception { - if (httpAsyncClient == null) { - start(); - } - long start = System.currentTimeMillis(); - CountDownLatch latch = new CountDownLatch(1); - Optional optional = new Optional(); - httpAsyncClient.request(request, new HttpAsync.HttpAsyncHandler() { - @Override - public void onFail(String msg, Exception e) { - optional.sucess = false; - optional.error = msg; - optional.exception = e; - latch.countDown(); - } - - @Override - public void handle(XHttpResponse rep) { - optional.sucess = true; - optional.response = rep; - latch.countDown(); - } - }); - latch.await(30, TimeUnit.SECONDS); - if (optional.sucess) { - logger.info("http request[" + request + "] cost " + (System.currentTimeMillis() - start) - + "ms, code[" + optional.response.code + "]."); - return optional.response; - } else { - logger.error("http request[" + request + "] fail, error: " + optional.error, - optional.exception); - throw optional.exception; - } - } - - private static Map genParams() { - Map vParams = new HashMap<>(); - vParams.put("username", "xflush"); - vParams.put("token", "fji73!sp"); - Map params = new HashMap<>(); - params.put("pageSize", 40000); - params.put("currentPage", 1); - - vParams.put("params", params); - return vParams; - } -} diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/Util.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/Util.java deleted file mode 100644 index 0bb989e77..000000000 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/Util.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. - */ -package io.holoinsight.server.home.alert.common.http; - -import org.apache.commons.lang3.StringUtils; -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.HttpException; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.ParseException; -import org.apache.http.message.BasicNameValuePair; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -public class Util { - - public static void checkUrl(String domain, String _url) throws HttpException { - if (StringUtils.isBlank(domain)) { - throw new HttpException("empty domain"); - } else if (!domain.startsWith("http://") && !domain.startsWith("https://")) { - throw new HttpException("inlegal domain: " + domain); - } - } - - public static String getUrl(String domain, String _url, Map params) { - StringBuilder args = new StringBuilder(); - if (params != null && params.size() != 0) { - for (Entry entry : params.entrySet()) { - if (args.length() != 0) { - args.append("&"); - } - args.append(entry.getKey()).append("=").append(entry.getValue()); - } - } - - StringBuilder urlBuilder = new StringBuilder(domain); - if (_url != null) - urlBuilder.append(_url); - if (args.length() > 0) { - if (_url != null && _url.contains("?")) { - urlBuilder.append("&").append(args.toString()); - } else { - urlBuilder.append("?").append(args.toString()); - } - } - return urlBuilder.toString(); - } - - public static Header[] buildHeaders(Map inHeaders) { - List

headerList = new ArrayList
(); - for (Entry inHeaderEntry : inHeaders.entrySet()) { - final Entry tmpE = inHeaderEntry; - headerList.add(new Header() { - - @Override - public String getValue() { - return tmpE.getValue(); - } - - @Override - public String getName() { - return tmpE.getKey(); - } - - @Override - public HeaderElement[] getElements() throws ParseException { - return null; - } - }); - } - return headerList.toArray(new Header[0]); - } - - public static String readData(InputStream in, String charsetName) throws IOException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - - byte[] buffer = new byte[1024]; - int len = 0; - while (true) { - len = in.read(buffer, 0, 1024); - if (len < 0) { - break; - } - bout.write(buffer, 0, len); - } - - return StringUtils.isBlank(charsetName) ? bout.toString() : bout.toString(charsetName); - } - - /** - * 获取response编码 - */ - public static String getCharsetName(HttpResponse response) { - Header header = response.getEntity().getContentType(); - if (header == null) { - return null; - } - HeaderElement[] eles = header.getElements(); - for (HeaderElement ele : eles) { - if (ele.getName().equals("charset")) { - return ele.getValue(); - } - } - return null; - } - - public static List buildFormPostBody(Map postForm) { - - List pairs = new ArrayList<>(); - for (Entry entry : postForm.entrySet()) { - pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); - } - return pairs; - } -} diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/XHttpRequest.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/XHttpRequest.java deleted file mode 100644 index cf3b7af14..000000000 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/XHttpRequest.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. - */ -package io.holoinsight.server.home.alert.common.http; - -import java.io.Serializable; -import java.util.Map; -import java.util.Map.Entry; - -public class XHttpRequest implements Serializable { - private static final long serialVersionUID = 5363323934924301982L; - public String url; - public Map params; - public String charset; - public String method; - public Map inHeaders; - public byte[] postBody; - public String file; - public String raw; - public Map postForm; - public String contentType; - public int timeoutMillisecond; - - public static XHttpRequest get(String url, Map params, - Map inHeaders, String charset, int timeoutMillisecond) { - XHttpRequest ret = new XHttpRequest(); - ret.method = "GET"; - ret.url = url; - ret.params = params; - ret.inHeaders = inHeaders; - ret.charset = charset; - ret.timeoutMillisecond = timeoutMillisecond; - return ret; - } - - public static XHttpRequest get(String url) { - return get(url, 5000); - } - - public static XHttpRequest get(String url, int timeout) { - return get(url, null, null, "utf-8", timeout); - } - - public static XHttpRequest post(String url, Map inHeaders, String charset, - int timeoutMillisecond, byte[] postString) { - return post(url, inHeaders, charset, timeoutMillisecond, postString, null); - } - - public static XHttpRequest post(String url, Map inHeaders, String charset, - int timeoutMillisecond, byte[] postString, String contentType) { - XHttpRequest ret = new XHttpRequest(); - ret.method = "POST"; - ret.url = url; - ret.inHeaders = inHeaders; - ret.charset = charset; - ret.timeoutMillisecond = timeoutMillisecond; - ret.postBody = postString; - ret.contentType = contentType; - return ret; - } - - public static XHttpRequest put(String url, Map inHeaders, String charset, - String raw, String contentType, int timeoutMillisecond) { - XHttpRequest ret = new XHttpRequest(); - ret.method = "put"; - ret.url = url; - ret.inHeaders = inHeaders; - ret.charset = charset; - ret.timeoutMillisecond = timeoutMillisecond; - ret.raw = raw; - ret.contentType = contentType; - return ret; - } - - public static XHttpRequest delete(String url, Map inHeaders, String charset, - int timeoutMillisecond) { - XHttpRequest ret = new XHttpRequest(); - ret.method = "delete"; - ret.url = url; - ret.inHeaders = inHeaders; - ret.charset = charset; - ret.timeoutMillisecond = timeoutMillisecond; - return ret; - } - - public static XHttpRequest putJson(String url, Map inHeaders, String charset, - String raw, int timeoutMillisecond) { - XHttpRequest ret = new XHttpRequest(); - ret.method = "put"; - ret.url = url; - ret.inHeaders = inHeaders; - ret.charset = charset; - ret.timeoutMillisecond = timeoutMillisecond; - ret.raw = raw; - ret.contentType = "application/json"; - return ret; - } - - public static XHttpRequest putFile(String url, String file, Map inHeaders, - int timeoutMillisecond) { - XHttpRequest ret = new XHttpRequest(); - ret.method = "put"; - ret.url = url; - ret.inHeaders = inHeaders; - ret.timeoutMillisecond = timeoutMillisecond; - ret.file = file; - return ret; - } - - public static XHttpRequest post(String url, Map inHeaders, String charset, - int timeoutMillisecond, Map postForm) { - return post(url, inHeaders, charset, timeoutMillisecond, postForm, null); - } - - public static XHttpRequest postJson(String url, Map inHeaders, String charset, - String raw, int timeoutMillisecond) { - XHttpRequest ret = new XHttpRequest(); - ret.method = "post"; - ret.url = url; - ret.inHeaders = inHeaders; - ret.charset = charset; - ret.timeoutMillisecond = timeoutMillisecond; - ret.raw = raw; - ret.contentType = "application/json; charset=utf-8"; - return ret; - } - - public static XHttpRequest post(String url, Map inHeaders, String charset, - int timeoutMillisecond, Map postForm, String contentType) { - XHttpRequest ret = new XHttpRequest(); - ret.method = "POST"; - ret.url = url; - ret.inHeaders = inHeaders; - ret.charset = charset; - ret.timeoutMillisecond = timeoutMillisecond; - ret.postForm = postForm; - ret.contentType = contentType; - return ret; - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("XHttpRequest [url:").append(url).append(";params:") - .append(mapToString(params)).append(";charset=").append(charset).append(", method=") - .append(method).append(", inHeaders=").append(mapToString(inHeaders)) - .append(", postString=").append(postBody).append(", postForm=") - .append(mapToString(postForm)).append(", contentType=").append(contentType) - .append(", timeoutMillisecond=").append(timeoutMillisecond).append("]"); - return stringBuilder.toString(); - } - - private String mapToString(Map map) { - StringBuilder stringBuilder = new StringBuilder(); - if (map == null) { - return null; - } - for (Entry entry : map.entrySet()) { - if (stringBuilder.length() != 0) { - stringBuilder.append("&"); - } - stringBuilder.append(entry.getKey().toString()).append("=") - .append(entry.getValue().toString()); - } - return stringBuilder.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((charset == null) ? 0 : charset.hashCode()); - result = prime * result + ((contentType == null) ? 0 : contentType.hashCode()); - result = prime * result + ((params == null) ? 0 : params.hashCode()); - result = prime * result + ((inHeaders == null) ? 0 : inHeaders.hashCode()); - result = prime * result + ((method == null) ? 0 : method.hashCode()); - result = prime * result + ((postForm == null) ? 0 : postForm.hashCode()); - result = prime * result + ((postBody == null) ? 0 : postBody.hashCode()); - result = prime * result + timeoutMillisecond; - result = prime * result + ((url == null) ? 0 : url.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - XHttpRequest other = (XHttpRequest) obj; - if (charset == null) { - if (other.charset != null) - return false; - } else if (!charset.equals(other.charset)) - return false; - if (contentType == null) { - if (other.contentType != null) - return false; - } else if (!contentType.equals(other.contentType)) - return false; - if (params == null) { - if (other.params != null) - return false; - } else if (other.params == null || !mapToString(this.params).equals(mapToString(other.params))) - return false; - if (inHeaders == null) { - if (other.inHeaders != null) - return false; - } else if (!inHeaders.equals(other.inHeaders)) - return false; - if (method == null) { - if (other.method != null) - return false; - } else if (!method.equals(other.method)) - return false; - if (postForm == null) { - if (other.postForm != null) - return false; - } else if (!postForm.equals(other.postForm)) - return false; - if (postBody == null) { - if (other.postBody != null) - return false; - } else if (!postBody.equals(other.postBody)) - return false; - if (timeoutMillisecond != other.timeoutMillisecond) - return false; - if (url == null) { - if (other.url != null) - return false; - } else if (!url.equals(other.url)) - return false; - return true; - } -} diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/XHttpResponse.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/XHttpResponse.java deleted file mode 100644 index 7222b70b4..000000000 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/common/http/XHttpResponse.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0. - */ -package io.holoinsight.server.home.alert.common.http; - -import java.io.Serializable; - -public class XHttpResponse implements Serializable { - private static final long serialVersionUID = 7444452124053478904L; - public int code; - private String response; - public byte[] byteResponse; - public String headerLastModify; // Last-Modified - public String headerEtag; // ETag - - public XHttpResponse(int code, String response, String headerEtag, String headerLastModify) { - super(); - this.code = code; - this.response = response; - this.headerEtag = headerEtag; - this.headerLastModify = headerLastModify; - } - - @Override - public String toString() { - return "HttpResponse [code=" + code + ", response=" + response + "]"; - } - - public String getStringResponse() { - if (response != null) { - return response; - } - if (byteResponse != null) { - return new String(byteResponse); - } - return null; - } - - public String getStringResponse(String charset) throws Exception { - if (response != null) - return response; - if (byteResponse != null) - return new String(byteResponse, charset); - return null; - } -} diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/plugin/AlertSaveHistoryHandler.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/plugin/AlertSaveHistoryHandler.java index 9a291731c..235bb9707 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/plugin/AlertSaveHistoryHandler.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/plugin/AlertSaveHistoryHandler.java @@ -7,9 +7,19 @@ import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import io.holoinsight.server.common.J; +import io.holoinsight.server.common.dao.entity.AlarmHistory; +import io.holoinsight.server.common.dao.entity.AlarmHistoryDetail; +import io.holoinsight.server.common.dao.entity.dto.AlertHistoryDetailExtra; +import io.holoinsight.server.common.dao.entity.dto.AlertHistoryExtra; +import io.holoinsight.server.common.dao.entity.dto.AlertNotifyRecordDTO; +import io.holoinsight.server.common.dao.entity.dto.AlertSilenceConfig; import io.holoinsight.server.common.dao.entity.dto.InspectConfig; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.DataSource; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.Trigger; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; +import io.holoinsight.server.common.dao.mapper.AlarmHistoryDetailMapper; +import io.holoinsight.server.common.dao.mapper.AlarmHistoryMapper; import io.holoinsight.server.home.alert.common.AlarmContentGenerator; -import io.holoinsight.server.home.alert.common.G; import io.holoinsight.server.home.alert.common.TimeRangeUtil; import io.holoinsight.server.home.alert.model.event.AlertNotify; import io.holoinsight.server.home.alert.model.event.NotifyDataInfo; @@ -17,17 +27,6 @@ import io.holoinsight.server.home.alert.service.event.AlertHandlerExecutor; import io.holoinsight.server.home.alert.service.event.RecordSucOrFailNotify; import io.holoinsight.server.home.common.service.QueryClientService; -import io.holoinsight.server.common.dao.mapper.AlarmHistoryDetailMapper; -import io.holoinsight.server.common.dao.mapper.AlarmHistoryMapper; -import io.holoinsight.server.common.dao.entity.AlarmHistory; -import io.holoinsight.server.common.dao.entity.AlarmHistoryDetail; -import io.holoinsight.server.common.dao.entity.dto.AlertHistoryExtra; -import io.holoinsight.server.common.dao.entity.dto.AlertNotifyRecordDTO; -import io.holoinsight.server.common.dao.entity.dto.AlertSilenceConfig; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; -import io.holoinsight.server.common.dao.entity.dto.AlertHistoryDetailExtra; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.DataSource; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.Trigger; import io.holoinsight.server.query.grpc.QueryProto; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -323,7 +322,7 @@ private void makeAlertHistory(Map alertHistoryMap, alertHistory.setRuleName(alertNotify.getRuleName()); alertHistory.setAlarmLevel(alertNotify.getAlarmLevel()); // 设置最新的触发条件 - Set triggerList = G.get().fromJson(alertHistory.getTriggerContent(), Set.class); + Set triggerList = J.fromJson(alertHistory.getTriggerContent(), Set.class); List notifyDataInfos = new ArrayList<>(); alertNotify.getNotifyDataInfos().forEach((key, value) -> { notifyDataInfos.addAll(value); @@ -334,7 +333,7 @@ private void makeAlertHistory(Map alertHistoryMap, .filter(trigger -> !triggerList.contains(trigger)).collect(Collectors.toSet()); if (!triggerListNew.isEmpty()) { triggerList.addAll(triggerListNew); - alertHistory.setTriggerContent(G.get().toJson(triggerList)); + alertHistory.setTriggerContent(J.toJson(triggerList)); } if (hasSilenceConfig(alertNotify)) { AlertHistoryExtra alertHistoryExtra = getAlertHistoryExtra(alertHistory.getExtra()); @@ -486,7 +485,7 @@ private void genPqlAlertHistoryDetail(AlertNotify alertNotify, Long historyId) { alarmHistoryDetail.setDatasource(alertNotify.getPqlRule().getPql()); List> tagList = alertNotify.getPqlRule().getDataResult().stream() .map(TriggerDataResult::getTags).collect(Collectors.toList()); - alarmHistoryDetail.setTags(G.get().toJson(tagList)); + alarmHistoryDetail.setTags(J.toJson(tagList)); alarmHistoryDetail.setAlarmContent(AlarmContentGenerator.genPqlAlarmContent( alertNotify.getPqlRule().getPql(), alertNotify.getPqlRule().getDataResult())); alarmHistoryDetailDOMapper.insert(alarmHistoryDetail); @@ -510,8 +509,8 @@ private void genAlertHistoryDetail(AlertNotify alertNotify, Long historyId) { alarmHistoryDetail.setTenant(alertNotify.getTenant()); alarmHistoryDetail.setGmtCreate(new Date()); alarmHistoryDetail.setEnvType(alertNotify.getEnvType()); - alarmHistoryDetail.setDatasource(G.get().toJson(trigger)); - alarmHistoryDetail.setTags(G.get().toJson(tagList)); + alarmHistoryDetail.setDatasource(J.toJson(trigger)); + alarmHistoryDetail.setTags(J.toJson(tagList)); alarmHistoryDetail.setWorkspace(alertNotify.getWorkspace()); String alarmContentJson = getAlertContentJsonList(notifyDataInfoList); alarmHistoryDetail.setAlarmContent(alarmContentJson); diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/plugin/GetSubscriptionHandler.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/plugin/GetSubscriptionHandler.java index c2a30d595..4f103fa2e 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/plugin/GetSubscriptionHandler.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/plugin/GetSubscriptionHandler.java @@ -7,29 +7,28 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.google.common.reflect.TypeToken; import io.holoinsight.server.common.J; -import io.holoinsight.server.common.dao.entity.dto.InspectConfig; -import io.holoinsight.server.home.alert.common.G; -import io.holoinsight.server.home.alert.model.event.AlertNotify; -import io.holoinsight.server.home.alert.model.event.NotifyDataInfo; -import io.holoinsight.server.home.alert.model.event.WebhookInfo; -import io.holoinsight.server.home.alert.service.converter.DoConvert; -import io.holoinsight.server.home.alert.service.event.AlertHandlerExecutor; -import io.holoinsight.server.home.alert.service.event.RecordSucOrFailNotify; -import io.holoinsight.server.common.service.RequestContextAdapter; -import io.holoinsight.server.common.dao.mapper.AlarmBlockMapper; -import io.holoinsight.server.common.dao.mapper.AlarmDingDingRobotMapper; -import io.holoinsight.server.common.dao.mapper.AlarmGroupMapper; -import io.holoinsight.server.common.dao.mapper.AlarmSubscribeMapper; -import io.holoinsight.server.common.dao.mapper.AlarmWebhookMapper; import io.holoinsight.server.common.dao.entity.AlarmBlock; import io.holoinsight.server.common.dao.entity.AlarmDingDingRobot; import io.holoinsight.server.common.dao.entity.AlarmGroup; import io.holoinsight.server.common.dao.entity.AlarmSubscribe; import io.holoinsight.server.common.dao.entity.AlarmWebhook; import io.holoinsight.server.common.dao.entity.dto.AlertSilenceConfig; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; +import io.holoinsight.server.common.dao.entity.dto.InspectConfig; import io.holoinsight.server.common.dao.entity.dto.alarm.PqlRule; import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.Trigger; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; +import io.holoinsight.server.common.dao.mapper.AlarmBlockMapper; +import io.holoinsight.server.common.dao.mapper.AlarmDingDingRobotMapper; +import io.holoinsight.server.common.dao.mapper.AlarmGroupMapper; +import io.holoinsight.server.common.dao.mapper.AlarmSubscribeMapper; +import io.holoinsight.server.common.dao.mapper.AlarmWebhookMapper; +import io.holoinsight.server.common.service.RequestContextAdapter; +import io.holoinsight.server.home.alert.model.event.AlertNotify; +import io.holoinsight.server.home.alert.model.event.NotifyDataInfo; +import io.holoinsight.server.home.alert.model.event.WebhookInfo; +import io.holoinsight.server.home.alert.service.converter.DoConvert; +import io.holoinsight.server.home.alert.service.event.AlertHandlerExecutor; +import io.holoinsight.server.home.alert.service.event.RecordSucOrFailNotify; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -83,7 +82,7 @@ public void handle(List alertNotifies) { try { Map> alertWebhookMap = getWebhookMap(alertNotifies); - LOGGER.info("AlertWebhookMap SUCCESS {} ", G.get().toJson(alertWebhookMap)); + LOGGER.info("AlertWebhookMap SUCCESS {} ", J.toJson(alertWebhookMap)); handleBlock(alertNotifies); @@ -101,7 +100,7 @@ public void handle(List alertNotifies) { List alertSubscribeList = alarmSubscribeDOMapper.selectList(alertSubscribeQueryWrapper); LOGGER.info("{} GetSubscription_SUCCESS {} {} ", alertNotify.getTraceId(), - alertNotify.getUniqueId(), G.get().toJson(alertSubscribeList)); + alertNotify.getUniqueId(), J.toJson(alertSubscribeList)); InspectConfig inspectConfig = alertNotify.getRuleConfig(); if (keepSilence(alertNotify.notifyRecover(), inspectConfig.getAlertSilenceConfig(), @@ -121,7 +120,7 @@ public void handle(List alertNotifies) { LOGGER.warn("{} invalid noticeTypeStr {}", alertNotify.getTraceId(), noticeTypeStr); continue; } - List noticeTypeList = G.parseList(noticeTypeStr, String.class); + List noticeTypeList = J.parseList(noticeTypeStr, String.class); for (String noticeType : noticeTypeList) { switch (noticeType) { case "dingDing": @@ -137,7 +136,7 @@ public void handle(List alertNotifies) { break; } Map> map = - G.get().fromJson(alarmGroup.getGroupInfo(), Map.class); + J.fromJson(alarmGroup.getGroupInfo(), Map.class); personList = map.get("person"); } else if (alertSubscribe.getSubscriber() != null) { String userId = alertSubscribe.getSubscriber(); @@ -161,7 +160,7 @@ public void handle(List alertNotifies) { AlarmGroup alarmGroup = alarmGroupDOMapper.selectOne(wrapper); if (StringUtils.isNotBlank(alarmGroup.getGroupInfo())) { Map> map = - G.get().fromJson(alarmGroup.getGroupInfo(), Map.class); + J.fromJson(alarmGroup.getGroupInfo(), Map.class); List ddRobotIds = map.get("ding_ding_robot"); if (!CollectionUtils.isEmpty(ddRobotIds)) { for (String id : ddRobotIds) { @@ -179,7 +178,7 @@ public void handle(List alertNotifies) { webhookInfos.add(DoConvert.alertWebhookDoConverter(alertWebhook)); } LOGGER.info("{} webhookInfos is {}.", alertNotify.getTraceId(), - G.get().toJson(webhookInfos)); + J.toJson(webhookInfos)); } else { LOGGER.info("{} alert is recover.", alertNotify.getTraceId()); } @@ -273,7 +272,7 @@ private void handleBlock(List alertNotifies) { } Map tagMap = - G.get().fromJson(alertBlock.getTags(), new TypeToken>() {}.getType()); + J.fromJson(alertBlock.getTags(), new TypeToken>() {}.getType()); if (!CollectionUtils.isEmpty(tagMap)) { if (alertNotify.isPqlNotify()) { @@ -354,8 +353,7 @@ private void addGlobalWebhook(AlertNotify alertNotify, webhookInfos.addAll(alertWebhookList.stream().map(DoConvert::alertWebhookDoConverter) .collect(Collectors.toList())); } - LOGGER.info("{} global webhookInfos is {}.", alertNotify.getTraceId(), - G.get().toJson(webhookInfos)); + LOGGER.info("{} global webhookInfos is {}.", alertNotify.getTraceId(), J.toJson(webhookInfos)); alertNotify.getWebhookInfos().addAll(webhookInfos); } diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/AlertService.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/AlertService.java index 36afa9a42..5225daad7 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/AlertService.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/AlertService.java @@ -8,11 +8,11 @@ import java.util.Collections; import java.util.Map; +import io.holoinsight.server.common.http.XHttpResponse; import org.springframework.stereotype.Service; import io.holoinsight.server.common.J; -import io.holoinsight.server.home.alert.common.http.XHttpResponse; -import io.holoinsight.server.home.alert.common.webhook.WebhookUtil; +import io.holoinsight.server.home.alert.common.WebhookUtil; import io.holoinsight.server.home.alert.model.event.WebhookInfo; import io.holoinsight.server.home.common.service.query.WebhookResponse; import io.holoinsight.server.common.dao.entity.dto.AlarmWebhookTestDTO; diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AlertTaskCompute.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AlertTaskCompute.java index 61027316a..094094576 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AlertTaskCompute.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AlertTaskCompute.java @@ -4,9 +4,13 @@ package io.holoinsight.server.home.alert.service.calculate; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import io.holoinsight.server.common.J; +import io.holoinsight.server.common.dao.entity.AlarmHistory; +import io.holoinsight.server.common.dao.entity.dto.AlertNotifyRecordDTO; import io.holoinsight.server.common.dao.entity.dto.InspectConfig; +import io.holoinsight.server.common.dao.mapper.AlarmHistoryMapper; +import io.holoinsight.server.common.model.HoloinsightAlertIllegalArgumentException; import io.holoinsight.server.home.alert.common.AlertStat; -import io.holoinsight.server.home.alert.common.G; import io.holoinsight.server.home.alert.model.compute.ComputeContext; import io.holoinsight.server.home.alert.model.compute.ComputeTaskPackage; import io.holoinsight.server.home.alert.model.event.AlertNotify; @@ -16,10 +20,6 @@ import io.holoinsight.server.home.alert.service.event.AlertEventService; import io.holoinsight.server.home.alert.service.event.RecordSucOrFailNotify; import io.holoinsight.server.home.alert.service.task.AlarmTaskExecutor; -import io.holoinsight.server.common.model.HoloinsightAlertIllegalArgumentException; -import io.holoinsight.server.common.dao.mapper.AlarmHistoryMapper; -import io.holoinsight.server.common.dao.entity.AlarmHistory; -import io.holoinsight.server.common.dao.entity.dto.AlertNotifyRecordDTO; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -184,8 +184,7 @@ protected List calculate(ComputeTaskPackage computeTaskPackage) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("{} {} {} calculate package {} ,eventList: {}", computeTaskPackage.getTraceId(), inspectConfig.getTraceId(), - inspectConfig.getUniqueId(), G.get().toJson(inspectConfig), - G.get().toJson(eventInfo)); + inspectConfig.getUniqueId(), J.toJson(inspectConfig), J.toJson(eventInfo)); } String result = eventInfo == null ? "N" : "Y"; LOGGER.info("{} {} {} calculate result: {}", computeTaskPackage.getTraceId(), diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AlgorithmHttp.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AlgorithmHttp.java index 039066549..fd9c915b1 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AlgorithmHttp.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AlgorithmHttp.java @@ -3,9 +3,9 @@ */ package io.holoinsight.server.home.alert.service.calculate; -import io.holoinsight.server.home.alert.common.http.HttpProxy; -import io.holoinsight.server.home.alert.common.http.XHttpRequest; -import io.holoinsight.server.home.alert.common.http.XHttpResponse; +import io.holoinsight.server.common.http.HttpProxy; +import io.holoinsight.server.common.http.XHttpRequest; +import io.holoinsight.server.common.http.XHttpResponse; import org.apache.http.client.config.RequestConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AnomalyDownAbnormalDetect.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AnomalyDownAbnormalDetect.java index 36e29bb04..3a038993c 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AnomalyDownAbnormalDetect.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AnomalyDownAbnormalDetect.java @@ -3,8 +3,11 @@ */ package io.holoinsight.server.home.alert.service.calculate; - -import io.holoinsight.server.home.alert.common.G; +import io.holoinsight.server.common.J; +import io.holoinsight.server.common.dao.emuns.FunctionEnum; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerAIResult; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerResult; import io.holoinsight.server.home.alert.model.compute.algorithm.anomaly.AlgorithmConfig; import io.holoinsight.server.home.alert.model.compute.algorithm.anomaly.AnomalyAlgorithmRequest; import io.holoinsight.server.home.alert.model.compute.algorithm.anomaly.AnomalyAlgorithmResponse; @@ -12,10 +15,6 @@ import io.holoinsight.server.home.alert.model.function.FunctionConfigAIParam; import io.holoinsight.server.home.alert.model.function.FunctionConfigParam; import io.holoinsight.server.home.alert.model.function.FunctionLogic; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; -import io.holoinsight.server.common.dao.emuns.FunctionEnum; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerAIResult; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -63,10 +62,10 @@ public TriggerResult invoke(TriggerDataResult triggerDataResult, // Set the name of the algorithm interface String algoUrl = url + "/anomaly_detect"; // Call algorithm interface - String abnormalResult = AlgorithmHttp.invokeAlgorithm(algoUrl, G.get().toJson(algorithmRequest), + String abnormalResult = AlgorithmHttp.invokeAlgorithm(algoUrl, J.toJson(algorithmRequest), functionConfigParam.getTraceId()); AnomalyAlgorithmResponse anomalyAlgorithmResponse = - G.get().fromJson(abnormalResult, AnomalyAlgorithmResponse.class); + J.fromJson(abnormalResult, AnomalyAlgorithmResponse.class); if (anomalyAlgorithmResponse != null && anomalyAlgorithmResponse.getIsSuccessful() && anomalyAlgorithmResponse.getIsException()) { triggerAIResult.setHit(true); diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AnomalyUpAbnormalDetect.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AnomalyUpAbnormalDetect.java index fa9f9c2de..c0a864d1d 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AnomalyUpAbnormalDetect.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/AnomalyUpAbnormalDetect.java @@ -3,8 +3,11 @@ */ package io.holoinsight.server.home.alert.service.calculate; - -import io.holoinsight.server.home.alert.common.G; +import io.holoinsight.server.common.J; +import io.holoinsight.server.common.dao.emuns.FunctionEnum; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerAIResult; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerResult; import io.holoinsight.server.home.alert.model.compute.algorithm.anomaly.AlgorithmConfig; import io.holoinsight.server.home.alert.model.compute.algorithm.anomaly.AnomalyAlgorithmRequest; import io.holoinsight.server.home.alert.model.compute.algorithm.anomaly.AnomalyAlgorithmResponse; @@ -12,10 +15,6 @@ import io.holoinsight.server.home.alert.model.function.FunctionConfigAIParam; import io.holoinsight.server.home.alert.model.function.FunctionConfigParam; import io.holoinsight.server.home.alert.model.function.FunctionLogic; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; -import io.holoinsight.server.common.dao.emuns.FunctionEnum; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerAIResult; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -63,10 +62,10 @@ public TriggerResult invoke(TriggerDataResult triggerDataResult, // Set the name of the algorithm interface String algoUrl = url + "/anomaly_detect"; // Call algorithm interface - String abnormalResult = AlgorithmHttp.invokeAlgorithm(algoUrl, G.get().toJson(algorithmRequest), + String abnormalResult = AlgorithmHttp.invokeAlgorithm(algoUrl, J.toJson(algorithmRequest), functionConfigParam.getTraceId()); AnomalyAlgorithmResponse anomalyAlgorithmResponse = - G.get().fromJson(abnormalResult, AnomalyAlgorithmResponse.class); + J.fromJson(abnormalResult, AnomalyAlgorithmResponse.class); if (anomalyAlgorithmResponse != null && anomalyAlgorithmResponse.getIsSuccessful() && anomalyAlgorithmResponse.getIsException()) { triggerAIResult.setHit(true); diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/ValueDownAbnormalDetect.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/ValueDownAbnormalDetect.java index 7536f7b3d..793c645f7 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/ValueDownAbnormalDetect.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/ValueDownAbnormalDetect.java @@ -3,8 +3,13 @@ */ package io.holoinsight.server.home.alert.service.calculate; - -import io.holoinsight.server.home.alert.common.G; +import io.holoinsight.server.common.J; +import io.holoinsight.server.common.dao.emuns.FunctionEnum; +import io.holoinsight.server.common.dao.emuns.PeriodType; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.RuleConfig; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerAIResult; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerResult; import io.holoinsight.server.home.alert.model.compute.algorithm.AlgorithmConfig; import io.holoinsight.server.home.alert.model.compute.algorithm.DatasourceConfig; import io.holoinsight.server.home.alert.model.compute.algorithm.ExtendConfig; @@ -13,12 +18,6 @@ import io.holoinsight.server.home.alert.model.function.FunctionConfigAIParam; import io.holoinsight.server.home.alert.model.function.FunctionConfigParam; import io.holoinsight.server.home.alert.model.function.FunctionLogic; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; -import io.holoinsight.server.common.dao.emuns.FunctionEnum; -import io.holoinsight.server.common.dao.emuns.PeriodType; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.RuleConfig; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerAIResult; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -74,10 +73,10 @@ public TriggerResult invoke(TriggerDataResult triggerDataResult, // Set the name of the algorithm interface String algoUrl = url + "/serving"; // Call algorithm interface - String abnormalResult = AlgorithmHttp.invokeAlgorithm(algoUrl, - G.get().toJson(valueAlgorithmRequest), functionConfigParam.getTraceId()); + String abnormalResult = AlgorithmHttp.invokeAlgorithm(algoUrl, J.toJson(valueAlgorithmRequest), + functionConfigParam.getTraceId()); ValueAlgorithmResponse valueAlgorithmResponse = - G.get().fromJson(abnormalResult, ValueAlgorithmResponse.class); + J.fromJson(abnormalResult, ValueAlgorithmResponse.class); if (valueAlgorithmResponse != null && valueAlgorithmResponse.getIsException()) { triggerAIResult.setHit(true); triggerAIResult diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/ValueUpAbnormalDetect.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/ValueUpAbnormalDetect.java index cc08d42d0..ce50b81a4 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/ValueUpAbnormalDetect.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/calculate/ValueUpAbnormalDetect.java @@ -3,8 +3,13 @@ */ package io.holoinsight.server.home.alert.service.calculate; - -import io.holoinsight.server.home.alert.common.G; +import io.holoinsight.server.common.J; +import io.holoinsight.server.common.dao.emuns.FunctionEnum; +import io.holoinsight.server.common.dao.emuns.PeriodType; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.RuleConfig; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerAIResult; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerResult; import io.holoinsight.server.home.alert.model.compute.algorithm.AlgorithmConfig; import io.holoinsight.server.home.alert.model.compute.algorithm.DatasourceConfig; import io.holoinsight.server.home.alert.model.compute.algorithm.ExtendConfig; @@ -13,12 +18,6 @@ import io.holoinsight.server.home.alert.model.function.FunctionConfigAIParam; import io.holoinsight.server.home.alert.model.function.FunctionConfigParam; import io.holoinsight.server.home.alert.model.function.FunctionLogic; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; -import io.holoinsight.server.common.dao.emuns.FunctionEnum; -import io.holoinsight.server.common.dao.emuns.PeriodType; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.RuleConfig; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerAIResult; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -74,10 +73,10 @@ public TriggerResult invoke(TriggerDataResult triggerDataResult, // Set the name of the algorithm interface String algoUrl = url + "/serving"; // Call algorithm interface - String abnormalResult = AlgorithmHttp.invokeAlgorithm(algoUrl, - G.get().toJson(valueAlgorithmRequest), functionConfigParam.getTraceId()); + String abnormalResult = AlgorithmHttp.invokeAlgorithm(algoUrl, J.toJson(valueAlgorithmRequest), + functionConfigParam.getTraceId()); ValueAlgorithmResponse valueAlgorithmResponse = - G.get().fromJson(abnormalResult, ValueAlgorithmResponse.class); + J.fromJson(abnormalResult, ValueAlgorithmResponse.class); if (valueAlgorithmResponse != null && valueAlgorithmResponse.getIsException()) { triggerAIResult.setHit(true); triggerAIResult diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/converter/DoConvert.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/converter/DoConvert.java index 532458c0f..a4c04a4fa 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/converter/DoConvert.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/converter/DoConvert.java @@ -4,20 +4,19 @@ package io.holoinsight.server.home.alert.service.converter; import io.holoinsight.server.common.J; -import io.holoinsight.server.home.alert.common.G; -import io.holoinsight.server.home.alert.model.event.AlertNotify; -import io.holoinsight.server.home.alert.model.event.NotifyDataInfo; -import io.holoinsight.server.home.alert.model.event.WebhookInfo; import io.holoinsight.server.common.dao.entity.AlarmHistory; import io.holoinsight.server.common.dao.entity.AlarmRule; import io.holoinsight.server.common.dao.entity.AlarmWebhook; import io.holoinsight.server.common.dao.entity.dto.AlertRuleExtra; import io.holoinsight.server.common.dao.entity.dto.InspectConfig; -import io.holoinsight.server.common.dao.entity.dto.alarm.PqlRule; import io.holoinsight.server.common.dao.entity.dto.alarm.AlarmRuleConf; +import io.holoinsight.server.common.dao.entity.dto.alarm.PqlRule; import io.holoinsight.server.common.dao.entity.dto.alarm.TimeFilter; import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.DataSource; import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.Trigger; +import io.holoinsight.server.home.alert.model.event.AlertNotify; +import io.holoinsight.server.home.alert.model.event.NotifyDataInfo; +import io.holoinsight.server.home.alert.model.event.WebhookInfo; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -52,11 +51,11 @@ public static InspectConfig alarmRuleConverter(AlarmRule alarmRuleDO) { inspectConfig.setIsPql(true); inspectConfig.setPqlRule(pqlRule); } else { - inspectConfig.setRule(G.get().fromJson(alarmRuleDO.getRule(), AlarmRuleConf.class)); + inspectConfig.setRule(J.fromJson(alarmRuleDO.getRule(), AlarmRuleConf.class)); inspectConfig.setIsPql(false); inspectConfig.setMetrics(getMetricsFromRule(inspectConfig.getRule())); } - inspectConfig.setTimeFilter(G.get().fromJson(alarmRuleDO.getTimeFilter(), TimeFilter.class)); + inspectConfig.setTimeFilter(J.fromJson(alarmRuleDO.getTimeFilter(), TimeFilter.class)); inspectConfig.setStatus(alarmRuleDO.getStatus() != 0); inspectConfig.setIsMerge(alarmRuleDO.getIsMerge() != 0); inspectConfig.setRecover(alarmRuleDO.getRecover() != 0); @@ -67,7 +66,7 @@ public static InspectConfig alarmRuleConverter(AlarmRule alarmRuleDO) { inspectConfig.setAlertSilenceConfig(alertRuleExtra.alertSilenceConfig); } } catch (Exception e) { - LOGGER.error("fail to convert alarmRule {}", G.get().toJson(alarmRuleDO), e); + LOGGER.error("fail to convert alarmRule {}", J.toJson(alarmRuleDO), e); } return inspectConfig; } @@ -110,7 +109,7 @@ public static AlarmHistory alertHistoryConverter(AlertNotify alertNotify) { notifyDataInfos.addAll(value); }); notifyDataInfos.forEach(e -> triggerContent.add(e.getTriggerContent())); - alarmHistory.setTriggerContent(G.get().toJson(triggerContent)); + alarmHistory.setTriggerContent(J.toJson(triggerContent)); } alarmHistory.setGmtCreate(new Date()); alarmHistory.setAlarmTime(new Date(alertNotify.getAlarmTime())); diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/data/load/AIAlarmLoadData.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/data/load/AIAlarmLoadData.java index 15a60af0f..153fa439d 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/data/load/AIAlarmLoadData.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/data/load/AIAlarmLoadData.java @@ -3,16 +3,16 @@ */ package io.holoinsight.server.home.alert.service.data.load; -import io.holoinsight.server.home.alert.common.G; -import io.holoinsight.server.home.alert.model.compute.ComputeTaskPackage; -import io.holoinsight.server.home.alert.service.data.AlarmLoadData; -import io.holoinsight.server.home.common.service.QueryClientService; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; -import io.holoinsight.server.common.dao.entity.dto.InspectConfig; +import io.holoinsight.server.common.J; import io.holoinsight.server.common.dao.emuns.PeriodType; +import io.holoinsight.server.common.dao.entity.dto.InspectConfig; import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.DataSource; import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.Filter; import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.Trigger; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; +import io.holoinsight.server.home.alert.model.compute.ComputeTaskPackage; +import io.holoinsight.server.home.alert.service.data.AlarmLoadData; +import io.holoinsight.server.home.common.service.QueryClientService; import io.holoinsight.server.query.grpc.QueryProto; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -137,11 +137,11 @@ private QueryProto.QueryResponse getData(InspectConfig inspectConfig, Trigger tr response = queryClientService.queryData(request, "AI_ALERT"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("{} QueryData Success Request:{} Response:{}", inspectConfig.getTraceId(), - G.get().toJson(request), G.get().toJson(response)); + J.toJson(request), J.toJson(response)); } } catch (Exception e) { - LOGGER.error("QueryData Exception Request:{} Response:{}", G.get().toJson(request), - G.get().toJson(response), e); + LOGGER.error("QueryData Exception Request:{} Response:{}", J.toJson(request), + J.toJson(response), e); } return response; } diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/data/load/RuleAlarmLoadData.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/data/load/RuleAlarmLoadData.java index d1c3b2b48..3b08a5e4d 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/data/load/RuleAlarmLoadData.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/data/load/RuleAlarmLoadData.java @@ -3,16 +3,16 @@ */ package io.holoinsight.server.home.alert.service.data.load; -import io.holoinsight.server.home.alert.common.G; -import io.holoinsight.server.home.alert.model.compute.ComputeTaskPackage; -import io.holoinsight.server.home.alert.service.data.AlarmLoadData; -import io.holoinsight.server.home.common.service.QueryClientService; -import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; -import io.holoinsight.server.common.dao.entity.dto.InspectConfig; +import io.holoinsight.server.common.J; import io.holoinsight.server.common.dao.emuns.PeriodType; +import io.holoinsight.server.common.dao.entity.dto.InspectConfig; import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.DataSource; import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.Filter; import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.Trigger; +import io.holoinsight.server.common.dao.entity.dto.alarm.trigger.TriggerDataResult; +import io.holoinsight.server.home.alert.model.compute.ComputeTaskPackage; +import io.holoinsight.server.home.alert.service.data.AlarmLoadData; +import io.holoinsight.server.home.common.service.QueryClientService; import io.holoinsight.server.query.grpc.QueryProto; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -61,8 +61,8 @@ public List queryDataResult(ComputeTaskPackage computeTask, } catch (Exception exception) { LOGGER.error( "{} QueryData Exception Request:{} Response:{} DeltaRequest:{} DeltaResponse: {}", - inspectConfig.getTraceId(), G.get().toJson(request), G.get().toJson(response), - G.get().toJson(deltaRequest), G.get().toJson(deltaResponse), exception); + inspectConfig.getTraceId(), J.toJson(request), J.toJson(response), J.toJson(deltaRequest), + J.toJson(deltaResponse), exception); } return triggerDataResults; } diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerBuildMsgHandler.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerBuildMsgHandler.java index a4da2ea5b..c7f3d6845 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerBuildMsgHandler.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerBuildMsgHandler.java @@ -4,16 +4,15 @@ package io.holoinsight.server.home.alert.service.event.alertManagerEvent; import io.holoinsight.server.common.J; +import io.holoinsight.server.common.dao.entity.dto.alarm.TemplateValue; +import io.holoinsight.server.common.model.HoloinsightAlertInternalException; import io.holoinsight.server.home.alert.common.AlarmConstant; import io.holoinsight.server.home.alert.common.AlarmRegexUtil; -import io.holoinsight.server.home.alert.common.G; import io.holoinsight.server.home.alert.common.ObjectToMapUtil; import io.holoinsight.server.home.alert.model.event.AlertNotify; import io.holoinsight.server.home.alert.model.event.ElementSpiEnum; import io.holoinsight.server.home.alert.service.event.AlertHandlerExecutor; import io.holoinsight.server.home.alert.service.event.element.ElementSpiServiceFactory; -import io.holoinsight.server.common.model.HoloinsightAlertInternalException; -import io.holoinsight.server.common.dao.entity.dto.alarm.TemplateValue; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -65,7 +64,7 @@ public void handle(List alarmNotifies) { alarmNotify.getMsgList().add(markDownMsg); }); }); - LOGGER.info("AlertManagerBuildMsgHandler SUCCESS {} ", G.get().toJson(alarmNotifies)); + LOGGER.info("AlertManagerBuildMsgHandler SUCCESS {} ", J.toJson(alarmNotifies)); } catch (Exception e) { LOGGER.error("AlertManagerBuildMsgHandler Exception", e); } diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerSaveHistoryHandler.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerSaveHistoryHandler.java index 47bf4acb2..bf3894b86 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerSaveHistoryHandler.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerSaveHistoryHandler.java @@ -3,11 +3,11 @@ */ package io.holoinsight.server.home.alert.service.event.alertManagerEvent; -import io.holoinsight.server.home.alert.common.G; +import io.holoinsight.server.common.J; +import io.holoinsight.server.common.dao.entity.AlarmHistory; +import io.holoinsight.server.common.dao.mapper.AlarmHistoryMapper; import io.holoinsight.server.home.alert.model.event.AlertNotify; import io.holoinsight.server.home.alert.service.event.AlertHandlerExecutor; -import io.holoinsight.server.common.dao.mapper.AlarmHistoryMapper; -import io.holoinsight.server.common.dao.entity.AlarmHistory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @@ -41,7 +41,7 @@ public void handle(List alarmNotifies) { alarmHistoryDOMap.insert(alertHistoryDO); }); - LOGGER.info("AlertManagerSaveHistoryHandler SUCCESS {} ", G.get().toJson(alarmNotifies)); + LOGGER.info("AlertManagerSaveHistoryHandler SUCCESS {} ", J.toJson(alarmNotifies)); } catch (Exception e) { LOGGER.error("AlertManagerSaveHistoryHandler Exception", e); } diff --git a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerSendMsgHandler.java b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerSendMsgHandler.java index 97cdeaf30..b6623612c 100644 --- a/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerSendMsgHandler.java +++ b/server/home/home-alert/src/main/java/io/holoinsight/server/home/alert/service/event/alertManagerEvent/AlertManagerSendMsgHandler.java @@ -3,9 +3,9 @@ */ package io.holoinsight.server.home.alert.service.event.alertManagerEvent; -import io.holoinsight.server.home.alert.common.G; -import io.holoinsight.server.home.alert.common.http.XHttpResponse; -import io.holoinsight.server.home.alert.common.webhook.WebhookUtil; +import io.holoinsight.server.common.J; +import io.holoinsight.server.common.http.XHttpResponse; +import io.holoinsight.server.home.alert.common.WebhookUtil; import io.holoinsight.server.home.alert.model.event.AlertNotify; import io.holoinsight.server.home.alert.service.event.AlertHandlerExecutor; import org.slf4j.Logger; @@ -34,12 +34,12 @@ public void handle(List alarmNotifies) { if (alarmNotify.getWebhookInfos() != null) { alarmNotify.getWebhookInfos().forEach(webhookInfo -> { XHttpResponse xHttpResponse = WebhookUtil.sendWebhook(webhookInfo); - LOGGER.info("XHttpResponse: {} ", G.get().toJson(xHttpResponse)); + LOGGER.info("XHttpResponse: {} ", J.toJson(xHttpResponse)); }); } }); - LOGGER.info("AlarmSendWebhook SUCCESS {} ", G.get().toJson(alarmNotifies)); + LOGGER.info("AlarmSendWebhook SUCCESS {} ", J.toJson(alarmNotifies)); } catch (Exception e) { LOGGER.error("AlarmSendWebhook Exception", e); } @@ -48,7 +48,7 @@ public void handle(List alarmNotifies) { try { alarmNotifies.forEach(alarmNotify -> { }); - LOGGER.info("AlarmSendMsgHandler SUCCESS {} ", G.get().toJson(alarmNotifies)); + LOGGER.info("AlarmSendMsgHandler SUCCESS {} ", J.toJson(alarmNotifies)); } catch (Exception e) { LOGGER.error("AlarmSendMsgHandler Exception", e); } diff --git a/server/home/home-common/pom.xml b/server/home/home-common/pom.xml index 1b88238fe..beb5d9e58 100644 --- a/server/home/home-common/pom.xml +++ b/server/home/home-common/pom.xml @@ -69,19 +69,19 @@ - - org.yaml - snakeyaml - - - com.aliyun.openservices - aliyun-log - - - org.springframework.boot - spring-boot-starter-web - provided - + + + + + + + + + + + + + net.devh grpc-client-spring-boot-autoconfigure @@ -92,10 +92,7 @@ org.apache.logging.log4j log4j-api - - org.apache.httpcomponents - httpasyncclient - + diff --git a/server/home/home-service/src/main/java/io/holoinsight/server/home/biz/service/gpt/GptService.java b/server/home/home-service/src/main/java/io/holoinsight/server/home/biz/service/gpt/GptService.java index 6b8ef5fc2..ab0d6ca04 100644 --- a/server/home/home-service/src/main/java/io/holoinsight/server/home/biz/service/gpt/GptService.java +++ b/server/home/home-service/src/main/java/io/holoinsight/server/home/biz/service/gpt/GptService.java @@ -5,9 +5,9 @@ import com.alibaba.fastjson.JSON; import io.holoinsight.server.common.config.EnvironmentProperties; -import io.holoinsight.server.home.common.http.HttpProxy; -import io.holoinsight.server.home.common.http.XHttpRequest; -import io.holoinsight.server.home.common.http.XHttpResponse; +import io.holoinsight.server.common.http.HttpProxy; +import io.holoinsight.server.common.http.XHttpRequest; +import io.holoinsight.server.common.http.XHttpResponse; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;