Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: make the controller response be easy #2679

Merged
merged 5 commits into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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 <T, E extends Exception> ResponseEntity<Message<T>> handle(Supplier<T, E> 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 <T, E extends Exception> ResponseEntity<Message<T>> 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<T, E extends Exception> {

/**
* Gets a result.
*
* @return a result
*/
T get() throws E;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<Message<Map<String, String>>> 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}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -66,88 +66,72 @@ public class AppController {
description = "The structure of the input parameters required to specify the monitoring type according to the app query")
public ResponseEntity<Message<List<ParamDefine>>> queryAppParamDefines(
@Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("app") final String app) {
List<ParamDefine> paramDefines = appService.getAppParamDefines(app.toLowerCase());
return ResponseEntity.ok(Message.success(paramDefines));
return ResponseUtil.handle(() -> appService.getAppParamDefines(app.toLowerCase()));
}

@GetMapping(path = "/{monitorId}/pushdefine")
@Operation(summary = "The definition structure of the specified monitoring type according to the push query",
description = "The definition structure of the specified monitoring type according to the push query")
public ResponseEntity<Message<Job>> 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")
@Operation(summary = "The definition structure of the specified monitoring type according to the push query",
description = "The definition structure of the specified monitoring type according to the push query")
public ResponseEntity<Message<Job>> 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")
@Operation(summary = "The definition structure of the specified monitoring type according to the app query",
description = "The definition structure of the specified monitoring type according to the app query")
public ResponseEntity<Message<Job>> 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")
@Operation(summary = "The definition yml of the specified monitoring type according to the app query",
description = "The definition yml of the specified monitoring type according to the app query")
public ResponseEntity<Message<String>> 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<Message<Void>> 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<Message<Void>> 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<Message<Void>> 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")
Expand All @@ -156,9 +140,8 @@ public ResponseEntity<Message<List<Hierarchy>>> queryAppsHierarchy(
@Parameter(description = "en: language type",
example = "zh-CN")
@RequestParam(name = "lang", required = false) String lang) {
lang = getLang(lang);
List<Hierarchy> appHierarchies = appService.getAllAppHierarchy(lang);
return ResponseEntity.ok(Message.success(appHierarchies));
String newLang = getLang(lang);
return ResponseUtil.handle(() -> appService.getAllAppHierarchy(newLang));
}

@GetMapping(path = "/hierarchy/{app}")
Expand All @@ -168,9 +151,8 @@ public ResponseEntity<Message<List<Hierarchy>>> 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<Hierarchy> 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")
Expand All @@ -179,9 +161,8 @@ public ResponseEntity<Message<Map<String, String>>> getAllAppDefines(
@Parameter(description = "en: language type",
example = "zh-CN")
@RequestParam(name = "lang", required = false) String lang) {
lang = getLang(lang);
Map<String, String> 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -103,8 +104,7 @@ public ResponseEntity<Message<Bulletin>> getBulletinByName(@Valid @PathVariable
@Operation(summary = "Get All Bulletin Names", description = "Get All Bulletin Names")
@GetMapping("/names")
public ResponseEntity<Message<List<String>>> getAllNames() {
List<String> names = bulletinService.getAllNames();
return ResponseEntity.ok(Message.success(names));
return ResponseUtil.handle(() -> bulletinService.getAllNames());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -56,8 +57,7 @@ public ResponseEntity<Message<Page<CollectorSummary>>> 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<CollectorSummary> receivers = collectorService.getCollectors(name, pageIndex, pageSize);
return ResponseEntity.ok(Message.success(receivers));
return ResponseUtil.handle(() -> collectorService.getCollectors(name, pageIndex, pageSize));
}

@PutMapping("/online")
Expand Down Expand Up @@ -92,7 +92,7 @@ public ResponseEntity<Message<Void>> deleteCollector(
public ResponseEntity<Message<Map<String, String>>> 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));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -63,15 +64,14 @@ public ResponseEntity<Message<String>> saveOrUpdateConfig(
public ResponseEntity<Message<Object>> 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}")
@Operation(summary = "Update the app template config")
public ResponseEntity<Message<Void>> 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));
}
}
Loading