From 8e353b2561210a4ac962859b81b1786aaac5cde0 Mon Sep 17 00:00:00 2001 From: brotherlu-xcq <1285823170@qq.com> Date: Thu, 27 May 2021 10:59:06 +0800 Subject: [PATCH] [FOR #5843 controller/model/enums] improve the code quality of nacos-console. (#5846) * [code quality] [nacos-console] [controller/enums/model] fix the ResponseEntity, the if nest optimize, the constants export, the enum create. * [code quality] [nacos-console] [controller/enums/model] add the javadoc for enums * [code quality] [nacos-console] [controller/enums/model] license problem --- .../console/controller/HealthController.java | 11 ++-- .../controller/NamespaceController.java | 44 ++++++++----- .../controller/PermissionController.java | 6 +- .../console/controller/RoleController.java | 6 +- .../controller/ServerStateController.java | 4 +- .../console/controller/UserController.java | 30 +++------ .../console/enums/NamespaceTypeEnum.java | 66 +++++++++++++++++++ .../nacos/console/model/Namespace.java | 2 +- 8 files changed, 120 insertions(+), 49 deletions(-) create mode 100644 console/src/main/java/com/alibaba/nacos/console/enums/NamespaceTypeEnum.java diff --git a/console/src/main/java/com/alibaba/nacos/console/controller/HealthController.java b/console/src/main/java/com/alibaba/nacos/console/controller/HealthController.java index 10d879657..f95cba770 100644 --- a/console/src/main/java/com/alibaba/nacos/console/controller/HealthController.java +++ b/console/src/main/java/com/alibaba/nacos/console/controller/HealthController.java @@ -21,6 +21,7 @@ import com.alibaba.nacos.naming.controllers.OperatorController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @@ -56,7 +57,7 @@ public class HealthController { * Nacos is in broken states. */ @GetMapping("/liveness") - public ResponseEntity liveness() { + public ResponseEntity liveness() { return ResponseEntity.ok().body("OK"); } @@ -67,7 +68,7 @@ public class HealthController { * ready. */ @GetMapping("/readiness") - public ResponseEntity readiness(HttpServletRequest request) { + public ResponseEntity readiness(HttpServletRequest request) { boolean isConfigReadiness = isConfigReadiness(); boolean isNamingReadiness = isNamingReadiness(request); @@ -76,14 +77,14 @@ public class HealthController { } if (!isConfigReadiness && !isNamingReadiness) { - return ResponseEntity.status(500).body("Config and Naming are not in readiness"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Config and Naming are not in readiness"); } if (!isConfigReadiness) { - return ResponseEntity.status(500).body("Config is not in readiness"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Config is not in readiness"); } - return ResponseEntity.status(500).body("Naming is not in readiness"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Naming is not in readiness"); } private boolean isConfigReadiness() { diff --git a/console/src/main/java/com/alibaba/nacos/console/controller/NamespaceController.java b/console/src/main/java/com/alibaba/nacos/console/controller/NamespaceController.java index d0ca0fe3e..99d7a5d7f 100644 --- a/console/src/main/java/com/alibaba/nacos/console/controller/NamespaceController.java +++ b/console/src/main/java/com/alibaba/nacos/console/controller/NamespaceController.java @@ -19,8 +19,10 @@ package com.alibaba.nacos.console.controller; import com.alibaba.nacos.auth.annotation.Secured; import com.alibaba.nacos.auth.common.ActionTypes; import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.common.model.RestResultUtils; import com.alibaba.nacos.config.server.model.TenantInfo; import com.alibaba.nacos.config.server.service.repository.PersistService; +import com.alibaba.nacos.console.enums.NamespaceTypeEnum; import com.alibaba.nacos.console.model.Namespace; import com.alibaba.nacos.console.model.NamespaceAllInfo; import com.alibaba.nacos.console.security.nacos.NacosAuthConfig; @@ -57,6 +59,20 @@ public class NamespaceController { private static final int NAMESPACE_ID_MAX_LENGTH = 128; + private static final String DEFAULT_NAMESPACE = "public"; + + private static final int DEFAULT_QUOTA = 200; + + private static final String DEFAULT_CREATE_SOURCE = "nacos"; + + private static final String DEFAULT_NAMESPACE_SHOW_NAME = "Public"; + + private static final String DEFAULT_NAMESPACE_DESCRIPTION = "Public Namespace"; + + private static final String DEFAULT_TENANT = ""; + + private static final String DEFAULT_KP = "1"; + /** * Get namespace list. * @@ -66,21 +82,19 @@ public class NamespaceController { */ @GetMapping public RestResult> getNamespaces(HttpServletRequest request, HttpServletResponse response) { - RestResult> rr = new RestResult>(); - rr.setCode(200); // TODO 获取用kp - List tenantInfos = persistService.findTenantByKp("1"); - Namespace namespace0 = new Namespace("", "public", 200, persistService.configInfoCount(""), 0); + List tenantInfos = persistService.findTenantByKp(DEFAULT_KP); + Namespace namespace0 = new Namespace("", DEFAULT_NAMESPACE, DEFAULT_QUOTA, persistService.configInfoCount(DEFAULT_TENANT), + NamespaceTypeEnum.GLOBAL.getType()); List namespaces = new ArrayList(); namespaces.add(namespace0); for (TenantInfo tenantInfo : tenantInfos) { int configCount = persistService.configInfoCount(tenantInfo.getTenantId()); - Namespace namespaceTmp = new Namespace(tenantInfo.getTenantId(), tenantInfo.getTenantName(), 200, - configCount, 2); + Namespace namespaceTmp = new Namespace(tenantInfo.getTenantId(), tenantInfo.getTenantName(), DEFAULT_QUOTA, + configCount, NamespaceTypeEnum.CUSTOM.getType()); namespaces.add(namespaceTmp); } - rr.setData(namespaces); - return rr; + return RestResultUtils.success(namespaces); } /** @@ -96,12 +110,12 @@ public class NamespaceController { @RequestParam("namespaceId") String namespaceId) { // TODO 获取用kp if (StringUtils.isBlank(namespaceId)) { - return new NamespaceAllInfo(namespaceId, "Public", 200, persistService.configInfoCount(""), 0, - "Public Namespace"); + return new NamespaceAllInfo(namespaceId, DEFAULT_NAMESPACE_SHOW_NAME, DEFAULT_QUOTA, persistService.configInfoCount(DEFAULT_TENANT), + NamespaceTypeEnum.GLOBAL.getType(), DEFAULT_NAMESPACE_DESCRIPTION); } else { - TenantInfo tenantInfo = persistService.findTenantByKp("1", namespaceId); + TenantInfo tenantInfo = persistService.findTenantByKp(DEFAULT_KP, namespaceId); int configCount = persistService.configInfoCount(namespaceId); - return new NamespaceAllInfo(namespaceId, tenantInfo.getTenantName(), 200, configCount, 2, + return new NamespaceAllInfo(namespaceId, tenantInfo.getTenantName(), DEFAULT_QUOTA, configCount, NamespaceTypeEnum.CUSTOM.getType(), tenantInfo.getTenantDesc()); } } @@ -135,7 +149,7 @@ public class NamespaceController { return false; } } - persistService.insertTenantInfoAtomic("1", namespaceId, namespaceName, namespaceDesc, "nacos", + persistService.insertTenantInfoAtomic(DEFAULT_KP, namespaceId, namespaceName, namespaceDesc, DEFAULT_CREATE_SOURCE, System.currentTimeMillis()); return true; } @@ -168,7 +182,7 @@ public class NamespaceController { @RequestParam("namespaceShowName") String namespaceShowName, @RequestParam(value = "namespaceDesc", required = false) String namespaceDesc) { // TODO 获取用kp - persistService.updateTenantNameAtomic("1", namespace, namespaceShowName, namespaceDesc); + persistService.updateTenantNameAtomic(DEFAULT_KP, namespace, namespaceShowName, namespaceDesc); return true; } @@ -184,7 +198,7 @@ public class NamespaceController { @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE) public Boolean deleteConfig(HttpServletRequest request, HttpServletResponse response, @RequestParam("namespaceId") String namespaceId) { - persistService.removeTenantInfoAtomic("1", namespaceId); + persistService.removeTenantInfoAtomic(DEFAULT_KP, namespaceId); return true; } diff --git a/console/src/main/java/com/alibaba/nacos/console/controller/PermissionController.java b/console/src/main/java/com/alibaba/nacos/console/controller/PermissionController.java index d808009f3..1db62a586 100644 --- a/console/src/main/java/com/alibaba/nacos/console/controller/PermissionController.java +++ b/console/src/main/java/com/alibaba/nacos/console/controller/PermissionController.java @@ -18,7 +18,7 @@ package com.alibaba.nacos.console.controller; import com.alibaba.nacos.auth.annotation.Secured; import com.alibaba.nacos.auth.common.ActionTypes; -import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.common.model.RestResultUtils; import com.alibaba.nacos.console.security.nacos.NacosAuthConfig; import com.alibaba.nacos.console.security.nacos.roles.NacosRoleServiceImpl; import org.apache.commons.lang3.StringUtils; @@ -70,7 +70,7 @@ public class PermissionController { @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.WRITE) public Object addPermission(@RequestParam String role, @RequestParam String resource, @RequestParam String action) { nacosRoleService.addPermission(role, resource, action); - return new RestResult<>(200, "add permission ok!"); + return RestResultUtils.success("add permission ok!"); } /** @@ -86,6 +86,6 @@ public class PermissionController { public Object deletePermission(@RequestParam String role, @RequestParam String resource, @RequestParam String action) { nacosRoleService.deletePermission(role, resource, action); - return new RestResult<>(200, "delete permission ok!"); + return RestResultUtils.success("delete permission ok!"); } } diff --git a/console/src/main/java/com/alibaba/nacos/console/controller/RoleController.java b/console/src/main/java/com/alibaba/nacos/console/controller/RoleController.java index 6592ed39f..9513545de 100644 --- a/console/src/main/java/com/alibaba/nacos/console/controller/RoleController.java +++ b/console/src/main/java/com/alibaba/nacos/console/controller/RoleController.java @@ -18,7 +18,7 @@ package com.alibaba.nacos.console.controller; import com.alibaba.nacos.auth.annotation.Secured; import com.alibaba.nacos.auth.common.ActionTypes; -import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.common.model.RestResultUtils; import com.alibaba.nacos.console.security.nacos.NacosAuthConfig; import com.alibaba.nacos.console.security.nacos.roles.NacosRoleServiceImpl; import org.apache.commons.lang3.StringUtils; @@ -85,7 +85,7 @@ public class RoleController { @Secured(resource = NacosAuthConfig.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.WRITE) public Object addRole(@RequestParam String role, @RequestParam String username) { roleService.addRole(role, username); - return new RestResult<>(200, "add role ok!"); + return RestResultUtils.success("add role ok!"); } /** @@ -104,7 +104,7 @@ public class RoleController { } else { roleService.deleteRole(role, username); } - return new RestResult<>(200, "delete role of user " + username + " ok!"); + return RestResultUtils.success("delete role of user " + username + " ok!"); } } diff --git a/console/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java b/console/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java index c2a83b48e..aa5ead4b1 100644 --- a/console/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java +++ b/console/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java @@ -41,8 +41,8 @@ public class ServerStateController { * @return state json. */ @GetMapping("/state") - public ResponseEntity serverState() { - Map serverState = new HashMap<>(3); + public ResponseEntity> serverState() { + Map serverState = new HashMap<>(4); serverState.put("standalone_mode", EnvUtil.getStandaloneMode() ? EnvUtil.STANDALONE_MODE_ALONE : EnvUtil.STANDALONE_MODE_CLUSTER); diff --git a/console/src/main/java/com/alibaba/nacos/console/controller/UserController.java b/console/src/main/java/com/alibaba/nacos/console/controller/UserController.java index 63c1970ee..2101603c5 100644 --- a/console/src/main/java/com/alibaba/nacos/console/controller/UserController.java +++ b/console/src/main/java/com/alibaba/nacos/console/controller/UserController.java @@ -23,6 +23,7 @@ import com.alibaba.nacos.auth.common.AuthConfigs; import com.alibaba.nacos.auth.common.AuthSystemTypes; import com.alibaba.nacos.auth.exception.AccessException; import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.common.model.RestResultUtils; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.Objects; import com.alibaba.nacos.config.server.auth.RoleInfo; @@ -37,6 +38,7 @@ import com.alibaba.nacos.console.security.nacos.users.NacosUserDetailsServiceImp import com.alibaba.nacos.console.utils.PasswordEncoderUtil; import com.fasterxml.jackson.databind.node.ObjectNode; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -102,7 +104,7 @@ public class UserController { throw new IllegalArgumentException("user '" + username + "' already exist!"); } userDetailsService.createUser(username, PasswordEncoderUtil.encode(password)); - return new RestResult<>(200, "create user ok!"); + return RestResultUtils.success("create user ok!"); } /** @@ -124,7 +126,7 @@ public class UserController { } } userDetailsService.deleteUser(username); - return new RestResult<>(200, "delete user ok!"); + return RestResultUtils.success("delete user ok!"); } /** @@ -154,7 +156,7 @@ public class UserController { userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword)); - return new RestResult<>(200, "update user ok!"); + return RestResultUtils.success("update user ok!"); } private boolean hasPermission(String username, HttpServletRequest request) { @@ -222,7 +224,6 @@ public class UserController { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); - RestResult rr = new RestResult(); try { // use the method authenticate of AuthenticationManager(default implement is ProviderManager) to valid Authentication Authentication authentication = authenticationManager.authenticate(authenticationToken); @@ -232,13 +233,9 @@ public class UserController { String token = jwtTokenManager.createToken(authentication); // write Token to Http header response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER, "Bearer " + token); - rr.setCode(200); - rr.setData("Bearer " + token); - return rr; + return RestResultUtils.success("Bearer " + token); } catch (BadCredentialsException authentication) { - rr.setCode(401); - rr.setMessage("Login failed"); - return rr; + return RestResultUtils.failed(HttpStatus.UNAUTHORIZED.value(), null, "Login failed"); } } @@ -253,8 +250,6 @@ public class UserController { @Deprecated public RestResult updatePassword(@RequestParam(value = "oldPassword") String oldPassword, @RequestParam(value = "newPassword") String newPassword) { - - RestResult rr = new RestResult(); Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = ((UserDetails) principal).getUsername(); User user = userDetailsService.getUserFromDatabase(username); @@ -264,17 +259,12 @@ public class UserController { try { if (PasswordEncoderUtil.matches(oldPassword, password)) { userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword)); - rr.setCode(200); - rr.setMessage("Update password success"); - } else { - rr.setCode(401); - rr.setMessage("Old password is invalid"); + return RestResultUtils.success("Update password success"); } + return RestResultUtils.failed(HttpStatus.UNAUTHORIZED.value(), "Old password is invalid"); } catch (Exception e) { - rr.setCode(500); - rr.setMessage("Update userpassword failed"); + return RestResultUtils.failed(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Update userpassword failed"); } - return rr; } diff --git a/console/src/main/java/com/alibaba/nacos/console/enums/NamespaceTypeEnum.java b/console/src/main/java/com/alibaba/nacos/console/enums/NamespaceTypeEnum.java new file mode 100644 index 000000000..8674ce8ae --- /dev/null +++ b/console/src/main/java/com/alibaba/nacos/console/enums/NamespaceTypeEnum.java @@ -0,0 +1,66 @@ +/* + * Copyright 1999-2021 Alibaba Group Holding Ltd. + * + * Licensed 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 com.alibaba.nacos.console.enums; + +/** + * the enum of namespace. + * 0 : Global configuration, 1 : Default private namespace ,2 : Custom namespace. + * + * @author chenglu + * @date 2021-05-25 17:01 + */ +public enum NamespaceTypeEnum { + + /** + * Global configuration. + */ + GLOBAL(0, "Global configuration"), + + /** + * Default private namespace. + */ + PRIVATE(1, "Default private namespace"), + + /** + * Custom namespace. + */ + CUSTOM(2, "Custom namespace"); + + /** + * the namespace type. + */ + private final int type; + + /** + * the description. + */ + private final String description; + + NamespaceTypeEnum(int type, String description) { + this.type = type; + this.description = description; + } + + public int getType() { + return type; + } + + public String getDescription() { + return description; + } +} + diff --git a/console/src/main/java/com/alibaba/nacos/console/model/Namespace.java b/console/src/main/java/com/alibaba/nacos/console/model/Namespace.java index 326b3f513..d762d1f16 100644 --- a/console/src/main/java/com/alibaba/nacos/console/model/Namespace.java +++ b/console/src/main/java/com/alibaba/nacos/console/model/Namespace.java @@ -32,7 +32,7 @@ public class Namespace { private int configCount; /** - * 0 : Global configuration, 1 : Default private namespace ,2 : Custom namespace. + * see {@link com.alibaba.nacos.console.enums.NamespaceTypeEnum}. */ private int type;