From e15465d41acb63c3f961b0d78a041d352fb22bd7 Mon Sep 17 00:00:00 2001 From: rick Date: Thu, 5 Sep 2024 06:05:33 +0000 Subject: [PATCH] chore: make the controller response be easy --- .../hertzbeat/common/util/ResponseUtil.java | 69 +++++++++++++++++++ .../manager/controller/AccountController.java | 7 +- .../manager/controller/AppController.java | 57 +++++---------- .../controller/BulletinController.java | 4 +- .../controller/CollectorController.java | 6 +- .../controller/GeneralConfigController.java | 6 +- 6 files changed, 98 insertions(+), 51 deletions(-) create mode 100644 common/src/main/java/org/apache/hertzbeat/common/util/ResponseUtil.java diff --git a/common/src/main/java/org/apache/hertzbeat/common/util/ResponseUtil.java b/common/src/main/java/org/apache/hertzbeat/common/util/ResponseUtil.java new file mode 100644 index 00000000000..1657c84ee50 --- /dev/null +++ b/common/src/main/java/org/apache/hertzbeat/common/util/ResponseUtil.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hertzbeat.common.util; + +import javax.naming.AuthenticationException; + +import org.apache.hertzbeat.common.constants.CommonConstants; +import org.apache.hertzbeat.common.entity.dto.Message; +import org.springframework.http.ResponseEntity; + +/** + * A tool which make the restful response be easy to use + */ +public class ResponseUtil { + public static ResponseEntity> handle(Supplier supplier) { + try { + T result = supplier.get(); + return ResponseEntity.ok(Message.success(result)); + } catch (Exception e) { + byte err = CommonConstants.FAIL_CODE; + if (e.getClass().equals(AuthenticationException.class)) { + err = CommonConstants.LOGIN_FAILED_CODE; + } + return ResponseEntity.ok(Message.fail(err, e.getMessage())); + } + } + + public static ResponseEntity> handle(Runnable runner) { + try { + runner.run(); + return ResponseEntity.ok(Message.success()); + } catch (Exception e) { + byte err = CommonConstants.FAIL_CODE; + if (e.getClass().equals(AuthenticationException.class)) { + err = CommonConstants.LOGIN_FAILED_CODE; + } + return ResponseEntity.ok(Message.fail(err, e.getMessage())); + } + } + + /** + * Supplier interface for getting result + */ + public interface Supplier { + + /** + * Gets a result. + * + * @return a result + */ + T get() throws E; + } + +} diff --git a/manager/src/main/java/org/apache/hertzbeat/manager/controller/AccountController.java b/manager/src/main/java/org/apache/hertzbeat/manager/controller/AccountController.java index 23ae16d77bc..2a2494cef20 100644 --- a/manager/src/main/java/org/apache/hertzbeat/manager/controller/AccountController.java +++ b/manager/src/main/java/org/apache/hertzbeat/manager/controller/AccountController.java @@ -29,6 +29,7 @@ import javax.naming.AuthenticationException; import lombok.extern.slf4j.Slf4j; import org.apache.hertzbeat.common.entity.dto.Message; +import org.apache.hertzbeat.common.util.ResponseUtil; import org.apache.hertzbeat.manager.pojo.dto.LoginDto; import org.apache.hertzbeat.manager.pojo.dto.RefreshTokenResponse; import org.apache.hertzbeat.manager.service.AccountService; @@ -56,11 +57,7 @@ public class AccountController { @PostMapping("/form") @Operation(summary = "Account password login to obtain associated user information", description = "Account password login to obtain associated user information") public ResponseEntity>> authGetToken(@Valid @RequestBody LoginDto loginDto) { - try { - return ResponseEntity.ok(Message.success(accountService.authGetToken(loginDto))); - } catch (AuthenticationException e) { - return ResponseEntity.ok(Message.fail(LOGIN_FAILED_CODE, e.getMessage())); - } + return ResponseUtil.handle(() -> accountService.authGetToken(loginDto)); } @GetMapping("/refresh/{refreshToken}") diff --git a/manager/src/main/java/org/apache/hertzbeat/manager/controller/AppController.java b/manager/src/main/java/org/apache/hertzbeat/manager/controller/AppController.java index 5472f0f39e2..ad0842e62e6 100644 --- a/manager/src/main/java/org/apache/hertzbeat/manager/controller/AppController.java +++ b/manager/src/main/java/org/apache/hertzbeat/manager/controller/AppController.java @@ -17,7 +17,6 @@ package org.apache.hertzbeat.manager.controller; -import static org.apache.hertzbeat.common.constants.CommonConstants.FAIL_CODE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -29,6 +28,7 @@ import org.apache.hertzbeat.common.entity.dto.Message; import org.apache.hertzbeat.common.entity.job.Job; import org.apache.hertzbeat.common.entity.manager.ParamDefine; +import org.apache.hertzbeat.common.util.ResponseUtil; import org.apache.hertzbeat.manager.pojo.dto.Hierarchy; import org.apache.hertzbeat.manager.pojo.dto.MonitorDefineDto; import org.apache.hertzbeat.manager.service.AppService; @@ -66,8 +66,7 @@ public class AppController { description = "The structure of the input parameters required to specify the monitoring type according to the app query") public ResponseEntity>> queryAppParamDefines( @Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("app") final String app) { - List paramDefines = appService.getAppParamDefines(app.toLowerCase()); - return ResponseEntity.ok(Message.success(paramDefines)); + return ResponseUtil.handle(() -> appService.getAppParamDefines(app.toLowerCase())); } @GetMapping(path = "/{monitorId}/pushdefine") @@ -75,8 +74,7 @@ public ResponseEntity>> queryAppParamDefines( description = "The definition structure of the specified monitoring type according to the push query") public ResponseEntity> queryPushDefine( @Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("monitorId") final Long monitorId) { - Job define = appService.getPushDefine(monitorId); - return ResponseEntity.ok(Message.success(define)); + return ResponseUtil.handle(() -> appService.getPushDefine(monitorId)); } @GetMapping(path = "/{monitorId}/define/dynamic") @@ -84,8 +82,7 @@ public ResponseEntity> queryPushDefine( description = "The definition structure of the specified monitoring type according to the push query") public ResponseEntity> queryAutoGenerateDynamicAppDefine( @Parameter(description = "Monitoring id", example = "5435345") @PathVariable("monitorId") final Long monitorId) { - Job define = appService.getAutoGenerateDynamicDefine(monitorId); - return ResponseEntity.ok(Message.success(define)); + return ResponseUtil.handle(() -> appService.getAutoGenerateDynamicDefine(monitorId)); } @GetMapping(path = "/{app}/define") @@ -93,8 +90,7 @@ public ResponseEntity> queryAutoGenerateDynamicAppDefine( description = "The definition structure of the specified monitoring type according to the app query") public ResponseEntity> queryAppDefine( @Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("app") final String app) { - Job define = appService.getAppDefine(app.toLowerCase()); - return ResponseEntity.ok(Message.success(define)); + return ResponseUtil.handle(() -> appService.getAppDefine(app.toLowerCase())); } @GetMapping(path = "/{app}/define/yml") @@ -102,52 +98,40 @@ public ResponseEntity> queryAppDefine( description = "The definition yml of the specified monitoring type according to the app query") public ResponseEntity> queryAppDefineYml( @Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("app") final String app) { - String defineContent = appService.getMonitorDefineFileContent(app); - return ResponseEntity.ok(Message.successWithData(defineContent)); + return ResponseUtil.handle(() -> appService.getMonitorDefineFileContent(app)); } @DeleteMapping(path = "/{app}/define/yml") @Operation(summary = "Delete monitor define yml", description = "Delete the definition YML for the specified monitoring type according to the app") public ResponseEntity> deleteAppDefineYml( @Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("app") final String app) { - try { - appService.deleteMonitorDefine(app); - } catch (Exception e) { - return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage())); - } - return ResponseEntity.ok(Message.success()); + return ResponseUtil.handle(() -> appService.deleteMonitorDefine(app)); } @PostMapping(path = "/define/yml") @Operation(summary = "Add new monitoring type define yml", description = "Add new monitoring type define yml") public ResponseEntity> newAppDefineYml(@Valid @RequestBody MonitorDefineDto defineDto) { - try { + return ResponseUtil.handle(() -> { for (String riskyToken : RISKY_STR_ARR) { if (defineDto.getDefine().contains(riskyToken)) { - return ResponseEntity.ok(Message.fail(FAIL_CODE, "can not has malicious remote script")); + throw new RuntimeException("can not has malicious remote script"); } } appService.applyMonitorDefineYml(defineDto.getDefine(), false); - } catch (Exception e) { - return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage())); - } - return ResponseEntity.ok(Message.success()); + }); } @PutMapping(path = "/define/yml") @Operation(summary = "Update monitoring type define yml", description = "Update monitoring type define yml") public ResponseEntity> updateAppDefineYml(@Valid @RequestBody MonitorDefineDto defineDto) { - try { + return ResponseUtil.handle(() -> { for (String riskyToken : RISKY_STR_ARR) { if (defineDto.getDefine().contains(riskyToken)) { - return ResponseEntity.ok(Message.fail(FAIL_CODE, "can not has malicious remote script")); + throw new RuntimeException("can not has malicious remote script"); } } appService.applyMonitorDefineYml(defineDto.getDefine(), true); - } catch (Exception e) { - return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage())); - } - return ResponseEntity.ok(Message.success()); + }); } @GetMapping(path = "/hierarchy") @@ -156,9 +140,8 @@ public ResponseEntity>> queryAppsHierarchy( @Parameter(description = "en: language type", example = "zh-CN") @RequestParam(name = "lang", required = false) String lang) { - lang = getLang(lang); - List appHierarchies = appService.getAllAppHierarchy(lang); - return ResponseEntity.ok(Message.success(appHierarchies)); + String newLang = getLang(lang); + return ResponseUtil.handle(() -> appService.getAllAppHierarchy(newLang)); } @GetMapping(path = "/hierarchy/{app}") @@ -168,9 +151,8 @@ public ResponseEntity>> queryAppsHierarchyByApp( example = "zh-CN") @RequestParam(name = "lang", required = false) String lang, @Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("app") final String app) { - lang = getLang(lang); - List appHierarchies = appService.getAppHierarchy(app, lang); - return ResponseEntity.ok(Message.success(appHierarchies)); + String newLang = getLang(lang); + return ResponseUtil.handle(() -> appService.getAppHierarchy(app, newLang)); } @GetMapping(path = "/defines") @@ -179,9 +161,8 @@ public ResponseEntity>> getAllAppDefines( @Parameter(description = "en: language type", example = "zh-CN") @RequestParam(name = "lang", required = false) String lang) { - lang = getLang(lang); - Map allAppDefines = appService.getI18nApps(lang); - return ResponseEntity.ok(Message.success(allAppDefines)); + String newLang = getLang(lang); + return ResponseUtil.handle(() -> appService.getI18nApps(newLang)); } private String getLang(@RequestParam(name = "lang", required = false) @Parameter(description = "en: language type", example = "zh-CN") String lang) { diff --git a/manager/src/main/java/org/apache/hertzbeat/manager/controller/BulletinController.java b/manager/src/main/java/org/apache/hertzbeat/manager/controller/BulletinController.java index ae049ae6969..9769de88db0 100644 --- a/manager/src/main/java/org/apache/hertzbeat/manager/controller/BulletinController.java +++ b/manager/src/main/java/org/apache/hertzbeat/manager/controller/BulletinController.java @@ -29,6 +29,7 @@ import org.apache.hertzbeat.common.entity.manager.bulletin.Bulletin; import org.apache.hertzbeat.common.entity.manager.bulletin.BulletinDto; import org.apache.hertzbeat.common.entity.manager.bulletin.BulletinMetricsData; +import org.apache.hertzbeat.common.util.ResponseUtil; import org.apache.hertzbeat.manager.service.BulletinService; import org.apache.hertzbeat.warehouse.store.realtime.RealTimeDataReader; import org.springframework.beans.factory.annotation.Autowired; @@ -103,8 +104,7 @@ public ResponseEntity> getBulletinByName(@Valid @PathVariable @Operation(summary = "Get All Bulletin Names", description = "Get All Bulletin Names") @GetMapping("/names") public ResponseEntity>> getAllNames() { - List names = bulletinService.getAllNames(); - return ResponseEntity.ok(Message.success(names)); + return ResponseUtil.handle(() -> bulletinService.getAllNames()); } /** diff --git a/manager/src/main/java/org/apache/hertzbeat/manager/controller/CollectorController.java b/manager/src/main/java/org/apache/hertzbeat/manager/controller/CollectorController.java index df31ef9d43e..475691b60d2 100644 --- a/manager/src/main/java/org/apache/hertzbeat/manager/controller/CollectorController.java +++ b/manager/src/main/java/org/apache/hertzbeat/manager/controller/CollectorController.java @@ -25,6 +25,7 @@ import java.util.Map; import org.apache.hertzbeat.common.entity.dto.CollectorSummary; import org.apache.hertzbeat.common.entity.dto.Message; +import org.apache.hertzbeat.common.util.ResponseUtil; import org.apache.hertzbeat.manager.service.CollectorService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; @@ -56,8 +57,7 @@ public ResponseEntity>> getCollectors( @Parameter(description = "collector name", example = "tom") @RequestParam(required = false) final String name, @Parameter(description = "List current page", example = "0") @RequestParam(defaultValue = "0") int pageIndex, @Parameter(description = "Number of list pagination", example = "8") @RequestParam(required = false) Integer pageSize) { - Page receivers = collectorService.getCollectors(name, pageIndex, pageSize); - return ResponseEntity.ok(Message.success(receivers)); + return ResponseUtil.handle(() -> collectorService.getCollectors(name, pageIndex, pageSize)); } @PutMapping("/online") @@ -92,7 +92,7 @@ public ResponseEntity> deleteCollector( public ResponseEntity>> generateCollectorDeployInfo( @Parameter(description = "collector name", example = "demo-collector") @PathVariable() String collector) { - return ResponseEntity.ok(Message.success(collectorService.generateCollectorDeployInfo(collector))); + return ResponseUtil.handle(() -> collectorService.generateCollectorDeployInfo(collector)); } } diff --git a/manager/src/main/java/org/apache/hertzbeat/manager/controller/GeneralConfigController.java b/manager/src/main/java/org/apache/hertzbeat/manager/controller/GeneralConfigController.java index 8747bc8b9d7..4a89e69c128 100644 --- a/manager/src/main/java/org/apache/hertzbeat/manager/controller/GeneralConfigController.java +++ b/manager/src/main/java/org/apache/hertzbeat/manager/controller/GeneralConfigController.java @@ -25,6 +25,7 @@ import jakarta.validation.constraints.NotNull; import lombok.extern.slf4j.Slf4j; import org.apache.hertzbeat.common.entity.dto.Message; +import org.apache.hertzbeat.common.util.ResponseUtil; import org.apache.hertzbeat.manager.pojo.dto.TemplateConfig; import org.apache.hertzbeat.manager.service.ConfigService; import org.springframework.http.ResponseEntity; @@ -63,7 +64,7 @@ public ResponseEntity> saveOrUpdateConfig( public ResponseEntity> getConfig( @Parameter(description = "Config Type", example = "email") @PathVariable("type") @NotNull final String type) { - return ResponseEntity.ok(Message.success(configService.getConfig(type))); + return ResponseUtil.handle(() -> configService.getConfig(type)); } @PutMapping(path = "/template/{app}") @@ -71,7 +72,6 @@ public ResponseEntity> getConfig( public ResponseEntity> updateTemplateAppConfig( @PathVariable("app") @NotNull final String app, @RequestBody TemplateConfig.AppTemplate template) { - configService.updateTemplateAppConfig(app, template); - return ResponseEntity.ok(Message.success()); + return ResponseUtil.handle(() -> configService.updateTemplateAppConfig(app, template)); } }