diff --git a/client/src/main/java/com/alibaba/nacos/client/config/impl/CacheData.java b/client/src/main/java/com/alibaba/nacos/client/config/impl/CacheData.java index 75f38b2ab0f..3d9c5d4f5e9 100644 --- a/client/src/main/java/com/alibaba/nacos/client/config/impl/CacheData.java +++ b/client/src/main/java/com/alibaba/nacos/client/config/impl/CacheData.java @@ -395,6 +395,7 @@ private static String getTrace(StackTraceElement[] stackTrace, int traceDeep) { return stringBuilder.toString(); } + @SuppressWarnings("PMD.MethodTooLongRule") private void safeNotifyListener(final String dataId, final String group, final String content, final String type, final String md5, final String encryptedDataKey, final ManagerListenerWrap listenerWrap) { final Listener listener = listenerWrap.listener; diff --git a/client/src/main/java/com/alibaba/nacos/client/config/impl/ClientWorker.java b/client/src/main/java/com/alibaba/nacos/client/config/impl/ClientWorker.java index a8629ecb0dc..de52a816ff7 100644 --- a/client/src/main/java/com/alibaba/nacos/client/config/impl/ClientWorker.java +++ b/client/src/main/java/com/alibaba/nacos/client/config/impl/ClientWorker.java @@ -998,6 +998,7 @@ private void checkRemoveListenCache(Map> removeListenCac } } + @SuppressWarnings("PMD.MethodTooLongRule") private boolean checkListenCache(Map> listenCachesMap) throws NacosException { final AtomicBoolean hasChangedKeys = new AtomicBoolean(false); diff --git a/common/pom.xml b/common/pom.xml index 5ca820055fe..024fee4d514 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -62,7 +62,7 @@ com.fasterxml.jackson.core jackson-databind - + commons-logging commons-logging @@ -74,7 +74,7 @@ mysql-connector-j test - + @@ -87,21 +87,5 @@ - - - - org.apache.maven.plugins - maven-surefire-plugin - - - --add-opens java.base/java.lang=ALL-UNNAMED - --add-opens java.base/java.lang.reflect=ALL-UNNAMED - --add-opens java.base/java.util=ALL-UNNAMED - --add-opens java.base/java.nio=ALL-UNNAMED - --add-opens java.base/sun.nio.ch=ALL-UNNAMED - - - - diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClient.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClient.java index 837497bd421..bfc48243f76 100644 --- a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClient.java +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClient.java @@ -236,6 +236,7 @@ public void onServerListChange() { /** * Start this client. */ + @SuppressWarnings("PMD.MethodTooLongRule") public final void start() throws NacosException { boolean success = rpcClientStatus.compareAndSet(RpcClientStatus.INITIALIZED, RpcClientStatus.STARTING); @@ -288,9 +289,9 @@ public final void start() throws NacosException { break; } - boolean statusFLowSuccess = RpcClient.this.rpcClientStatus + boolean statusFlowSuccess = RpcClient.this.rpcClientStatus .compareAndSet(rpcClientStatus, RpcClientStatus.UNHEALTHY); - if (statusFLowSuccess) { + if (statusFlowSuccess) { reconnectContext = new ReconnectContext(null, false); } else { continue; @@ -470,6 +471,7 @@ protected void switchServerAsync(final ServerInfo recommendServerInfo, boolean o /** * switch server . */ + @SuppressWarnings("PMD.MethodTooLongRule") protected void reconnect(final ServerInfo recommendServerInfo, boolean onRequestFail) { try { diff --git a/common/src/test/java/com/alibaba/nacos/common/tls/TlsFileWatcherTest.java b/common/src/test/java/com/alibaba/nacos/common/tls/TlsFileWatcherTest.java index f3a7033af9d..d0ecfaddf58 100644 --- a/common/src/test/java/com/alibaba/nacos/common/tls/TlsFileWatcherTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/tls/TlsFileWatcherTest.java @@ -31,8 +31,6 @@ import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; @@ -70,41 +68,15 @@ static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { watchFilesMapField = TlsFileWatcher.getInstance().getClass().getDeclaredField("watchFilesMap"); watchFilesMapField.setAccessible(true); - Method getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class); - getDeclaredFields0.setAccessible(true); - Field[] fields = (Field[]) getDeclaredFields0.invoke(Field.class, false); - Field modifiersField1 = null; - for (Field each : fields) { - if ("modifiers".equals(each.getName())) { - modifiersField1 = each; - } - } - if (modifiersField1 != null) { - modifiersField1.setAccessible(true); - modifiersField1.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL); - } fileMd5MapField = TlsFileWatcher.getInstance().getClass().getDeclaredField("fileMd5Map"); fileMd5MapField.setAccessible(true); serviceField = TlsFileWatcher.getInstance().getClass().getDeclaredField("service"); serviceField.setAccessible(true); - Field modifiersField2 = null; - for (Field each : fields) { - if ("modifiers".equals(each.getName())) { - modifiersField2 = each; - } - } - if (modifiersField2 != null) { - modifiersField2.setAccessible(true); - modifiersField2.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL); - } startedField = TlsFileWatcher.getInstance().getClass().getDeclaredField("started"); startedField.setAccessible(true); - Field modifiersField3 = Field.class.getDeclaredField("modifiers"); - modifiersField3.setAccessible(true); - modifiersField3.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL); } @BeforeEach diff --git a/config/pom.xml b/config/pom.xml index 50e67c842ce..eeaaf2f0d3d 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -144,14 +144,6 @@ - org.apache.maven.plugins maven-assembly-plugin diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigGrayModelMigrateService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigGrayModelMigrateService.java index 23fd821c842..c8bc7910ab4 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigGrayModelMigrateService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigGrayModelMigrateService.java @@ -142,6 +142,7 @@ public void checkMigrateTag(String dataId, String group, String tenant, String t } } + @SuppressWarnings("PMD.MethodTooLongRule") private void doCheckMigrate() throws Exception { int migrateMulti = EnvUtil.getProperty("nacos.gray.migrate.executor.multi", Integer.class, Integer.valueOf(4)); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigRocksDbDiskService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigRocksDbDiskService.java index 0da0cc40284..755eb3fe5a3 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigRocksDbDiskService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigRocksDbDiskService.java @@ -40,7 +40,7 @@ * * @author shiyiyue */ -@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule") +@SuppressWarnings({"PMD.ServiceOrDaoClassShouldEndWithImplRule", "PMD.LowerCamelCaseVariableNamingRule"}) public class ConfigRocksDbDiskService implements ConfigDiskService { private static final String ROCKSDB_DATA = File.separator + "rocksdata" + File.separator; diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImpl.java index 2b379cd269d..e029605e811 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImpl.java @@ -91,7 +91,7 @@ * * @author lixiaoshuang */ -@SuppressWarnings({"PMD.MethodReturnWrapperTypeRule", "checkstyle:linelength"}) +@SuppressWarnings({"PMD.MethodReturnWrapperTypeRule", "checkstyle:linelength", "PMD.MethodTooLongRule"}) @Conditional(value = ConditionOnEmbeddedStorage.class) @Service("embeddedConfigInfoPersistServiceImpl") public class EmbeddedConfigInfoPersistServiceImpl implements ConfigInfoPersistService { diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java index 4e4ca9cf0d1..9195fe79631 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java @@ -43,6 +43,7 @@ import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.sys.env.EnvUtil; import com.fasterxml.jackson.databind.JsonNode; +import jakarta.servlet.ServletContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -62,7 +63,6 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import jakarta.servlet.ServletContext; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -71,7 +71,7 @@ import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; @@ -124,6 +124,7 @@ void setUp() { ReflectionTestUtils.setField(configController, "configOperationService", configOperationService); ReflectionTestUtils.setField(configController, "inner", inner); mockmvc = MockMvcBuilders.standaloneSetup(configController).build(); + NotifyCenter.deregisterPublisher(ConfigDataChangeEvent.class); } @Test @@ -220,9 +221,9 @@ public Class subscribeType() { String data = JacksonUtils.toObj(actualValue).get("data").toString(); assertEquals("200", code); assertEquals("true", data); - Thread.sleep(200L); + Thread.sleep(1200L); //expect - assertTrue(reference.get() != null); + assertNotNull(reference.get()); } @Test diff --git a/config/src/test/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandlerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandlerTest.java index 34e193a0627..b8c8af2a423 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandlerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandlerTest.java @@ -19,11 +19,14 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.config.server.controller.v2.HistoryControllerV2; +import com.alibaba.nacos.core.listener.startup.NacosStartUp; +import com.alibaba.nacos.core.listener.startup.NacosStartUpManager; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @@ -41,9 +44,14 @@ class GlobalExceptionHandlerTest { @Autowired private WebApplicationContext context; - @MockBean + @MockitoBean private HistoryControllerV2 historyControllerV2; + @BeforeAll + static void beforeAll() { + NacosStartUpManager.start(NacosStartUp.CORE_START_UP_PHASE); + } + @BeforeEach void before() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); @@ -52,8 +60,10 @@ void before() { @Test void testNacosRunTimeExceptionHandler() throws Exception { // 设置HistoryControllerV2的行为,使其抛出NacosRuntimeException并被GlobalExceptionHandler捕获处理 - when(historyControllerV2.getConfigsByTenant("test")).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) - .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503)); + when(historyControllerV2.getConfigsByTenant("test")).thenThrow( + new NacosRuntimeException(NacosException.INVALID_PARAM)) + .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)) + .thenThrow(new NacosRuntimeException(503)); // 执行请求并验证响应码 ResultActions resultActions = mockMvc.perform(get("/v2/cs/history/configs").param("namespaceId", "test")); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/model/ConfigCachePostProcessorDelegateTest.java b/config/src/test/java/com/alibaba/nacos/config/server/model/ConfigCachePostProcessorDelegateTest.java index a68d78d5b40..6ef9c02d06a 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/model/ConfigCachePostProcessorDelegateTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/model/ConfigCachePostProcessorDelegateTest.java @@ -30,6 +30,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collections; @@ -82,14 +83,27 @@ void test2() .thenReturn(Collections.singletonList(mockConfigCacheMd5PostProcessor)); Constructor constructor = ConfigCachePostProcessorDelegate.class.getDeclaredConstructor(); constructor.setAccessible(true); - Field field = ConfigCachePostProcessorDelegate.class.getDeclaredField("INSTANCE"); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - field.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); ConfigCachePostProcessorDelegate delegate = (ConfigCachePostProcessorDelegate) constructor.newInstance(); - field.set(null, delegate); + Field field = ConfigCachePostProcessorDelegate.class.getDeclaredField("INSTANCE"); + setStaticFinalField(field, delegate); ConfigCachePostProcessorDelegate.getInstance().postProcess(null, null); verify(mockConfigCacheMd5PostProcessor, times(1)).postProcess(null, null); } + + private void setStaticFinalField(Field finalField, Object value) + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Method getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class); + getDeclaredFields0.setAccessible(true); + Field[] fields = (Field[]) getDeclaredFields0.invoke(Field.class, false); + Field modifiers = null; + for (Field each : fields) { + if ("modifiers".equals(each.getName())) { + modifiers = each; + } + } + modifiers.setAccessible(true); + modifiers.setInt(finalField, finalField.getModifiers() & ~Modifier.FINAL); + finalField.setAccessible(true); + finalField.set(null, value); + } } \ No newline at end of file diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/Md5ComparatorDelegateTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/Md5ComparatorDelegateTest.java index 640aad0f184..6203f0b960d 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/Md5ComparatorDelegateTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/Md5ComparatorDelegateTest.java @@ -31,6 +31,8 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.HashMap; @@ -89,17 +91,30 @@ public void test2() throws Exception { .thenReturn(Collections.singletonList(nacosMd5Comparator)); Constructor constructor = Md5ComparatorDelegate.class.getDeclaredConstructor(); constructor.setAccessible(true); - Field field = Md5ComparatorDelegate.class.getDeclaredField("INSTANCE"); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - field.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); Md5ComparatorDelegate delegate = (Md5ComparatorDelegate) constructor.newInstance(); - field.set(null, delegate); + Field field = Md5ComparatorDelegate.class.getDeclaredField("INSTANCE"); + setStaticFinalField(field, delegate); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); HashMap clientMd5Map = new HashMap<>(); Md5ComparatorDelegate.getInstance().compareMd5(request, response, clientMd5Map); verify(nacosMd5Comparator, times(1)).compareMd5(request, response, clientMd5Map); } + + private void setStaticFinalField(Field finalField, Object value) + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Method getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class); + getDeclaredFields0.setAccessible(true); + Field[] fields = (Field[]) getDeclaredFields0.invoke(Field.class, false); + Field modifiers = null; + for (Field each : fields) { + if ("modifiers".equals(each.getName())) { + modifiers = each; + } + } + modifiers.setAccessible(true); + modifiers.setInt(finalField, finalField.getModifiers() & ~Modifier.FINAL); + finalField.setAccessible(true); + finalField.set(null, value); + } } \ No newline at end of file diff --git a/console/src/test/java/com/alibaba/nacos/console/controller/v3/config/ConsoleHistoryControllerTest.java b/console/src/test/java/com/alibaba/nacos/console/controller/v3/config/ConsoleHistoryControllerTest.java index 9db5e896ec3..e228c42976f 100644 --- a/console/src/test/java/com/alibaba/nacos/console/controller/v3/config/ConsoleHistoryControllerTest.java +++ b/console/src/test/java/com/alibaba/nacos/console/controller/v3/config/ConsoleHistoryControllerTest.java @@ -39,6 +39,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import java.sql.Timestamp; import java.util.Collections; import java.util.List; @@ -72,6 +73,8 @@ void testGetConfigHistoryInfo() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId("testDataId"); configHistoryInfo.setGroup("testGroup"); + configHistoryInfo.setCreatedTime(new Timestamp(System.currentTimeMillis())); + configHistoryInfo.setLastModifiedTime(new Timestamp(System.currentTimeMillis())); when(historyProxy.getConfigHistoryInfo("testDataId", "testGroup", Constants.DEFAULT_NAMESPACE_ID, 1L)).thenReturn(configHistoryInfo); @@ -99,6 +102,8 @@ void testListConfigHistory() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId("testDataId"); configHistoryInfo.setGroup("testGroup"); + configHistoryInfo.setCreatedTime(new Timestamp(System.currentTimeMillis())); + configHistoryInfo.setLastModifiedTime(new Timestamp(System.currentTimeMillis())); page.setPageItems(Collections.singletonList(configHistoryInfo)); when(historyProxy.listConfigHistory("testDataId", "testGroup", Constants.DEFAULT_NAMESPACE_ID, 1, 100)).thenReturn(page); @@ -125,6 +130,8 @@ void testGetPreviousConfigHistoryInfo() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId("testDataId"); configHistoryInfo.setGroup("testGroup"); + configHistoryInfo.setCreatedTime(new Timestamp(System.currentTimeMillis())); + configHistoryInfo.setLastModifiedTime(new Timestamp(System.currentTimeMillis())); when(historyProxy.getPreviousConfigHistoryInfo("testDataId", "testGroup", Constants.DEFAULT_NAMESPACE_ID, 1L)).thenReturn( configHistoryInfo); diff --git a/console/src/test/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandlerTest.java b/console/src/test/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandlerTest.java index bd843cd201a..f7138d4a829 100644 --- a/console/src/test/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandlerTest.java +++ b/console/src/test/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandlerTest.java @@ -27,7 +27,7 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; @@ -47,7 +47,7 @@ class ConsoleExceptionHandlerTest { @Autowired private WebApplicationContext context; - @MockBean + @MockitoBean private HealthControllerV2 healthControllerV2; @BeforeAll @@ -64,7 +64,8 @@ void before() { void testNacosRunTimeExceptionHandler() throws Exception { // 设置HealthControllerV2的行为,使其抛出NacosRuntimeException并被ConsoleExceptionHandler捕获处理 when(healthControllerV2.liveness()).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) - .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503)); + .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)) + .thenThrow(new NacosRuntimeException(503)); // 执行请求并验证响应码 ResultActions resultActions = mockMvc.perform(get("/v2/console/health/liveness")); diff --git a/console/src/test/java/com/alibaba/nacos/console/exception/NacosApiExceptionHandlerTest.java b/console/src/test/java/com/alibaba/nacos/console/exception/NacosApiExceptionHandlerTest.java index d7907a32ede..401d7af0c76 100644 --- a/console/src/test/java/com/alibaba/nacos/console/exception/NacosApiExceptionHandlerTest.java +++ b/console/src/test/java/com/alibaba/nacos/console/exception/NacosApiExceptionHandlerTest.java @@ -26,7 +26,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @@ -45,7 +45,7 @@ class NacosApiExceptionHandlerTest { @Autowired private WebApplicationContext context; - @MockBean + @MockitoBean private NamespaceControllerV2 namespaceControllerV2; @BeforeAll diff --git a/console/src/test/resources/nacos-console.properties b/console/src/test/resources/nacos-console.properties new file mode 100644 index 00000000000..78584d08a26 --- /dev/null +++ b/console/src/test/resources/nacos-console.properties @@ -0,0 +1,19 @@ +# +# Copyright 1999-2023 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. +# + +### nacos console port: +server.port=${nacos.console.port:8080} +server.servlet.contextPath=${nacos.console.contextPath:} \ No newline at end of file diff --git a/core/src/main/java/com/alibaba/nacos/core/controller/ServerLoaderController.java b/core/src/main/java/com/alibaba/nacos/core/controller/ServerLoaderController.java index 3f4eb4f5c0a..af1e5dee926 100644 --- a/core/src/main/java/com/alibaba/nacos/core/controller/ServerLoaderController.java +++ b/core/src/main/java/com/alibaba/nacos/core/controller/ServerLoaderController.java @@ -67,6 +67,7 @@ @RestController @RequestMapping(Commons.NACOS_CORE_CONTEXT_V2 + "/loader") @Deprecated +@SuppressWarnings("PMD.MethodTooLongRule") public class ServerLoaderController { private static final Logger LOGGER = LoggerFactory.getLogger(ServerLoaderController.class); diff --git a/core/src/main/java/com/alibaba/nacos/core/controller/v3/ServerLoaderControllerV3.java b/core/src/main/java/com/alibaba/nacos/core/controller/v3/ServerLoaderControllerV3.java index 16f1e20ed8b..47388a78e85 100644 --- a/core/src/main/java/com/alibaba/nacos/core/controller/v3/ServerLoaderControllerV3.java +++ b/core/src/main/java/com/alibaba/nacos/core/controller/v3/ServerLoaderControllerV3.java @@ -69,6 +69,7 @@ @NacosApi @RestController @RequestMapping(NACOS_ADMIN_CORE_CONTEXT_V3 + "/loader") +@SuppressWarnings("PMD.MethodTooLongRule") public class ServerLoaderControllerV3 { private static final Logger LOGGER = LoggerFactory.getLogger(ServerLoaderControllerV3.class); diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptor.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptor.java index ad815f4f60e..370fadc0b8b 100644 --- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptor.java +++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptor.java @@ -78,6 +78,7 @@ private void traceIfNecessary(Payload grpcRequest, boolean receive) { } @Override + @SuppressWarnings("PMD.MethodTooLongRule") public void request(Payload grpcRequest, StreamObserver responseObserver) { traceIfNecessary(grpcRequest, true); diff --git a/k8s-sync/pom.xml b/k8s-sync/pom.xml index 10fe2050bfc..4d63a1218e6 100644 --- a/k8s-sync/pom.xml +++ b/k8s-sync/pom.xml @@ -32,10 +32,6 @@ http://nacos.io - - ${project.groupId} - nacos-core - ${project.groupId} nacos-naming @@ -49,11 +45,5 @@ io.kubernetes client-java - - org.springframework - spring-beans - 5.3.20 - compile - \ No newline at end of file diff --git a/k8s-sync/src/main/java/com/alibaba/nacos/k8s/sync/K8sSyncServer.java b/k8s-sync/src/main/java/com/alibaba/nacos/k8s/sync/K8sSyncServer.java index 45205b28701..43334608034 100644 --- a/k8s-sync/src/main/java/com/alibaba/nacos/k8s/sync/K8sSyncServer.java +++ b/k8s-sync/src/main/java/com/alibaba/nacos/k8s/sync/K8sSyncServer.java @@ -118,18 +118,11 @@ public void startInformer() throws IOException { SharedIndexInformer serviceInformer = factory.sharedIndexInformerFor( (CallGeneratorParams params) -> { - return coreV1Api.listServiceForAllNamespacesCall( - null, - null, - null, - null, - null, - null, - params.resourceVersion, - null, - params.timeoutSeconds, - params.watch, - null); + CoreV1Api.APIlistServiceForAllNamespacesRequest request = coreV1Api.listServiceForAllNamespaces(); + request.resourceVersion(params.resourceVersion); + request.timeoutSeconds(params.timeoutSeconds); + request.watch(params.watch); + return request.buildCall(null); }, V1Service.class, V1ServiceList.class); @@ -137,18 +130,11 @@ public void startInformer() throws IOException { SharedIndexInformer endpointInformer = factory.sharedIndexInformerFor( (CallGeneratorParams params) -> { - return coreV1Api.listEndpointsForAllNamespacesCall( - null, - null, - null, - null, - null, - null, - params.resourceVersion, - null, - params.timeoutSeconds, - params.watch, - null); + CoreV1Api.APIlistEndpointsForAllNamespacesRequest request = coreV1Api.listEndpointsForAllNamespaces(); + request.resourceVersion(params.resourceVersion); + request.timeoutSeconds(params.timeoutSeconds); + request.watch(params.watch); + return request.buildCall(null); }, V1Endpoints.class, V1EndpointsList.class); diff --git a/lock/src/main/java/com/alibaba/nacos/lock/remote/rpc/handler/LockRequestHandler.java b/lock/src/main/java/com/alibaba/nacos/lock/remote/rpc/handler/LockRequestHandler.java index 59f369cd9c5..ec36311d0b2 100644 --- a/lock/src/main/java/com/alibaba/nacos/lock/remote/rpc/handler/LockRequestHandler.java +++ b/lock/src/main/java/com/alibaba/nacos/lock/remote/rpc/handler/LockRequestHandler.java @@ -22,7 +22,6 @@ import com.alibaba.nacos.api.lock.remote.request.LockOperationRequest; import com.alibaba.nacos.api.lock.remote.response.LockOperationResponse; import com.alibaba.nacos.api.remote.request.RequestMeta; -import com.alibaba.nacos.auth.annotation.Secured; import com.alibaba.nacos.core.remote.RequestHandler; import com.alibaba.nacos.lock.exception.NacosLockException; import com.alibaba.nacos.lock.service.LockOperationService; @@ -48,8 +47,10 @@ public LockRequestHandler(LockOperationService lockOperationService) { this.lockOperationService = lockOperationService; } + /** + * TODO Support auth. + */ @Override - @Secured(resource = "grpc/lock") public LockOperationResponse handle(LockOperationRequest request, RequestMeta meta) throws NacosException { Boolean lock = null; LOGGER.info("request: {}, instance: {}", request.getLockOperationEnum(), request.getLockInstance()); diff --git a/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4J2NacosLoggingAdapterTest.java b/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4J2NacosLoggingAdapterTest.java index a39228b186c..44914ff3f86 100644 --- a/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4J2NacosLoggingAdapterTest.java +++ b/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4J2NacosLoggingAdapterTest.java @@ -34,6 +34,8 @@ import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.util.Map; import java.util.logging.Logger; @@ -135,11 +137,14 @@ void testLoadConfigurationWithWrongLocation() { @Test void testGetConfigurationSourceForNonFileProtocol() - throws NoSuchMethodException, IOException, InvocationTargetException, IllegalAccessException { + throws NoSuchMethodException, IOException, InvocationTargetException, IllegalAccessException, URISyntaxException { Method getConfigurationSourceMethod = Log4J2NacosLoggingAdapter.class.getDeclaredMethod("getConfigurationSource", URL.class); getConfigurationSourceMethod.setAccessible(true); URL url = mock(URL.class); + URI uri = mock(URI.class); InputStream inputStream = mock(InputStream.class); + when(uri.toURL()).thenReturn(url); + when(url.toURI()).thenReturn(uri); when(url.openStream()).thenReturn(inputStream); when(url.getProtocol()).thenReturn("http"); ConfigurationSource actual = (ConfigurationSource) getConfigurationSourceMethod.invoke(log4J2NacosLoggingAdapter, url); diff --git a/naming/pom.xml b/naming/pom.xml index 35754741a3c..119f1f7c977 100644 --- a/naming/pom.xml +++ b/naming/pom.xml @@ -127,28 +127,10 @@ io.micrometer micrometer-registry-influx - - - - - - - - - - - - - - - - - - org.apache.maven.plugins maven-assembly-plugin diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java index 08899735da4..53d966ee0f3 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java @@ -340,12 +340,12 @@ public Object list(HttpServletRequest request) throws Exception { String agent = WebUtils.getUserAgent(request); String clusters = WebUtils.optional(request, "clusters", StringUtils.EMPTY); - String clientIP = WebUtils.optional(request, "clientIP", StringUtils.EMPTY); + String clientIp = WebUtils.optional(request, "clientIP", StringUtils.EMPTY); int udpPort = Integer.parseInt(WebUtils.optional(request, "udpPort", "0")); boolean healthyOnly = Boolean.parseBoolean(WebUtils.optional(request, "healthyOnly", "false")); String app = WebUtils.optional(request, "app", StringUtils.EMPTY); - Subscriber subscriber = new Subscriber(clientIP + ":" + udpPort, agent, app, clientIP, namespaceId, serviceName, + Subscriber subscriber = new Subscriber(clientIp + ":" + udpPort, agent, app, clientIp, namespaceId, serviceName, udpPort, clusters); return getInstanceOperator().listInstance(namespaceId, serviceName, subscriber, clusters, healthyOnly); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java index 0a62348116c..0f1fbb0beb5 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java @@ -150,7 +150,7 @@ void testUpdate() throws Exception { e.printStackTrace(); fail(e.getMessage()); } - TimeUnit.SECONDS.sleep(1); + TimeUnit.MILLISECONDS.sleep(1200L); assertEquals(UpdateServiceTraceEvent.class, eventReceivedClass); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandlerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandlerTest.java index 0d72fb4c40b..f6b98dab5d7 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandlerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandlerTest.java @@ -69,8 +69,7 @@ class ServiceQueryRequestHandlerTest { @BeforeEach void setUp() { - ApplicationUtils applicationUtils = new ApplicationUtils(); - applicationUtils.initialize(applicationContext); + ApplicationUtils.injectContext(applicationContext); Mockito.when(applicationContext.getBean(SelectorManager.class)).thenReturn(selectorManager); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandlerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandlerTest.java index 673792f30dd..6d6b735f3be 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandlerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandlerTest.java @@ -75,8 +75,7 @@ class SubscribeServiceRequestHandlerTest { @BeforeEach void setUp() { - ApplicationUtils applicationUtils = new ApplicationUtils(); - applicationUtils.initialize(applicationContext); + ApplicationUtils.injectContext(applicationContext); Mockito.when(applicationContext.getBean(SelectorManager.class)).thenReturn(selectorManager); } diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourceServiceImplTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourceServiceImplTest.java index d163b43b074..56fff3ee85f 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourceServiceImplTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourceServiceImplTest.java @@ -81,8 +81,8 @@ void setUp() { ReflectionTestUtils.setField(service, "jt", jt); ReflectionTestUtils.setField(service, "tm", tm); ReflectionTestUtils.setField(service, "tjt", tjt); - ReflectionTestUtils.setField(service, "testMasterJT", testMasterJT); - ReflectionTestUtils.setField(service, "testMasterWritableJT", testMasterWritableJT); + ReflectionTestUtils.setField(service, "testMasterJt", testMasterJT); + ReflectionTestUtils.setField(service, "testMasterWritableJt", testMasterWritableJT); List dataSourceList = new ArrayList<>(); dataSourceList.add(new HikariDataSource()); ReflectionTestUtils.setField(service, "dataSourceList", dataSourceList); diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/exception/NJdbcExceptionTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/exception/NJdbcExceptionTest.java index 0b2fd9ebdf9..38c592fe667 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/exception/NJdbcExceptionTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/exception/NJdbcExceptionTest.java @@ -55,7 +55,7 @@ public void testConstructorWithMessageCauseAndOriginExceptionName() { String msg = "test msg"; String originExceptionName = "OriginException"; NJdbcException exception = new NJdbcException(msg, cause, originExceptionName); - assertEquals("test msg; nested exception is java.lang.IllegalStateException: IllegalStateException", exception.getMessage()); + assertEquals("test msg", exception.getMessage()); assertSame(cause, exception.getCause()); assertEquals(originExceptionName, exception.getOriginExceptionName()); } @@ -64,7 +64,7 @@ public void testConstructorWithMessageCauseAndOriginExceptionName() { public void testConstructorWithMessageAndCause() { String msg = "test msg"; NJdbcException exception = new NJdbcException(msg, cause); - assertEquals("test msg; nested exception is java.lang.IllegalStateException: IllegalStateException", exception.getMessage()); + assertEquals("test msg", exception.getMessage()); assertSame(cause, exception.getCause()); assertNull(exception.getOriginExceptionName()); } @@ -72,7 +72,7 @@ public void testConstructorWithMessageAndCause() { @Test public void testConstructorWithCause() { NJdbcException exception = new NJdbcException(cause); - assertEquals("; nested exception is java.lang.IllegalStateException: IllegalStateException", exception.getMessage()); + assertEquals("", exception.getMessage()); assertSame(cause, exception.getCause()); assertNull(exception.getOriginExceptionName()); } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImpl.java b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImpl.java index 852a4ef0946..22d6f8e74b4 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImpl.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImpl.java @@ -60,8 +60,6 @@ public class NacosRoleServiceImpl { private static final int DEFAULT_PAGE_NO = 1; - private static final Set WHITE_PERMISSION = new HashSet<>(); - @Autowired private AuthConfigs authConfigs; @@ -80,11 +78,6 @@ public class NacosRoleServiceImpl { private volatile Map> permissionInfoMap = new ConcurrentHashMap<>(); - static { - WHITE_PERMISSION.add(AuthConstants.UPDATE_PASSWORD_ENTRY_POINT); - WHITE_PERMISSION.add(AuthConstants.LOCK_OPERATOR_POINT); - } - @Scheduled(initialDelay = 5000, fixedDelay = 15000) private void reload() { try { @@ -129,11 +122,6 @@ private void reload() { * @return true if granted, false otherwise */ public boolean hasPermission(NacosUser nacosUser, Permission permission) { - //white permission - if (WHITE_PERMISSION.contains(permission.getResource().getName())) { - return true; - } - if (isUpdatePasswordPermission(permission)) { return true; } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/TokenManagerDelegateTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/TokenManagerDelegateTest.java index b0a354b0e7e..ef37f2860a8 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/TokenManagerDelegateTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/TokenManagerDelegateTest.java @@ -18,7 +18,6 @@ import com.alibaba.nacos.plugin.auth.exception.AccessException; import com.alibaba.nacos.plugin.auth.impl.token.impl.CachedJwtTokenManager; -import com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager; import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -29,8 +28,6 @@ import org.mockito.quality.Strictness; import org.springframework.security.core.Authentication; -import java.lang.reflect.Field; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -52,9 +49,6 @@ class TokenManagerDelegateTest { @Mock private CachedJwtTokenManager cachedJwtTokenManager; - @Mock - private JwtTokenManager jwtTokenManager; - @Mock private Authentication authentication; @@ -63,8 +57,7 @@ class TokenManagerDelegateTest { @BeforeEach void setUp() throws Exception { - tokenManagerDelegate = new TokenManagerDelegate(jwtTokenManager); - injectObject("tokenCacheEnabled", Boolean.TRUE); + tokenManagerDelegate = new TokenManagerDelegate(cachedJwtTokenManager); when(cachedJwtTokenManager.getTokenValidityInSeconds()).thenReturn(100L); when(cachedJwtTokenManager.getTokenTtlInSeconds(anyString())).thenReturn(100L); when(cachedJwtTokenManager.getAuthentication(anyString())).thenReturn(authentication); @@ -107,10 +100,4 @@ void testGetTokenTtlInSeconds() throws AccessException { void testGetTokenValidityInSeconds() throws AccessException { assertTrue(tokenManagerDelegate.getTokenValidityInSeconds() > 0); } - - private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { - Field field = TokenManagerDelegate.class.getDeclaredField(fieldName); - field.setAccessible(true); - field.set(tokenManagerDelegate, value); - } } diff --git a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/ControlManagerCenterTest.java b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/ControlManagerCenterTest.java index c09cef1cb3b..3b074df39e3 100644 --- a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/ControlManagerCenterTest.java +++ b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/ControlManagerCenterTest.java @@ -32,6 +32,8 @@ import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.concurrent.TimeUnit; @@ -55,21 +57,31 @@ private void resetRuleStorageProxy() { try { //reset instance for reload spi Field instanceRuleStorageProxy = RuleStorageProxy.class.getDeclaredField("INSTANCE"); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(instanceRuleStorageProxy, instanceRuleStorageProxy.getModifiers() & ~Modifier.FINAL); - instanceRuleStorageProxy.setAccessible(true); Constructor constructor = RuleStorageProxy.class.getDeclaredConstructor(); constructor.setAccessible(true); - Field modifiersFieldConstructor = Constructor.class.getDeclaredField("modifiers"); - modifiersFieldConstructor.setAccessible(true); - modifiersFieldConstructor.setInt(constructor, constructor.getModifiers() & ~Modifier.PRIVATE); - instanceRuleStorageProxy.set(null, constructor.newInstance()); + setStaticFinalField(instanceRuleStorageProxy, constructor.newInstance()); } catch (Exception e) { e.printStackTrace(); } } + private void setStaticFinalField(Field finalField, Object value) + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Method getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class); + getDeclaredFields0.setAccessible(true); + Field[] fields = (Field[]) getDeclaredFields0.invoke(Field.class, false); + Field modifiers = null; + for (Field each : fields) { + if ("modifiers".equals(each.getName())) { + modifiers = each; + } + } + modifiers.setAccessible(true); + modifiers.setInt(finalField, finalField.getModifiers() & ~Modifier.FINAL); + finalField.setAccessible(true); + finalField.set(null, value); + } + @Test void testGetInstance() { ControlConfigs.getInstance().setControlManagerType("test"); @@ -92,7 +104,8 @@ void testGetInstanceWithDefault() { @Test void testReloadTpsControlRule() throws Exception { - String localRuleStorageBaseDir = EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tps" + File.separator; + String localRuleStorageBaseDir = + EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tps" + File.separator; ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); resetRuleStorageProxy(); final ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance(); @@ -178,7 +191,8 @@ void testReloadTpsControlRuleExternal() throws Exception { @Test void testReloadConnectionControlRule() throws Exception { String localRuleStorageBaseDir = - EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connection" + File.separator; + EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connection" + + File.separator; ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); resetRuleStorageProxy(); ConnectionControlRule connectionLimitRule = new ConnectionControlRule(); @@ -209,7 +223,8 @@ void testReloadConnectionControlRule() throws Exception { @Test void testReloadConnectionControlRuleExternal() throws Exception { String localRuleStorageBaseDir = - EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connectionExternal" + File.separator; + EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connectionExternal" + + File.separator; ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); ControlConfigs.getInstance().setRuleExternalStorage("test"); resetRuleStorageProxy(); diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxyTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxyTest.java index 3b0be29fb90..4ea3cdd42d3 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxyTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxyTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.lang.reflect.Field; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -67,33 +66,23 @@ public String count(List where) { public String getTableName() { return "test"; } - + @Override public String getDataSource() { return "test"; } - + @Override public String[] getPrimaryKeyGeneratedKeys() { return new String[0]; } - + @Override public String getFunction(String functionName) { return TrustedMysqlFunctionEnum.getFunctionByName(functionName); } }; Mapper proxy = mapperProxy.createProxy(mapper); - try { - Field field = proxy.getClass().getSuperclass().getDeclaredField("h"); - field.setAccessible(true); - MapperProxy mapperProxy = (MapperProxy) field.get(proxy); - Field mapperField = mapperProxy.getClass().getDeclaredField("mapper"); - mapperField.setAccessible(true); - Class clazz = mapperField.getDeclaringClass(); - assertEquals(MapperProxy.class, clazz); - } catch (NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); - } + assertEquals("select-test", proxy.select(null, null)); } } diff --git a/pom.xml b/pom.xml index 899865ec300..d9669d832a2 100644 --- a/pom.xml +++ b/pom.xml @@ -110,7 +110,7 @@ 2.10.4 3.2.2 3.0.1 - 3.15.0 + 3.16.0 0.12 3.0.2 0.8.7 @@ -129,17 +129,16 @@ 1.1.3 3.4.1 - 6.1.0 2.14.0 3.2.2 2.0.13 - 1.5.6 - 2.17.1 + 1.5.12 + 2.24.3 8.2.0 10.14.2.0 0.11.2 - 1.65.1 + 1.68.2 2.17.0 3.25.5 ${grpc-java.version} @@ -149,7 +148,7 @@ 1.3.14 ${jraft-core.version} 2.0 - 14.0.0 + 22.0.0 5.10.2 @@ -317,7 +316,8 @@ UTF-8 true true - **/consistency/entity/**,**/nacos/test/**,**/api/grpc/auto/**,**/istio/**,**/protobuf/** + **/consistency/entity/**,**/nacos/test/**,**/api/grpc/auto/**,**/istio/**,**/protobuf/** + @@ -425,6 +425,15 @@ maven-surefire-plugin ${maven-surefire-plugin.version} + + + --add-opens java.base/java.lang=ALL-UNNAMED + --add-opens java.base/java.lang.reflect=ALL-UNNAMED + --add-opens java.base/java.util=ALL-UNNAMED + --add-opens java.base/java.nio=ALL-UNNAMED + --add-opens java.base/sun.nio.ch=ALL-UNNAMED + + com.github.spotbugs @@ -847,20 +856,6 @@ ${project.version} - - - jakarta.servlet - jakarta.servlet-api - ${servlet-api.version} - provided - - - javax.servlet - servlet-api - 3.0 - provided - - com.zaxxer @@ -1080,10 +1075,9 @@ com.google.code.gson gson - 2.9.0 compile - + org.yaml snakeyaml diff --git a/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/exception/PrometheusApiExceptionHandlerTest.java b/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/exception/PrometheusApiExceptionHandlerTest.java index 373010264fc..72026319126 100644 --- a/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/exception/PrometheusApiExceptionHandlerTest.java +++ b/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/exception/PrometheusApiExceptionHandlerTest.java @@ -18,12 +18,15 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; +import com.alibaba.nacos.core.listener.startup.NacosStartUp; +import com.alibaba.nacos.core.listener.startup.NacosStartUpManager; import com.alibaba.nacos.prometheus.controller.PrometheusController; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @@ -41,9 +44,14 @@ public class PrometheusApiExceptionHandlerTest { @Autowired private WebApplicationContext context; - @MockBean + @MockitoBean private PrometheusController prometheusController; + @BeforeAll + public static void init() { + NacosStartUpManager.start(NacosStartUp.CORE_START_UP_PHASE); + } + @BeforeEach public void before() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); @@ -53,7 +61,8 @@ public void before() { public void testNacosRunTimeExceptionHandler() throws Exception { // 设置PrometheusController的行为,使其抛出NacosRuntimeException并被PrometheusApiExceptionHandler捕获处理 when(prometheusController.metric()).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) - .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503)); + .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)) + .thenThrow(new NacosRuntimeException(503)); // 执行请求并验证响应码 ResultActions resultActions = mockMvc.perform(get("/prometheus")); diff --git a/sys/src/main/java/com/alibaba/nacos/sys/utils/InetUtils.java b/sys/src/main/java/com/alibaba/nacos/sys/utils/InetUtils.java index 9cfa77198b7..361b94330ca 100644 --- a/sys/src/main/java/com/alibaba/nacos/sys/utils/InetUtils.java +++ b/sys/src/main/java/com/alibaba/nacos/sys/utils/InetUtils.java @@ -52,6 +52,7 @@ * * @author Nacos */ +@SuppressWarnings("PMD.LowerCamelCaseVariableNamingRule") public class InetUtils { private static final Logger LOG = LoggerFactory.getLogger(InetUtils.class);