Skip to content

Commit 98354f2

Browse files
LinuxSuRenshownAias00
authored
[chore] make the controller response be easy (apache#2679)
Co-authored-by: rick <[email protected]> Co-authored-by: shown <[email protected]> Co-authored-by: aias00 <[email protected]>
1 parent 9080ccd commit 98354f2

File tree

6 files changed

+98
-51
lines changed

6 files changed

+98
-51
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.hertzbeat.common.util;
19+
20+
import javax.naming.AuthenticationException;
21+
22+
import org.apache.hertzbeat.common.constants.CommonConstants;
23+
import org.apache.hertzbeat.common.entity.dto.Message;
24+
import org.springframework.http.ResponseEntity;
25+
26+
/**
27+
* A tool which make the restful response be easy to use
28+
*/
29+
public class ResponseUtil {
30+
public static <T, E extends Exception> ResponseEntity<Message<T>> handle(Supplier<T, E> supplier) {
31+
try {
32+
T result = supplier.get();
33+
return ResponseEntity.ok(Message.success(result));
34+
} catch (Exception e) {
35+
byte err = CommonConstants.FAIL_CODE;
36+
if (e.getClass().equals(AuthenticationException.class)) {
37+
err = CommonConstants.LOGIN_FAILED_CODE;
38+
}
39+
return ResponseEntity.ok(Message.fail(err, e.getMessage()));
40+
}
41+
}
42+
43+
public static <T, E extends Exception> ResponseEntity<Message<T>> handle(Runnable runner) {
44+
try {
45+
runner.run();
46+
return ResponseEntity.ok(Message.success());
47+
} catch (Exception e) {
48+
byte err = CommonConstants.FAIL_CODE;
49+
if (e.getClass().equals(AuthenticationException.class)) {
50+
err = CommonConstants.LOGIN_FAILED_CODE;
51+
}
52+
return ResponseEntity.ok(Message.fail(err, e.getMessage()));
53+
}
54+
}
55+
56+
/**
57+
* Supplier interface for getting result
58+
*/
59+
public interface Supplier<T, E extends Exception> {
60+
61+
/**
62+
* Gets a result.
63+
*
64+
* @return a result
65+
*/
66+
T get() throws E;
67+
}
68+
69+
}

manager/src/main/java/org/apache/hertzbeat/manager/controller/AccountController.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import javax.naming.AuthenticationException;
3030
import lombok.extern.slf4j.Slf4j;
3131
import org.apache.hertzbeat.common.entity.dto.Message;
32+
import org.apache.hertzbeat.common.util.ResponseUtil;
3233
import org.apache.hertzbeat.manager.pojo.dto.LoginDto;
3334
import org.apache.hertzbeat.manager.pojo.dto.RefreshTokenResponse;
3435
import org.apache.hertzbeat.manager.service.AccountService;
@@ -56,11 +57,7 @@ public class AccountController {
5657
@PostMapping("/form")
5758
@Operation(summary = "Account password login to obtain associated user information", description = "Account password login to obtain associated user information")
5859
public ResponseEntity<Message<Map<String, String>>> authGetToken(@Valid @RequestBody LoginDto loginDto) {
59-
try {
60-
return ResponseEntity.ok(Message.success(accountService.authGetToken(loginDto)));
61-
} catch (AuthenticationException e) {
62-
return ResponseEntity.ok(Message.fail(LOGIN_FAILED_CODE, e.getMessage()));
63-
}
60+
return ResponseUtil.handle(() -> accountService.authGetToken(loginDto));
6461
}
6562

6663
@GetMapping("/refresh/{refreshToken}")

manager/src/main/java/org/apache/hertzbeat/manager/controller/AppController.java

Lines changed: 19 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717

1818
package org.apache.hertzbeat.manager.controller;
1919

20-
import static org.apache.hertzbeat.common.constants.CommonConstants.FAIL_CODE;
2120
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
2221
import io.swagger.v3.oas.annotations.Operation;
2322
import io.swagger.v3.oas.annotations.Parameter;
@@ -29,6 +28,7 @@
2928
import org.apache.hertzbeat.common.entity.dto.Message;
3029
import org.apache.hertzbeat.common.entity.job.Job;
3130
import org.apache.hertzbeat.common.entity.manager.ParamDefine;
31+
import org.apache.hertzbeat.common.util.ResponseUtil;
3232
import org.apache.hertzbeat.manager.pojo.dto.Hierarchy;
3333
import org.apache.hertzbeat.manager.pojo.dto.MonitorDefineDto;
3434
import org.apache.hertzbeat.manager.service.AppService;
@@ -66,88 +66,72 @@ public class AppController {
6666
description = "The structure of the input parameters required to specify the monitoring type according to the app query")
6767
public ResponseEntity<Message<List<ParamDefine>>> queryAppParamDefines(
6868
@Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("app") final String app) {
69-
List<ParamDefine> paramDefines = appService.getAppParamDefines(app.toLowerCase());
70-
return ResponseEntity.ok(Message.success(paramDefines));
69+
return ResponseUtil.handle(() -> appService.getAppParamDefines(app.toLowerCase()));
7170
}
7271

7372
@GetMapping(path = "/{monitorId}/pushdefine")
7473
@Operation(summary = "The definition structure of the specified monitoring type according to the push query",
7574
description = "The definition structure of the specified monitoring type according to the push query")
7675
public ResponseEntity<Message<Job>> queryPushDefine(
7776
@Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("monitorId") final Long monitorId) {
78-
Job define = appService.getPushDefine(monitorId);
79-
return ResponseEntity.ok(Message.success(define));
77+
return ResponseUtil.handle(() -> appService.getPushDefine(monitorId));
8078
}
8179

8280
@GetMapping(path = "/{monitorId}/define/dynamic")
8381
@Operation(summary = "The definition structure of the specified monitoring type according to the push query",
8482
description = "The definition structure of the specified monitoring type according to the push query")
8583
public ResponseEntity<Message<Job>> queryAutoGenerateDynamicAppDefine(
8684
@Parameter(description = "Monitoring id", example = "5435345") @PathVariable("monitorId") final Long monitorId) {
87-
Job define = appService.getAutoGenerateDynamicDefine(monitorId);
88-
return ResponseEntity.ok(Message.success(define));
85+
return ResponseUtil.handle(() -> appService.getAutoGenerateDynamicDefine(monitorId));
8986
}
9087

9188
@GetMapping(path = "/{app}/define")
9289
@Operation(summary = "The definition structure of the specified monitoring type according to the app query",
9390
description = "The definition structure of the specified monitoring type according to the app query")
9491
public ResponseEntity<Message<Job>> queryAppDefine(
9592
@Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("app") final String app) {
96-
Job define = appService.getAppDefine(app.toLowerCase());
97-
return ResponseEntity.ok(Message.success(define));
93+
return ResponseUtil.handle(() -> appService.getAppDefine(app.toLowerCase()));
9894
}
9995

10096
@GetMapping(path = "/{app}/define/yml")
10197
@Operation(summary = "The definition yml of the specified monitoring type according to the app query",
10298
description = "The definition yml of the specified monitoring type according to the app query")
10399
public ResponseEntity<Message<String>> queryAppDefineYml(
104100
@Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("app") final String app) {
105-
String defineContent = appService.getMonitorDefineFileContent(app);
106-
return ResponseEntity.ok(Message.successWithData(defineContent));
101+
return ResponseUtil.handle(() -> appService.getMonitorDefineFileContent(app));
107102
}
108103

109104
@DeleteMapping(path = "/{app}/define/yml")
110105
@Operation(summary = "Delete monitor define yml", description = "Delete the definition YML for the specified monitoring type according to the app")
111106
public ResponseEntity<Message<Void>> deleteAppDefineYml(
112107
@Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("app") final String app) {
113-
try {
114-
appService.deleteMonitorDefine(app);
115-
} catch (Exception e) {
116-
return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage()));
117-
}
118-
return ResponseEntity.ok(Message.success());
108+
return ResponseUtil.handle(() -> appService.deleteMonitorDefine(app));
119109
}
120110

121111
@PostMapping(path = "/define/yml")
122112
@Operation(summary = "Add new monitoring type define yml", description = "Add new monitoring type define yml")
123113
public ResponseEntity<Message<Void>> newAppDefineYml(@Valid @RequestBody MonitorDefineDto defineDto) {
124-
try {
114+
return ResponseUtil.handle(() -> {
125115
for (String riskyToken : RISKY_STR_ARR) {
126116
if (defineDto.getDefine().contains(riskyToken)) {
127-
return ResponseEntity.ok(Message.fail(FAIL_CODE, "can not has malicious remote script"));
117+
throw new RuntimeException("can not has malicious remote script");
128118
}
129119
}
130120
appService.applyMonitorDefineYml(defineDto.getDefine(), false);
131-
} catch (Exception e) {
132-
return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage()));
133-
}
134-
return ResponseEntity.ok(Message.success());
121+
});
135122
}
136123

137124
@PutMapping(path = "/define/yml")
138125
@Operation(summary = "Update monitoring type define yml", description = "Update monitoring type define yml")
139126
public ResponseEntity<Message<Void>> updateAppDefineYml(@Valid @RequestBody MonitorDefineDto defineDto) {
140-
try {
127+
return ResponseUtil.handle(() -> {
141128
for (String riskyToken : RISKY_STR_ARR) {
142129
if (defineDto.getDefine().contains(riskyToken)) {
143-
return ResponseEntity.ok(Message.fail(FAIL_CODE, "can not has malicious remote script"));
130+
throw new RuntimeException("can not has malicious remote script");
144131
}
145132
}
146133
appService.applyMonitorDefineYml(defineDto.getDefine(), true);
147-
} catch (Exception e) {
148-
return ResponseEntity.ok(Message.fail(FAIL_CODE, e.getMessage()));
149-
}
150-
return ResponseEntity.ok(Message.success());
134+
});
151135
}
152136

153137
@GetMapping(path = "/hierarchy")
@@ -156,9 +140,8 @@ public ResponseEntity<Message<List<Hierarchy>>> queryAppsHierarchy(
156140
@Parameter(description = "en: language type",
157141
example = "zh-CN")
158142
@RequestParam(name = "lang", required = false) String lang) {
159-
lang = getLang(lang);
160-
List<Hierarchy> appHierarchies = appService.getAllAppHierarchy(lang);
161-
return ResponseEntity.ok(Message.success(appHierarchies));
143+
String newLang = getLang(lang);
144+
return ResponseUtil.handle(() -> appService.getAllAppHierarchy(newLang));
162145
}
163146

164147
@GetMapping(path = "/hierarchy/{app}")
@@ -168,9 +151,8 @@ public ResponseEntity<Message<List<Hierarchy>>> queryAppsHierarchyByApp(
168151
example = "zh-CN")
169152
@RequestParam(name = "lang", required = false) String lang,
170153
@Parameter(description = "en: Monitoring type name", example = "api") @PathVariable("app") final String app) {
171-
lang = getLang(lang);
172-
List<Hierarchy> appHierarchies = appService.getAppHierarchy(app, lang);
173-
return ResponseEntity.ok(Message.success(appHierarchies));
154+
String newLang = getLang(lang);
155+
return ResponseUtil.handle(() -> appService.getAppHierarchy(app, newLang));
174156
}
175157

176158
@GetMapping(path = "/defines")
@@ -179,9 +161,8 @@ public ResponseEntity<Message<Map<String, String>>> getAllAppDefines(
179161
@Parameter(description = "en: language type",
180162
example = "zh-CN")
181163
@RequestParam(name = "lang", required = false) String lang) {
182-
lang = getLang(lang);
183-
Map<String, String> allAppDefines = appService.getI18nApps(lang);
184-
return ResponseEntity.ok(Message.success(allAppDefines));
164+
String newLang = getLang(lang);
165+
return ResponseUtil.handle(() -> appService.getI18nApps(newLang));
185166
}
186167

187168
private String getLang(@RequestParam(name = "lang", required = false) @Parameter(description = "en: language type", example = "zh-CN") String lang) {

manager/src/main/java/org/apache/hertzbeat/manager/controller/BulletinController.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import org.apache.hertzbeat.common.entity.manager.bulletin.Bulletin;
3030
import org.apache.hertzbeat.common.entity.manager.bulletin.BulletinDto;
3131
import org.apache.hertzbeat.common.entity.manager.bulletin.BulletinMetricsData;
32+
import org.apache.hertzbeat.common.util.ResponseUtil;
3233
import org.apache.hertzbeat.manager.service.BulletinService;
3334
import org.apache.hertzbeat.warehouse.store.realtime.RealTimeDataReader;
3435
import org.springframework.beans.factory.annotation.Autowired;
@@ -103,8 +104,7 @@ public ResponseEntity<Message<Bulletin>> getBulletinByName(@Valid @PathVariable
103104
@Operation(summary = "Get All Bulletin Names", description = "Get All Bulletin Names")
104105
@GetMapping("/names")
105106
public ResponseEntity<Message<List<String>>> getAllNames() {
106-
List<String> names = bulletinService.getAllNames();
107-
return ResponseEntity.ok(Message.success(names));
107+
return ResponseUtil.handle(() -> bulletinService.getAllNames());
108108
}
109109

110110
/**

manager/src/main/java/org/apache/hertzbeat/manager/controller/CollectorController.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import java.util.Map;
2626
import org.apache.hertzbeat.common.entity.dto.CollectorSummary;
2727
import org.apache.hertzbeat.common.entity.dto.Message;
28+
import org.apache.hertzbeat.common.util.ResponseUtil;
2829
import org.apache.hertzbeat.manager.service.CollectorService;
2930
import org.springframework.beans.factory.annotation.Autowired;
3031
import org.springframework.data.domain.Page;
@@ -56,8 +57,7 @@ public ResponseEntity<Message<Page<CollectorSummary>>> getCollectors(
5657
@Parameter(description = "collector name", example = "tom") @RequestParam(required = false) final String name,
5758
@Parameter(description = "List current page", example = "0") @RequestParam(defaultValue = "0") int pageIndex,
5859
@Parameter(description = "Number of list pagination", example = "8") @RequestParam(required = false) Integer pageSize) {
59-
Page<CollectorSummary> receivers = collectorService.getCollectors(name, pageIndex, pageSize);
60-
return ResponseEntity.ok(Message.success(receivers));
60+
return ResponseUtil.handle(() -> collectorService.getCollectors(name, pageIndex, pageSize));
6161
}
6262

6363
@PutMapping("/online")
@@ -92,7 +92,7 @@ public ResponseEntity<Message<Void>> deleteCollector(
9292
public ResponseEntity<Message<Map<String, String>>> generateCollectorDeployInfo(
9393
@Parameter(description = "collector name", example = "demo-collector")
9494
@PathVariable() String collector) {
95-
return ResponseEntity.ok(Message.success(collectorService.generateCollectorDeployInfo(collector)));
95+
return ResponseUtil.handle(() -> collectorService.generateCollectorDeployInfo(collector));
9696
}
9797

9898
}

manager/src/main/java/org/apache/hertzbeat/manager/controller/GeneralConfigController.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import jakarta.validation.constraints.NotNull;
2626
import lombok.extern.slf4j.Slf4j;
2727
import org.apache.hertzbeat.common.entity.dto.Message;
28+
import org.apache.hertzbeat.common.util.ResponseUtil;
2829
import org.apache.hertzbeat.manager.pojo.dto.TemplateConfig;
2930
import org.apache.hertzbeat.manager.service.ConfigService;
3031
import org.springframework.http.ResponseEntity;
@@ -63,15 +64,14 @@ public ResponseEntity<Message<String>> saveOrUpdateConfig(
6364
public ResponseEntity<Message<Object>> getConfig(
6465
@Parameter(description = "Config Type", example = "email")
6566
@PathVariable("type") @NotNull final String type) {
66-
return ResponseEntity.ok(Message.success(configService.getConfig(type)));
67+
return ResponseUtil.handle(() -> configService.getConfig(type));
6768
}
6869

6970
@PutMapping(path = "/template/{app}")
7071
@Operation(summary = "Update the app template config")
7172
public ResponseEntity<Message<Void>> updateTemplateAppConfig(
7273
@PathVariable("app") @NotNull final String app,
7374
@RequestBody TemplateConfig.AppTemplate template) {
74-
configService.updateTemplateAppConfig(app, template);
75-
return ResponseEntity.ok(Message.success());
75+
return ResponseUtil.handle(() -> configService.updateTemplateAppConfig(app, template));
7676
}
7777
}

0 commit comments

Comments
 (0)