diff --git a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertConvergeController.java b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertConvergeController.java index 06485446c7b..25742040423 100644 --- a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertConvergeController.java +++ b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertConvergeController.java @@ -35,8 +35,8 @@ /** * Alarm Converge management API * 告警收敛管理API - * @author tom * + * @author tom */ @Tag(name = "Alert Converge API | 告警收敛管理API") @RestController @@ -51,7 +51,7 @@ public class AlertConvergeController { public ResponseEntity> addNewAlertConverge(@Valid @RequestBody AlertConverge alertConverge) { alertConvergeService.validate(alertConverge, false); alertConvergeService.addAlertConverge(alertConverge); - return ResponseEntity.ok(new Message<>("Add success")); + return ResponseEntity.ok(Message.success("Add success")); } @PutMapping @@ -59,7 +59,7 @@ public ResponseEntity> addNewAlertConverge(@Valid @RequestBody Ale public ResponseEntity> modifyAlertConverge(@Valid @RequestBody AlertConverge alertConverge) { alertConvergeService.validate(alertConverge, true); alertConvergeService.modifyAlertConverge(alertConverge); - return ResponseEntity.ok(new Message<>("Modify success")); + return ResponseEntity.ok(Message.success("Modify success")); } @GetMapping(path = "/{id}") @@ -68,13 +68,11 @@ public ResponseEntity> modifyAlertConverge(@Valid @RequestBody Ale public ResponseEntity> getAlertConverge( @Parameter(description = "Alarm Converge ID | 告警收敛ID", example = "6565463543") @PathVariable("id") long id) { AlertConverge alertConverge = alertConvergeService.getAlertConverge(id); - Message.MessageBuilder messageBuilder = Message.builder(); if (alertConverge == null) { - messageBuilder.code(MONITOR_NOT_EXIST_CODE).msg("AlertConverge not exist."); + return ResponseEntity.ok(Message.fail(MONITOR_NOT_EXIST_CODE, "AlertConverge not exist.")); } else { - messageBuilder.data(alertConverge); + return ResponseEntity.ok(Message.success(alertConverge)); } - return ResponseEntity.ok(messageBuilder.build()); } } diff --git a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertConvergesController.java b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertConvergesController.java index cf60dd94788..b89c25e49d2 100644 --- a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertConvergesController.java +++ b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertConvergesController.java @@ -42,8 +42,8 @@ /** * Converge the batch API for alarms * 收敛告警批量API - * @author tom * + * @author tom */ @Tag(name = "Alert Converge Batch API | 告警收敛管理API") @RestController @@ -66,7 +66,7 @@ public ResponseEntity>> getAlertConverges( Specification specification = (root, query, criteriaBuilder) -> { List andList = new ArrayList<>(); if (ids != null && !ids.isEmpty()) { - CriteriaBuilder.In inPredicate= criteriaBuilder.in(root.get("id")); + CriteriaBuilder.In inPredicate = criteriaBuilder.in(root.get("id")); for (long id : ids) { inPredicate.value(id); } @@ -77,9 +77,8 @@ public ResponseEntity>> getAlertConverges( }; Sort sortExp = Sort.by(new Sort.Order(Sort.Direction.fromString(order), sort)); PageRequest pageRequest = PageRequest.of(pageIndex, pageSize, sortExp); - Page alertConvergePage = alertConvergeService.getAlertConverges(specification,pageRequest); - Message> message = new Message<>(alertConvergePage); - return ResponseEntity.ok(message); + Page alertConvergePage = alertConvergeService.getAlertConverges(specification, pageRequest); + return ResponseEntity.ok(Message.success(alertConvergePage)); } @DeleteMapping @@ -91,8 +90,7 @@ public ResponseEntity> deleteAlertDefines( if (ids != null && !ids.isEmpty()) { alertConvergeService.deleteAlertConverges(new HashSet<>(ids)); } - Message message = new Message<>(); - return ResponseEntity.ok(message); + return ResponseEntity.ok(Message.success()); } } diff --git a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertDefineController.java b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertDefineController.java index 5d493e98add..d5d21e7eb1f 100644 --- a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertDefineController.java +++ b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertDefineController.java @@ -46,8 +46,8 @@ /** * Alarm definition management API * 告警定义管理API - * @author tom * + * @author tom */ @Tag(name = "Alert Define API | 告警定义管理API") @RestController @@ -64,7 +64,7 @@ public ResponseEntity> addNewAlertDefine(@Valid @RequestBody Alert // 校验请求数据 alertDefineService.validate(alertDefine, false); alertDefineService.addAlertDefine(alertDefine); - return ResponseEntity.ok(new Message<>("Add success")); + return ResponseEntity.ok(Message.success("Add success")); } @PutMapping @@ -74,7 +74,7 @@ public ResponseEntity> modifyAlertDefine(@Valid @RequestBody Alert // 校验请求数据 alertDefineService.validate(alertDefine, true); alertDefineService.modifyAlertDefine(alertDefine); - return ResponseEntity.ok(new Message<>("Modify success")); + return ResponseEntity.ok(Message.success("Modify success")); } @GetMapping(path = "/{id}") @@ -85,13 +85,11 @@ public ResponseEntity> getAlertDefine( // Obtaining Monitoring Information // 获取监控信息 AlertDefine alertDefine = alertDefineService.getAlertDefine(id); - Message.MessageBuilder messageBuilder = Message.builder(); if (alertDefine == null) { - messageBuilder.code(MONITOR_NOT_EXIST_CODE).msg("AlertDefine not exist."); + return ResponseEntity.ok(Message.fail(MONITOR_NOT_EXIST_CODE, "AlertDefine not exist.")); } else { - messageBuilder.data(alertDefine); + return ResponseEntity.ok(Message.success(alertDefine)); } - return ResponseEntity.ok(messageBuilder.build()); } @DeleteMapping(path = "/{id}") @@ -102,7 +100,7 @@ public ResponseEntity> deleteAlertDefine( // If the alarm definition does not exist or is deleted successfully, the deletion succeeds // 删除告警定义不存在或删除成功都返回成功 alertDefineService.deleteAlertDefine(id); - return ResponseEntity.ok(new Message<>("Delete success")); + return ResponseEntity.ok(Message.success("Delete success")); } @PostMapping(path = "/{alertDefineId}/monitors") @@ -112,7 +110,7 @@ public ResponseEntity> applyAlertDefineMonitorsBind( @Parameter(description = "Alarm Definition ID | 告警定义ID", example = "6565463543") @PathVariable("alertDefineId") long alertDefineId, @RequestBody List alertDefineMonitorBinds) { alertDefineService.applyBindAlertDefineMonitors(alertDefineId, alertDefineMonitorBinds); - return ResponseEntity.ok(new Message<>("Apply success")); + return ResponseEntity.ok(Message.success("Apply success")); } @GetMapping(path = "/{alertDefineId}/monitors") @@ -122,7 +120,7 @@ public ResponseEntity>> getAlertDefineMonit @Parameter(description = "Alarm Definition ID | 告警定义ID", example = "6565463543") @PathVariable("alertDefineId") long alertDefineId) { List defineBinds = alertDefineService.getBindAlertDefineMonitors(alertDefineId); defineBinds = defineBinds.stream().filter(item -> item.getMonitor() != null).collect(Collectors.toList()); - return ResponseEntity.ok(new Message<>(defineBinds)); + return ResponseEntity.ok(Message.success(defineBinds)); } } diff --git a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertDefinesController.java b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertDefinesController.java index 296cc989ab7..fb8b2393d68 100644 --- a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertDefinesController.java +++ b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertDefinesController.java @@ -46,8 +46,8 @@ /** * Define the batch API for alarms * 告警定义批量API - * @author tom * + * @author tom */ @Tag(name = "Alert Define Batch API | 告警定义管理API") @RestController @@ -71,7 +71,7 @@ public ResponseEntity>> getAlertDefines( Specification specification = (root, query, criteriaBuilder) -> { List andList = new ArrayList<>(); if (ids != null && !ids.isEmpty()) { - CriteriaBuilder.In inPredicate= criteriaBuilder.in(root.get("id")); + CriteriaBuilder.In inPredicate = criteriaBuilder.in(root.get("id")); for (long id : ids) { inPredicate.value(id); } @@ -87,9 +87,8 @@ public ResponseEntity>> getAlertDefines( // 分页是必须的 Sort sortExp = Sort.by(new Sort.Order(Sort.Direction.fromString(order), sort)); PageRequest pageRequest = PageRequest.of(pageIndex, pageSize, sortExp); - Page alertDefinePage = alertDefineService.getAlertDefines(specification,pageRequest); - Message> message = new Message<>(alertDefinePage); - return ResponseEntity.ok(message); + Page alertDefinePage = alertDefineService.getAlertDefines(specification, pageRequest); + return ResponseEntity.ok(Message.success(alertDefinePage)); } @DeleteMapping @@ -101,8 +100,7 @@ public ResponseEntity> deleteAlertDefines( if (ids != null && !ids.isEmpty()) { alertDefineService.deleteAlertDefines(new HashSet<>(ids)); } - Message message = new Message<>(); - return ResponseEntity.ok(message); + return ResponseEntity.ok(Message.success()); } @GetMapping("/app") @@ -136,9 +134,8 @@ public ResponseEntity>> getAlertDefinesByName( // 分页是必须的 Sort sortExp = Sort.by(new Sort.Order(Sort.Direction.fromString(order), sort)); PageRequest pageRequest = PageRequest.of(pageIndex, pageSize, sortExp); - Page alertDefinePage = alertDefineService.getAlertDefines(specification,pageRequest); - Message> message = new Message<>(alertDefinePage); - return ResponseEntity.ok(message); + Page alertDefinePage = alertDefineService.getAlertDefines(specification, pageRequest); + return ResponseEntity.ok(Message.success(alertDefinePage)); } } diff --git a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertReportController.java b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertReportController.java index 54a879ae779..548eccd1d3b 100644 --- a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertReportController.java +++ b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertReportController.java @@ -25,20 +25,20 @@ @RestController @RequestMapping(path = "/api/alerts/report", produces = {APPLICATION_JSON_VALUE}) public class AlertReportController { - + @Autowired AlertConvertTenCloudServiceImpl alertConvertTenCloudService; - + @Autowired private AlertService alertService; - + @PostMapping("/tencloud") @Operation(summary = "Interface for reporting external alarm information of tencloud | 对外上报告警信息 接口", description = "对外 新增一个腾讯云告警") public ResponseEntity> addNewAlertReportTencent(@Valid @RequestBody String alertReport) { AlertReport convert = alertConvertTenCloudService.convert(alertReport); alertService.addNewAlertReport(convert); - return ResponseEntity.ok(new Message<>("Add report success")); + return ResponseEntity.ok(Message.success("Add report success")); } @PostMapping @@ -47,6 +47,6 @@ public ResponseEntity> addNewAlertReportTencent(@Valid @RequestBod public ResponseEntity> addNewAlertReport(@Valid @RequestBody AlertReport alertReport) { // 校验请求数据 TODO alertService.addNewAlertReport(alertReport); - return ResponseEntity.ok(new Message<>("Add report success")); + return ResponseEntity.ok(Message.success("Add report success")); } } diff --git a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertSilenceController.java b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertSilenceController.java index 79bcf52cd13..257c1f43441 100644 --- a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertSilenceController.java +++ b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertSilenceController.java @@ -36,8 +36,8 @@ /** * Alarm Silence management API * 告警静默管理API - * @author tom * + * @author tom */ @Tag(name = "Alert Silence API | 告警静默管理API") @RestController @@ -52,7 +52,7 @@ public class AlertSilenceController { public ResponseEntity> addNewAlertSilence(@Valid @RequestBody AlertSilence alertSilence) { alertSilenceService.validate(alertSilence, false); alertSilenceService.addAlertSilence(alertSilence); - return ResponseEntity.ok(new Message<>("Add success")); + return ResponseEntity.ok(Message.success("Add success")); } @PutMapping @@ -60,7 +60,7 @@ public ResponseEntity> addNewAlertSilence(@Valid @RequestBody Aler public ResponseEntity> modifyAlertSilence(@Valid @RequestBody AlertSilence alertSilence) { alertSilenceService.validate(alertSilence, true); alertSilenceService.modifyAlertSilence(alertSilence); - return ResponseEntity.ok(new Message<>("Modify success")); + return ResponseEntity.ok(Message.success("Modify success")); } @GetMapping(path = "/{id}") @@ -69,13 +69,11 @@ public ResponseEntity> modifyAlertSilence(@Valid @RequestBody Aler public ResponseEntity> getAlertSilence( @Parameter(description = "Alarm Silence ID | 告警静默ID", example = "6565463543") @PathVariable("id") long id) { AlertSilence alertSilence = alertSilenceService.getAlertSilence(id); - Message.MessageBuilder messageBuilder = Message.builder(); if (alertSilence == null) { - messageBuilder.code(MONITOR_NOT_EXIST_CODE).msg("AlertSilence not exist."); + return ResponseEntity.ok(Message.fail(MONITOR_NOT_EXIST_CODE, "AlertSilence not exist.")); } else { - messageBuilder.data(alertSilence); + return ResponseEntity.ok(Message.success(alertSilence)); } - return ResponseEntity.ok(messageBuilder.build()); } } diff --git a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertSilencesController.java b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertSilencesController.java index 4c80e57530a..c2ae18719d3 100644 --- a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertSilencesController.java +++ b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertSilencesController.java @@ -78,7 +78,7 @@ public ResponseEntity>> getAlertSilences( Sort sortExp = Sort.by(new Sort.Order(Sort.Direction.fromString(order), sort)); PageRequest pageRequest = PageRequest.of(pageIndex, pageSize, sortExp); Page alertSilencePage = alertSilenceService.getAlertSilences(specification,pageRequest); - Message> message = new Message<>(alertSilencePage); + Message> message = Message.success(alertSilencePage); return ResponseEntity.ok(message); } @@ -91,7 +91,7 @@ public ResponseEntity> deleteAlertDefines( if (ids != null && !ids.isEmpty()) { alertSilenceService.deleteAlertSilences(new HashSet<>(ids)); } - Message message = new Message<>(); + Message message = Message.success(); return ResponseEntity.ok(message); } diff --git a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertsController.java b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertsController.java index 3242bcafa25..43e71f1cff6 100644 --- a/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertsController.java +++ b/alerter/src/main/java/org/dromara/hertzbeat/alert/controller/AlertsController.java @@ -90,7 +90,7 @@ public ResponseEntity>> getAlerts( Predicate predicate = criteriaBuilder.equal(root.get("status"), status); andList.add(predicate); } - if (content != null && !"".equals(content)) { + if (content != null && !content.isEmpty()) { Predicate predicateContent = criteriaBuilder.like(root.get("content"), "%" + content + "%"); andList.add(predicateContent); } @@ -100,7 +100,7 @@ public ResponseEntity>> getAlerts( Sort sortExp = Sort.by(new Sort.Order(Sort.Direction.fromString(order), sort)); PageRequest pageRequest = PageRequest.of(pageIndex, pageSize, sortExp); Page alertPage = alertService.getAlerts(specification, pageRequest); - Message> message = new Message<>(alertPage); + Message> message = Message.success(alertPage); return ResponseEntity.ok(message); } @@ -111,7 +111,7 @@ public ResponseEntity> deleteAlerts( if (ids != null && !ids.isEmpty()) { alertService.deleteAlerts(new HashSet<>(ids)); } - Message message = new Message<>(); + Message message = Message.success(); return ResponseEntity.ok(message); } @@ -119,7 +119,7 @@ public ResponseEntity> deleteAlerts( @Operation(summary = "Delete alarms in batches", description = "清空所有告警信息") public ResponseEntity> clearAllAlerts() { alertService.clearAlerts(); - Message message = new Message<>(); + Message message = Message.success(); return ResponseEntity.ok(message); } @@ -131,7 +131,7 @@ public ResponseEntity> applyAlertDefinesStatus( if (ids != null && status != null && !ids.isEmpty()) { alertService.editAlertStatus(status, ids); } - Message message = new Message<>(); + Message message = Message.success(); return ResponseEntity.ok(message); } @@ -139,7 +139,7 @@ public ResponseEntity> applyAlertDefinesStatus( @Operation(summary = "Get alarm statistics", description = "获取告警统计信息") public ResponseEntity> getAlertsSummary() { AlertSummary alertSummary = alertService.getAlertsSummary(); - Message message = new Message<>(alertSummary); + Message message = Message.success(alertSummary); return ResponseEntity.ok(message); } diff --git a/common/src/main/java/org/dromara/hertzbeat/common/entity/dto/Message.java b/common/src/main/java/org/dromara/hertzbeat/common/entity/dto/Message.java index 71f5a299f25..a584a0be916 100644 --- a/common/src/main/java/org/dromara/hertzbeat/common/entity/dto/Message.java +++ b/common/src/main/java/org/dromara/hertzbeat/common/entity/dto/Message.java @@ -18,28 +18,22 @@ package org.dromara.hertzbeat.common.entity.dto; import io.swagger.v3.oas.annotations.media.Schema; -import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Data; -import lombok.NoArgsConstructor; import static org.dromara.hertzbeat.common.constants.CommonConstants.SUCCESS_CODE; /** * Unified message structure definition for front and back ends - * + *

* { - * data:{....}, - * msg: message, - * code: 3432 + * data:{....}, + * msg: message, + * code: 3432 * } - * @author tomsun28 * + * @author tomsun28 */ @Data -@Builder -@AllArgsConstructor -@NoArgsConstructor @Schema(description = "公共消息包装") public class Message { @@ -61,16 +55,35 @@ public class Message { @Schema(title = "携带编码") private byte code = SUCCESS_CODE; - public Message(String msg) { + public static Message success() { + return new Message<>(); + } + + public static Message success(String msg) { + return new Message<>(msg); + } + + public static Message fail(byte code, String msg) { + return new Message<>(code, msg); + } + + public static Message success(T data) { + return new Message<>(data); + } + + private Message() { + } + + private Message(String msg) { this.msg = msg; } - public Message(byte code, String msg) { + private Message(byte code, String msg) { this.code = code; this.msg = msg; } - public Message(T data) { + private Message(T data) { this.data = data; } } diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/AccountController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/AccountController.java index c2a3bee452e..92a99fcf3e7 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/AccountController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/AccountController.java @@ -27,7 +27,6 @@ import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; -import org.dromara.hertzbeat.common.constants.CommonConstants; import org.dromara.hertzbeat.common.entity.dto.Message; import org.dromara.hertzbeat.common.util.JsonUtil; import org.dromara.hertzbeat.manager.pojo.dto.LoginDto; @@ -41,6 +40,7 @@ import java.util.List; import java.util.Map; +import static org.dromara.hertzbeat.common.constants.CommonConstants.MONITOR_LOGIN_FAILED_CODE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; /** @@ -48,7 +48,6 @@ * 认证注册TOKEN管理API * * @author tomsun28 - * */ @Tag(name = "Auth Manage API | 认证注册TOKEN管理API") @RestController() @@ -70,23 +69,17 @@ public class AccountController { public ResponseEntity>> authGetToken(@Valid @RequestBody LoginDto loginDto) { SurenessAccount account = accountProvider.loadAccount(loginDto.getIdentifier()); if (account == null || account.getPassword() == null) { - Message> message = Message.>builder().msg("账户密码错误") - .code(CommonConstants.MONITOR_LOGIN_FAILED_CODE).build(); - return ResponseEntity.ok(message); + return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "账户密码错误")); } else { String password = loginDto.getCredential(); if (account.getSalt() != null) { password = Md5Util.md5(password + account.getSalt()); } if (!account.getPassword().equals(password)) { - Message> message = Message.>builder().msg("账户密码错误") - .code(CommonConstants.MONITOR_LOGIN_FAILED_CODE).build(); - return ResponseEntity.ok(message); + return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "账户密码错误")); } if (account.isDisabledAccount() || account.isExcessiveAttempts()) { - Message> message = Message.>builder().msg("账户过期或被锁定") - .code(CommonConstants.MONITOR_LOGIN_FAILED_CODE).build(); - return ResponseEntity.ok(message); + return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "账户过期或被锁定")); } } // Get the roles the user has - rbac @@ -100,7 +93,7 @@ public ResponseEntity>> authGetToken(@Valid @Request resp.put("token", issueToken); resp.put("refreshToken", issueRefresh); resp.put("role", JsonUtil.toJson(roles)); - return ResponseEntity.ok(new Message<>(resp)); + return ResponseEntity.ok(Message.success(resp)); } @GetMapping("/refresh/{refreshToken}") @@ -113,22 +106,23 @@ public ResponseEntity> refreshToken( String userId = String.valueOf(claims.getSubject()); boolean isRefresh = claims.get("refresh", Boolean.class); if (userId == null || !isRefresh) { - return ResponseEntity.ok(new Message<>(CommonConstants.MONITOR_LOGIN_FAILED_CODE, "非法的刷新TOKEN")); + return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "非法的刷新TOKEN")); } SurenessAccount account = accountProvider.loadAccount(userId); if (account == null) { - return ResponseEntity.ok(new Message<>(CommonConstants.MONITOR_LOGIN_FAILED_CODE, "TOKEN对应的账户不存在")); + return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "TOKEN对应的账户不存在")); } List roles = account.getOwnRoles(); String issueToken = issueToken(userId, roles, PERIOD_TIME); String issueRefresh = issueToken(userId, roles, PERIOD_TIME << 5); RefreshTokenResponse response = new RefreshTokenResponse(issueToken, issueRefresh); - return ResponseEntity.ok(new Message<>(response)); + return ResponseEntity.ok(Message.success(response)); } catch (Exception e) { log.error("Exception occurred during token refresh: {}", e.getClass().getName(), e); - return ResponseEntity.ok(new Message<>(CommonConstants.MONITOR_LOGIN_FAILED_CODE, "刷新TOKEN过期或错误")); + return ResponseEntity.ok(Message.fail(MONITOR_LOGIN_FAILED_CODE, "刷新TOKEN过期或错误")); } } + private String issueToken(String userId, List roles, long expirationMillis) { Map customClaimMap = new HashMap<>(1); customClaimMap.put("refresh", true); diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/AppController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/AppController.java index f4c36b69912..c7c68787855 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/AppController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/AppController.java @@ -17,16 +17,15 @@ package org.dromara.hertzbeat.manager.controller; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; import org.dromara.hertzbeat.common.entity.dto.Message; import org.dromara.hertzbeat.common.entity.job.Job; import org.dromara.hertzbeat.common.entity.manager.ParamDefine; -import org.dromara.hertzbeat.common.constants.CommonConstants; import org.dromara.hertzbeat.manager.pojo.dto.Hierarchy; import org.dromara.hertzbeat.manager.pojo.dto.MonitorDefineDto; import org.dromara.hertzbeat.manager.service.AppService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -34,13 +33,15 @@ import javax.validation.Valid; import java.util.List; import java.util.Locale; + +import static org.dromara.hertzbeat.common.constants.CommonConstants.FAIL_CODE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; /** * Monitoring Type Management API * 监控类型管理API - * @author tomsun28 * + * @author tomsun28 */ @Tag(name = "Monitor Type Manage API | 监控类型管理API") @RestController @@ -55,7 +56,7 @@ public class AppController { public ResponseEntity>> queryAppParamDefines( @Parameter(description = "en: Monitoring type name,zh: 监控类型名称", example = "api") @PathVariable("app") final String app) { List paramDefines = appService.getAppParamDefines(app.toLowerCase()); - return ResponseEntity.ok(new Message<>(paramDefines)); + return ResponseEntity.ok(Message.success(paramDefines)); } @GetMapping(path = "/{app}/define") @@ -63,7 +64,7 @@ public ResponseEntity>> queryAppParamDefines( public ResponseEntity> queryAppDefine( @Parameter(description = "en: Monitoring type name,zh: 监控类型名称", example = "api") @PathVariable("app") final String app) { Job define = appService.getAppDefine(app.toLowerCase()); - return ResponseEntity.ok(new Message<>(define)); + return ResponseEntity.ok(Message.success(define)); } @GetMapping(path = "/{app}/define/yml") @@ -71,7 +72,7 @@ public ResponseEntity> queryAppDefine( public ResponseEntity> queryAppDefineYml( @Parameter(description = "en: Monitoring type name,zh: 监控类型名称", example = "api") @PathVariable("app") final String app) { String defineContent = appService.getMonitorDefineFileContent(app); - return ResponseEntity.ok(Message.builder().data(defineContent).build()); + return ResponseEntity.ok(Message.success(defineContent)); } @DeleteMapping(path = "/{app}/define/yml") @@ -81,11 +82,9 @@ public ResponseEntity> deleteAppDefineYml( try { appService.deleteMonitorDefine(app); } catch (Exception e) { - return ResponseEntity.ok(Message.builder() - .code(CommonConstants.FAIL_CODE) - .msg(e.getMessage()).build()); + return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage())); } - return ResponseEntity.ok(Message.builder().build()); + return ResponseEntity.ok(Message.success()); } @PostMapping(path = "/define/yml") @@ -94,24 +93,20 @@ public ResponseEntity> newAppDefineYml(@Valid @RequestBody Monitor try { appService.applyMonitorDefineYml(defineDto.getDefine(), false); } catch (Exception e) { - return ResponseEntity.ok(Message.builder() - .code(CommonConstants.FAIL_CODE) - .msg(e.getMessage()).build()); + return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage())); } - return ResponseEntity.ok(Message.builder().build()); + return ResponseEntity.ok(Message.success()); } - + @PutMapping(path = "/define/yml") @Operation(summary = "Update monitoring type define yml", description = "更新监控类型的定义YML") public ResponseEntity> updateAppDefineYml(@Valid @RequestBody MonitorDefineDto defineDto) { try { appService.applyMonitorDefineYml(defineDto.getDefine(), true); } catch (Exception e) { - return ResponseEntity.ok(Message.builder() - .code(CommonConstants.FAIL_CODE) - .msg(e.getMessage()).build()); + return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage())); } - return ResponseEntity.ok(Message.builder().build()); + return ResponseEntity.ok(Message.success()); } @GetMapping(path = "/hierarchy") @@ -120,7 +115,7 @@ public ResponseEntity>> queryAppsHierarchy( @Parameter(description = "en: language type,zh: 语言类型", example = "zh-CN") @RequestParam(name = "lang", required = false) String lang) { - if (lang == null || "".equals(lang)) { + if (lang == null || lang.isEmpty()) { lang = "zh-CN"; } if (lang.contains(Locale.ENGLISH.getLanguage())) { @@ -131,6 +126,6 @@ public ResponseEntity>> queryAppsHierarchy( lang = "en-US"; } List appHierarchies = appService.getAllAppHierarchy(lang); - return ResponseEntity.ok(new Message<>(appHierarchies)); + return ResponseEntity.ok(Message.success(appHierarchies)); } } diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/CollectorController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/CollectorController.java index d75315c8af7..03e9025167e 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/CollectorController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/CollectorController.java @@ -62,7 +62,7 @@ public ResponseEntity>> getCollectors( } Specification specification = (root, query, criteriaBuilder) -> { Predicate predicate = criteriaBuilder.conjunction(); - if (name != null && !"".equals(name)) { + if (name != null && !name.isEmpty()) { Predicate predicateName = criteriaBuilder.like(root.get("name"), "%" + name + "%"); predicate = criteriaBuilder.and(predicateName); } @@ -70,7 +70,7 @@ public ResponseEntity>> getCollectors( }; PageRequest pageRequest = PageRequest.of(pageIndex, pageSize); Page receivers = collectorService.getCollectors(specification, pageRequest); - Message> message = new Message<>(receivers); + Message> message = Message.success(receivers); return ResponseEntity.ok(message); } } diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/GeneralConfigController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/GeneralConfigController.java index 01caf12217f..e4605fc8bee 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/GeneralConfigController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/GeneralConfigController.java @@ -22,7 +22,6 @@ * 告警发送端配置API * * @author zqr10159 - * */ @RestController @RequestMapping(value = "/api/config", produces = {APPLICATION_JSON_VALUE}) @@ -30,14 +29,14 @@ @Slf4j public class GeneralConfigController { private Map configServiceMap; - + public GeneralConfigController(List generalConfigServices) { configServiceMap = new HashMap<>(8); if (generalConfigServices != null) { generalConfigServices.forEach(config -> configServiceMap.put(config.type(), config)); } } - + @PostMapping(path = "/{type}") @Operation(summary = "Save the sender config", description = "保存公共配置") public ResponseEntity> saveOrUpdateConfig( @@ -49,18 +48,18 @@ public ResponseEntity> saveOrUpdateConfig( throw new IllegalArgumentException("Not supported this config type: " + type); } configService.saveConfig(config); - return ResponseEntity.ok(new Message<>("Update config success")); + return ResponseEntity.ok(Message.success("Update config success")); } @GetMapping(path = "/{type}") @Operation(summary = "Get the sender config", description = "获取发送端配置") public ResponseEntity> getConfig( @Parameter(description = "Config Type", example = "email") - @PathVariable("type") @NotNull final String type){ + @PathVariable("type") @NotNull final String type) { GeneralConfigService configService = configServiceMap.get(type); if (configService == null) { throw new IllegalArgumentException("Not supported this config type: " + type); } - return ResponseEntity.ok(new Message<>(configService.getConfig())); + return ResponseEntity.ok(Message.success(configService.getConfig())); } } diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/I18nController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/I18nController.java index bdf6c120232..8180582e16e 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/I18nController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/I18nController.java @@ -50,12 +50,12 @@ public class I18nController { public ResponseEntity>> queryI18n( @Parameter(description = "en: language type,zh: 语言类型", example = "zh-CN") @PathVariable(name = "lang", required = false) String lang) { - if (lang == null || "".equals(lang)) { + if (lang == null || lang.isEmpty()) { lang = "zh-CN"; } lang = "zh-cn".equalsIgnoreCase(lang) || "zh_cn".equalsIgnoreCase(lang) ? "zh-CN" : lang; lang = "en-us".equalsIgnoreCase(lang) || "en_us".equalsIgnoreCase(lang) ? "en-US" : lang; Map i18nResource = appService.getI18nResources(lang); - return ResponseEntity.ok(new Message<>(i18nResource)); + return ResponseEntity.ok(Message.success(i18nResource)); } } diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MetricsController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MetricsController.java index 6d51a3e9b9d..4f163df4ef2 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MetricsController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MetricsController.java @@ -54,6 +54,6 @@ public ResponseEntity>> getMetricsInfo() { Map queueInfo = ((InMemoryCommonDataQueue) commonDataQueue).getQueueSizeMetricsInfo(); metricsInfo.putAll(queueInfo); } - return ResponseEntity.ok(new Message<>(metricsInfo)); + return ResponseEntity.ok(Message.success(metricsInfo)); } } diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorController.java index 2936336bcb9..dc8654e3556 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorController.java @@ -17,14 +17,13 @@ package org.dromara.hertzbeat.manager.controller; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; import org.dromara.hertzbeat.common.entity.dto.Message; import org.dromara.hertzbeat.common.entity.manager.Monitor; import org.dromara.hertzbeat.manager.pojo.dto.MonitorDto; import org.dromara.hertzbeat.manager.service.MonitorService; -import org.dromara.hertzbeat.common.constants.CommonConstants; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -32,6 +31,7 @@ import javax.validation.Valid; import java.util.List; +import static org.dromara.hertzbeat.common.constants.CommonConstants.MONITOR_NOT_EXIST_CODE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; /** @@ -58,7 +58,7 @@ public ResponseEntity> addNewMonitor(@Valid @RequestBody MonitorDt monitorService.detectMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector()); } monitorService.addMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector()); - return ResponseEntity.ok(new Message<>("Add success")); + return ResponseEntity.ok(Message.success("Add success")); } @PutMapping @@ -71,7 +71,7 @@ public ResponseEntity> modifyMonitor(@Valid @RequestBody MonitorDt monitorService.detectMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector()); } monitorService.modifyMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector()); - return ResponseEntity.ok(new Message<>("Modify success")); + return ResponseEntity.ok(Message.success("Modify success")); } @GetMapping(path = "/{id}") @@ -81,13 +81,11 @@ public ResponseEntity> getMonitor( // Get monitoring information // 获取监控信息 MonitorDto monitorDto = monitorService.getMonitorDto(id); - Message.MessageBuilder messageBuilder = Message.builder(); if (monitorDto == null) { - messageBuilder.code(CommonConstants.MONITOR_NOT_EXIST_CODE).msg("Monitor not exist."); + return ResponseEntity.ok(Message.fail(MONITOR_NOT_EXIST_CODE, "Monitor not exist.")); } else { - messageBuilder.data(monitorDto); + return ResponseEntity.ok(Message.success(monitorDto)); } - return ResponseEntity.ok(messageBuilder.build()); } @DeleteMapping(path = "/{id}") @@ -97,10 +95,10 @@ public ResponseEntity> deleteMonitor( // delete monitor 删除监控 Monitor monitor = monitorService.getMonitor(id); if (monitor == null) { - return ResponseEntity.ok(new Message<>("The specified monitoring was not queried, please check whether the parameters are correct")); + return ResponseEntity.ok(Message.success("The specified monitoring was not queried, please check whether the parameters are correct")); } monitorService.deleteMonitor(id); - return ResponseEntity.ok(new Message<>("Delete success")); + return ResponseEntity.ok(Message.success("Delete success")); } @PostMapping(path = "/detect") @@ -108,7 +106,7 @@ public ResponseEntity> deleteMonitor( public ResponseEntity> detectMonitor(@Valid @RequestBody MonitorDto monitorDto) { monitorService.validate(monitorDto, null); monitorService.detectMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector()); - return ResponseEntity.ok(new Message<>("Detect success.")); + return ResponseEntity.ok(Message.success("Detect success.")); } @PostMapping("/optional") @@ -119,7 +117,7 @@ public ResponseEntity> addNewMonitorOptionalMetrics(@Valid @Reques monitorService.detectMonitor(monitorDto.getMonitor(), monitorDto.getParams(), monitorDto.getCollector()); } monitorService.addNewMonitorOptionalMetrics(monitorDto.getMetrics(), monitorDto.getMonitor(), monitorDto.getParams()); - return ResponseEntity.ok(new Message<>("Add success")); + return ResponseEntity.ok(Message.success("Add success")); } @GetMapping(value = {"/metric/{app}", "/metric"}) @@ -127,7 +125,7 @@ public ResponseEntity> addNewMonitorOptionalMetrics(@Valid @Reques public ResponseEntity>> getMonitorMetrics( @PathVariable(value = "app", required = false) String app) { List metricNames = monitorService.getMonitorMetrics(app); - return ResponseEntity.ok(new Message<>(metricNames)); + return ResponseEntity.ok(Message.success(metricNames)); } } diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorsController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorsController.java index 64ac774b3de..27065d3c54c 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorsController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/MonitorsController.java @@ -38,11 +38,9 @@ import javax.persistence.criteria.ListJoin; import javax.persistence.criteria.Predicate; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; -import java.util.stream.Collectors; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; @@ -56,14 +54,14 @@ @RestController @RequestMapping(path = "/api/monitors", produces = {APPLICATION_JSON_VALUE}) public class MonitorsController { - + private static final byte ALL_MONITOR_STATUS = 9; - + private static final int TAG_LENGTH = 2; - + @Autowired private MonitorService monitorService; - + @GetMapping @Operation(summary = "Obtain a list of monitoring information based on query filter items", description = "根据查询过滤项获取监控信息列表") @@ -95,7 +93,7 @@ public ResponseEntity>> getMonitors( Predicate predicateStatus = criteriaBuilder.equal(root.get("status"), status); andList.add(predicateStatus); } - + if (StringUtils.hasText(tag)) { String[] tagArr = tag.split(":"); String tagName = tagArr[0]; @@ -112,7 +110,7 @@ public ResponseEntity>> getMonitors( } Predicate[] andPredicates = new Predicate[andList.size()]; Predicate andPredicate = criteriaBuilder.and(andList.toArray(andPredicates)); - + List orList = new ArrayList<>(); if (StringUtils.hasText(host)) { Predicate predicateHost = criteriaBuilder.like(root.get("host"), "%" + host + "%"); @@ -124,7 +122,7 @@ public ResponseEntity>> getMonitors( } Predicate[] orPredicates = new Predicate[orList.size()]; Predicate orPredicate = criteriaBuilder.or(orList.toArray(orPredicates)); - + if (andPredicate.getExpressions().isEmpty() && orPredicate.getExpressions().isEmpty()) { return query.where().getRestriction(); } else if (andPredicate.getExpressions().isEmpty()) { @@ -139,20 +137,20 @@ public ResponseEntity>> getMonitors( Sort sortExp = Sort.by(new Sort.Order(Sort.Direction.fromString(order), sort)); PageRequest pageRequest = PageRequest.of(pageIndex, pageSize, sortExp); Page monitorPage = monitorService.getMonitors(specification, pageRequest); - Message> message = new Message<>(monitorPage); + Message> message = Message.success(monitorPage); return ResponseEntity.ok(message); } - + @GetMapping(path = "/{app}") @Operation(summary = "Filter all acquired monitoring information lists of the specified monitoring type according to the query", description = "根据查询过滤指定监控类型的所有获取监控信息列表") public ResponseEntity>> getAppMonitors( @Parameter(description = "en: Monitoring type,zh: 监控类型", example = "linux") @PathVariable(required = false) final String app) { List monitors = monitorService.getAppMonitors(app); - Message> message = new Message<>(monitors); + Message> message = Message.success(monitors); return ResponseEntity.ok(message); } - + @DeleteMapping @Operation(summary = "Delete monitoring items in batches according to the monitoring ID list", description = "根据监控ID列表批量删除监控项") @@ -162,10 +160,10 @@ public ResponseEntity> deleteMonitors( if (ids != null && !ids.isEmpty()) { monitorService.deleteMonitors(new HashSet<>(ids)); } - Message message = new Message<>(); + Message message = Message.success(); return ResponseEntity.ok(message); } - + @DeleteMapping("manage") @Operation(summary = "Unmanaged monitoring items in batches according to the monitoring ID list", description = "根据监控ID列表批量取消纳管监控项") @@ -175,10 +173,10 @@ public ResponseEntity> cancelManageMonitors( if (ids != null && !ids.isEmpty()) { monitorService.cancelManageMonitors(new HashSet<>(ids)); } - Message message = new Message<>(); + Message message = Message.success(); return ResponseEntity.ok(message); } - + @GetMapping("manage") @Operation(summary = "Start the managed monitoring items in batches according to the monitoring ID list", description = "根据监控ID列表批量启动纳管监控项") @@ -188,10 +186,10 @@ public ResponseEntity> enableManageMonitors( if (ids != null && !ids.isEmpty()) { monitorService.enableManageMonitors(new HashSet<>(ids)); } - Message message = new Message<>(); + Message message = Message.success(); return ResponseEntity.ok(message); } - + @GetMapping("/export") @Operation(summary = "export monitor config", description = "导出监控配置") public void export( @@ -200,15 +198,15 @@ public void export( HttpServletResponse res) throws Exception { monitorService.export(ids, type, res); } - + @PostMapping("/import") @Operation(summary = "import monitor config", description = "导入监控配置") public ResponseEntity> export(MultipartFile file) throws Exception { monitorService.importConfig(file); - return ResponseEntity.ok(new Message<>("Import success")); + return ResponseEntity.ok(Message.success("Import success")); } - - + + @PostMapping("/copy") @Operation(summary = "copy monitors by ids", description = "根据id批量复制monitor") public ResponseEntity> duplicateMonitors( @@ -217,8 +215,8 @@ public ResponseEntity> duplicateMonitors( if (ids != null && !ids.isEmpty()) { monitorService.copyMonitors(ids); } - return ResponseEntity.ok(new Message<>("copy success")); + return ResponseEntity.ok(Message.success("copy success")); } - - + + } diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/NoticeConfigController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/NoticeConfigController.java index 7a39740fcb2..5d49ca4b56a 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/NoticeConfigController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/NoticeConfigController.java @@ -17,37 +17,30 @@ package org.dromara.hertzbeat.manager.controller; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; import org.dromara.hertzbeat.common.entity.dto.Message; import org.dromara.hertzbeat.common.entity.manager.NoticeReceiver; import org.dromara.hertzbeat.common.entity.manager.NoticeRule; import org.dromara.hertzbeat.manager.service.NoticeConfigService; -import org.dromara.hertzbeat.common.constants.CommonConstants; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; + import javax.persistence.criteria.Predicate; import javax.validation.Valid; import java.util.List; +import static org.dromara.hertzbeat.common.constants.CommonConstants.FAIL_CODE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; /** * Message Notification Configuration API * 消息通知配置API - * @author tom * + * @author tom */ @Tag(name = "Notification Config API | 消息通知配置API") @RestController() @@ -61,14 +54,14 @@ public class NoticeConfigController { @Operation(summary = "Add a recipient", description = "新增一个接收人") public ResponseEntity> addNewNoticeReceiver(@Valid @RequestBody NoticeReceiver noticeReceiver) { noticeConfigService.addReceiver(noticeReceiver); - return ResponseEntity.ok(new Message<>("Add success")); + return ResponseEntity.ok(Message.success("Add success")); } @PutMapping(path = "/receiver") @Operation(summary = "Modify existing recipient information", description = "修改已存在的接收人信息") public ResponseEntity> editNoticeReceiver(@Valid @RequestBody NoticeReceiver noticeReceiver) { noticeConfigService.editReceiver(noticeReceiver); - return ResponseEntity.ok(new Message<>("Edit success")); + return ResponseEntity.ok(Message.success("Edit success")); } @DeleteMapping(path = "/receiver/{id}") @@ -77,10 +70,10 @@ public ResponseEntity> deleteNoticeReceiver( @Parameter(description = "en: Recipient ID,zh: 接收人ID", example = "6565463543") @PathVariable("id") final Long receiverId) { NoticeReceiver noticeReceiver = noticeConfigService.getReceiverById(receiverId); if (noticeReceiver == null) { - return ResponseEntity.ok(new Message<>("The relevant information of the recipient could not be found, please check whether the parameters are correct")); + return ResponseEntity.ok(Message.success("The relevant information of the recipient could not be found, please check whether the parameters are correct")); } noticeConfigService.deleteReceiver(receiverId); - return ResponseEntity.ok(new Message<>("Delete success")); + return ResponseEntity.ok(Message.success("Delete success")); } @GetMapping(path = "/receivers") @@ -90,14 +83,14 @@ public ResponseEntity>> getReceivers( @Parameter(description = "en: Recipient name,zh: 接收人名称,模糊查询", example = "tom") @RequestParam(required = false) final String name) { Specification specification = (root, query, criteriaBuilder) -> { Predicate predicate = criteriaBuilder.conjunction(); - if (name != null && !"".equals(name)) { + if (name != null && !name.isEmpty()) { Predicate predicateName = criteriaBuilder.like(root.get("name"), "%" + name + "%"); predicate = criteriaBuilder.and(predicateName); } return predicate; }; List receivers = noticeConfigService.getNoticeReceivers(specification); - Message> message = new Message<>(receivers); + Message> message = Message.success(receivers); return ResponseEntity.ok(message); } @@ -105,14 +98,14 @@ public ResponseEntity>> getReceivers( @Operation(summary = "Add a notification policy", description = "新增一个通知策略") public ResponseEntity> addNewNoticeRule(@Valid @RequestBody NoticeRule noticeRule) { noticeConfigService.addNoticeRule(noticeRule); - return ResponseEntity.ok(new Message<>("Add success")); + return ResponseEntity.ok(Message.success("Add success")); } @PutMapping(path = "/rule") @Operation(summary = "Modify existing notification policy information", description = "修改已存在的通知策略信息") public ResponseEntity> editNoticeRule(@Valid @RequestBody NoticeRule noticeRule) { noticeConfigService.editNoticeRule(noticeRule); - return ResponseEntity.ok(new Message<>("Edit success")); + return ResponseEntity.ok(Message.success("Edit success")); } @DeleteMapping(path = "/rule/{id}") @@ -123,10 +116,10 @@ public ResponseEntity> deleteNoticeRule( // todo 不存在或删除成功都返回成功 NoticeRule noticeRule = noticeConfigService.getNoticeRulesById(ruleId); if (noticeRule == null) { - return ResponseEntity.ok(new Message<>("The specified notification rule could not be queried, please check whether the parameters are correct")); + return ResponseEntity.ok(Message.success("The specified notification rule could not be queried, please check whether the parameters are correct")); } noticeConfigService.deleteNoticeRule(ruleId); - return ResponseEntity.ok(new Message<>("Delete success")); + return ResponseEntity.ok(Message.success("Delete success")); } @GetMapping(path = "/rules") @@ -136,14 +129,14 @@ public ResponseEntity>> getRules( @Parameter(description = "en: Recipient name,zh: 接收人名称,模糊查询", example = "rule1") @RequestParam(required = false) final String name) { Specification specification = (root, query, criteriaBuilder) -> { Predicate predicate = criteriaBuilder.conjunction(); - if (name != null && !"".equals(name)) { + if (name != null && !name.isEmpty()) { Predicate predicateName = criteriaBuilder.like(root.get("name"), "%" + name + "%"); predicate = criteriaBuilder.and(predicateName); } return predicate; }; List receiverPage = noticeConfigService.getNoticeRules(specification); - Message> message = new Message<>(receiverPage); + Message> message = Message.success(receiverPage); return ResponseEntity.ok(message); } @@ -152,12 +145,8 @@ public ResponseEntity>> getRules( public ResponseEntity> sendTestMsg(@Valid @RequestBody NoticeReceiver noticeReceiver) { boolean sendFlag = noticeConfigService.sendTestMsg(noticeReceiver); if (sendFlag) { - return ResponseEntity.ok(new Message<>()); + return ResponseEntity.ok(Message.success()); } - Message message = Message.builder() - .msg("Notify service not available, please check config!") - .code(CommonConstants.FAIL_CODE) - .build(); - return ResponseEntity.ok(message); + return ResponseEntity.ok(Message.fail(FAIL_CODE, "Notify service not available, please check config!")); } } diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/SummaryController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/SummaryController.java index 2278784aa9e..a761eb1bad3 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/SummaryController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/SummaryController.java @@ -49,7 +49,7 @@ public class SummaryController { @Operation(summary = "Query all application category monitoring statistics", description = "查询所有应用类别监控统计信息") public ResponseEntity> appMonitors() { List appsCount = monitorService.getAllAppMonitorsCount(); - Message message = new Message<>(new Dashboard(appsCount)); + Message message = Message.success(new Dashboard(appsCount)); return ResponseEntity.ok(message); } } diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/TagController.java b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/TagController.java index 0f12e9d7ff6..bc929d22020 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/controller/TagController.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/controller/TagController.java @@ -58,7 +58,7 @@ public ResponseEntity> addNewTags(@Valid @RequestBody List ta tag.setId(null); }).distinct().collect(Collectors.toList()); tagService.addTags(tags); - return ResponseEntity.ok(new Message<>("Add success")); + return ResponseEntity.ok(Message.success("Add success")); } @PutMapping @@ -69,7 +69,7 @@ public ResponseEntity> modifyMonitor(@Valid @RequestBody Tag tag) throw new IllegalArgumentException("The Tag not exist."); } tagService.modifyTag(tag); - return ResponseEntity.ok(new Message<>("Modify success")); + return ResponseEntity.ok(Message.success("Modify success")); } @GetMapping() @@ -90,7 +90,7 @@ public ResponseEntity>> getTags( Predicate andPredicate = criteriaBuilder.and(andList.toArray(andPredicates)); List orList = new ArrayList<>(); - if (search != null && !"".equals(search)) { + if (search != null && !search.isEmpty()) { Predicate predicateName = criteriaBuilder.like(root.get("name"), "%" + search + "%"); orList.add(predicateName); Predicate predicateValue = criteriaBuilder.like(root.get("value"), "%" + search + "%"); @@ -111,7 +111,7 @@ public ResponseEntity>> getTags( }; PageRequest pageRequest = PageRequest.of(pageIndex, pageSize); Page alertPage = tagService.getTags(specification, pageRequest); - Message> message = new Message<>(alertPage); + Message> message = Message.success(alertPage); return ResponseEntity.ok(message); } @@ -122,6 +122,6 @@ public ResponseEntity> deleteTags( if (ids != null && !ids.isEmpty()) { tagService.deleteTags(new HashSet<>(ids)); } - return ResponseEntity.ok(new Message<>("Delete success")); + return ResponseEntity.ok(Message.success("Delete success")); } } diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/pojo/dto/WeWorkWebHookDto.java b/manager/src/main/java/org/dromara/hertzbeat/manager/pojo/dto/WeWorkWebHookDto.java index 217a1752aaa..be33fc0a164 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/pojo/dto/WeWorkWebHookDto.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/pojo/dto/WeWorkWebHookDto.java @@ -27,7 +27,6 @@ * * @author 花城 * @version 1.0 - * */ @Data @Builder @@ -48,6 +47,7 @@ public class WeWorkWebHookDto { /** * 消息类型 */ + @Builder.Default private String msgtype = MARKDOWN; /** diff --git a/manager/src/main/java/org/dromara/hertzbeat/manager/support/GlobalExceptionHandler.java b/manager/src/main/java/org/dromara/hertzbeat/manager/support/GlobalExceptionHandler.java index 5b09b0a19ef..63a3e2d9a2f 100644 --- a/manager/src/main/java/org/dromara/hertzbeat/manager/support/GlobalExceptionHandler.java +++ b/manager/src/main/java/org/dromara/hertzbeat/manager/support/GlobalExceptionHandler.java @@ -17,13 +17,12 @@ package org.dromara.hertzbeat.manager.support; +import lombok.extern.slf4j.Slf4j; import org.dromara.hertzbeat.common.entity.dto.Message; import org.dromara.hertzbeat.manager.support.exception.AlertNoticeException; import org.dromara.hertzbeat.manager.support.exception.MonitorDatabaseException; import org.dromara.hertzbeat.manager.support.exception.MonitorDetectException; import org.dromara.hertzbeat.manager.support.exception.MonitorMetricsException; -import org.dromara.hertzbeat.common.constants.CommonConstants; -import lombok.extern.slf4j.Slf4j; import org.springframework.dao.DataAccessException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -37,10 +36,12 @@ import java.util.Objects; +import static org.dromara.hertzbeat.common.constants.CommonConstants.*; + /** * controller exception handler - * @author tomsun28 * + * @author tomsun28 */ @RestControllerAdvice @Slf4j @@ -50,49 +51,53 @@ public class GlobalExceptionHandler { /** * 处理探测失败 + * * @param exception 探测异常 * @return response */ @ExceptionHandler(MonitorDetectException.class) @ResponseBody ResponseEntity> handleMonitorDetectException(MonitorDetectException exception) { - Message message = Message.builder().msg(exception.getMessage()).code(CommonConstants.DETECT_FAILED_CODE).build(); + Message message = Message.fail(DETECT_FAILED_CODE, exception.getMessage()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message); } /** * 处理数据库操作异常 + * * @param exception 探测异常 * @return response */ @ExceptionHandler(MonitorDatabaseException.class) @ResponseBody ResponseEntity> handleMonitorDatabaseException(MonitorDatabaseException exception) { - Message message = Message.builder().msg(exception.getMessage()).code(CommonConstants.MONITOR_CONFLICT_CODE).build(); + Message message = Message.fail(MONITOR_CONFLICT_CODE, exception.getMessage()); return ResponseEntity.ok(message); } /** * 处理参数错误的失败 + * * @param exception 参数异常 * @return response */ @ExceptionHandler(IllegalArgumentException.class) @ResponseBody ResponseEntity> handleIllegalArgumentException(IllegalArgumentException exception) { - Message message = Message.builder().msg(exception.getMessage()).code(CommonConstants.PARAM_INVALID_CODE).build(); + Message message = Message.fail(PARAM_INVALID_CODE, exception.getMessage()); return ResponseEntity.ok(message); } @ExceptionHandler(AlertNoticeException.class) @ResponseBody ResponseEntity> handleAlertNoticeException(AlertNoticeException noticeException) { - Message message = Message.builder().msg(noticeException.getMessage()).code(CommonConstants.FAIL_CODE).build(); + Message message = Message.fail(FAIL_CODE, noticeException.getMessage()); return ResponseEntity.ok(message); } /** * 处理请求参数错误的失败, 请求参数json映射body时出错 + * * @param exception 参数映射body异常 * @return response */ @@ -104,10 +109,10 @@ ResponseEntity> handleHttpMessageNotReadableException(HttpMessageN if (msg == null) { msg = exception.getMessage(); } - Message message = Message.builder().msg(msg).code(CommonConstants.PARAM_INVALID_CODE).build(); + Message message = Message.fail(PARAM_INVALID_CODE, msg); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message); } catch (Exception e) { - Message message = Message.builder().msg(exception.getMessage()).code(CommonConstants.PARAM_INVALID_CODE).build(); + Message message = Message.fail(PARAM_INVALID_CODE, exception.getMessage()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message); } } @@ -116,6 +121,7 @@ ResponseEntity> handleHttpMessageNotReadableException(HttpMessageN /** * handler the exception thrown for data input verify * valid注解校验框架校验异常统一处理 + * * @param e data input verify exception * @return response */ @@ -124,7 +130,7 @@ ResponseEntity> handleHttpMessageNotReadableException(HttpMessageN ResponseEntity> handleInputValidException(Exception e) { StringBuffer errorMessage = new StringBuffer(); if (e instanceof MethodArgumentNotValidException) { - MethodArgumentNotValidException exception = (MethodArgumentNotValidException)e; + MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e; exception.getBindingResult().getAllErrors().forEach(error -> { try { String field = Objects.requireNonNull(error.getCodes())[0]; @@ -134,7 +140,7 @@ ResponseEntity> handleInputValidException(Exception e) { } }); } else if (e instanceof BindException) { - BindException exception = (BindException)e; + BindException exception = (BindException) e; exception.getAllErrors().forEach(error -> errorMessage.append(error.getDefaultMessage()).append(CONNECT_STR)); } @@ -145,13 +151,14 @@ ResponseEntity> handleInputValidException(Exception e) { if (log.isDebugEnabled()) { log.debug("[input argument not valid happen]-{}", errorMsg, e); } - Message message = Message.builder().msg(errorMsg).code(CommonConstants.PARAM_INVALID_CODE).build(); + Message message = Message.fail(PARAM_INVALID_CODE, errorMsg); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message); } /** * handler the exception thrown for datastore error + * * @param exception datastore exception * @return response */ @@ -163,12 +170,13 @@ ResponseEntity> handleDataAccessException(DataAccessException exce errorMessage = exception.getMessage(); } log.warn("[database error happen]-{}", errorMessage, exception); - Message message = Message.builder().msg(errorMessage).code(CommonConstants.MONITOR_CONFLICT_CODE).build(); + Message message = Message.fail(MONITOR_CONFLICT_CODE, errorMessage); return ResponseEntity.status(HttpStatus.CONFLICT).body(message); } /** * handle Request method not supported + * * @param exception Request method not supported * @return response */ @@ -180,12 +188,13 @@ ResponseEntity> handleMethodNotSupportException(HttpRequestMethodN errorMessage = exception.getMessage(); } log.info("[monitor]-[Request method not supported]-{}", errorMessage); - Message message = Message.builder().msg(errorMessage).build(); + Message message = Message.success(errorMessage); return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).body(message); } /** * handler the exception thrown for unCatch and unKnown + * * @param exception UnknownException * @return response */ @@ -197,19 +206,20 @@ ResponseEntity> handleUnknownException(Exception exception) { errorMessage = exception.getMessage(); } log.error("[monitor]-[unknown error happen]-{}", errorMessage, exception); - Message message = Message.builder().msg(errorMessage).code(CommonConstants.MONITOR_CONFLICT_CODE).build(); + Message message = Message.fail(MONITOR_CONFLICT_CODE, errorMessage); return ResponseEntity.status(HttpStatus.CONFLICT).body(message); } /** * 处理监控指标传参异常 + * * @param exception 指标参数异常 * @return */ @ExceptionHandler(MonitorMetricsException.class) @ResponseBody ResponseEntity> handleMonitorMetricsException(MonitorMetricsException exception) { - Message message = Message.builder().msg(exception.getMessage()).code(CommonConstants.PARAM_INVALID_CODE).build(); + Message message = Message.fail(PARAM_INVALID_CODE, exception.getMessage()); return ResponseEntity.ok(message); } diff --git a/warehouse/src/main/java/org/dromara/hertzbeat/warehouse/controller/MetricsDataController.java b/warehouse/src/main/java/org/dromara/hertzbeat/warehouse/controller/MetricsDataController.java index 7ac758e910e..3da9aa5107e 100644 --- a/warehouse/src/main/java/org/dromara/hertzbeat/warehouse/controller/MetricsDataController.java +++ b/warehouse/src/main/java/org/dromara/hertzbeat/warehouse/controller/MetricsDataController.java @@ -50,7 +50,6 @@ * 指标数据查询接口 * * @author tom - * */ @RestController @RequestMapping(produces = {APPLICATION_JSON_VALUE}) @@ -77,9 +76,9 @@ public ResponseEntity> getWarehouseStorageServerStatus() { available = historyDataStorages.stream().anyMatch(AbstractHistoryDataStorage::isServerAvailable); } if (available) { - return ResponseEntity.ok(Message.builder().build()); + return ResponseEntity.ok(Message.success()); } else { - return ResponseEntity.ok(new Message<>(FAIL_CODE, "Service not available!")); + return ResponseEntity.ok(Message.fail(FAIL_CODE, "Service not available!")); } } @@ -102,11 +101,11 @@ public ResponseEntity> getMetricsData( } }).orElse(null); if (realTimeDataStorage == null) { - return ResponseEntity.ok().body(new Message<>(FAIL_CODE, "real time store not available")); + return ResponseEntity.ok(Message.fail(FAIL_CODE, "real time store not available")); } CollectRep.MetricsData storageData = realTimeDataStorage.getCurrentMetricsData(monitorId, metrics); if (storageData == null) { - return ResponseEntity.ok().body(new Message<>("query metrics data is empty")); + return ResponseEntity.ok(Message.success("query metrics data is empty")); } { MetricsData.MetricsDataBuilder dataBuilder = MetricsData.builder(); @@ -122,11 +121,11 @@ public ResponseEntity> getMetricsData( List valueRows = storageData.getValuesList().stream().map(redisValueRow -> ValueRow.builder().instance(redisValueRow.getInstance()) .values(redisValueRow.getColumnsList().stream() - .map(origin -> CommonConstants.NULL_VALUE.equals(origin) ? new Value() - : new Value(origin)).collect(Collectors.toList())) + .map(origin -> CommonConstants.NULL_VALUE.equals(origin) ? new Value() + : new Value(origin)).collect(Collectors.toList())) .build()).collect(Collectors.toList()); dataBuilder.valueRows(valueRows); - return ResponseEntity.ok().body(new Message<>(dataBuilder.build())); + return ResponseEntity.ok(Message.success(dataBuilder.build())); } } @@ -155,7 +154,7 @@ public ResponseEntity> getMetricHistoryData( } }).orElse(null); if (historyDataStorage == null) { - return ResponseEntity.ok().body(new Message<>(FAIL_CODE, "time series database not available")); + return ResponseEntity.ok(Message.fail(FAIL_CODE, "time series database not available")); } String[] names = metricFull.split("\\."); if (names.length != METRIC_FULL_LENGTH) { @@ -177,6 +176,6 @@ public ResponseEntity> getMetricHistoryData( .id(monitorId).metric(metrics).values(instanceValuesMap) .field(Field.builder().name(metric).type(CommonConstants.TYPE_NUMBER).build()) .build(); - return ResponseEntity.ok().body(new Message<>(historyData)); + return ResponseEntity.ok(Message.success(historyData)); } }