diff --git a/api/src/main/java/com/alibaba/nacos/api/naming/utils/NamingUtils.java b/api/src/main/java/com/alibaba/nacos/api/naming/utils/NamingUtils.java index 6259d0a87..0ab3bd615 100644 --- a/api/src/main/java/com/alibaba/nacos/api/naming/utils/NamingUtils.java +++ b/api/src/main/java/com/alibaba/nacos/api/naming/utils/NamingUtils.java @@ -27,6 +27,19 @@ import com.alibaba.nacos.api.utils.StringUtils; */ public class NamingUtils { + /** + * Returns a combined string with serviceName and groupName. serviceName can not be nil. + * + *

In most cases, serviceName can not be nil. In other cases, for search or anything, See {@link + * com.alibaba.nacos.api.naming.utils.NamingUtils#getGroupedNameOptional(String, String)} + * + *

etc: + *

serviceName | groupName | result

+ *

serviceA | groupA | groupA@@serviceA

+ *

nil | groupA | threw IllegalArgumentException

+ * + * @return 'groupName@@serviceName' + */ public static String getGroupedName(final String serviceName, final String groupName) { if (StringUtils.isBlank(serviceName)) { throw new IllegalArgumentException("Param 'serviceName' is illegal, serviceName is blank"); @@ -73,4 +86,20 @@ public class NamingUtils { "Param 'serviceName' is illegal, it should be format as 'groupName@@serviceName'"); } } + + /** + * Returns a combined string with serviceName and groupName. Such as 'groupName@@serviceName' + *

This method works similar with {@link com.alibaba.nacos.api.naming.utils.NamingUtils#getGroupedName} But not verify any parameters. + * + *

etc: + *

serviceName | groupName | result

+ *

serviceA | groupA | groupA@@serviceA

+ *

nil | groupA | groupA@@

+ *

nil | nil | @@

+ * + * @return 'groupName@@serviceName' + */ + public static String getGroupedNameOptional(final String serviceName, final String groupName) { + return groupName + Constants.SERVICE_INFO_SPLITER + serviceName; + } } diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/utils/NamingUtilsTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/utils/NamingUtilsTest.java new file mode 100644 index 000000000..41c58a556 --- /dev/null +++ b/api/src/test/java/com/alibaba/nacos/api/naming/utils/NamingUtilsTest.java @@ -0,0 +1,37 @@ +/* + * Copyright 1999-2018 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.api.naming.utils; + +import com.alibaba.nacos.api.utils.StringUtils; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class NamingUtilsTest { + + @Test + public void testGetGroupedNameOptional() { + String onlyGroupName = NamingUtils.getGroupedNameOptional(StringUtils.EMPTY, "groupA"); + assertEquals(onlyGroupName, "groupA@@"); + + String onlyServiceName = NamingUtils.getGroupedNameOptional("serviceA", StringUtils.EMPTY); + assertEquals(onlyServiceName, "@@serviceA"); + + String groupNameAndServiceName = NamingUtils.getGroupedNameOptional("serviceA", "groupA"); + assertEquals(groupNameAndServiceName, "groupA@@serviceA"); + } +} \ No newline at end of file diff --git a/auth/src/main/java/com/alibaba/nacos/auth/common/AuthConfigs.java b/auth/src/main/java/com/alibaba/nacos/auth/common/AuthConfigs.java index 721359b36..a13238fd4 100644 --- a/auth/src/main/java/com/alibaba/nacos/auth/common/AuthConfigs.java +++ b/auth/src/main/java/com/alibaba/nacos/auth/common/AuthConfigs.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.auth.common; import com.alibaba.nacos.common.JustForTest; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import io.jsonwebtoken.io.Decoders; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; @@ -89,7 +89,7 @@ public class AuthConfigs { return BooleanUtils.toBoolean(enabled); } return BooleanUtils - .toBoolean(ApplicationUtils.getProperty("nacos.core.auth.enabled", "false")); + .toBoolean(EnvUtil.getProperty("nacos.core.auth.enabled", "false")); } /** @@ -102,7 +102,7 @@ public class AuthConfigs { return cachingEnabled; } return BooleanUtils - .toBoolean(ApplicationUtils.getProperty("nacos.core.auth.caching.enabled", "true")); + .toBoolean(EnvUtil.getProperty("nacos.core.auth.caching.enabled", "true")); } @JustForTest diff --git a/client/src/main/java/com/alibaba/nacos/client/config/http/ServerHttpAgent.java b/client/src/main/java/com/alibaba/nacos/client/config/http/ServerHttpAgent.java index 7381167f7..f9e4d7f01 100644 --- a/client/src/main/java/com/alibaba/nacos/client/config/http/ServerHttpAgent.java +++ b/client/src/main/java/com/alibaba/nacos/client/config/http/ServerHttpAgent.java @@ -19,6 +19,7 @@ package com.alibaba.nacos.client.config.http; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.client.config.impl.ConfigHttpClientManager; import com.alibaba.nacos.client.config.impl.ServerListManager; +import com.alibaba.nacos.client.utils.ContextPathUtil; import com.alibaba.nacos.client.utils.LogUtils; import com.alibaba.nacos.client.utils.ParamUtil; import com.alibaba.nacos.common.http.HttpClientConfig; @@ -212,9 +213,7 @@ public class ServerHttpAgent implements HttpAgent { } private String getUrl(String serverAddr, String relativePath) { - String contextPath = serverListMgr.getContentPath().startsWith("/") ? serverListMgr.getContentPath() - : "/" + serverListMgr.getContentPath(); - return serverAddr + contextPath + relativePath; + return serverAddr + ContextPathUtil.normalizeContextPath(serverListMgr.getContentPath()) + relativePath; } private boolean isFail(HttpRestResult result) { diff --git a/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java b/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java index 5ee77dfae..89fe4ef3c 100644 --- a/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java +++ b/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java @@ -19,6 +19,7 @@ package com.alibaba.nacos.client.config.impl; import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.SystemPropertyKeyConst; import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.client.utils.ContextPathUtil; import com.alibaba.nacos.client.utils.EnvUtil; import com.alibaba.nacos.client.utils.LogUtils; import com.alibaba.nacos.client.utils.ParamUtil; @@ -109,7 +110,9 @@ public class ServerListManager implements Closeable { this.isFixed = false; this.isStarted = false; this.name = CUSTOM_NAME + "-" + host + "-" + port; - this.addressServerUrl = String.format("http://%s:%d/%s/%s", host, port, this.contentPath, this.serverListName); + this.addressServerUrl = String + .format("http://%s:%d%s/%s", host, port, ContextPathUtil.normalizeContextPath(this.contentPath), + this.serverListName); } public ServerListManager(String endpoint) throws NacosException { @@ -128,8 +131,8 @@ public class ServerListManager implements Closeable { } if (StringUtils.isBlank(namespace)) { this.name = endpoint; - this.addressServerUrl = String - .format("http://%s:%d/%s/%s", endpoint, this.endpointPort, this.contentPath, this.serverListName); + this.addressServerUrl = String.format("http://%s:%d%s/%s", endpoint, this.endpointPort, + ContextPathUtil.normalizeContextPath(this.contentPath), this.serverListName); } else { if (StringUtils.isBlank(endpoint)) { throw new NacosException(NacosException.CLIENT_INVALID_PARAM, "endpoint is blank"); @@ -137,9 +140,8 @@ public class ServerListManager implements Closeable { this.name = endpoint + "-" + namespace; this.namespace = namespace; this.tenant = namespace; - this.addressServerUrl = String - .format("http://%s:%d/%s/%s?namespace=%s", endpoint, this.endpointPort, this.contentPath, - this.serverListName, namespace); + this.addressServerUrl = String.format("http://%s:%d%s/%s?namespace=%s", endpoint, this.endpointPort, + ContextPathUtil.normalizeContextPath(this.contentPath), this.serverListName, namespace); } } @@ -183,16 +185,15 @@ public class ServerListManager implements Closeable { this.isFixed = false; if (StringUtils.isBlank(namespace)) { this.name = endpoint; - this.addressServerUrl = String - .format("http://%s:%d/%s/%s", this.endpoint, this.endpointPort, this.contentPath, - this.serverListName); + this.addressServerUrl = String.format("http://%s:%d%s/%s", this.endpoint, this.endpointPort, + ContextPathUtil.normalizeContextPath(this.contentPath), this.serverListName); } else { this.namespace = namespace; this.tenant = namespace; this.name = this.endpoint + "-" + namespace; this.addressServerUrl = String - .format("http://%s:%d/%s/%s?namespace=%s", this.endpoint, this.endpointPort, this.contentPath, - this.serverListName, namespace); + .format("http://%s:%d%s/%s?namespace=%s", this.endpoint, this.endpointPort, + ContextPathUtil.normalizeContextPath(this.contentPath), this.serverListName, namespace); } } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingMaintainService.java b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingMaintainService.java index 2a553c22f..ddc521ed9 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingMaintainService.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingMaintainService.java @@ -60,7 +60,7 @@ public class NacosNamingMaintainService implements NamingMaintainService { ValidatorUtils.checkInitParam(properties); namespace = InitUtils.initNamespaceForNaming(properties); InitUtils.initSerialization(); - InitUtils.initWebRootContext(); + InitUtils.initWebRootContext(properties; ServerListManager serverListManager = new ServerListManager(properties); serverProxy = new NamingHttpClientProxy(namespace, serverListManager, properties, null); } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java index dff28674f..b35cb02fc 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java @@ -78,7 +78,7 @@ public class NacosNamingService implements NamingService { ValidatorUtils.checkInitParam(properties); this.namespace = InitUtils.initNamespaceForNaming(properties); InitUtils.initSerialization(); - InitUtils.initWebRootContext(); + InitUtils.initWebRootContext(properties); initLogName(properties); this.changeNotifier = new InstancesChangeNotifier(); diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/utils/InitUtils.java b/client/src/main/java/com/alibaba/nacos/client/naming/utils/InitUtils.java index 61998b755..133b2e04a 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/utils/InitUtils.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/utils/InitUtils.java @@ -22,6 +22,7 @@ import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.selector.ExpressionSelector; import com.alibaba.nacos.api.selector.NoneSelector; import com.alibaba.nacos.api.selector.SelectorType; +import com.alibaba.nacos.client.utils.ContextPathUtil; import com.alibaba.nacos.client.utils.LogUtils; import com.alibaba.nacos.client.utils.ParamUtil; import com.alibaba.nacos.client.utils.TemplateUtils; @@ -100,15 +101,34 @@ public class InitUtils { /** * Init web root context. + * + * @param properties properties + * @since 1.4.1 */ + public static void initWebRootContext(Properties properties) { + final String webContext = properties.getProperty(PropertyKeyConst.CONTEXT_PATH); + TemplateUtils.stringNotEmptyAndThenExecute(webContext, new Runnable() { + @Override + public void run() { + UtilAndComs.webContext = ContextPathUtil.normalizeContextPath(webContext); + UtilAndComs.nacosUrlBase = UtilAndComs.webContext + "/v1/ns"; + UtilAndComs.nacosUrlInstance = UtilAndComs.nacosUrlBase + "/instance"; + } + }); + initWebRootContext(); + } + + /** + * Init web root context. + */ + @Deprecated public static void initWebRootContext() { // support the web context with ali-yun if the app deploy by EDAS final String webContext = System.getProperty(SystemPropertyKeyConst.NAMING_WEB_CONTEXT); TemplateUtils.stringNotEmptyAndThenExecute(webContext, new Runnable() { @Override public void run() { - UtilAndComs.webContext = webContext.indexOf("/") > -1 ? webContext : "/" + webContext; - + UtilAndComs.webContext = ContextPathUtil.normalizeContextPath(webContext); UtilAndComs.nacosUrlBase = UtilAndComs.webContext + "/v1/ns"; UtilAndComs.nacosUrlInstance = UtilAndComs.nacosUrlBase + "/instance"; } diff --git a/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java b/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java index f0b956b32..0407ef0b0 100644 --- a/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java +++ b/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java @@ -18,6 +18,7 @@ package com.alibaba.nacos.client.security; import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.client.utils.ContextPathUtil; import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.param.Header; @@ -88,8 +89,7 @@ public class SecurityProxy { public SecurityProxy(Properties properties, NacosRestTemplate nacosRestTemplate) { username = properties.getProperty(PropertyKeyConst.USERNAME, StringUtils.EMPTY); password = properties.getProperty(PropertyKeyConst.PASSWORD, StringUtils.EMPTY); - contextPath = properties.getProperty(PropertyKeyConst.CONTEXT_PATH, "/nacos"); - contextPath = contextPath.startsWith("/") ? contextPath : "/" + contextPath; + contextPath = ContextPathUtil.normalizeContextPath(properties.getProperty(PropertyKeyConst.CONTEXT_PATH, "/nacos")); this.nacosRestTemplate = nacosRestTemplate; } diff --git a/client/src/main/java/com/alibaba/nacos/client/utils/ContextPathUtil.java b/client/src/main/java/com/alibaba/nacos/client/utils/ContextPathUtil.java new file mode 100644 index 000000000..265fd4784 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/utils/ContextPathUtil.java @@ -0,0 +1,42 @@ +/* + * Copyright 1999-2018 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.client.utils; + +import com.alibaba.nacos.common.utils.StringUtils; + +/** + * Context path Util. + * + * @author Wei.Wang + */ +public class ContextPathUtil { + + private static final String ROOT_WEB_CONTEXT_PATH = "/"; + + /** + * normalize context path. + * + * @param contextPath origin context path + * @return normalized context path + */ + public static String normalizeContextPath(String contextPath) { + if (StringUtils.isBlank(contextPath) || ROOT_WEB_CONTEXT_PATH.equals(contextPath)) { + return StringUtils.EMPTY; + } + return contextPath.startsWith("/") ? contextPath : "/" + contextPath; + } +} diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java new file mode 100644 index 000000000..c1953d8b1 --- /dev/null +++ b/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 1999-2018 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.client.utils; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * ContextPathUtil test. + * + * @author Wei.Wang + * @date 2020/11/26 3:13 PM + */ +public class ContextPathUtilTest { + + @Test + public void testNormalizeContextPath() { + assertEquals("/nacos", ContextPathUtil.normalizeContextPath("/nacos")); + assertEquals("/nacos", ContextPathUtil.normalizeContextPath("nacos")); + assertEquals("", ContextPathUtil.normalizeContextPath("/")); + assertEquals("", ContextPathUtil.normalizeContextPath("")); + } +} diff --git a/common/src/main/java/com/alibaba/nacos/common/model/RestResultUtils.java b/common/src/main/java/com/alibaba/nacos/common/model/RestResultUtils.java index 8f3ffa3cf..7b73c50f7 100644 --- a/common/src/main/java/com/alibaba/nacos/common/model/RestResultUtils.java +++ b/common/src/main/java/com/alibaba/nacos/common/model/RestResultUtils.java @@ -16,6 +16,8 @@ package com.alibaba.nacos.common.model; +import com.alibaba.nacos.common.model.core.IResultCode; + /** * Rest result utils. * @@ -31,6 +33,10 @@ public class RestResultUtils { return RestResult.builder().withCode(200).withData(data).build(); } + public static RestResult success(String msg, T data) { + return RestResult.builder().withCode(200).withMsg(msg).withData(data).build(); + } + public static RestResult success(int code, T data) { return RestResult.builder().withCode(code).withData(data).build(); } @@ -54,5 +60,8 @@ public class RestResultUtils { public static RestResult failedWithMsg(int code, String errMsg) { return RestResult.builder().withCode(code).withMsg(errMsg).build(); } - + + public static RestResult buildResult(IResultCode resultCode, T data) { + return RestResult.builder().withCode(resultCode.getCode()).withMsg(resultCode.getCodeMsg()).withData(data).build(); + } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/result/core/IResultCode.java b/common/src/main/java/com/alibaba/nacos/common/model/core/IResultCode.java similarity index 95% rename from config/src/main/java/com/alibaba/nacos/config/server/result/core/IResultCode.java rename to common/src/main/java/com/alibaba/nacos/common/model/core/IResultCode.java index d299fa823..e7d9ed83e 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/result/core/IResultCode.java +++ b/common/src/main/java/com/alibaba/nacos/common/model/core/IResultCode.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.alibaba.nacos.config.server.result.core; +package com.alibaba.nacos.common.model.core; /** * IResultCode. diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/NamespaceUtil.java b/common/src/main/java/com/alibaba/nacos/common/utils/NamespaceUtil.java similarity index 94% rename from config/src/main/java/com/alibaba/nacos/config/server/utils/NamespaceUtil.java rename to common/src/main/java/com/alibaba/nacos/common/utils/NamespaceUtil.java index 2fc0277ef..dc6009d2b 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/NamespaceUtil.java +++ b/common/src/main/java/com/alibaba/nacos/common/utils/NamespaceUtil.java @@ -14,9 +14,7 @@ * limitations under the License. */ -package com.alibaba.nacos.config.server.utils; - -import org.apache.commons.lang3.StringUtils; +package com.alibaba.nacos.common.utils; /** * namespace(tenant) util. diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/NamespaceUtilTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java similarity index 97% rename from config/src/test/java/com/alibaba/nacos/config/server/utils/NamespaceUtilTest.java rename to common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java index 16bbd700d..c653a5e1b 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/NamespaceUtilTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.alibaba.nacos.config.server.utils; +package com.alibaba.nacos.common.utils; import org.junit.Assert; import org.junit.Test; diff --git a/config/src/main/java/com/alibaba/nacos/config/server/auth/ConfigResourceParser.java b/config/src/main/java/com/alibaba/nacos/config/server/auth/ConfigResourceParser.java index 8f594be82..b4dbbdc7f 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/auth/ConfigResourceParser.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/auth/ConfigResourceParser.java @@ -20,6 +20,7 @@ import com.alibaba.nacos.api.remote.request.Request; import com.alibaba.nacos.auth.model.Resource; import com.alibaba.nacos.auth.parser.ResourceParser; import com.alibaba.nacos.common.utils.ReflectUtils; +import com.alibaba.nacos.common.utils.NamespaceUtil; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest; @@ -42,7 +43,7 @@ public class ConfigResourceParser implements ResourceParser { String dataId = null; if (requestObj instanceof HttpServletRequest) { HttpServletRequest req = (HttpServletRequest) requestObj; - namespaceId = req.getParameter("tenant"); + namespaceId = NamespaceUtil.processNamespaceParameter(req.getParameter("tenant")); groupName = req.getParameter("group"); dataId = req.getParameter("dataId"); } else if (requestObj instanceof Request) { diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionDistributedEmbedStorage.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionDistributedEmbedStorage.java index 5d3d0b8a6..cc545f7cc 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionDistributedEmbedStorage.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionDistributedEmbedStorage.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.config.server.configuration; import com.alibaba.nacos.config.server.utils.PropertyUtil; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; @@ -31,6 +31,6 @@ public class ConditionDistributedEmbedStorage implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - return PropertyUtil.isEmbeddedStorage() && !ApplicationUtils.getStandaloneMode(); + return PropertyUtil.isEmbeddedStorage() && !EnvUtil.getStandaloneMode(); } -} \ No newline at end of file +} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionStandaloneEmbedStorage.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionStandaloneEmbedStorage.java index 2a6fcf56d..7006cb07c 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionStandaloneEmbedStorage.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionStandaloneEmbedStorage.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.config.server.configuration; import com.alibaba.nacos.config.server.utils.PropertyUtil; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; @@ -32,6 +32,6 @@ public class ConditionStandaloneEmbedStorage implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - return PropertyUtil.isEmbeddedStorage() && ApplicationUtils.getStandaloneMode(); + return PropertyUtil.isEmbeddedStorage() && EnvUtil.getStandaloneMode(); } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java index 6f2972e27..4cb1af6cf 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java @@ -22,6 +22,8 @@ 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.utils.MapUtil; +import com.alibaba.nacos.common.model.RestResultUtils; +import com.alibaba.nacos.common.utils.MapUtils; import com.alibaba.nacos.config.server.auth.ConfigResourceParser; import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.controller.parameters.SameNamespaceCloneConfigBean; @@ -34,7 +36,6 @@ import com.alibaba.nacos.config.server.model.Page; import com.alibaba.nacos.config.server.model.SameConfigPolicy; import com.alibaba.nacos.config.server.model.SampleResult; import com.alibaba.nacos.config.server.model.event.ConfigDataChangeEvent; -import com.alibaba.nacos.config.server.result.ResultBuilder; import com.alibaba.nacos.config.server.result.code.ResultCodeEnum; import com.alibaba.nacos.config.server.service.AggrWhitelist; import com.alibaba.nacos.config.server.service.ConfigChangePublisher; @@ -45,6 +46,7 @@ import com.alibaba.nacos.config.server.utils.MD5Util; import com.alibaba.nacos.config.server.utils.NamespaceUtil; import com.alibaba.nacos.config.server.utils.ParamUtils; import com.alibaba.nacos.config.server.utils.RequestUtil; +import com.alibaba.nacos.common.utils.NamespaceUtil; import com.alibaba.nacos.config.server.utils.TimeUtils; import com.alibaba.nacos.config.server.utils.ZipUtils; import com.alibaba.nacos.sys.utils.InetUtils; @@ -284,7 +286,7 @@ public class ConfigController { null, time.getTime(), clientIp, ConfigTraceService.PERSISTENCE_EVENT_REMOVE, null); } } - return ResultBuilder.buildSuccessResult(true); + return RestResultUtils.success(true); } @GetMapping("/catalog") @@ -529,13 +531,13 @@ public class ConfigController { Map failedData = new HashMap<>(4); if (Objects.isNull(file)) { - return ResultBuilder.buildResult(ResultCodeEnum.DATA_EMPTY, failedData); + return RestResultUtils.buildResult(ResultCodeEnum.DATA_EMPTY, failedData); } namespace = NamespaceUtil.processNamespaceParameter(namespace); if (StringUtils.isNotBlank(namespace) && persistService.tenantInfoCountByTenantId(namespace) <= 0) { failedData.put("succCount", 0); - return ResultBuilder.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, failedData); + return RestResultUtils.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, failedData); } List configInfoList = null; @@ -550,7 +552,7 @@ public class ConfigController { String[] metaDataItemArr = metaDataItem.split("="); if (metaDataItemArr.length != 2) { failedData.put("succCount", 0); - return ResultBuilder.buildResult(ResultCodeEnum.METADATA_ILLEGAL, failedData); + return RestResultUtils.buildResult(ResultCodeEnum.METADATA_ILLEGAL, failedData); } metaDataMap.put(metaDataItemArr[0], metaDataItemArr[1]); } @@ -562,7 +564,7 @@ public class ConfigController { String[] groupAdnDataId = item.getItemName().split("/"); if (!item.getItemName().contains("/") || groupAdnDataId.length != 2) { failedData.put("succCount", 0); - return ResultBuilder.buildResult(ResultCodeEnum.DATA_VALIDATION_FAILED, failedData); + return RestResultUtils.buildResult(ResultCodeEnum.DATA_VALIDATION_FAILED, failedData); } String group = groupAdnDataId[0]; String dataId = groupAdnDataId[1]; @@ -586,11 +588,11 @@ public class ConfigController { } catch (IOException e) { failedData.put("succCount", 0); LOGGER.error("parsing data failed", e); - return ResultBuilder.buildResult(ResultCodeEnum.PARSING_DATA_FAILED, failedData); + return RestResultUtils.buildResult(ResultCodeEnum.PARSING_DATA_FAILED, failedData); } if (configInfoList == null || configInfoList.isEmpty()) { failedData.put("succCount", 0); - return ResultBuilder.buildResult(ResultCodeEnum.DATA_EMPTY, failedData); + return RestResultUtils.buildResult(ResultCodeEnum.DATA_EMPTY, failedData); } final String srcIp = RequestUtil.getRemoteIp(request); String requestIpApp = RequestUtil.getAppName(request); @@ -606,7 +608,7 @@ public class ConfigController { requestIpApp, time.getTime(), InetUtils.getSelfIP(), ConfigTraceService.PERSISTENCE_EVENT_PUB, configInfo.getContent()); } - return ResultBuilder.buildSuccessResult("导入成功", saveResult); + return RestResultUtils.success("导入成功", saveResult); } /** @@ -630,14 +632,14 @@ public class ConfigController { Map failedData = new HashMap<>(4); if (CollectionUtils.isEmpty(configBeansList)) { failedData.put("succCount", 0); - return ResultBuilder.buildResult(ResultCodeEnum.NO_SELECTED_CONFIG, failedData); + return RestResultUtils.buildResult(ResultCodeEnum.NO_SELECTED_CONFIG, failedData); } configBeansList.removeAll(Collections.singleton(null)); namespace = NamespaceUtil.processNamespaceParameter(namespace); if (StringUtils.isNotBlank(namespace) && persistService.tenantInfoCountByTenantId(namespace) <= 0) { failedData.put("succCount", 0); - return ResultBuilder.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, failedData); + return RestResultUtils.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, failedData); } List idList = new ArrayList<>(configBeansList.size()); @@ -651,7 +653,7 @@ public class ConfigController { if (queryedDataList == null || queryedDataList.isEmpty()) { failedData.put("succCount", 0); - return ResultBuilder.buildResult(ResultCodeEnum.DATA_EMPTY, failedData); + return RestResultUtils.buildResult(ResultCodeEnum.DATA_EMPTY, failedData); } List configInfoList4Clone = new ArrayList<>(queryedDataList.size()); @@ -675,7 +677,7 @@ public class ConfigController { if (configInfoList4Clone.isEmpty()) { failedData.put("succCount", 0); - return ResultBuilder.buildResult(ResultCodeEnum.DATA_EMPTY, failedData); + return RestResultUtils.buildResult(ResultCodeEnum.DATA_EMPTY, failedData); } final String srcIp = RequestUtil.getRemoteIp(request); String requestIpApp = RequestUtil.getAppName(request); @@ -691,7 +693,7 @@ public class ConfigController { requestIpApp, time.getTime(), InetUtils.getSelfIP(), ConfigTraceService.PERSISTENCE_EVENT_PUB, configInfo.getContent()); } - return ResultBuilder.buildSuccessResult("Clone Completed Successfully", saveResult); + return RestResultUtils.success("Clone Completed Successfully", saveResult); } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/result/ResultBuilder.java b/config/src/main/java/com/alibaba/nacos/config/server/result/ResultBuilder.java deleted file mode 100644 index 1e64af8a6..000000000 --- a/config/src/main/java/com/alibaba/nacos/config/server/result/ResultBuilder.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 1999-2018 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.config.server.result; - -import com.alibaba.nacos.common.model.RestResult; -import com.alibaba.nacos.config.server.result.code.ResultCodeEnum; -import com.alibaba.nacos.config.server.result.core.IResultCode; -import org.springframework.util.Assert; - -/** - * ResultBuilder. - * - * @author klw - * @ClassName: ResultBuilder - * @Description: util for generating {@link RestResult} - * @date 2019/6/28 14:47 - */ -@Deprecated -public class ResultBuilder { - - /** - * BuildResult. - * - * @param resultCode resultCode. - * @param resultData resultData. - * @param T. - * @return RestResult. - */ - public static RestResult buildResult(IResultCode resultCode, T resultData) { - Assert.notNull(resultCode, "the resultCode can not be null"); - RestResult rr = new RestResult<>(resultCode.getCode(), resultCode.getCodeMsg(), resultData); - return rr; - } - - public static RestResult buildSuccessResult(T resultData) { - return buildResult(ResultCodeEnum.SUCCESS, resultData); - } - - /** - * BuildSuccessResult. - * - * @param successMsg successMsg string value. - * @param resultData resultData. - * @param T. - * @return RestResult. - */ - public static RestResult buildSuccessResult(String successMsg, T resultData) { - RestResult rr = buildResult(ResultCodeEnum.SUCCESS, resultData); - rr.setMessage(successMsg); - return rr; - } - - public static RestResult buildSuccessResult() { - return buildResult(ResultCodeEnum.SUCCESS, null); - } - - /** - * BuildSuccessResult. - * - * @param successMsg successMsg string value. - * @param T. - * @return RestResult. - */ - public static RestResult buildSuccessResult(String successMsg) { - RestResult rr = buildResult(ResultCodeEnum.SUCCESS, null); - rr.setMessage(successMsg); - return rr; - } -} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/result/code/ResultCodeEnum.java b/config/src/main/java/com/alibaba/nacos/config/server/result/code/ResultCodeEnum.java index 202334eb3..19a0f7ac2 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/result/code/ResultCodeEnum.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/result/code/ResultCodeEnum.java @@ -16,7 +16,7 @@ package com.alibaba.nacos.config.server.result.code; -import com.alibaba.nacos.config.server.result.core.IResultCode; +import com.alibaba.nacos.common.model.core.IResultCode; /** * ResultCodeEnum. diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigChangePublisher.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigChangePublisher.java index 928641657..b7fc85c2e 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigChangePublisher.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigChangePublisher.java @@ -19,7 +19,7 @@ package com.alibaba.nacos.config.server.service; import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.config.server.model.event.ConfigDataChangeEvent; import com.alibaba.nacos.config.server.utils.PropertyUtil; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; /** * ConfigChangePublisher. @@ -34,7 +34,7 @@ public class ConfigChangePublisher { * @param event ConfigDataChangeEvent instance. */ public static void notifyConfigChange(ConfigDataChangeEvent event) { - if (PropertyUtil.isEmbeddedStorage() && !ApplicationUtils.getStandaloneMode()) { + if (PropertyUtil.isEmbeddedStorage() && !EnvUtil.getStandaloneMode()) { return; } NotifyCenter.publishEvent(event); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java index 03b6bc8cb..ba2afba5a 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java @@ -25,7 +25,7 @@ import com.alibaba.nacos.config.server.utils.ConfigExecutor; import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.ServerMemberManager; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -74,7 +74,7 @@ public class ConfigSubService { * @return all path. */ private String getUrl(String ip, String relativePath) { - return "http://" + ip + ApplicationUtils.getContextPath() + relativePath; + return "http://" + ip + EnvUtil.getContextPath() + relativePath; } private List runCollectionJob(String url, Map params, diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceServiceImpl.java index 99688fed2..c42393388 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceServiceImpl.java @@ -22,7 +22,7 @@ import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.config.server.monitor.MetricsMonitor; import com.alibaba.nacos.config.server.utils.ConfigExecutor; import com.alibaba.nacos.config.server.utils.PropertyUtil; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import com.zaxxer.hikari.HikariDataSource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.CannotGetJdbcConnectionException; @@ -116,7 +116,7 @@ public class ExternalDataSourceServiceImpl implements DataSourceService { public synchronized void reload() throws IOException { try { dataSourceList = new ExternalDataSourceProperties() - .build(ApplicationUtils.getEnvironment(), (dataSource) -> { + .build(EnvUtil.getEnvironment(), (dataSource) -> { JdbcTemplate jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setQueryTimeout(queryTimeout); jdbcTemplate.setDataSource(dataSource); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/LocalDataSourceServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/LocalDataSourceServiceImpl.java index 33224ee78..81f4c1db6 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/LocalDataSourceServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/LocalDataSourceServiceImpl.java @@ -21,7 +21,7 @@ import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.PropertyUtil; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.DiskUtils; import com.zaxxer.hikari.HikariDataSource; import org.apache.commons.lang3.StringUtils; @@ -77,7 +77,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService { if (!initialize) { LogUtil.DEFAULT_LOG.info("use local db service for init"); final String jdbcUrl = - "jdbc:derby:" + Paths.get(ApplicationUtils.getNacosHome(), derbyBaseDir).toString() + "jdbc:derby:" + Paths.get(EnvUtil.getNacosHome(), derbyBaseDir).toString() + ";create=true"; initialize(jdbcUrl); initialize = true; @@ -113,7 +113,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService { public void cleanAndReopenDerby() throws Exception { doDerbyClean(); final String jdbcUrl = - "jdbc:derby:" + Paths.get(ApplicationUtils.getNacosHome(), derbyBaseDir).toString() + ";create=true"; + "jdbc:derby:" + Paths.get(EnvUtil.getNacosHome(), derbyBaseDir).toString() + ";create=true"; initialize(jdbcUrl); } @@ -140,11 +140,11 @@ public class LocalDataSourceServiceImpl implements DataSourceService { throw e; } } - DiskUtils.deleteDirectory(Paths.get(ApplicationUtils.getNacosHome(), derbyBaseDir).toString()); + DiskUtils.deleteDirectory(Paths.get(EnvUtil.getNacosHome(), derbyBaseDir).toString()); } private synchronized void initialize(String jdbcUrl) { - DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(ApplicationUtils.getEnvironment()); + DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(EnvUtil.getEnvironment()); poolProperties.setDriverClassName(jdbcDriverName); poolProperties.setJdbcUrl(jdbcUrl); poolProperties.setUsername(userName); @@ -184,7 +184,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService { @Override public String getCurrentDbUrl() { - return "jdbc:derby:" + ApplicationUtils.getNacosHome() + File.separator + derbyBaseDir + ";create=true"; + return "jdbc:derby:" + EnvUtil.getNacosHome() + File.separator + derbyBaseDir + ";create=true"; } @Override @@ -208,8 +208,8 @@ public class LocalDataSourceServiceImpl implements DataSourceService { InputStream sqlFileIn = null; try { File file = new File( - ApplicationUtils.getNacosHome() + File.separator + "conf" + File.separator + "schema.sql"); - if (StringUtils.isBlank(ApplicationUtils.getNacosHome()) || !file.exists()) { + EnvUtil.getNacosHome() + File.separator + "conf" + File.separator + "schema.sql"); + if (StringUtils.isBlank(EnvUtil.getNacosHome()) || !file.exists()) { ClassLoader classLoader = getClass().getClassLoader(); URL url = classLoader.getResource(sqlFile); sqlFileIn = url.openStream(); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java index c5f6d7683..5e706e15d 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java @@ -49,7 +49,7 @@ import com.alibaba.nacos.config.server.utils.GroupKey2; import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.TimeUtils; import com.alibaba.nacos.core.cluster.ServerMemberManager; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.InetUtils; import com.alibaba.nacos.core.utils.TimerContext; import org.slf4j.Logger; @@ -203,7 +203,7 @@ public abstract class DumpService { "Nacos Server did not start because dumpservice bean construction failure :\n" + e.getMessage(), e); } - if (!ApplicationUtils.getStandaloneMode()) { + if (!EnvUtil.getStandaloneMode()) { Runnable heartbeat = () -> { String heartBeatTime = TimeUtils.getCurrentTime().toString(); // write disk @@ -305,7 +305,7 @@ public abstract class DumpService { private Boolean isQuickStart() { try { String val = null; - val = ApplicationUtils.getProperty("isQuickStart"); + val = EnvUtil.getProperty("isQuickStart"); if (val != null && TRUE_STR.equals(val)) { isQuickStart = true; } @@ -317,7 +317,7 @@ public abstract class DumpService { } private int getRetentionDays() { - String val = ApplicationUtils.getProperty("nacos.config.retention.days"); + String val = EnvUtil.getProperty("nacos.config.retention.days"); if (null == val) { return retentionDays; } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/EmbeddedDumpService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/EmbeddedDumpService.java index 85abd81fa..3c702964d 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/EmbeddedDumpService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/EmbeddedDumpService.java @@ -28,7 +28,7 @@ import com.alibaba.nacos.consistency.cp.CPProtocol; import com.alibaba.nacos.consistency.cp.MetadataKey; import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.core.distributed.ProtocolManager; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.core.utils.GlobalExecutor; import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Component; @@ -76,7 +76,7 @@ public class EmbeddedDumpService extends DumpService { @PostConstruct @Override protected void init() throws Throwable { - if (ApplicationUtils.getStandaloneMode()) { + if (EnvUtil.getStandaloneMode()) { dumpOperate(processor, dumpAllProcessor, dumpAllBetaProcessor, dumpAllTagProcessor); return; } @@ -155,7 +155,7 @@ public class EmbeddedDumpService extends DumpService { @Override protected boolean canExecute() { - if (ApplicationUtils.getStandaloneMode()) { + if (EnvUtil.getStandaloneMode()) { return true; } // if is derby + raft mode, only leader can execute diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java index e08a56020..cb4e115d5 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java @@ -27,6 +27,7 @@ import com.alibaba.nacos.config.server.utils.ContentUtils; import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.TimeUtils; import com.alibaba.nacos.core.distributed.ProtocolManager; +import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; import com.alibaba.nacos.sys.utils.InetUtils; import org.slf4j.Logger; @@ -114,7 +115,7 @@ public class MergeDatumService { if (!PropertyUtil.isEmbeddedStorage()) { return true; } - if (ApplicationUtils.getStandaloneMode()) { + if (EnvUtil.getStandaloneMode()) { return true; } ProtocolManager protocolManager = ApplicationUtils.getBean(ProtocolManager.class); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java index 493430ed7..8fa7e4101 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java @@ -39,7 +39,7 @@ import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.MemberUtils; import com.alibaba.nacos.core.cluster.ServerMemberManager; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.InetUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -434,10 +434,10 @@ public class AsyncNotifyService { LOGGER.error("URLEncoder encode error", e); } if (StringUtils.isBlank(tenant)) { - this.url = MessageFormat.format(URL_PATTERN, target, ApplicationUtils.getContextPath(), dataId, group); + this.url = MessageFormat.format(URL_PATTERN, target, EnvUtil.getContextPath(), dataId, group); } else { this.url = MessageFormat - .format(URL_PATTERN_TENANT, target, ApplicationUtils.getContextPath(), dataId, group, tenant); + .format(URL_PATTERN_TENANT, target, EnvUtil.getContextPath(), dataId, group, tenant); } if (StringUtils.isNotEmpty(tag)) { url = url + "&tag=" + tag; diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java index aa505c7fb..673aca553 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java @@ -24,7 +24,7 @@ import com.alibaba.nacos.config.server.monitor.MetricsMonitor; import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.ServerMemberManager; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.InetUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -75,7 +75,7 @@ public class NotifyTaskProcessor implements NacosTaskProcessor { .asList(NotifyService.NOTIFY_HEADER_LAST_MODIFIED, String.valueOf(lastModified), NotifyService.NOTIFY_HEADER_OP_HANDLE_IP, InetUtils.getSelfIP()); String urlString = MessageFormat - .format(URL_PATTERN, serverIp, ApplicationUtils.getContextPath(), dataId, group); + .format(URL_PATTERN, serverIp, EnvUtil.getContextPath(), dataId, group); RestResult result = NotifyService.invokeURL(urlString, headers, Constants.ENCODE); if (result.ok()) { diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/RowMapperManager.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/RowMapperManager.java index b86e441f2..5b3c9c302 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/RowMapperManager.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/RowMapperManager.java @@ -35,8 +35,10 @@ import com.alibaba.nacos.config.server.model.TenantInfo; import com.alibaba.nacos.config.server.model.User; import java.sql.ResultSet; +import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import org.springframework.jdbc.core.RowMapper; @@ -84,6 +86,8 @@ public final class RowMapperManager { public static final PermissionRowMapper PERMISSION_ROW_MAPPER = new PermissionRowMapper(); + public static final MapRowMapper MAP_ROW_MAPPER = new MapRowMapper(); + public static Map mapperMap = new HashMap<>(16); static { @@ -161,12 +165,30 @@ public final class RowMapperManager { // PERMISSION_ROW_MAPPER mapperMap.put(PERMISSION_ROW_MAPPER.getClass().getCanonicalName(), PERMISSION_ROW_MAPPER); + + // MAP_ROW_MAPPER + + mapperMap.put(MAP_ROW_MAPPER.getClass().getCanonicalName(), MAP_ROW_MAPPER); } public static RowMapper getRowMapper(String classFullName) { return (RowMapper) mapperMap.get(classFullName); } + public static final class MapRowMapper implements RowMapper> { + + @Override + public Map mapRow(ResultSet resultSet, int rowNum) throws SQLException { + ResultSetMetaData metaData = resultSet.getMetaData(); + int columnCount = metaData.getColumnCount(); + Map map = new LinkedHashMap<>(columnCount); + for (int i = 1; i <= columnCount; i++) { + map.put(metaData.getColumnLabel(i), resultSet.getObject(i)); + } + return map; + } + } + public static final class ConfigInfoWrapperRowMapper implements RowMapper { @Override diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/DerbySnapshotOperation.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/DerbySnapshotOperation.java index 75d6684cf..4575b6c7e 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/DerbySnapshotOperation.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/DerbySnapshotOperation.java @@ -27,8 +27,8 @@ import com.alibaba.nacos.consistency.snapshot.Reader; import com.alibaba.nacos.consistency.snapshot.SnapshotOperation; import com.alibaba.nacos.consistency.snapshot.Writer; import com.alibaba.nacos.core.distributed.raft.utils.RaftExecutor; +import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.DiskUtils; -import com.alibaba.nacos.sys.utils.ApplicationUtils; import com.alibaba.nacos.core.utils.TimerContext; import com.alipay.sofa.jraft.util.CRC64; @@ -61,7 +61,7 @@ public class DerbySnapshotOperation implements SnapshotOperation { private final String snapshotArchive = "derby_data.zip"; - private final String derbyBaseDir = Paths.get(ApplicationUtils.getNacosHome(), "data", "derby-data").toString(); + private final String derbyBaseDir = Paths.get(EnvUtil.getNacosHome(), "data", "derby-data").toString(); private final String restoreDB = "jdbc:derby:" + derbyBaseDir; diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedStoragePersistServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedStoragePersistServiceImpl.java index 83baef999..6e5d2d039 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedStoragePersistServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedStoragePersistServiceImpl.java @@ -72,6 +72,7 @@ import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.function.BiConsumer; +import java.util.stream.Collectors; import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.CONFIG_ADVANCE_INFO_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.CONFIG_ALL_INFO_ROW_MAPPER; @@ -88,6 +89,7 @@ import static com.alibaba.nacos.config.server.service.repository.RowMapperManage import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.HISTORY_DETAIL_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.HISTORY_LIST_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.TENANT_INFO_ROW_MAPPER; +import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.MAP_ROW_MAPPER; import static com.alibaba.nacos.config.server.utils.LogUtil.DEFAULT_LOG; /** @@ -1116,16 +1118,30 @@ public class EmbeddedStoragePersistServiceImpl implements PersistService { @Override public List getTenantIdList(int page, int pageSize) { - String sql = "SELECT tenant_id FROM config_info WHERE tenant_id != '' GROUP BY tenant_id LIMIT ?, ?"; + PaginationHelper> helper = createPaginationHelper(); + + String sql = "SELECT tenant_id FROM config_info WHERE tenant_id != '' GROUP BY tenant_id LIMIT ?,?"; int from = (page - 1) * pageSize; - return databaseOperate.queryMany(sql, new Object[] {from, pageSize}, String.class); + + Page> pageList = helper + .fetchPageLimit(sql, new Object[] {from, pageSize}, page, pageSize, MAP_ROW_MAPPER); + return pageList.getPageItems().stream() + .map(map -> String.valueOf(map.get("TENANT_ID"))) + .collect(Collectors.toList()); } @Override public List getGroupIdList(int page, int pageSize) { - String sql = "SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id LIMIT ?, ?"; + PaginationHelper> helper = createPaginationHelper(); + + String sql = "SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id LIMIT ?,?"; int from = (page - 1) * pageSize; - return databaseOperate.queryMany(sql, new Object[] {from, pageSize}, String.class); + + Page> pageList = helper + .fetchPageLimit(sql, new Object[] {from, pageSize}, page, pageSize, MAP_ROW_MAPPER); + return pageList.getPageItems().stream() + .map(map -> String.valueOf(map.get("GROUP_ID"))) + .collect(Collectors.toList()); } @Override diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePaginationHelperImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePaginationHelperImpl.java index 18323134e..ca1cc29c5 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePaginationHelperImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePaginationHelperImpl.java @@ -20,7 +20,7 @@ import com.alibaba.nacos.config.server.model.Page; import com.alibaba.nacos.config.server.service.repository.PaginationHelper; import com.alibaba.nacos.config.server.service.sql.EmbeddedStorageContextUtils; import com.alibaba.nacos.config.server.utils.PropertyUtil; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; @@ -214,7 +214,7 @@ class ExternalStoragePaginationHelperImpl implements PaginationHelper { } private boolean isDerby() { - return (ApplicationUtils.getStandaloneMode() && !PropertyUtil.isUseExternalDB()) || PropertyUtil + return (EnvUtil.getStandaloneMode() && !PropertyUtil.isUseExternalDB()) || PropertyUtil .isEmbeddedStorage(); } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/sql/EmbeddedStorageContextUtils.java b/config/src/main/java/com/alibaba/nacos/config/server/service/sql/EmbeddedStorageContextUtils.java index 8fe679396..fa2aa3c23 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/sql/EmbeddedStorageContextUtils.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/sql/EmbeddedStorageContextUtils.java @@ -21,7 +21,7 @@ import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.model.ConfigInfo; import com.alibaba.nacos.config.server.model.event.ConfigDumpEvent; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import java.sql.Timestamp; import java.util.ArrayList; @@ -88,7 +88,7 @@ public class EmbeddedStorageContextUtils { * @param time Operating time */ public static void onModifyConfigInfo(ConfigInfo configInfo, String srcIp, Timestamp time) { - if (!ApplicationUtils.getStandaloneMode()) { + if (!EnvUtil.getStandaloneMode()) { ConfigDumpEvent event = ConfigDumpEvent.builder().remove(false).namespaceId(configInfo.getTenant()) .dataId(configInfo.getDataId()).group(configInfo.getGroup()).isBeta(false) .content(configInfo.getContent()).type(configInfo.getType()).handleIp(srcIp) @@ -110,7 +110,7 @@ public class EmbeddedStorageContextUtils { * @param time Operating time */ public static void onModifyConfigBetaInfo(ConfigInfo configInfo, String betaIps, String srcIp, Timestamp time) { - if (!ApplicationUtils.getStandaloneMode()) { + if (!EnvUtil.getStandaloneMode()) { ConfigDumpEvent event = ConfigDumpEvent.builder().remove(false).namespaceId(configInfo.getTenant()) .dataId(configInfo.getDataId()).group(configInfo.getGroup()).isBeta(true).betaIps(betaIps) .content(configInfo.getContent()).type(configInfo.getType()).handleIp(srcIp) @@ -132,7 +132,7 @@ public class EmbeddedStorageContextUtils { * @param time Operating time */ public static void onModifyConfigTagInfo(ConfigInfo configInfo, String tag, String srcIp, Timestamp time) { - if (!ApplicationUtils.getStandaloneMode()) { + if (!EnvUtil.getStandaloneMode()) { ConfigDumpEvent event = ConfigDumpEvent.builder().remove(false).namespaceId(configInfo.getTenant()) .dataId(configInfo.getDataId()).group(configInfo.getGroup()).isBeta(false).tag(tag) .content(configInfo.getContent()).type(configInfo.getType()).handleIp(srcIp) @@ -156,7 +156,7 @@ public class EmbeddedStorageContextUtils { */ public static void onDeleteConfigInfo(String namespaceId, String group, String dataId, String srcIp, Timestamp time) { - if (!ApplicationUtils.getStandaloneMode()) { + if (!EnvUtil.getStandaloneMode()) { ConfigDumpEvent event = ConfigDumpEvent.builder().remove(true).namespaceId(namespaceId).group(group) .dataId(dataId).isBeta(false).handleIp(srcIp).lastModifiedTs(time.getTime()).build(); @@ -173,7 +173,7 @@ public class EmbeddedStorageContextUtils { * @param configInfos {@link ConfigInfo} list */ public static void onBatchDeleteConfigInfo(List configInfos) { - if (!ApplicationUtils.getStandaloneMode()) { + if (!EnvUtil.getStandaloneMode()) { List events = new ArrayList<>(); for (ConfigInfo configInfo : configInfos) { String namespaceId = @@ -200,7 +200,7 @@ public class EmbeddedStorageContextUtils { * @param time Operating time */ public static void onDeleteConfigBetaInfo(String namespaceId, String group, String dataId, long time) { - if (!ApplicationUtils.getStandaloneMode()) { + if (!EnvUtil.getStandaloneMode()) { ConfigDumpEvent event = ConfigDumpEvent.builder().remove(true).namespaceId(namespaceId).dataId(dataId) .group(group).isBeta(true).build(); @@ -222,7 +222,7 @@ public class EmbeddedStorageContextUtils { */ public static void onDeleteConfigTagInfo(String namespaceId, String group, String dataId, String tag, String srcIp) { - if (!ApplicationUtils.getStandaloneMode()) { + if (!EnvUtil.getStandaloneMode()) { ConfigDumpEvent event = ConfigDumpEvent.builder().remove(true).namespaceId(namespaceId).group(group) .dataId(dataId).isBeta(true).tag(tag).handleIp(srcIp).build(); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/DiskUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/DiskUtil.java index 9096a84c6..40bcb646f 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/DiskUtil.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/DiskUtil.java @@ -19,7 +19,7 @@ package com.alibaba.nacos.config.server.utils; import com.alibaba.nacos.common.utils.IoUtils; import com.alibaba.nacos.common.utils.MD5Utils; import com.alibaba.nacos.config.server.constant.Constants; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; @@ -107,9 +107,9 @@ public class DiskUtil { public static File targetFile(String dataId, String group, String tenant) { File file = null; if (StringUtils.isBlank(tenant)) { - file = new File(ApplicationUtils.getNacosHome(), BASE_DIR); + file = new File(EnvUtil.getNacosHome(), BASE_DIR); } else { - file = new File(ApplicationUtils.getNacosHome(), TENANT_BASE_DIR); + file = new File(EnvUtil.getNacosHome(), TENANT_BASE_DIR); file = new File(file, tenant); } file = new File(file, group); @@ -123,9 +123,9 @@ public class DiskUtil { public static File targetBetaFile(String dataId, String group, String tenant) { File file = null; if (StringUtils.isBlank(tenant)) { - file = new File(ApplicationUtils.getNacosHome(), BETA_DIR); + file = new File(EnvUtil.getNacosHome(), BETA_DIR); } else { - file = new File(ApplicationUtils.getNacosHome(), TENANT_BETA_DIR); + file = new File(EnvUtil.getNacosHome(), TENANT_BETA_DIR); file = new File(file, tenant); } file = new File(file, group); @@ -139,9 +139,9 @@ public class DiskUtil { public static File targetTagFile(String dataId, String group, String tenant, String tag) { File file = null; if (StringUtils.isBlank(tenant)) { - file = new File(ApplicationUtils.getNacosHome(), TAG_DIR); + file = new File(EnvUtil.getNacosHome(), TAG_DIR); } else { - file = new File(ApplicationUtils.getNacosHome(), TENANT_TAG_DIR); + file = new File(EnvUtil.getNacosHome(), TENANT_TAG_DIR); file = new File(file, tenant); } file = new File(file, group); @@ -169,7 +169,7 @@ public class DiskUtil { } public static File heartBeatFile() { - return new File(ApplicationUtils.getNacosHome(), "status" + File.separator + "heartBeat.txt"); + return new File(EnvUtil.getNacosHome(), "status" + File.separator + "heartBeat.txt"); } public static String relativePath(String dataId, String group) { @@ -180,13 +180,13 @@ public class DiskUtil { * Clear all config file. */ public static void clearAll() { - File file = new File(ApplicationUtils.getNacosHome(), BASE_DIR); + File file = new File(EnvUtil.getNacosHome(), BASE_DIR); if (FileUtils.deleteQuietly(file)) { LogUtil.DEFAULT_LOG.info("clear all config-info success."); } else { LogUtil.DEFAULT_LOG.warn("clear all config-info failed."); } - File fileTenant = new File(ApplicationUtils.getNacosHome(), TENANT_BASE_DIR); + File fileTenant = new File(EnvUtil.getNacosHome(), TENANT_BASE_DIR); if (FileUtils.deleteQuietly(fileTenant)) { LogUtil.DEFAULT_LOG.info("clear all config-info-tenant success."); } else { @@ -198,13 +198,13 @@ public class DiskUtil { * Clear all beta config file. */ public static void clearAllBeta() { - File file = new File(ApplicationUtils.getNacosHome(), BETA_DIR); + File file = new File(EnvUtil.getNacosHome(), BETA_DIR); if (FileUtils.deleteQuietly(file)) { LogUtil.DEFAULT_LOG.info("clear all config-info-beta success."); } else { LogUtil.DEFAULT_LOG.warn("clear all config-info-beta failed."); } - File fileTenant = new File(ApplicationUtils.getNacosHome(), TENANT_BETA_DIR); + File fileTenant = new File(EnvUtil.getNacosHome(), TENANT_BETA_DIR); if (FileUtils.deleteQuietly(fileTenant)) { LogUtil.DEFAULT_LOG.info("clear all config-info-beta-tenant success."); } else { @@ -216,13 +216,13 @@ public class DiskUtil { * Clear all tag config file. */ public static void clearAllTag() { - File file = new File(ApplicationUtils.getNacosHome(), TAG_DIR); + File file = new File(EnvUtil.getNacosHome(), TAG_DIR); if (FileUtils.deleteQuietly(file)) { LogUtil.DEFAULT_LOG.info("clear all config-info-tag success."); } else { LogUtil.DEFAULT_LOG.warn("clear all config-info-tag failed."); } - File fileTenant = new File(ApplicationUtils.getNacosHome(), TENANT_TAG_DIR); + File fileTenant = new File(EnvUtil.getNacosHome(), TENANT_TAG_DIR); if (FileUtils.deleteQuietly(fileTenant)) { LogUtil.DEFAULT_LOG.info("clear all config-info-tag-tenant success."); } else { diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java index 99197597b..46f7277ef 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java @@ -16,7 +16,7 @@ package com.alibaba.nacos.config.server.utils; -import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.alibaba.nacos.sys.env.EnvUtil; import org.slf4j.Logger; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; @@ -101,7 +101,7 @@ public class PropertyUtil implements ApplicationContextInitializerpushContent. @@ -242,7 +242,7 @@ public class PropertyUtil implements ApplicationContextInitializer