diff --git a/api/src/main/java/com/alibaba/nacos/api/naming/pojo/ServiceInfo.java b/api/src/main/java/com/alibaba/nacos/api/naming/pojo/ServiceInfo.java index 1b5281d42c3..4d8b13da19d 100644 --- a/api/src/main/java/com/alibaba/nacos/api/naming/pojo/ServiceInfo.java +++ b/api/src/main/java/com/alibaba/nacos/api/naming/pojo/ServiceInfo.java @@ -194,7 +194,7 @@ public boolean validate() { continue; } - for (int i = 0; i < host.getWeight(); i++) { + if (host.getWeight() > 0) { validHosts.add(host); } } diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/AntPathMatcher.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/AntPathMatcher.java index 6feb0ab09f2..93dbd1965e5 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/AntPathMatcher.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/AntPathMatcher.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.common.packagescan.resource; import com.alibaba.nacos.common.packagescan.util.PathMatcher; -import com.alibaba.nacos.common.utils.AbstractAssert; +import com.alibaba.nacos.common.packagescan.util.AbstractAssert; import com.alibaba.nacos.common.utils.StringUtils; import java.util.ArrayList; diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/ByteArrayResource.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/ByteArrayResource.java index a602f1b6842..07d1e27f3d7 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/ByteArrayResource.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/ByteArrayResource.java @@ -16,7 +16,7 @@ package com.alibaba.nacos.common.packagescan.resource; -import com.alibaba.nacos.common.utils.AbstractAssert; +import com.alibaba.nacos.common.packagescan.util.AbstractAssert; import java.io.ByteArrayInputStream; import java.io.IOException; diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/ClassPathResource.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/ClassPathResource.java index 098dd4f08fd..451450ca31f 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/ClassPathResource.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/ClassPathResource.java @@ -16,8 +16,8 @@ package com.alibaba.nacos.common.packagescan.resource; -import com.alibaba.nacos.common.utils.AbstractObjectUtils; -import com.alibaba.nacos.common.utils.AbstractAssert; +import com.alibaba.nacos.common.packagescan.util.AbstractObjectUtils; +import com.alibaba.nacos.common.packagescan.util.AbstractAssert; import com.alibaba.nacos.common.utils.ClassUtils; import com.alibaba.nacos.common.utils.StringUtils; diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/DefaultResourceLoader.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/DefaultResourceLoader.java index f8e956ecb6c..5c88be58b3b 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/DefaultResourceLoader.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/DefaultResourceLoader.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.common.packagescan.resource; import com.alibaba.nacos.common.packagescan.util.ResourceUtils; -import com.alibaba.nacos.common.utils.AbstractAssert; +import com.alibaba.nacos.common.packagescan.util.AbstractAssert; import com.alibaba.nacos.common.utils.ClassUtils; import com.alibaba.nacos.common.utils.StringUtils; diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/FileSystemResource.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/FileSystemResource.java index e61b977e449..a94a4ed3065 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/FileSystemResource.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/FileSystemResource.java @@ -16,7 +16,7 @@ package com.alibaba.nacos.common.packagescan.resource; -import com.alibaba.nacos.common.utils.AbstractAssert; +import com.alibaba.nacos.common.packagescan.util.AbstractAssert; import com.alibaba.nacos.common.utils.StringUtils; import java.io.File; diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/InputStreamResource.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/InputStreamResource.java index ece35370644..d4ec787de00 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/InputStreamResource.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/InputStreamResource.java @@ -16,7 +16,7 @@ package com.alibaba.nacos.common.packagescan.resource; -import com.alibaba.nacos.common.utils.AbstractAssert; +import com.alibaba.nacos.common.packagescan.util.AbstractAssert; import java.io.IOException; import java.io.InputStream; diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/PathMatchingResourcePatternResolver.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/PathMatchingResourcePatternResolver.java index 31dacb5de62..a2913ed6cf9 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/PathMatchingResourcePatternResolver.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/PathMatchingResourcePatternResolver.java @@ -18,7 +18,7 @@ import com.alibaba.nacos.common.packagescan.util.PathMatcher; import com.alibaba.nacos.common.packagescan.util.ResourceUtils; -import com.alibaba.nacos.common.utils.AbstractAssert; +import com.alibaba.nacos.common.packagescan.util.AbstractAssert; import com.alibaba.nacos.common.utils.ClassUtils; import com.alibaba.nacos.common.utils.ReflectUtils; import com.alibaba.nacos.common.utils.StringUtils; diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/PathResource.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/PathResource.java index cd42fad2ae4..29c1d386091 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/PathResource.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/PathResource.java @@ -16,7 +16,7 @@ package com.alibaba.nacos.common.packagescan.resource; -import com.alibaba.nacos.common.utils.AbstractAssert; +import com.alibaba.nacos.common.packagescan.util.AbstractAssert; import java.io.File; import java.io.FileNotFoundException; diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/UrlResource.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/UrlResource.java index a0a7572acff..2e634ebdda5 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/UrlResource.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/UrlResource.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.common.packagescan.resource; import com.alibaba.nacos.common.packagescan.util.ResourceUtils; -import com.alibaba.nacos.common.utils.AbstractAssert; +import com.alibaba.nacos.common.packagescan.util.AbstractAssert; import com.alibaba.nacos.common.utils.StringUtils; import java.io.File; diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/VfsResource.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/VfsResource.java index 3996e0dc45d..9b0491c16f9 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/VfsResource.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/resource/VfsResource.java @@ -16,7 +16,7 @@ package com.alibaba.nacos.common.packagescan.resource; -import com.alibaba.nacos.common.utils.AbstractAssert; +import com.alibaba.nacos.common.packagescan.util.AbstractAssert; import com.alibaba.nacos.common.packagescan.util.NestedIoException; import java.io.File; diff --git a/common/src/main/java/com/alibaba/nacos/common/utils/AbstractAssert.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/util/AbstractAssert.java similarity index 99% rename from common/src/main/java/com/alibaba/nacos/common/utils/AbstractAssert.java rename to common/src/main/java/com/alibaba/nacos/common/packagescan/util/AbstractAssert.java index eadfe6fc952..e33db0b3bf8 100644 --- a/common/src/main/java/com/alibaba/nacos/common/utils/AbstractAssert.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/util/AbstractAssert.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors. + * 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 * - * https://www.apache.org/licenses/LICENSE-2.0 + * 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, @@ -14,7 +14,10 @@ * limitations under the License. */ -package com.alibaba.nacos.common.utils; +package com.alibaba.nacos.common.packagescan.util; + +import com.alibaba.nacos.common.utils.CollectionUtils; +import com.alibaba.nacos.common.utils.StringUtils; import java.util.Collection; import java.util.Map; diff --git a/common/src/main/java/com/alibaba/nacos/common/utils/AbstractObjectUtils.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/util/AbstractObjectUtils.java similarity index 99% rename from common/src/main/java/com/alibaba/nacos/common/utils/AbstractObjectUtils.java rename to common/src/main/java/com/alibaba/nacos/common/packagescan/util/AbstractObjectUtils.java index 284fbcee305..6bdcf738148 100644 --- a/common/src/main/java/com/alibaba/nacos/common/utils/AbstractObjectUtils.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/util/AbstractObjectUtils.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2021 the original author or authors. + * 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 * - * https://www.apache.org/licenses/LICENSE-2.0 + * 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, @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.alibaba.nacos.common.utils; +package com.alibaba.nacos.common.packagescan.util; import java.lang.reflect.Array; import java.util.Arrays; diff --git a/common/src/main/java/com/alibaba/nacos/common/packagescan/util/ResourceUtils.java b/common/src/main/java/com/alibaba/nacos/common/packagescan/util/ResourceUtils.java index 05d74272fff..e11b1eeda7a 100644 --- a/common/src/main/java/com/alibaba/nacos/common/packagescan/util/ResourceUtils.java +++ b/common/src/main/java/com/alibaba/nacos/common/packagescan/util/ResourceUtils.java @@ -17,7 +17,6 @@ package com.alibaba.nacos.common.packagescan.util; import com.alibaba.nacos.common.packagescan.resource.Resource; -import com.alibaba.nacos.common.utils.AbstractAssert; import com.alibaba.nacos.common.utils.ClassUtils; import com.alibaba.nacos.common.utils.StringUtils; diff --git a/common/src/main/java/com/alibaba/nacos/common/utils/ClassUtils.java b/common/src/main/java/com/alibaba/nacos/common/utils/ClassUtils.java index 52d9c459c5a..cba39b303cb 100644 --- a/common/src/main/java/com/alibaba/nacos/common/utils/ClassUtils.java +++ b/common/src/main/java/com/alibaba/nacos/common/utils/ClassUtils.java @@ -43,7 +43,7 @@ * @author liaochuntao */ public final class ClassUtils { - + private ClassUtils() { } @@ -241,7 +241,7 @@ public static String getSimpleName(Object obj) { */ public static Class forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { - AbstractAssert.notNull(name, "Name must not be null"); + Objects.requireNonNull(name, "Name must not be null"); Class clazz = resolvePrimitiveClassName(name); if (clazz == null) { @@ -386,7 +386,7 @@ public static String classPackageAsResourcePath(Class clazz) { * @return the corresponding resource path, pointing to the class */ public static String convertClassNameToResourcePath(String className) { - AbstractAssert.notNull(className, "Class name must not be null"); + Objects.requireNonNull(className, "Class name must not be null"); return className.replace(PACKAGE_SEPARATOR, PATH_SEPARATOR); } @@ -397,7 +397,7 @@ public static String convertClassNameToResourcePath(String className) { * @return the corresponding resource path, pointing to the class */ public static String resourcePathToConvertClassName(String className) { - AbstractAssert.notNull(className, "Class name must not be null"); + Objects.requireNonNull(className, "Class name must not be null"); return className.replace(PATH_SEPARATOR, PACKAGE_SEPARATOR); } } diff --git a/common/src/main/java/com/alibaba/nacos/common/utils/InetAddressValidator.java b/common/src/main/java/com/alibaba/nacos/common/utils/InetAddressValidator.java index 2499e20f33d..993224403aa 100644 --- a/common/src/main/java/com/alibaba/nacos/common/utils/InetAddressValidator.java +++ b/common/src/main/java/com/alibaba/nacos/common/utils/InetAddressValidator.java @@ -1,14 +1,10 @@ /** - * Copyright 2018-2021 Dynatrace LLC - * 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. + * Copyright 2018-2021 Dynatrace LLC 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.common.utils; @@ -22,7 +18,7 @@ */ @SuppressWarnings({"checkstyle:AbbreviationAsWordInName", "PMD.ClassNamingShouldBeCamelRule"}) public class InetAddressValidator { - + private InetAddressValidator() { } @@ -59,9 +55,8 @@ private InetAddressValidator() { .compile("^" + "(?:[0-9a-fA-F]{1,4}:){6}" + "$"); /** - * Check if input is a valid IPv4 address. - * The format is 'xxx.xxx.xxx.xxx'. Four blocks of integer numbers ranging from 0 to 255 - * are required. Letters are not allowed. + * Check if input is a valid IPv4 address. The format is 'xxx.xxx.xxx.xxx'. Four blocks of integer + * numbers ranging from 0 to 255 are required. Letters are not allowed. * * @param input ip-address to check * @return true if input is in correct IPv4 notation. @@ -71,9 +66,8 @@ public static boolean isIPv4Address(final String input) { } /** - * Check if the given address is a valid IPv6 address in the standard format - * The format is 'xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx'. Eight blocks of hexadecimal digits - * are required. + * Check if the given address is a valid IPv6 address in the standard format The format is + * 'xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx'. Eight blocks of hexadecimal digits are required. * * @param input ip-address to check * @return true if input is in correct IPv6 notation. @@ -83,9 +77,8 @@ public static boolean isIPv6StdAddress(final String input) { } /** - * Check if the given address is a valid IPv6 address in the hex-compressed notation - * The format is 'xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx'. If all digits in a block are '0' - * the block can be left empty. + * Check if the given address is a valid IPv6 address in the hex-compressed notation The format is + * 'xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx'. If all digits in a block are '0' the block can be left empty. * * @param input ip-address to check * @return true if input is in correct IPv6 (hex-compressed) notation. @@ -95,13 +88,8 @@ public static boolean isIPv6HexCompressedAddress(final String input) { } /** - * Check if input is a IPv6 address. - * Possible notations for valid IPv6 are: - * - Standard IPv6 address - * - Hex-compressed IPv6 address - * - Link-local IPv6 address - * - IPv4-mapped-to-IPV6 address - * - IPv6 mixed address + * Check if input is a IPv6 address. Possible notations for valid IPv6 are: - Standard IPv6 address - + * Hex-compressed IPv6 address - Link-local IPv6 address - IPv4-mapped-to-IPV6 address - IPv6 mixed address * * @param input ip-address to check * @return true if input is in correct IPv6 notation. @@ -112,11 +100,9 @@ public static boolean isIPv6Address(final String input) { } /** - * Check if the given address is a valid IPv6 address in the mixed-standard or mixed-compressed notation. - * IPV6 Mixed mode consists of two parts, the first 96 bits (up to 6 blocks of 4 hex digits) are IPv6 - * the IPV6 part can be either compressed or uncompressed - * the second block is a full IPv4 address - * e.g. '0:0:0:0:0:0:172.12.55.18' + * Check if the given address is a valid IPv6 address in the mixed-standard or mixed-compressed notation. IPV6 Mixed + * mode consists of two parts, the first 96 bits (up to 6 blocks of 4 hex digits) are IPv6 the IPV6 part can be + * either compressed or uncompressed the second block is a full IPv4 address e.g. '0:0:0:0:0:0:172.12.55.18' * * @param input ip-address to check * @return true if input is in correct IPv6 (mixed-standard or mixed-compressed) notation. @@ -143,9 +129,8 @@ public static boolean isIPv6MixedAddress(final String input) { } /** - * Check if input is an IPv4 address mapped into a IPv6 address. These are - * starting with "::ffff:" followed by the IPv4 address in a dot-seperated notation. - * The format is '::ffff:d.d.d.d' + * Check if input is an IPv4 address mapped into a IPv6 address. These are starting with "::ffff:" + * followed by the IPv4 address in a dot-seperated notation. The format is '::ffff:d.d.d.d' * * @param input ip-address to check * @return true if input is in correct IPv6 notation containing an IPv4 address @@ -159,8 +144,8 @@ public static boolean isIPv6IPv4MappedAddress(final String input) { } /** - * Check if input is a link local IPv6 address starting with "fe80:" and containing - * a zone index with "%xxx". The zone index will not be checked. + * Check if input is a link local IPv6 address starting with "fe80:" and containing a zone index with + * "%xxx". The zone index will not be checked. * * @param input ip-address to check * @return true if address part of input is in correct IPv6 notation. @@ -176,27 +161,4 @@ public static boolean isLinkLocalIPv6WithZoneIndex(String input) { return false; } - /** - * Check if input is a valid IPv4 or IPv6 address. - * - * @param ipAddress ip-address to check - * @return true if ipAddress is a valid ip-address - */ - public static boolean isValidIP(String ipAddress) { - if (ipAddress == null || ipAddress.length() == 0) { - return false; - } - - return isIPv4Address(ipAddress) || isIPv6Address(ipAddress); - } - - /** - * get to ipv4 pattern. - * - * @return - */ - public static Pattern getIpv4Pattern() { - return IPV4_PATTERN; - } - } diff --git a/common/src/main/java/com/alibaba/nacos/common/utils/IoUtils.java b/common/src/main/java/com/alibaba/nacos/common/utils/IoUtils.java index b281007a6ce..87b155e9364 100644 --- a/common/src/main/java/com/alibaba/nacos/common/utils/IoUtils.java +++ b/common/src/main/java/com/alibaba/nacos/common/utils/IoUtils.java @@ -24,7 +24,6 @@ import java.io.CharArrayWriter; import java.io.Closeable; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -33,7 +32,6 @@ import java.io.Reader; import java.io.Writer; import java.net.HttpURLConnection; -import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -46,7 +44,7 @@ * @author nacos */ public class IoUtils { - + private IoUtils() { } @@ -75,11 +73,7 @@ public static byte[] tryDecompress(byte[] raw) throws Exception { if (!isGzipStream(raw)) { return raw; } - try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(raw)); - ByteArrayOutputStream out = new ByteArrayOutputStream()) { - copy(gis, out); - return out.toByteArray(); - } + return tryDecompress(new ByteArrayInputStream(raw)); } /** @@ -276,31 +270,6 @@ public static void cleanDirectory(File directory) throws IOException { } } - /** - * Copy File. - * - * @param source source file path - * @param target target file path - * @throws IOException io exception - */ - public static void copyFile(String source, String target) throws IOException { - File sf = new File(source); - if (!sf.exists()) { - throw new IllegalArgumentException("source file does not exist."); - } - File tf = new File(target); - if (!tf.getParentFile().mkdirs()) { - throw new RuntimeException("failed to create parent directory."); - } - if (!tf.exists() && !tf.createNewFile()) { - throw new RuntimeException("failed to create target file."); - } - try (FileChannel sc = new FileInputStream(sf).getChannel(); - FileChannel tc = new FileOutputStream(tf).getChannel()) { - sc.transferTo(0, sc.size(), tc); - } - } - /** * Judge whether is Gzip stream. * diff --git a/common/src/main/java/com/alibaba/nacos/common/utils/StringUtils.java b/common/src/main/java/com/alibaba/nacos/common/utils/StringUtils.java index a2b1f0e29ab..57e351ed26c 100644 --- a/common/src/main/java/com/alibaba/nacos/common/utils/StringUtils.java +++ b/common/src/main/java/com/alibaba/nacos/common/utils/StringUtils.java @@ -16,9 +16,6 @@ package com.alibaba.nacos.common.utils; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.ArrayDeque; import java.util.ArrayList; @@ -26,7 +23,6 @@ import java.util.Deque; import java.util.Iterator; import java.util.List; -import java.util.Locale; import java.util.StringTokenizer; /** @@ -36,7 +32,7 @@ * @author zzq */ public class StringUtils { - + private StringUtils() { } @@ -226,108 +222,6 @@ public static String join(Collection collection, String separator) { return stringBuilder.toString(); } - public static String escapeJavaScript(String str) { - return escapeJavaStyleString(str, true, true); - } - - private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes, boolean escapeForwardSlash) { - if (str == null) { - return null; - } - try { - StringWriter writer = new StringWriter(str.length() * 2); - escapeJavaStyleString(writer, str, escapeSingleQuotes, escapeForwardSlash); - return writer.toString(); - } catch (IOException ioe) { - // this should never ever happen while writing to a StringWriter - return null; - } - } - - private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote, - boolean escapeForwardSlash) throws IOException { - if (out == null) { - throw new IllegalArgumentException("The Writer must not be null"); - } - if (str == null) { - return; - } - int sz; - sz = str.length(); - for (int i = 0; i < sz; i++) { - char ch = str.charAt(i); - - // handle unicode - if (ch > 0xfff) { - out.write("\\u" + hex(ch)); - } else if (ch > 0xff) { - out.write("\\u0" + hex(ch)); - } else if (ch > 0x7f) { - out.write("\\u00" + hex(ch)); - } else if (ch < 32) { - switch (ch) { - case '\b': - out.write('\\'); - out.write('b'); - break; - case '\n': - out.write('\\'); - out.write('n'); - break; - case '\t': - out.write('\\'); - out.write('t'); - break; - case '\f': - out.write('\\'); - out.write('f'); - break; - case '\r': - out.write('\\'); - out.write('r'); - break; - default: - if (ch > 0xf) { - out.write("\\u00" + hex(ch)); - } else { - out.write("\\u000" + hex(ch)); - } - break; - } - } else { - switch (ch) { - case '\'': - if (escapeSingleQuote) { - out.write('\\'); - } - out.write('\''); - break; - case '"': - out.write('\\'); - out.write('"'); - break; - case '\\': - out.write('\\'); - out.write('\\'); - break; - case '/': - if (escapeForwardSlash) { - out.write('\\'); - } - out.write('/'); - break; - default: - out.write(ch); - break; - } - } - } - } - - private static String hex(char ch) { - return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH); - } - /** * Checks if CharSequence contains a search CharSequence irrespective of case, handling {@code null}. * Case-insensitivity is defined as by {@link String#equalsIgnoreCase(String)}. @@ -503,10 +397,6 @@ public static String[] split(final String str, String separatorChars) { return str.split(separatorChars); } - private static String[] tokenizeLocaleSource(String localeSource) { - return tokenizeToStringArray(localeSource, "_ ", false, false); - } - /** * Tokenize the given {@code String} into a {@code String} array via a {@link StringTokenizer}. * @@ -899,21 +789,17 @@ public static String getFilename(String path) { * @return the capitalized {@code String} */ public static String capitalize(String str) { - return changeFirstCharacterCase(str, true); + return changeFirstCharacterCase(str); } - private static String changeFirstCharacterCase(String str, boolean capitalize) { + private static String changeFirstCharacterCase(String str) { if (!hasLength(str)) { return str; } char baseChar = str.charAt(0); char updatedChar; - if (capitalize) { - updatedChar = Character.toUpperCase(baseChar); - } else { - updatedChar = Character.toLowerCase(baseChar); - } + updatedChar = Character.toUpperCase(baseChar); if (baseChar == updatedChar) { return str; } diff --git a/common/src/main/java/com/alibaba/nacos/common/utils/ThreadUtils.java b/common/src/main/java/com/alibaba/nacos/common/utils/ThreadUtils.java index da34ece684d..e96f912f097 100644 --- a/common/src/main/java/com/alibaba/nacos/common/utils/ThreadUtils.java +++ b/common/src/main/java/com/alibaba/nacos/common/utils/ThreadUtils.java @@ -29,25 +29,12 @@ * @author liaochuntao */ public final class ThreadUtils { - + private ThreadUtils() { } private static final int THREAD_MULTIPLER = 2; - /** - * Wait. - * - * @param object load object - */ - public static void objectWait(Object object) { - try { - object.wait(); - } catch (InterruptedException ignore) { - Thread.interrupted(); - } - } - /** * Sleep. * diff --git a/common/src/test/java/ClassUtilsTestMockClass.java b/common/src/test/java/ClassUtilsTestMockClass.java new file mode 100644 index 00000000000..5183078632f --- /dev/null +++ b/common/src/test/java/ClassUtilsTestMockClass.java @@ -0,0 +1,18 @@ +/* + * 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. + */ + +public class ClassUtilsTestMockClass { +} diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/AbstractAssertTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/AbstractAssertTest.java deleted file mode 100644 index 9443428d46e..00000000000 --- a/common/src/test/java/com/alibaba/nacos/common/utils/AbstractAssertTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 1999-2022 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.common.utils; - -import org.junit.Test; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.Assert.assertThrows; - -public class AbstractAssertTest { - - @Test - public void testState() { - assertThrows("error message", IllegalStateException.class, () -> AbstractAssert.state(false, "error message")); - assertThrows("error", IllegalStateException.class, () -> AbstractAssert.state(false, () -> "error")); - } - - @Test - public void testIsTrue() { - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.isTrue(false, "error")); - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.isTrue(false, () -> "error")); - } - - @Test - public void testIsNull() { - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.isNull(new Object(), "error")); - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.isNull(new Object(), () -> "error")); - } - - @Test - public void testNotNull() { - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.notNull(null, "error")); - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.notNull(null, () -> "error")); - } - - @Test - public void testHasLength() { - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.hasLength(null, "error")); - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.hasLength(null, () -> "error")); - } - - @Test - public void testHasText() { - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.hasText(null, "error")); - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.hasText(null, () -> "error")); - } - - @Test - public void testDoesNotContain() { - assertThrows(IllegalArgumentException.class, () -> AbstractAssert.doesNotContain("abcd", "bc")); - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.doesNotContain("abcd", "bc", () -> "error")); - } - - @Test - public void testNotEmpty() { - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.notEmpty(Collections.EMPTY_MAP, "error")); - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.notEmpty(Collections.EMPTY_MAP, () -> "error")); - - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.notEmpty(new Object[] {}, "error")); - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.notEmpty(new Object[] {}, () -> "error")); - - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.notEmpty(Collections.emptyList(), "error")); - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.notEmpty(Collections.emptyList(), () -> "error")); - } - - @Test - public void testNoNullElements() { - List list = new LinkedList<>(); - list.add(null); - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.noNullElements(list, "error")); - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.noNullElements(list, () -> "error")); - - Object[] objects = new Object[1]; - assertThrows("error", IllegalArgumentException.class, () -> AbstractAssert.noNullElements(objects, "error")); - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.noNullElements(objects, () -> "error")); - } - - @Test - public void testIsInstanceOf() { - assertThrows("", IllegalArgumentException.class, () -> AbstractAssert.isInstanceOf(String.class, new Object())); - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.isInstanceOf(String.class, new Object(), "error")); - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.isInstanceOf(String.class, new Object(), () -> "error")); - } - - @Test - public void testIsAssignable() { - assertThrows("", IllegalArgumentException.class, () -> AbstractAssert.isAssignable(String.class, null)); - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.isAssignable(String.class, null, "error")); - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.isAssignable(String.class, Integer.class, "error")); - assertThrows("error", IllegalArgumentException.class, - () -> AbstractAssert.isAssignable(String.class, Integer.class, () -> "error")); - } - -} diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/AbstractObjectUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/AbstractObjectUtilsTest.java deleted file mode 100644 index 7ce85e29f94..00000000000 --- a/common/src/test/java/com/alibaba/nacos/common/utils/AbstractObjectUtilsTest.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 1999-2022 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.common.utils; - -import com.alibaba.nacos.api.exception.NacosException; -import org.junit.Test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Optional; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; - -public class AbstractObjectUtilsTest { - - @Test - public void testIsCheckedException() { - assertTrue(AbstractObjectUtils.isCheckedException(new NacosException())); - assertFalse(AbstractObjectUtils.isCheckedException(new RuntimeException())); - assertFalse(AbstractObjectUtils.isCheckedException(new Error())); - } - - @Test - public void testIsCompatibleWithThrowsClause() { - assertTrue(AbstractObjectUtils.isCompatibleWithThrowsClause(new NacosException(), Exception.class)); - assertFalse(AbstractObjectUtils.isCompatibleWithThrowsClause(new NacosException(), RuntimeException.class)); - } - - @Test - public void testIsArray() { - assertTrue(AbstractObjectUtils.isArray(new Object[] {})); - assertFalse(AbstractObjectUtils.isArray(new Object())); - } - - @Test - public void testIsEmpty() { - assertTrue(AbstractObjectUtils.isEmpty(null)); - - assertTrue(AbstractObjectUtils.isEmpty(Optional.empty())); - assertFalse(AbstractObjectUtils.isEmpty(Optional.of("1"))); - - assertTrue(AbstractObjectUtils.isEmpty("")); - assertFalse(AbstractObjectUtils.isEmpty("1")); - - assertTrue(AbstractObjectUtils.isEmpty(Collections.EMPTY_LIST)); - assertFalse(AbstractObjectUtils.isEmpty(Arrays.asList(1, 2))); - - assertTrue(AbstractObjectUtils.isEmpty(Collections.EMPTY_MAP)); - assertFalse(AbstractObjectUtils.isEmpty(new HashMap() { - { - put("k", "v"); - } - })); - - assertFalse(AbstractObjectUtils.isEmpty(new Object())); - - assertTrue(AbstractObjectUtils.isEmpty(new Object[] {})); - assertFalse(AbstractObjectUtils.isEmpty(new Object[] {""})); - } - - @Test - public void testUnwrapOptional() { - Object o = new Object(); - assertNull(AbstractObjectUtils.unwrapOptional(null)); - assertNull(AbstractObjectUtils.unwrapOptional(Optional.empty())); - assertEquals(o, AbstractObjectUtils.unwrapOptional(Optional.of(o))); - assertEquals(o, AbstractObjectUtils.unwrapOptional(o)); - } - - @Test - public void testContainsElement() { - Object[] objects = new Object[] {1, 2, 3}; - assertTrue(AbstractObjectUtils.containsElement(objects, 1)); - assertFalse(AbstractObjectUtils.containsElement(objects, 4)); - assertFalse(AbstractObjectUtils.containsElement(null, 1)); - } - - private enum ETest { - CASE1, - CASE2 - } - - @Test - public void testContainsConstant() { - assertTrue(AbstractObjectUtils.containsConstant(ETest.values(), "case1")); - assertFalse(AbstractObjectUtils.containsConstant(ETest.values(), "case3")); - - assertTrue(AbstractObjectUtils.containsConstant(ETest.values(), "CASE1", true)); - assertTrue(AbstractObjectUtils.containsConstant(ETest.values(), "CASE1", false)); - assertFalse(AbstractObjectUtils.containsConstant(ETest.values(), "case1", true)); - } - - @Test - public void testCaseInsensitiveValueOf() { - assertEquals(ETest.CASE1, AbstractObjectUtils.caseInsensitiveValueOf(ETest.values(), "case1")); - assertThrows(IllegalArgumentException.class, - () -> AbstractObjectUtils.caseInsensitiveValueOf(ETest.values(), "3")); - } - - @Test - public void testAddObjectToArray() { - Object[] objects = new Object[0]; - Object[] objects1 = AbstractObjectUtils.addObjectToArray(objects, 1); - assertEquals(1, objects1.length); - } - - @Test - public void testToObjectArray() { - Object[] objects = new Object[0]; - assertArrayEquals(objects, AbstractObjectUtils.toObjectArray(objects)); - assertNotNull(AbstractObjectUtils.toObjectArray(null)); - assertThrows(IllegalArgumentException.class, () -> AbstractObjectUtils.toObjectArray(new Object())); - } - - @Test - public void testNullSafeEquals() { - Integer o1 = new Integer(1111); - Integer o2 = new Integer(1111); - AbstractObjectUtils.nullSafeEquals(1, 1); - assertTrue(AbstractObjectUtils.nullSafeEquals(o1, o2)); - assertTrue(AbstractObjectUtils.nullSafeEquals(null, null)); - - assertFalse(AbstractObjectUtils.nullSafeEquals(o1, null)); - assertFalse(AbstractObjectUtils.nullSafeEquals(null, o2)); - - assertTrue(AbstractObjectUtils.nullSafeEquals(1111, 1111)); - - assertTrue(AbstractObjectUtils.nullSafeEquals(new Integer[] {1, 2}, new Integer[] {1, 2})); - assertFalse(AbstractObjectUtils.nullSafeEquals(new Integer[] {1, 2}, new Integer[] {1, 2, 3})); - } - - @Test - public void testNullSafeHashCode() { - Object o = null; - assertEquals(0, AbstractObjectUtils.nullSafeHashCode(o)); - assertNotEquals(0, AbstractObjectUtils.nullSafeHashCode(new Object[] {})); - } - - @Test - public void testIdentityToString() { - assertEquals("", AbstractObjectUtils.identityToString(null)); - - String str = "1"; - assertEquals(str.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(str)), - AbstractObjectUtils.identityToString(str)); - } - - @Test - public void testGetIdentityHexString() { - assertEquals(Integer.toHexString(System.identityHashCode("1")), AbstractObjectUtils.getIdentityHexString("1")); - } - - @Test - public void testGetDisplayString() { - assertEquals("", AbstractObjectUtils.getDisplayString(null)); - } - - @Test - public void testNullSafeClassName() { - assertEquals("null", AbstractObjectUtils.nullSafeClassName(null)); - assertEquals(Integer.class.getName(), AbstractObjectUtils.nullSafeClassName(1)); - } - - @Test - public void testNullSafeToString() { - Object o = null; - assertEquals("null", AbstractObjectUtils.nullSafeToString(o)); - assertSame("1", AbstractObjectUtils.nullSafeToString("1")); - assertEquals("{1, 2}", AbstractObjectUtils.nullSafeToString(new Object[] {1, 2})); - assertEquals("{true, false}", AbstractObjectUtils.nullSafeToString(new boolean[] {true, false})); - assertEquals("{1}", AbstractObjectUtils.nullSafeToString(new byte[] {1})); - assertEquals("{'a'}", AbstractObjectUtils.nullSafeToString(new char[] {'a'})); - assertEquals("{1.1}", AbstractObjectUtils.nullSafeToString(new double[] {1.1d})); - assertEquals("{1.1}", AbstractObjectUtils.nullSafeToString(new float[] {1.1f})); - assertEquals("{11}", AbstractObjectUtils.nullSafeToString(new int[] {11})); - assertEquals("{11}", AbstractObjectUtils.nullSafeToString(new long[] {11L})); - assertEquals("{11}", AbstractObjectUtils.nullSafeToString(new short[] {11})); - } - -} diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ByteUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ByteUtilsTest.java index 7d309a8c340..153291d6f8e 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ByteUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ByteUtilsTest.java @@ -21,7 +21,8 @@ import org.junit.Test; /** - * ByteUtils Test. + * ByteUtils Test. + * * @ClassName: ByteUtilsTest * @Author: ChenHao26 * @Date: 2022/8/22 10:58 @@ -48,6 +49,13 @@ public void toStringTest() { Assert.assertEquals(str, "google"); } + @Test + public void testForInputNull() { + Assert.assertEquals(0, ByteUtils.toBytes(null).length); + Assert.assertEquals(0, ByteUtils.toBytes((Object) null).length); + Assert.assertEquals("", ByteUtils.toString(null)); + } + @Test public void isEmpty() { byte[] bytes = ByteUtils.toBytes(""); diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ClassUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ClassUtilsTest.java index 4679b57e3ff..b7068dacf4c 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ClassUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ClassUtilsTest.java @@ -20,7 +20,11 @@ import org.junit.Assert; import org.junit.Test; +import java.lang.reflect.Field; +import java.util.Map; + public class ClassUtilsTest { + @Test public void testFindClassByName1() { Class clazz = ClassUtils.findClassByName("java.lang.Integer"); @@ -50,4 +54,57 @@ public void testGetName() { public void testIsAssignableFrom() { Assert.assertTrue(ClassUtils.isAssignableFrom(Object.class, Integer.class)); } + + @Test + public void testForNameArray() throws ClassNotFoundException { + Class clazz = ClassUtils.forName("[Lcom.alibaba.nacos.common.utils.ClassUtilsTest;", null); + Assert.assertEquals("[Lcom.alibaba.nacos.common.utils.ClassUtilsTest;", clazz.getName()); + clazz = ClassUtils.forName("java.lang.String[]", null); + Assert.assertEquals("[Ljava.lang.String;", clazz.getName()); + clazz = ClassUtils.forName("[[Ljava.lang.String;", null); + Assert.assertEquals("[[Ljava.lang.String;", clazz.getName()); + } + + @Test(expected = ClassNotFoundException.class) + public void testForNameNonExist() throws ClassNotFoundException { + ClassUtils.forName("com.alibaba.nacos.common.NonExistClass", null); + } + + @Test + public void testForNameFromPrimitive() throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException { + Field field = ClassUtils.class.getDeclaredField("PRIMITIVE_TYPE_NAME_MAP"); + field.setAccessible(true); + Map> map = (Map>) field.get(null); + map.put("Test", ClassUtilsTest.class); + Assert.assertEquals(ClassUtilsTest.class, ClassUtils.forName("Test", null)); + } + + @Test + public void testGetDefaultClassLoader() { + ClassLoader cachedClassLoader = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(null); + Assert.assertNotNull(ClassUtils.getDefaultClassLoader()); + } finally { + Thread.currentThread().setContextClassLoader(cachedClassLoader); + } + } + + @Test + public void testClassPackageAsResourcePath() throws ClassNotFoundException { + Class noPackageClass = ClassUtils.forName("ClassUtilsTestMockClass", null); + Assert.assertEquals("", ClassUtils.classPackageAsResourcePath(null)); + Assert.assertEquals("", ClassUtils.classPackageAsResourcePath(noPackageClass)); + Assert.assertEquals("com/alibaba/nacos/common/utils", + ClassUtils.classPackageAsResourcePath(ClassUtilsTest.class)); + } + + @Test + public void testConvertClassNameAndClassPath() { + String name = ClassUtilsTest.class.getName(); + Assert.assertEquals("com/alibaba/nacos/common/utils/ClassUtilsTest", + ClassUtils.convertClassNameToResourcePath(name)); + Assert.assertEquals(name, + ClassUtils.resourcePathToConvertClassName("com/alibaba/nacos/common/utils/ClassUtilsTest")); + } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/CollectionUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/CollectionUtilsTest.java index 0ced44ed378..8531c1c6138 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/CollectionUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/CollectionUtilsTest.java @@ -22,14 +22,14 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.Enumeration; import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.HashSet; -import java.util.LinkedHashSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.Vector; @@ -38,7 +38,7 @@ /** * Unit test of CollectionUtil. - * + * * @author sunjifeng */ public class CollectionUtilsTest { @@ -189,7 +189,7 @@ public void testSize() { Assert.assertEquals(0, CollectionUtils.size(Collections.emptyList())); Assert.assertEquals(1, CollectionUtils.size(Collections.singletonList(""))); Assert.assertEquals(10, CollectionUtils.size(IntStream.range(0, 10).boxed().collect(Collectors.toList()))); - + // map Map map = new HashMap<>(); map.put("key1", "value1"); @@ -197,8 +197,7 @@ public void testSize() { map.put("key2", "value2"); Assert.assertEquals(2, CollectionUtils.size(map)); map.put("key3", "value3"); - Assert.assertEquals(3, - CollectionUtils.size(map)); + Assert.assertEquals(3, CollectionUtils.size(map)); // array Assert.assertEquals(1, CollectionUtils.size(new Object[] {"1"})); @@ -318,7 +317,7 @@ private Enumeration asEnumeration(final Iterator iterator) { public boolean hasMoreElements() { return iterator.hasNext(); } - + public T nextElement() { return iterator.next(); } @@ -341,10 +340,15 @@ public void testSetNullPointerException() { @Test(expected = IllegalArgumentException.class) public void testGetOnlyElementIllegalArgumentException() { - List list = Arrays.asList(1, 2, 3); + List list = Arrays.asList(1, 2, 3, 4, 5, 6); CollectionUtils.getOnlyElement(list); } + @Test(expected = IllegalArgumentException.class) + public void testGetOnlyElementIllegalArgumentException2() { + CollectionUtils.getOnlyElement(null); + } + @Test(expected = NoSuchElementException.class) public void testGetOnlyElementNoSuchElementException() { List list = new ArrayList<>(); @@ -357,4 +361,35 @@ public void testGetOnly() { int element = CollectionUtils.getOnlyElement(list); Assert.assertEquals(1, element); } + + @Test + public void testIsListEqualForNull() { + Assert.assertTrue(CollectionUtils.isListEqual(null, null)); + Assert.assertFalse(CollectionUtils.isListEqual(Collections.emptyList(), null)); + Assert.assertFalse(CollectionUtils.isListEqual(null, Collections.emptyList())); + } + + @Test + public void testIsListEqualForEquals() { + List list1 = Arrays.asList("1", "2", "3"); + List list2 = Arrays.asList("1", "2", "3"); + Assert.assertTrue(CollectionUtils.isListEqual(list1, list1)); + Assert.assertTrue(CollectionUtils.isListEqual(list1, list2)); + Assert.assertTrue(CollectionUtils.isListEqual(list2, list1)); + } + + @Test + public void testIsListEqualForNotEquals() { + List list1 = Arrays.asList("1", "2", "3"); + List list2 = Arrays.asList("1", "2", "3", "4"); + List list3 = Arrays.asList("1", "2", "3", "5"); + Assert.assertFalse(CollectionUtils.isListEqual(list1, list2)); + Assert.assertFalse(CollectionUtils.isListEqual(list2, list3)); + } + + @Test + public void testIsMapEmpty() { + Assert.assertTrue(CollectionUtils.isMapEmpty(null)); + Assert.assertTrue(CollectionUtils.isMapEmpty(Collections.emptyMap())); + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/DateFormatUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/DateFormatUtilsTest.java index 79ea441f6e4..70a956b5c42 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/DateFormatUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/DateFormatUtilsTest.java @@ -20,6 +20,7 @@ import org.junit.Test; import java.util.Calendar; +import java.util.Date; import java.util.TimeZone; /** @@ -44,4 +45,14 @@ public void testformat() { buffer.append(hour); Assert.assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH")); } + + @Test(expected = NullPointerException.class) + public void testForNullPointerExceptionWithDate() { + DateFormatUtils.format(new Date(), null); + } + + @Test(expected = NullPointerException.class) + public void testForNullPointerExceptionWithPattern() { + DateFormatUtils.format(null, "yyyyMdH"); + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ExceptionUtilTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ExceptionUtilTest.java new file mode 100644 index 00000000000..087a8f1fc83 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ExceptionUtilTest.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package com.alibaba.nacos.common.utils; + +import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class ExceptionUtilTest { + + NacosRuntimeException nacosRuntimeException; + + @Before + public void setUp() { + RuntimeException caused = new RuntimeException("I'm caused exception."); + nacosRuntimeException = new NacosRuntimeException(500, "Test", caused); + + } + + @Test + public void testGetAllExceptionMsg() { + String msg = ExceptionUtil.getAllExceptionMsg(nacosRuntimeException); + assertEquals("caused: errCode: 500, errMsg: Test ;caused: I'm caused exception.;", msg); + } + + @Test + public void testGetCause() { + assertEquals("I'm caused exception.", ExceptionUtil.getCause(nacosRuntimeException).getMessage()); + NacosRuntimeException nreWithoutCaused = new NacosRuntimeException(500); + assertEquals(nreWithoutCaused, ExceptionUtil.getCause(nreWithoutCaused)); + } + + @Test + public void testGetStackTrace() { + assertEquals("", ExceptionUtil.getStackTrace(null)); + String stackTrace = ExceptionUtil.getStackTrace(nacosRuntimeException); + assertTrue(stackTrace.contains( + "com.alibaba.nacos.api.exception.runtime.NacosRuntimeException: errCode: 500, errMsg: Test \n")); + assertTrue(stackTrace.contains("at ")); + assertTrue(stackTrace.contains("Caused by: java.lang.RuntimeException: I'm caused exception.\n")); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/InetAddressValidatorTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/InetAddressValidatorTest.java index e06134c74b0..b85b89a89b0 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/InetAddressValidatorTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/InetAddressValidatorTest.java @@ -38,6 +38,7 @@ public void isIPv6Address() { @Test public void isIPv6MixedAddress() { Assert.assertTrue(InetAddressValidator.isIPv6MixedAddress("1:0:0:0:0:0:172.12.55.18")); + Assert.assertTrue(InetAddressValidator.isIPv6MixedAddress("::172.12.55.18")); Assert.assertFalse(InetAddressValidator.isIPv6MixedAddress("2001:DB8::8:800:200C141aA")); } @@ -51,4 +52,10 @@ public void isIPv6IPv4MappedAddress() { public void isIPv4Address() { Assert.assertTrue(InetAddressValidator.isIPv4Address("192.168.1.2")); } + + @Test + public void isLinkLocalIPv6WithZoneIndex() { + Assert.assertTrue(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("fe80::1%lo0")); + Assert.assertFalse(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("2000:0000:0000:0000:0001:2345:6789:abcd")); + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/InternetAddressUtilTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/InternetAddressUtilTest.java index 5bc5d86f993..8dd89895f89 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/InternetAddressUtilTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/InternetAddressUtilTest.java @@ -24,6 +24,7 @@ /** * test IpUtil. + * * @ClassName: IpUtilTest * @date 2020/9/3 10:31 */ @@ -56,7 +57,8 @@ public void testIsIP() { @Test public void testGetIPFromString() { - Assert.assertEquals("[::1]", InternetAddressUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3")); + Assert.assertEquals("[::1]", + InternetAddressUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3")); Assert.assertEquals("[::1]", InternetAddressUtil.getIPFromString( "jdbc:mysql://[::1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000" + "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC")); @@ -66,7 +68,7 @@ public void testGetIPFromString() { "jdbc:mysql://127.0.0.1:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000" + "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC")); Assert.assertEquals("", InternetAddressUtil.getIPFromString("http://[::1:666")); - + Assert.assertEquals("", InternetAddressUtil.getIPFromString("http://[dddd]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3")); Assert.assertEquals("", InternetAddressUtil.getIPFromString( @@ -107,7 +109,7 @@ public void testSplitIpPort() { checkSplitIPPortStr("[2001:DB8:0:0:1::1]:88", false, "[2001:DB8:0:0:1::1]", "88"); checkSplitIPPortStr("localhost:8848", false, "localhost", "8848"); checkSplitIPPortStr("[dead::beef]:88", false, "[dead::beef]", "88"); - + // illegal ip will get abnormal results checkSplitIPPortStr("::1:88", false, "", "", "1", "88"); checkSplitIPPortStr("[::1:88", false, "[", "", "1", "88"); @@ -174,11 +176,22 @@ public void testLocalHostIP() throws NoSuchFieldException, IllegalAccessExceptio Assert.assertEquals("[::1]", InternetAddressUtil.localHostIP()); } + @Test + public void testIpToInt() { + Assert.assertEquals(2130706433, InternetAddressUtil.ipToInt("127.0.0.1")); + Assert.assertEquals(-1062731775, InternetAddressUtil.ipToInt("192.168.0.1")); + } + + @Test(expected = IllegalArgumentException.class) + public void testIllegalIpToInt() { + InternetAddressUtil.ipToInt("127.0.0.256"); + } + /** - * checkSplitIpPortStr. - * 2020/9/4 14:12 - * @param addr addr - * @param isEx isEx + * checkSplitIpPortStr. 2020/9/4 14:12 + * + * @param addr addr + * @param isEx isEx * @param equalsStrs equalsStrs */ public static void checkSplitIPPortStr(String addr, boolean isEx, String... equalsStrs) { diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/IoUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/IoUtilsTest.java index 54b993594d7..667c4d008e1 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/IoUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/IoUtilsTest.java @@ -19,11 +19,23 @@ import org.apache.commons.io.Charsets; import org.junit.Assert; import org.junit.Test; +import sun.security.action.GetPropertyAction; import java.io.BufferedReader; import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileReader; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.nio.charset.StandardCharsets; +import java.security.AccessController; +import java.util.List; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * Unit test of IoUtils. @@ -32,6 +44,142 @@ */ public class IoUtilsTest { + @Test + public void testTryDecompressForNotGzip() throws Exception { + byte[] testCase = "123".getBytes(Charsets.toCharset("UTF-8")); + Assert.assertEquals(testCase, IoUtils.tryDecompress(testCase)); + } + + @Test + public void testTryDecompressForGzip() throws Exception { + byte[] testCase = IoUtils.tryCompress("123", "UTF-8"); + Assert.assertEquals("123", new String(IoUtils.tryDecompress(testCase), StandardCharsets.UTF_8)); + } + + @Test + public void testTryCompressWithEmptyString() { + Assert.assertEquals(0, IoUtils.tryCompress("", "UTF-8").length); + Assert.assertEquals(0, IoUtils.tryCompress(null, "UTF-8").length); + } + + @Test + public void testWriteStringToFile() throws IOException { + File file = null; + try { + file = File.createTempFile("test_writeStringToFile", ".txt"); + IoUtils.writeStringToFile(file, "123", "UTF-8"); + List actual = IoUtils.readLines(new FileReader(file)); + Assert.assertEquals(1, actual.size()); + Assert.assertEquals("123", actual.get(0)); + } finally { + if (null != file) { + file.deleteOnExit(); + } + } + } + + @Test + public void testToStringWithNull() throws IOException { + Assert.assertEquals("", IoUtils.toString(null, "UTF-8")); + } + + @Test + public void testToStringWithReader() throws IOException { + String testCase = "123"; + Assert.assertEquals(testCase, + IoUtils.toString(new ByteArrayInputStream(testCase.getBytes(Charsets.toCharset("UTF-8"))), "UTF-8")); + } + + @Test + public void testDeleteForNullFile() throws IOException { + IoUtils.delete(null); + } + + @Test + public void testDeleteSuccess() throws IOException { + File file = null; + try { + file = File.createTempFile("test_deleteForFile", ".txt"); + Assert.assertTrue(file.exists()); + IoUtils.delete(file); + Assert.assertFalse(file.exists()); + } finally { + if (null != file) { + file.deleteOnExit(); + } + } + } + + @Test(expected = IOException.class) + public void testDeleteFileFailure() throws IOException { + File file = mock(File.class); + when(file.exists()).thenReturn(true); + when(file.delete()).thenReturn(false); + IoUtils.delete(file); + } + + @Test + public void testDeleteForDirectory() throws IOException { + File file = null; + try { + String tmpDir = AccessController.doPrivileged(new GetPropertyAction("java.io.tmpdir")); + File tmpDirFile = new File(tmpDir, "IoUtilsTest"); + tmpDirFile.mkdirs(); + file = File.createTempFile("test_deleteForDirectory", ".txt", tmpDirFile); + Assert.assertTrue(file.exists()); + IoUtils.delete(file.getParentFile()); + Assert.assertTrue(tmpDirFile.exists()); + Assert.assertFalse(file.exists()); + } finally { + if (null != file) { + file.getParentFile().deleteOnExit(); + file.deleteOnExit(); + } + } + } + + @Test(expected = IllegalArgumentException.class) + public void testCleanDirectoryForNonExistingDirectory() throws IOException { + File nonexistentDir = new File("non_exist"); + IoUtils.cleanDirectory(nonexistentDir); + } + + @Test(expected = IllegalArgumentException.class) + public void testCleanDirectoryForFile() throws IOException { + File mockFile = mock(File.class); + when(mockFile.exists()).thenReturn(true); + IoUtils.cleanDirectory(mockFile); + } + + @Test(expected = IOException.class) + public void testCleanDirectoryWithEmptyDirectory() throws IOException { + File mockFile = mock(File.class); + when(mockFile.exists()).thenReturn(true); + when(mockFile.isDirectory()).thenReturn(true); + IoUtils.cleanDirectory(mockFile); + } + + @Test(expected = IOException.class) + public void testCleanDirectory() throws IOException { + File mockFile = mock(File.class); + when(mockFile.exists()).thenReturn(true); + when(mockFile.isDirectory()).thenReturn(true); + File mockSubFile = mock(File.class); + when(mockSubFile.exists()).thenReturn(true); + when(mockFile.listFiles()).thenReturn(new File[] {mockSubFile}); + IoUtils.cleanDirectory(mockFile); + } + + @Test + public void testIsGzipStreamWithNull() { + Assert.assertFalse(IoUtils.isGzipStream(null)); + } + + @Test + public void testIsGzipStreamWithEmpty() { + Assert.assertFalse(IoUtils.isGzipStream(new byte[0])); + } + @Test() public void testCloseQuietly() throws IOException { BufferedReader br = new BufferedReader( @@ -70,4 +218,13 @@ public void testCloseQuietly2() throws IOException { Assert.fail(); } + @Test + public void testCloseQuietlyForHttpConnection() throws IOException { + HttpURLConnection conn = mock(HttpURLConnection.class); + InputStream inputStream = mock(InputStream.class); + when(conn.getInputStream()).thenReturn(inputStream); + IoUtils.closeQuietly(conn); + verify(inputStream).close(); + } + } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/JacksonUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/JacksonUtilsTest.java index 2aff441aa47..5c593be1695 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/JacksonUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/JacksonUtilsTest.java @@ -17,6 +17,7 @@ package com.alibaba.nacos.common.utils; import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.api.exception.runtime.NacosDeserializationException; import com.alibaba.nacos.api.exception.runtime.NacosSerializationException; import com.alibaba.nacos.common.model.RestResult; import com.fasterxml.jackson.annotation.JsonFormat; @@ -52,14 +53,10 @@ public void testToJson1() { Assert.assertEquals("\"string\"", JacksonUtils.toJson("string")); Assert.assertEquals("30", JacksonUtils.toJson(new BigDecimal(30))); Assert.assertEquals("{\"key\":\"value\"}", JacksonUtils.toJson(Collections.singletonMap("key", "value"))); - Assert.assertEquals( - "[{\"key\":\"value\"}]", - JacksonUtils.toJson(Collections.singletonList(Collections.singletonMap("key", "value"))) - ); - Assert.assertEquals( - "{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}", - JacksonUtils.toJson(new TestOfAtomicObject()) - ); + Assert.assertEquals("[{\"key\":\"value\"}]", + JacksonUtils.toJson(Collections.singletonList(Collections.singletonMap("key", "value")))); + Assert.assertEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}", + JacksonUtils.toJson(new TestOfAtomicObject())); Assert.assertEquals("{\"date\":1626192000000}", JacksonUtils.toJson(new TestOfDate())); // only public Assert.assertEquals("{\"publicAccessModifier\":\"public\"}", JacksonUtils.toJson(new TestOfAccessModifier())); @@ -67,10 +64,8 @@ public void testToJson1() { Assert.assertEquals("{\"value\":\"value\",\"key\":\"key\"}", JacksonUtils.toJson(new TestOfGetter())); // annotation available Assert.assertEquals( - "{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\"," - + "\"camelCase\":\"value\"}", - JacksonUtils.toJson(new TestOfAnnotationSub()) - ); + "{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\"," + + "\"camelCase\":\"value\"}", JacksonUtils.toJson(new TestOfAnnotationSub())); } @Test(expected = NacosSerializationException.class) @@ -84,35 +79,23 @@ public void testToJsonBytes1() { Assert.assertArrayEquals("null".getBytes(), JacksonUtils.toJsonBytes(null)); Assert.assertArrayEquals("\"string\"".getBytes(), JacksonUtils.toJsonBytes("string")); Assert.assertArrayEquals("30".getBytes(), JacksonUtils.toJsonBytes(new BigDecimal(30))); - Assert.assertArrayEquals( - "{\"key\":\"value\"}".getBytes(), - JacksonUtils.toJsonBytes(Collections.singletonMap("key", "value")) - ); - Assert.assertArrayEquals( - "[{\"key\":\"value\"}]".getBytes(), - JacksonUtils.toJsonBytes(Collections.singletonList(Collections.singletonMap("key", "value"))) - ); - Assert.assertArrayEquals( - "{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), - JacksonUtils.toJsonBytes(new TestOfAtomicObject()) - ); + Assert.assertArrayEquals("{\"key\":\"value\"}".getBytes(), + JacksonUtils.toJsonBytes(Collections.singletonMap("key", "value"))); + Assert.assertArrayEquals("[{\"key\":\"value\"}]".getBytes(), + JacksonUtils.toJsonBytes(Collections.singletonList(Collections.singletonMap("key", "value")))); + Assert.assertArrayEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), + JacksonUtils.toJsonBytes(new TestOfAtomicObject())); Assert.assertArrayEquals("{\"date\":1626192000000}".getBytes(), JacksonUtils.toJsonBytes(new TestOfDate())); // only public - Assert.assertArrayEquals( - "{\"publicAccessModifier\":\"public\"}".getBytes(), - JacksonUtils.toJsonBytes(new TestOfAccessModifier()) - ); + Assert.assertArrayEquals("{\"publicAccessModifier\":\"public\"}".getBytes(), + JacksonUtils.toJsonBytes(new TestOfAccessModifier())); // getter is also recognized - Assert.assertArrayEquals( - "{\"value\":\"value\",\"key\":\"key\"}".getBytes(), - JacksonUtils.toJsonBytes(new TestOfGetter()) - ); + Assert.assertArrayEquals("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), + JacksonUtils.toJsonBytes(new TestOfGetter())); // annotation available Assert.assertArrayEquals( - ("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\"," - + "\"camelCase\":\"value\"}").getBytes(), - JacksonUtils.toJsonBytes(new TestOfAnnotationSub()) - ); + ("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\"," + + "\"camelCase\":\"value\"}").getBytes(), JacksonUtils.toJsonBytes(new TestOfAnnotationSub())); } @Test(expected = NacosSerializationException.class) @@ -129,36 +112,21 @@ public void testToObject1() { Assert.assertNull(JacksonUtils.toObj("null".getBytes(), Object.class)); Assert.assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), String.class)); Assert.assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), BigDecimal.class)); - Assert.assertEquals( - Collections.singletonMap("key", "value"), - JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Map.class) - ); - Assert.assertEquals( - Collections.singletonList(Collections.singletonMap("key", "value")), - JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), List.class) - ); - Assert.assertEquals( - new TestOfAtomicObject(), - JacksonUtils.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), - TestOfAtomicObject.class) - ); - Assert.assertEquals( - new TestOfDate(), - JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), TestOfDate.class) - ); - Assert.assertEquals( - new TestOfAccessModifier(), - JacksonUtils.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), TestOfAccessModifier.class) - ); - Assert.assertEquals( - new TestOfGetter(), - JacksonUtils.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), TestOfGetter.class) - ); - Assert.assertEquals( - new TestOfAnnotationSub(), - JacksonUtils.toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\"," - + "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(), TestOfAnnotation.class) - ); + Assert.assertEquals(Collections.singletonMap("key", "value"), + JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Map.class)); + Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), + JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), List.class)); + Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils + .toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), TestOfAtomicObject.class)); + Assert.assertEquals(new TestOfDate(), + JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), TestOfDate.class)); + Assert.assertEquals(new TestOfAccessModifier(), + JacksonUtils.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), TestOfAccessModifier.class)); + Assert.assertEquals(new TestOfGetter(), + JacksonUtils.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), TestOfGetter.class)); + Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils + .toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\"," + + "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(), TestOfAnnotation.class)); } /** @@ -174,16 +142,12 @@ public void testToObject2() { */ @Test public void testToObject3() { - Assert.assertEquals( - Collections.singletonMap("key", "value"), - JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), TypeUtils.parameterize(Map.class, - String.class, String.class)) - ); - Assert.assertEquals( - Collections.singletonList(Collections.singletonMap("key", "value")), - JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), TypeUtils.parameterize(List.class, - TypeUtils.parameterize(Map.class, String.class, String.class))) - ); + Assert.assertEquals(Collections.singletonMap("key", "value"), JacksonUtils + .toObj("{\"key\":\"value\"}".getBytes(), + TypeUtils.parameterize(Map.class, String.class, String.class))); + Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), JacksonUtils + .toObj("[{\"key\":\"value\"}]".getBytes(), TypeUtils + .parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class)))); } /** @@ -191,10 +155,8 @@ public void testToObject3() { */ @Test(expected = Exception.class) public void testToObject4() { - JacksonUtils.toObj( - "{not_A}Json:String}".getBytes(), - TypeUtils.parameterize(Map.class, String.class, String.class) - ); + JacksonUtils + .toObj("{not_A}Json:String}".getBytes(), TypeUtils.parameterize(Map.class, String.class, String.class)); } /** @@ -211,47 +173,29 @@ public void testToObject5() { @Test public void testToObject6() { Assert.assertNull(JacksonUtils.toObj(new ByteArrayInputStream("null".getBytes()), Object.class)); - Assert.assertEquals( - "string", - JacksonUtils.toObj(new ByteArrayInputStream("\"string\"".getBytes()), String.class) - ); - Assert.assertEquals( - new BigDecimal(30), - JacksonUtils.toObj(new ByteArrayInputStream("30".getBytes()), BigDecimal.class) - ); - Assert.assertEquals( - Collections.singletonMap("key", "value"), - JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Map.class) - ); - Assert.assertEquals( - Collections.singletonList(Collections.singletonMap("key", "value")), - JacksonUtils.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), List.class) - ); - Assert.assertEquals( - new TestOfAtomicObject(), - JacksonUtils.toObj(new ByteArrayInputStream("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}" - .getBytes()), TestOfAtomicObject.class) - ); - Assert.assertEquals( - new TestOfDate(), - JacksonUtils.toObj(new ByteArrayInputStream("{\"date\":1626192000000}".getBytes()), TestOfDate.class) - ); - Assert.assertEquals( - new TestOfAccessModifier(), - JacksonUtils.toObj(new ByteArrayInputStream("{\"publicAccessModifier\":\"public\"}".getBytes()), - TestOfAccessModifier.class) - ); - Assert.assertEquals( - new TestOfGetter(), - JacksonUtils.toObj(new ByteArrayInputStream("{\"value\":\"value\",\"key\":\"key\"}".getBytes()), - TestOfGetter.class) - ); - Assert.assertEquals( - new TestOfAnnotationSub(), - JacksonUtils.toObj((new ByteArrayInputStream(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\"," - + "\"date\":\"2021-07-14\",\"subField\":\"subField\",\"camelCase\":\"value\"}") - .getBytes())), TestOfAnnotation.class) - ); + Assert.assertEquals("string", + JacksonUtils.toObj(new ByteArrayInputStream("\"string\"".getBytes()), String.class)); + Assert.assertEquals(new BigDecimal(30), + JacksonUtils.toObj(new ByteArrayInputStream("30".getBytes()), BigDecimal.class)); + Assert.assertEquals(Collections.singletonMap("key", "value"), + JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Map.class)); + Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), + JacksonUtils.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), List.class)); + Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils + .toObj(new ByteArrayInputStream("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes()), + TestOfAtomicObject.class)); + Assert.assertEquals(new TestOfDate(), + JacksonUtils.toObj(new ByteArrayInputStream("{\"date\":1626192000000}".getBytes()), TestOfDate.class)); + Assert.assertEquals(new TestOfAccessModifier(), JacksonUtils + .toObj(new ByteArrayInputStream("{\"publicAccessModifier\":\"public\"}".getBytes()), + TestOfAccessModifier.class)); + Assert.assertEquals(new TestOfGetter(), JacksonUtils + .toObj(new ByteArrayInputStream("{\"value\":\"value\",\"key\":\"key\"}".getBytes()), + TestOfGetter.class)); + Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils.toObj((new ByteArrayInputStream( + ("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\"," + + "\"date\":\"2021-07-14\",\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes())), + TestOfAnnotation.class)); } /** @@ -275,41 +219,36 @@ public void testToObject8() { */ @Test public void testToObject9() { - Assert.assertNull(JacksonUtils.toObj("null".getBytes(), new TypeReference() { })); - Assert.assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), new TypeReference() { })); - Assert.assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), new TypeReference() { })); - Assert.assertEquals( - Collections.singletonMap("key", "value"), - JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), new TypeReference>() { }) - ); - Assert.assertEquals( - Collections.singletonList(Collections.singletonMap("key", "value")), - JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), new TypeReference>>() { }) - ); - Assert.assertEquals( - new TestOfAtomicObject(), - JacksonUtils.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), - new TypeReference() { }) - ); - Assert.assertEquals( - new TestOfDate(), - JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), new TypeReference() { }) - ); - Assert.assertEquals( - new TestOfAccessModifier(), - JacksonUtils.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), - new TypeReference() { }) - ); - Assert.assertEquals( - new TestOfGetter(), - JacksonUtils.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), new TypeReference() { }) - ); - Assert.assertEquals( - new TestOfAnnotationSub(), - JacksonUtils.toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\"," - + "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(), - new TypeReference() { }) - ); + Assert.assertNull(JacksonUtils.toObj("null".getBytes(), new TypeReference() { + })); + Assert.assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), new TypeReference() { + })); + Assert.assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), new TypeReference() { + })); + Assert.assertEquals(Collections.singletonMap("key", "value"), + JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), new TypeReference>() { + })); + Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), + JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), new TypeReference>>() { + })); + Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils + .toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), + new TypeReference() { + })); + Assert.assertEquals(new TestOfDate(), + JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), new TypeReference() { + })); + Assert.assertEquals(new TestOfAccessModifier(), JacksonUtils + .toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), new TypeReference() { + })); + Assert.assertEquals(new TestOfGetter(), JacksonUtils + .toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), new TypeReference() { + })); + Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils + .toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\"," + + "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(), + new TypeReference() { + })); } /** @@ -317,7 +256,8 @@ public void testToObject9() { */ @Test(expected = Exception.class) public void testToObject10() { - JacksonUtils.toObj("{not_A}Json:String}".getBytes(), new TypeReference() { }); + JacksonUtils.toObj("{not_A}Json:String}".getBytes(), new TypeReference() { + }); } /** @@ -325,16 +265,12 @@ public void testToObject10() { */ @Test public void testToObject11() { - Assert.assertEquals( - Collections.singletonMap("key", "value"), - JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), - TypeUtils.parameterize(Map.class, String.class, String.class)) - ); - Assert.assertEquals( - Collections.singletonList(Collections.singletonMap("key", "value")), - JacksonUtils.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), TypeUtils - .parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class))) - ); + Assert.assertEquals(Collections.singletonMap("key", "value"), JacksonUtils + .toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), + TypeUtils.parameterize(Map.class, String.class, String.class))); + Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), JacksonUtils + .toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), TypeUtils + .parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class)))); } /** @@ -342,10 +278,8 @@ public void testToObject11() { */ @Test(expected = Exception.class) public void testToObject12() { - JacksonUtils.toObj( - new ByteArrayInputStream("{not_A}Json:String}".getBytes()), - TypeUtils.parameterize(Map.class, String.class, String.class) - ); + JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()), + TypeUtils.parameterize(Map.class, String.class, String.class)); } /** @@ -353,9 +287,8 @@ public void testToObject12() { */ @Test(expected = Exception.class) public void testToObject13() { - JacksonUtils.toObj( - new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Object.class.getGenericSuperclass() - ); + JacksonUtils + .toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Object.class.getGenericSuperclass()); } /** @@ -363,9 +296,7 @@ public void testToObject13() { */ @Test(expected = Exception.class) public void testToObject14() { - JacksonUtils.toObj( - (InputStream) null, Object.class.getGenericSuperclass() - ); + JacksonUtils.toObj((InputStream) null, Object.class.getGenericSuperclass()); } /** @@ -395,12 +326,10 @@ public void testToObject16() { @Test public void testRegisterSubtype() { JacksonUtils.registerSubtype(TestOfChild.class, "JacksonUtilsTest$TestOfChild"); - - Assert.assertEquals( - new TestOfChild(), - JacksonUtils.toObj("{\"@type\":\"JacksonUtilsTest$TestOfChild\",\"parentField\":\"parentValue\"," - + "\"childField\":\"childValue\"}", TestOfParent.class) - ); + + Assert.assertEquals(new TestOfChild(), JacksonUtils + .toObj("{\"@type\":\"JacksonUtilsTest$TestOfChild\",\"parentField\":\"parentValue\"," + + "\"childField\":\"childValue\"}", TestOfParent.class)); } @Test @@ -420,7 +349,7 @@ public void testCreateEmptyArrayNode() { public void testTransferToJsonNode() { JsonNode jsonNode1 = JacksonUtils.transferToJsonNode(Collections.singletonMap("key", "value")); Assert.assertEquals("value", jsonNode1.get("key").asText()); - + JsonNode jsonNode2 = JacksonUtils.transferToJsonNode(new TestOfAtomicObject()); Assert.assertEquals("0", jsonNode2.get("aLong").asText()); Assert.assertEquals("1", jsonNode2.get("aInteger").asText()); @@ -432,7 +361,7 @@ public void testConstructJavaType() { Assert.assertEquals("java.lang.String", JacksonUtils.constructJavaType(String.class).getRawClass().getName()); Assert.assertTrue(JacksonUtils.constructJavaType(String.class).isFinal()); } - + @Test public void testToJsonBytes() { Map map = new LinkedHashMap(); @@ -440,7 +369,7 @@ public void testToJsonBytes() { map.put("integer", 999); RestResult> restResult = new RestResult(); restResult.setData(map); - + byte[] bytes = JacksonUtils.toJsonBytes(restResult); String jsonFromBytes = ByteUtils.toString(bytes); Assert.assertTrue(jsonFromBytes.contains("\"code\":0")); @@ -453,30 +382,48 @@ public void testToJsonBytes() { // throw new NacosSerializationException(obj.getClass(), e); // } // } - + // here is a verification to compare with the old implementation byte[] bytesFromOldImplementation = ByteUtils.toBytes(JacksonUtils.toJson(restResult)); - String jsonFromBytesOldImplementation = new String(bytesFromOldImplementation, Charset.forName(Constants.ENCODE)); + String jsonFromBytesOldImplementation = new String(bytesFromOldImplementation, + Charset.forName(Constants.ENCODE)); Assert.assertTrue(jsonFromBytesOldImplementation.contains("\"code\":0")); Assert.assertTrue(jsonFromBytesOldImplementation.contains("\"data\":{\"string\":\"你好,中国!\",\"integer\":999}")); } - + @Test public void testToObjFromBytes() { String json = "{\"code\":0,\"data\":{\"string\":\"你好,中国!\",\"integer\":999}}"; - + RestResult> restResult = JacksonUtils.toObj(json, RestResult.class); Assert.assertEquals(0, restResult.getCode()); Assert.assertEquals("你好,中国!", restResult.getData().get("string")); Assert.assertEquals(999, restResult.getData().get("integer")); - - restResult = JacksonUtils.toObj(json, new TypeReference>>() { }); + + restResult = JacksonUtils.toObj(json, new TypeReference>>() { + }); Assert.assertEquals(0, restResult.getCode()); Assert.assertEquals("你好,中国!", restResult.getData().get("string")); Assert.assertEquals(999, restResult.getData().get("integer")); } - @JsonPropertyOrder({ "aLong", "aInteger", "aBoolean"}) + @Test(expected = NacosDeserializationException.class) + public void tesToObjForClassWithException() { + JacksonUtils.toObj("aaa", JsonNode.class); + } + + @Test(expected = NacosDeserializationException.class) + public void tesToObjForTypeWithException() { + JacksonUtils.toObj("aaa", TypeUtils.parameterize(JsonNode.class)); + } + + @Test(expected = NacosDeserializationException.class) + public void tesToObjForTypeTypeReferenceWithException() { + JacksonUtils.toObj("aaa", new TypeReference() { + }); + } + + @JsonPropertyOrder({"aLong", "aInteger", "aBoolean"}) static class TestOfAtomicObject { public AtomicLong aLong = new AtomicLong(0); @@ -561,7 +508,7 @@ public int hashCode() { } } - @JsonPropertyOrder({ "value", "key" }) + @JsonPropertyOrder({"value", "key"}) static class TestOfGetter { public String getKey() { @@ -704,7 +651,7 @@ public int hashCode() { static class TestOfParent { public String parentField = "parentValue"; - + @Override public boolean equals(Object o) { if (this == o) { @@ -713,12 +660,12 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } - + TestOfParent that = (TestOfParent) o; - + return parentField != null ? parentField.equals(that.parentField) : that.parentField == null; } - + @Override public int hashCode() { return parentField != null ? parentField.hashCode() : 0; @@ -728,7 +675,7 @@ public int hashCode() { static class TestOfChild extends TestOfParent { public String childField = "childValue"; - + @Override public boolean equals(Object o) { if (this == o) { @@ -740,12 +687,12 @@ public boolean equals(Object o) { if (!super.equals(o)) { return false; } - + TestOfChild that = (TestOfChild) o; - + return childField != null ? childField.equals(that.childField) : that.childField == null; } - + @Override public int hashCode() { int result = super.hashCode(); diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/LoggerUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/LoggerUtilsTest.java new file mode 100644 index 00000000000..a7836ec617c --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/utils/LoggerUtilsTest.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package com.alibaba.nacos.common.utils; + +import org.junit.Test; +import org.mockito.Mockito; +import org.slf4j.Logger; + +public class LoggerUtilsTest { + + @Test + public void testPrintIfDebugEnabled() { + Logger logger = Mockito.mock(Logger.class); + Mockito.when(logger.isDebugEnabled()).thenReturn(true); + LoggerUtils.printIfDebugEnabled(logger, "test", "arg1", "arg2", "arg3"); + Mockito.verify(logger, Mockito.times(1)).debug("test", "arg1", "arg2", "arg3"); + } + + @Test + public void testPrintIfInfoEnabled() { + Logger logger = Mockito.mock(Logger.class); + Mockito.when(logger.isInfoEnabled()).thenReturn(true); + LoggerUtils.printIfInfoEnabled(logger, "test", "arg1", "arg2", "arg3"); + Mockito.verify(logger, Mockito.times(1)).info("test", "arg1", "arg2", "arg3"); + } + + @Test + public void testPrintIfTraceEnabled() { + Logger logger = Mockito.mock(Logger.class); + Mockito.when(logger.isTraceEnabled()).thenReturn(true); + LoggerUtils.printIfTraceEnabled(logger, "test", "arg1", "arg2", "arg3"); + Mockito.verify(logger, Mockito.times(1)).trace("test", "arg1", "arg2", "arg3"); + } + + @Test + public void testPrintIfWarnEnabled() { + Logger logger = Mockito.mock(Logger.class); + Mockito.when(logger.isWarnEnabled()).thenReturn(true); + LoggerUtils.printIfWarnEnabled(logger, "test", "arg1", "arg2", "arg3"); + Mockito.verify(logger, Mockito.times(1)).warn("test", "arg1", "arg2", "arg3"); + } + + @Test + public void testPrintIfErrorEnabled() { + Logger logger = Mockito.mock(Logger.class); + Mockito.when(logger.isErrorEnabled()).thenReturn(true); + LoggerUtils.printIfErrorEnabled(logger, "test", "arg1", "arg2", "arg3"); + Mockito.verify(logger, Mockito.times(1)).error("test", "arg1", "arg2", "arg3"); + } + +} diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/MapUtilTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/MapUtilTest.java index a170b47d983..0374d4594b0 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/MapUtilTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/MapUtilTest.java @@ -16,51 +16,135 @@ package com.alibaba.nacos.common.utils; -import org.junit.Assert; import org.junit.Test; +import org.mockito.Mockito; import java.util.Collections; +import java.util.Dictionary; import java.util.HashMap; +import java.util.Hashtable; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiFunction; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class MapUtilTest { @Test - public void testMap() { - Map map = new HashMap(); - + public void testIsEmptyAndNotEmptyMap() { + Map map = null; + assertTrue(MapUtil.isEmpty(map)); + assertFalse(MapUtil.isNotEmpty(map)); + map = new HashMap<>(); + assertTrue(MapUtil.isEmpty(map)); + assertFalse(MapUtil.isNotEmpty(map)); + map.put("a", "b"); + assertFalse(MapUtil.isEmpty(map)); + assertTrue(MapUtil.isNotEmpty(map)); + } + + @Test + public void testIsEmptyOrEmptyDictionary() { + Dictionary dictionary = null; + assertTrue(MapUtil.isEmpty(dictionary)); + assertFalse(MapUtil.isNotEmpty(dictionary)); + dictionary = new Hashtable<>(); + assertTrue(MapUtil.isEmpty(dictionary)); + assertFalse(MapUtil.isNotEmpty(dictionary)); + dictionary.put("a", "b"); + assertFalse(MapUtil.isEmpty(dictionary)); + assertTrue(MapUtil.isNotEmpty(dictionary)); + } + + @Test + public void testPutIfValNoNull() { + Map map = new HashMap<>(); MapUtil.putIfValNoNull(map, "key-1", null); - Assert.assertFalse(map.containsKey("key-1")); + assertTrue(map.isEmpty()); + MapUtil.putIfValNoNull(map, "key-1", "null"); + assertTrue(map.containsKey("key-1")); + } + + @Test + public void testPutIfValNoEmptyMap() { + Map map = new HashMap<>(); MapUtil.putIfValNoEmpty(map, "key-str", null); - Assert.assertFalse(map.containsKey("key-str")); + assertFalse(map.containsKey("key-str")); MapUtil.putIfValNoEmpty(map, "key-str", ""); - Assert.assertFalse(map.containsKey("key-str")); + assertFalse(map.containsKey("key-str")); MapUtil.putIfValNoEmpty(map, "key-str", "1"); - Assert.assertTrue(map.containsKey("key-str")); + assertTrue(map.containsKey("key-str")); MapUtil.putIfValNoEmpty(map, "key-list", null); - Assert.assertFalse(map.containsKey("key-list")); + assertFalse(map.containsKey("key-list")); MapUtil.putIfValNoEmpty(map, "key-list", Collections.emptyList()); - Assert.assertFalse(map.containsKey("key-list")); + assertFalse(map.containsKey("key-list")); MapUtil.putIfValNoEmpty(map, "key-list", Collections.singletonList(1)); - Assert.assertTrue(map.containsKey("key-list")); + assertTrue(map.containsKey("key-list")); MapUtil.putIfValNoEmpty(map, "key-map", null); - Assert.assertFalse(map.containsKey("key-map")); + assertFalse(map.containsKey("key-map")); MapUtil.putIfValNoEmpty(map, "key-map", Collections.emptyMap()); - Assert.assertFalse(map.containsKey("key-map")); + assertFalse(map.containsKey("key-map")); - Map map1 = new HashMap(); + Map map1 = new HashMap<>(); map1.put("1123", "123"); MapUtil.putIfValNoEmpty(map, "key-map", map1); - Assert.assertTrue(map.containsKey("key-map")); + assertTrue(map.containsKey("key-map")); + + Dictionary dictionary = Mockito.mock(Dictionary.class); + when(dictionary.isEmpty()).thenReturn(true); + MapUtil.putIfValNoEmpty(map, "key-dict", dictionary); + assertFalse(map.containsKey("key-dict")); + when(dictionary.isEmpty()).thenReturn(false); + MapUtil.putIfValNoEmpty(map, "key-dict", dictionary); + assertTrue(map.containsKey("key-dict")); + } + + @Test + public void testComputeIfAbsent() { + Map target = new HashMap<>(); + String key = "key"; + String param1 = "param1"; + String param2 = "param2"; + BiFunction mappingFunction = (p1, p2) -> p1 + p2; + + String result = MapUtil.computeIfAbsent(target, key, mappingFunction, param1, param2); + assertEquals("param1param2", result); + + // Test that the mappingFunction is only called once + AtomicInteger counter = new AtomicInteger(); + mappingFunction = (p1, p2) -> { + counter.incrementAndGet(); + return p1 + p2; + }; + + result = MapUtil.computeIfAbsent(target, key, mappingFunction, param1, param2); + assertEquals("param1param2", result); + assertEquals(0, counter.get()); } + @Test + public void testRemoveKey() { + Map map = new HashMap<>(); + map.put("A", 1); + map.put("B", 2); + map.put("C", 3); + + MapUtil.removeKey(map, "B", integer -> integer == 1); + assertEquals(3, map.size()); + MapUtil.removeKey(map, "B", integer -> integer == 2); + assertEquals(2, map.size()); + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java index c653a5e1bf8..ff399a7119b 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java @@ -16,6 +16,7 @@ package com.alibaba.nacos.common.utils; +import org.junit.After; import org.junit.Assert; import org.junit.Test; @@ -27,6 +28,11 @@ */ public class NamespaceUtilTest { + @After + public void tearDown() { + NamespaceUtil.setNamespaceDefaultId(""); + } + @Test public void testProcessTenantParameter() { String strPublic = "public"; @@ -44,4 +50,9 @@ public void testProcessTenantParameter() { Assert.assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbcHasSpace)); } + @Test + public void testSetNamespaceDefaultId() { + NamespaceUtil.setNamespaceDefaultId("Deprecated"); + Assert.assertEquals("Deprecated", NamespaceUtil.getNamespaceDefaultId()); + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ObservableTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ObservableTest.java new file mode 100644 index 00000000000..0142fff7546 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ObservableTest.java @@ -0,0 +1,85 @@ +/* + * 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. + */ + +package com.alibaba.nacos.common.utils; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; + +@RunWith(MockitoJUnitRunner.class) +public class ObservableTest { + + @Mock + private Observer observer; + + private Observable observable; + + @Before + public void setUp() throws Exception { + observable = new Observable(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testAddObserver() { + observable.addObserver(observer); + assertEquals(1, observable.countObservers()); + verify(observer).update(observable); + } + + @Test + public void testDeleteObserver() { + observable.addObserver(observer); + assertEquals(1, observable.countObservers()); + observable.deleteObserver(observer); + assertEquals(0, observable.countObservers()); + } + + @Test + public void testNotifyObservers() { + observable.addObserver(observer); + reset(observer); + observable.notifyObservers(); + assertFalse(observable.hasChanged()); + verify(observer, never()).update(observable); + observable.setChanged(); + assertTrue(observable.hasChanged()); + observable.notifyObservers(); + verify(observer).update(observable); + assertFalse(observable.hasChanged()); + } + + @Test + public void testDeleteObservers() { + observable.addObserver(observer); + observable.deleteObservers(); + assertEquals(1, observable.countObservers()); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/PairTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/PairTest.java new file mode 100644 index 00000000000..511bdfc80b9 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/utils/PairTest.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package com.alibaba.nacos.common.utils; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class PairTest { + + @Test + public void testPair() { + Pair pair = Pair.with("a", "b"); + assertEquals("a", pair.getFirst()); + assertEquals("b", pair.getSecond()); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/RandomUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/RandomUtilsTest.java index 76ec4ecaf0f..8ba35941e2f 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/RandomUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/RandomUtilsTest.java @@ -21,19 +21,42 @@ /** * test RandomUtils. + * * @author zzq */ public class RandomUtilsTest { @Test - public void nextLong() { + public void testNextLong() { final long result = RandomUtils.nextLong(1L, 199L); Assert.assertTrue(result >= 1L && result < 199L); } @Test - public void nextInt() { + public void testNextLongWithSame() { + final long result = RandomUtils.nextLong(1L, 1L); + Assert.assertEquals(1L, result); + } + + @Test(expected = IllegalArgumentException.class) + public void testNextLongWithIllegalArgumentException() { + RandomUtils.nextLong(999L, 199L); + } + + @Test(expected = IllegalArgumentException.class) + public void testNextLongWithIllegalArgumentException2() { + RandomUtils.nextLong(-10L, 199L); + } + + @Test + public void testNextInt() { final int result = RandomUtils.nextInt(1, 199); Assert.assertTrue(result >= 1 && result < 199); } + + @Test + public void testNextIntWithSame() { + final int result = RandomUtils.nextInt(1, 1); + Assert.assertEquals(1, result); + } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ReflectUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ReflectUtilsTest.java index 88f0fa67819..327665121e8 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ReflectUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ReflectUtilsTest.java @@ -20,7 +20,11 @@ import org.junit.Before; import org.junit.Test; +import java.io.IOException; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.UndeclaredThrowableException; import java.util.ArrayList; import java.util.List; @@ -31,38 +35,101 @@ * @date 2022/08/19 */ public class ReflectUtilsTest { - + List listStr; - + @Before public void before() { listStr = new ArrayList<>(2); } - + @Test - public void getFieldValue() { + public void testGetFieldValue() { Object elementData = ReflectUtils.getFieldValue(listStr, "elementData"); Assert.assertTrue(elementData instanceof Object[]); - Assert.assertEquals(((Object[]) elementData).length, 2); + Assert.assertEquals(2, ((Object[]) elementData).length); } - + + @Test(expected = RuntimeException.class) + public void testGetFieldValueWithoutField() { + ReflectUtils.getFieldValue(listStr, "elementDataxx"); + } + @Test - public void getFieldValue2() { + public void testGetFieldValueWithDefault() { Object elementData = ReflectUtils.getFieldValue(listStr, "elementDataxx", 3); Assert.assertEquals(elementData, 3); + elementData = ReflectUtils.getFieldValue(listStr, "elementData", 3); + Assert.assertTrue(elementData instanceof Object[]); + Assert.assertEquals(2, ((Object[]) elementData).length); } - + @Test - public void getField() { + public void testGetField() throws NoSuchFieldException { + Field field = listStr.getClass().getDeclaredField("elementData"); + field.setAccessible(true); + Object elementData = ReflectUtils.getField(field, listStr); + Assert.assertTrue(elementData instanceof Object[]); + } + + @Test(expected = IllegalStateException.class) + public void testGetFieldWithoutAccess() throws NoSuchFieldException { + Field field = listStr.getClass().getDeclaredField("elementData"); + ReflectUtils.getField(field, listStr); + } + + @Test + public void testInvokeMethod() throws Exception { + Method method = listStr.getClass().getDeclaredMethod("grow", int.class); + method.setAccessible(true); + ReflectUtils.invokeMethod(method, listStr, 4); + Object elementData = ReflectUtils.getFieldValue(listStr, "elementData"); + Assert.assertEquals(4, ((Object[]) elementData).length); + } + + @Test(expected = IllegalStateException.class) + public void testInvokeMethodWithoutAccess() throws Exception { + Method method = listStr.getClass().getDeclaredMethod("grow", int.class); + ReflectUtils.invokeMethod(method, listStr, 4); + } + + @Test(expected = UndeclaredThrowableException.class) + public void testHandleReflectionException() { try { - Field field = listStr.getClass().getDeclaredField("elementData"); - field.setAccessible(true); - Object elementData = ReflectUtils.getField(field, listStr); - Assert.assertTrue(elementData instanceof Object[]); - } catch (NoSuchFieldException e) { - e.printStackTrace(); + NoSuchMethodException exception = new NoSuchMethodException("test"); + ReflectUtils.handleReflectionException(exception); + } catch (Exception e) { + Assert.assertEquals("Method not found: test", e.getMessage()); } - + try { + IllegalAccessException exception = new IllegalAccessException("test"); + ReflectUtils.handleReflectionException(exception); + } catch (Exception e) { + Assert.assertEquals("Could not access method or field: test", e.getMessage()); + } + RuntimeException exception = new RuntimeException("test"); + try { + ReflectUtils.handleReflectionException(exception); + } catch (Exception e) { + Assert.assertEquals(exception, e); + } + try { + InvocationTargetException invocationTargetException = new InvocationTargetException(exception); + ReflectUtils.handleReflectionException(invocationTargetException); + } catch (Exception e) { + Assert.assertEquals(exception, e); + } + ReflectUtils.handleReflectionException(new IOException()); + } + + @Test(expected = UndeclaredThrowableException.class) + public void testRethrowRuntimeException() { + ClassFormatError error = new ClassFormatError("test"); + try { + ReflectUtils.rethrowRuntimeException(error); + } catch (Error e) { + Assert.assertEquals(error, e); + } + ReflectUtils.rethrowRuntimeException(new IOException()); } - } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ResourceUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ResourceUtilsTest.java new file mode 100644 index 00000000000..d678532572b --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ResourceUtilsTest.java @@ -0,0 +1,147 @@ +/* + * 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. + */ + +package com.alibaba.nacos.common.utils; + +import org.junit.Test; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.net.URL; +import java.util.Properties; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class ResourceUtilsTest { + + @Test + public void testGetResourceUrlForClasspath() throws IOException { + URL url = ResourceUtils.getResourceUrl("classpath:test-tls-cert.pem"); + assertNotNull(url); + } + + @Test(expected = FileNotFoundException.class) + public void testGetResourceUrlForClasspathNotExists() throws IOException { + ResourceUtils.getResourceUrl("classpath:non-exist.pem"); + } + + @Test + public void testGetResourceUrlForFile() throws IOException { + File file = File.createTempFile("test", ".txt"); + try { + URL url = ResourceUtils.getResourceUrl("file://" + file.getPath()); + assertNotNull(url); + } finally { + file.deleteOnExit(); + } + } + + @Test + public void testGetResourceUrlForFileWithoutProtocol() throws IOException { + File file = File.createTempFile("test", ".txt"); + try { + URL url = ResourceUtils.getResourceUrl(file.getPath()); + assertNotNull(url); + } finally { + file.deleteOnExit(); + } + } + + @Test + public void testGetResourceUrlFromLoader() throws IOException { + URL url = ResourceUtils.getResourceUrl(this.getClass().getClassLoader(), "test-tls-cert.pem"); + assertNotNull(url); + } + + @Test + public void testGetResourceUrlFromSystemLoader() throws IOException { + URL url = ResourceUtils.getResourceUrl(null, "test-tls-cert.pem"); + assertNotNull(url); + } + + @Test(expected = IOException.class) + public void testGetResourceUrlFromLoaderWithoutExist() throws IOException { + URL url = ResourceUtils.getResourceUrl(null, "non-exist"); + assertNotNull(url); + } + + @Test + public void testGetResourceAsStreamForClasspath() throws IOException { + try (InputStream inputStream = ResourceUtils.getResourceAsStream("test-tls-cert.pem")) { + assertNotNull(inputStream); + } + } + + @Test + public void testGetResourceAsStreamForClasspathFromSystem() throws IOException { + try (InputStream inputStream = ResourceUtils.getResourceAsStream(null, "test-tls-cert.pem")) { + assertNotNull(inputStream); + } + } + + @Test(expected = IOException.class) + public void testGetResourceAsStreamForClasspathWithoutExist() throws IOException { + URL url = ResourceUtils.getResourceUrl("non-exist"); + ResourceUtils.getResourceAsStream(null, url.toString()); + } + + @Test + public void testGetResourceAsPropertiesForClasspath() throws IOException { + Properties properties = ResourceUtils.getResourceAsProperties("resource_utils_test.properties"); + assertNotNull(properties); + assertTrue(properties.containsKey("a")); + } + + @Test + public void testGetResourceAsReader() throws IOException { + try (Reader reader = ResourceUtils.getResourceAsReader("resource_utils_test.properties", "UTF-8")) { + assertNotNull(reader); + } + } + + @Test + public void testGetResourceAsReaderWithLoader() throws IOException { + try (Reader reader = ResourceUtils + .getResourceAsReader(ResourceUtilsTest.class.getClassLoader(), "resource_utils_test.properties", + "UTF-8")) { + assertNotNull(reader); + } + } + + @Test + public void testGetResourceAsFile() throws IOException { + File file = ResourceUtils.getResourceAsFile("classpath:resource_utils_test.properties"); + assertNotNull(file); + } + + @Test + public void testGetResourceAsFileByUrl() throws IOException { + File file = ResourceUtils + .getResourceAsFile(ResourceUtils.getResourceUrl("classpath:resource_utils_test.properties")); + assertNotNull(file); + } + + @Test + public void testGetResourceAsFileByLoader() throws IOException { + File file = ResourceUtils + .getResourceAsFile(ResourceUtils.class.getClassLoader(), "resource_utils_test.properties"); + assertNotNull(file); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/StringUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/StringUtilsTest.java index d60c4752460..143c76e83f9 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/StringUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/StringUtilsTest.java @@ -24,6 +24,7 @@ /** * String utils. + * * @author zzq */ public class StringUtilsTest { @@ -77,7 +78,24 @@ public void testDefaultIfEmpty() { Assert.assertEquals("NULL", StringUtils.defaultIfEmpty("", "NULL")); Assert.assertEquals(" ", StringUtils.defaultIfEmpty(" ", "NULL")); Assert.assertEquals("bat", StringUtils.defaultIfEmpty("bat", "NULL")); - Assert.assertEquals(null, StringUtils.defaultIfEmpty("", null)); + Assert.assertNull(StringUtils.defaultIfEmpty("", null)); + } + + @Test + public void testDefaultIfBlank() { + Assert.assertEquals("NULL", StringUtils.defaultIfBlank(null, "NULL")); + Assert.assertEquals("NULL", StringUtils.defaultIfBlank("", "NULL")); + Assert.assertEquals("NULL", StringUtils.defaultIfBlank(" ", "NULL")); + Assert.assertEquals("bat", StringUtils.defaultIfBlank("bat", "NULL")); + Assert.assertNull(StringUtils.defaultIfBlank("", null)); + } + + @Test + public void testDefaultEmptyIfBlank() { + Assert.assertEquals("", StringUtils.defaultEmptyIfBlank(null)); + Assert.assertEquals("", StringUtils.defaultEmptyIfBlank("")); + Assert.assertEquals("", StringUtils.defaultEmptyIfBlank(" ")); + Assert.assertEquals("bat", StringUtils.defaultEmptyIfBlank("bat")); } @Test @@ -125,11 +143,6 @@ public void testJoin() { Assert.assertEquals("abc", StringUtils.join(Arrays.asList("a", "b", "c"), null)); } - @Test - public void escapeJavaScript() { - //TODO - } - @Test public void testContainsIgnoreCase() { Assert.assertFalse(StringUtils.containsIgnoreCase(null, "1")); @@ -185,6 +198,7 @@ public void testStartsWith() { Assert.assertFalse(StringUtils.startsWith("abcdef", null)); Assert.assertTrue(StringUtils.startsWith("abcdef", "abc")); Assert.assertFalse(StringUtils.startsWith("ABCDEF", "abc")); + Assert.assertFalse(StringUtils.startsWith("ABC", "ABCDEF")); } @Test @@ -217,8 +231,283 @@ public void testEqualsIgnoreCase() { public void testSplit() { Assert.assertNull(StringUtils.split(null, ",")); Assert.assertArrayEquals(new String[0], StringUtils.split("", ",")); - Assert.assertArrayEquals(new String[]{"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null)); - Assert.assertArrayEquals(new String[]{"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null)); - Assert.assertArrayEquals(new String[]{"ab", "cd", "ef"}, StringUtils.split("ab:cd:ef", ":")); + Assert.assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null)); + Assert.assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null)); + Assert.assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab:cd:ef", ":")); + } + + @Test + public void testTokenizeToStringArray() { + // Test case 1: Empty string + String str1 = ""; + String delimiters1 = ","; + boolean trimTokens1 = true; + boolean ignoreEmptyTokens1 = false; + String[] expected1 = new String[0]; + String[] result1 = StringUtils.tokenizeToStringArray(str1, delimiters1, trimTokens1, ignoreEmptyTokens1); + Assert.assertArrayEquals(expected1, result1); + + // Test case 2: Null string + String str2 = null; + String delimiters2 = " "; + boolean trimTokens2 = false; + boolean ignoreEmptyTokens2 = true; + String[] expected2 = new String[0]; + String[] result2 = StringUtils.tokenizeToStringArray(str2, delimiters2, trimTokens2, ignoreEmptyTokens2); + Assert.assertArrayEquals(expected2, result2); + + // Test case 3: Single token + String str3 = "Hello"; + String delimiters3 = ","; + boolean trimTokens3 = true; + boolean ignoreEmptyTokens3 = false; + String[] expected3 = {"Hello"}; + String[] result3 = StringUtils.tokenizeToStringArray(str3, delimiters3, trimTokens3, ignoreEmptyTokens3); + Assert.assertArrayEquals(expected3, result3); + + // Test case 4: Multiple tokens with trimming + String str4 = " Hello, World, "; + String delimiters4 = ","; + boolean trimTokens4 = true; + boolean ignoreEmptyTokens4 = false; + String[] expected4 = {"Hello", "World", ""}; + String[] result4 = StringUtils.tokenizeToStringArray(str4, delimiters4, trimTokens4, ignoreEmptyTokens4); + Assert.assertArrayEquals(expected4, result4); + + // Test case 5: Multiple tokens with empty tokens ignored + String str5 = " ,Hello, ,World, "; + String delimiters5 = ","; + boolean trimTokens5 = true; + boolean ignoreEmptyTokens5 = true; + String[] expected5 = {"Hello", "World"}; + String[] result5 = StringUtils.tokenizeToStringArray(str5, delimiters5, trimTokens5, ignoreEmptyTokens5); + Assert.assertArrayEquals(expected5, result5); + } + + @Test + public void testHasText() { + // Test case 1: Empty string + Assert.assertFalse(StringUtils.hasText("")); + + // Test case 2: String with whitespace only + Assert.assertFalse(StringUtils.hasText(" ")); + + // Test case 3: Null string + Assert.assertFalse(StringUtils.hasText(null)); + + // Test case 4: String with non-whitespace characters + Assert.assertTrue(StringUtils.hasText("hello")); + + // Test case 5: String with both text and whitespace + Assert.assertTrue(StringUtils.hasText(" hello ")); + } + + @Test + public void testCleanPath() { + // Test case 1: path with no length + String path1 = ""; + String expected1 = ""; + Assert.assertEquals(expected1, StringUtils.cleanPath(path1)); + + // Test case 2: normal path + String path2 = "path/to/file"; + String expected2 = "path/to/file"; + Assert.assertEquals(expected2, StringUtils.cleanPath(path2)); + + // Test case 3: path with Windows folder separator + String path3 = "path\\to\\文件"; + String expected3 = "path/to/文件"; + Assert.assertEquals(expected3, StringUtils.cleanPath(path3)); + + // Test case 4: path with dot + String path4 = "path/.."; + String expected4 = ""; + Assert.assertEquals(expected4, StringUtils.cleanPath(path4)); + + // Test case 5: path with top path + String path5 = "path/../top"; + String expected5 = "top"; + Assert.assertEquals(expected5, StringUtils.cleanPath(path5)); + + // Test case 6: path with multiple top path + String path6 = "path/../../top"; + String expected6 = "../top"; + Assert.assertEquals(expected6, StringUtils.cleanPath(path6)); + + // Test case 7: path with leading colon + String path7 = "file:../top"; + String expected7 = "file:../top"; + Assert.assertEquals(expected7, StringUtils.cleanPath(path7)); + + // Test case 8: path with leading slash + String path8 = "file:/path/../file"; + String expected8 = "file:/file"; + Assert.assertEquals(expected8, StringUtils.cleanPath(path8)); + + // Test case 9: path with empty prefix + String path9 = "file:path/../file"; + String expected9 = "file:file"; + Assert.assertEquals(expected9, StringUtils.cleanPath(path9)); + + // Test case 10: prefix contain separator + String path10 = "file/:path/../file"; + String expected10 = "file/file"; + Assert.assertEquals(expected10, StringUtils.cleanPath(path10)); + + // Test case 11: dot in file name + String path11 = "file:/path/to/file.txt"; + String expected11 = "file:/path/to/file.txt"; + Assert.assertEquals(expected11, StringUtils.cleanPath(path11)); + + // Test case 12: dot in path + String path12 = "file:/path/./file.txt"; + String expected12 = "file:/path/file.txt"; + Assert.assertEquals(expected12, StringUtils.cleanPath(path12)); + + // Test case 13: path with dot and slash + String path13 = "file:aaa/../"; + String expected13 = "file:./"; + Assert.assertEquals(expected13, StringUtils.cleanPath(path13)); + } + + @Test + public void testDelimitedListToStringArrayWithNull() { + Assert.assertEquals(0, StringUtils.delimitedListToStringArray(null, ",", "").length); + Assert.assertEquals(1, StringUtils.delimitedListToStringArray("a,b", null, "").length); + } + + @Test + public void testDelimitedListToStringArrayWithEmptyDelimiter() { + String testCase = "a,b"; + String[] actual = StringUtils.delimitedListToStringArray(testCase, "", ""); + Assert.assertEquals(3, actual.length); + Assert.assertEquals("a", actual[0]); + Assert.assertEquals(",", actual[1]); + Assert.assertEquals("b", actual[2]); + } + + @Test + public void testDeleteAny() { + // Test case 1: inString is empty, charsToDelete is empty + String inString1 = ""; + String charsToDelete1 = ""; + Assert.assertEquals("", StringUtils.deleteAny(inString1, charsToDelete1)); + + // Test case 2: inString is empty, charsToDelete is not empty + String inString2 = ""; + String charsToDelete2 = "abc"; + Assert.assertEquals("", StringUtils.deleteAny(inString2, charsToDelete2)); + + // Test case 3: inString is not empty, charsToDelete is empty + String inString3 = "abc"; + String charsToDelete3 = ""; + Assert.assertEquals("abc", StringUtils.deleteAny(inString3, charsToDelete3)); + + // Test case 4: inString is not empty, charsToDelete is not empty + String inString4 = "abc"; + String charsToDelete4 = "a"; + Assert.assertEquals("bc", StringUtils.deleteAny(inString4, charsToDelete4)); + + // Test case 5: inString contains special characters + String inString5 = "abc\n"; + String charsToDelete5 = "\n"; + Assert.assertEquals("abc", StringUtils.deleteAny(inString5, charsToDelete5)); + + // Test case 6: inString not contains special characters + String inString6 = "abc\n"; + String charsToDelete6 = "d"; + Assert.assertEquals("abc\n", StringUtils.deleteAny(inString6, charsToDelete6)); + } + + @Test + public void testReplace() { + // Test case 1: pattern is empty + Assert.assertEquals("abc", StringUtils.replace("abc", "", "a")); + + // Test case 2: oldPattern less than newPattern + Assert.assertEquals("aabc", StringUtils.replace("abc", "a", "aa")); + + // Test case 3: oldPattern more than newPattern + Assert.assertEquals("dc", StringUtils.replace("abc", "ab", "d")); + } + + @Test + public void testApplyRelativePath() { + // Test case 1 + String path1 = "/path/to/file"; + String relativePath1 = "subfolder/subfile"; + String expected1 = "/path/to/subfolder/subfile"; + String result1 = StringUtils.applyRelativePath(path1, relativePath1); + Assert.assertEquals(expected1, result1); + + // Test case 2 + String path2 = "path/to/file"; + String relativePath2 = "subfolder/subfile"; + String expected2 = "path/to/subfolder/subfile"; + String result2 = StringUtils.applyRelativePath(path2, relativePath2); + Assert.assertEquals(expected2, result2); + + // Test case 3 + String path3 = "/path/to/file"; + String relativePath3 = "/subfolder/subfile"; + String expected3 = "/path/to/subfolder/subfile"; + String result3 = StringUtils.applyRelativePath(path3, relativePath3); + Assert.assertEquals(expected3, result3); + + //Test case 4 + String path4 = "file"; + String relativePath4 = "/subfolder/subfile"; + String expected4 = "/subfolder/subfile"; + String result4 = StringUtils.applyRelativePath(path4, relativePath4); + Assert.assertEquals(expected4, result4); + } + + @Test + public void testGetFilename() { + // Test case 1: null path + String path1 = null; + String result1 = StringUtils.getFilename(path1); + Assert.assertNull(result1); + + // Test case 2: path without separator + String path2 = "myFile.txt"; + String expectedResult2 = "myFile.txt"; + String result2 = StringUtils.getFilename(path2); + Assert.assertEquals(expectedResult2, result2); + + // Test case 3: path with separator + String path3 = "myPath/myFile.txt"; + String expectedResult3 = "myFile.txt"; + String result3 = StringUtils.getFilename(path3); + Assert.assertEquals(expectedResult3, result3); + + // Test case 4: path with multiple separators + String path4 = "myPath/subPath/myFile.txt"; + String expectedResult4 = "myFile.txt"; + String result4 = StringUtils.getFilename(path4); + Assert.assertEquals(expectedResult4, result4); + } + + @Test + public void testCapitalize() { + // Test for an empty string + String str1 = ""; + Assert.assertEquals("", StringUtils.capitalize(str1)); + + // Test for a single word string + String str2 = "hello"; + Assert.assertEquals("Hello", StringUtils.capitalize(str2)); + + // Test for a multiple word string + String str3 = "hello world"; + Assert.assertEquals("Hello world", StringUtils.capitalize(str3)); + + // Test for a string with special characters + String str4 = "!@#$%^&*()"; + Assert.assertEquals("!@#$%^&*()", StringUtils.capitalize(str4)); + + // Test for a string with numbers + String str5 = "abc123"; + Assert.assertEquals("Abc123", StringUtils.capitalize(str5)); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ThreadUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ThreadUtilsTest.java new file mode 100644 index 00000000000..e6ea4f1b82c --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ThreadUtilsTest.java @@ -0,0 +1,105 @@ +/* + * 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. + */ + +package com.alibaba.nacos.common.utils; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class ThreadUtilsTest { + + private ExecutorService executorService; + + @Before + public void setUp() throws Exception { + System.setProperty("nacos.common.processors", "2"); + executorService = Executors.newFixedThreadPool(1); + } + + @After + public void tearDown() throws Exception { + System.setProperty("nacos.common.processors", ""); + ThreadUtils.shutdownThreadPool(executorService); + } + + @Test + public void testLatchAwait() { + final CountDownLatch countDownLatch = new CountDownLatch(1); + long currentTime = System.currentTimeMillis(); + executorService.execute(() -> { + ThreadUtils.sleep(100); + ThreadUtils.countDown(countDownLatch); + }); + ThreadUtils.latchAwait(countDownLatch); + assertTrue(System.currentTimeMillis() - currentTime >= 100); + } + + @Test + public void testLatchAwaitForTimeout() { + final CountDownLatch countDownLatch = new CountDownLatch(1); + long currentTime = System.currentTimeMillis(); + ThreadUtils.latchAwait(countDownLatch, 50, TimeUnit.MILLISECONDS); + assertTrue(System.currentTimeMillis() - currentTime >= 50); + + } + + @Test + public void testGetSuitableThreadCount() { + assertEquals(4, ThreadUtils.getSuitableThreadCount()); + assertEquals(8, ThreadUtils.getSuitableThreadCount(3)); + } + + @Test + public void testShutdownThreadPoolWithInterruptedException() throws InterruptedException { + ExecutorService executor = mock(ExecutorService.class); + when(executor.awaitTermination(100, TimeUnit.MILLISECONDS)).thenThrow(new InterruptedException()); + ThreadUtils.shutdownThreadPool(executor); + verify(executor, times(4)).shutdownNow(); + } + + @Test + public void testShutdownThreadPoolWithOtherException() throws InterruptedException { + ExecutorService executor = mock(ExecutorService.class); + Logger logger = mock(Logger.class); + Throwable cause = new RuntimeException(); + when(executor.awaitTermination(100, TimeUnit.MILLISECONDS)).thenThrow(cause); + ThreadUtils.shutdownThreadPool(executor, logger); + verify(executor).shutdownNow(); + verify(logger, times(3)).error("ThreadPoolManager shutdown executor has error : ", cause); + } + + @Test + public void testAddShutdownHook() { + Runnable shutdownHook = () -> { + }; + ThreadUtils.addShutdownHook(shutdownHook); + // It seems no way to check it. + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/TlsTypeResolveTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/TlsTypeResolveTest.java index 97f0f46fbe1..40ac12d35ed 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/TlsTypeResolveTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/TlsTypeResolveTest.java @@ -36,6 +36,8 @@ public void test() { SslProvider anySsl = TlsTypeResolve.getSslProvider("anySSL"); Assert.assertEquals(SslProvider.OPENSSL, anySsl); - + + SslProvider refcnt = TlsTypeResolve.getSslProvider("openSSL_refcnt"); + Assert.assertEquals(SslProvider.OPENSSL_REFCNT, refcnt); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/TypeUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/TypeUtilsTest.java index ed47bc31bd3..0e98c560b52 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/TypeUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/TypeUtilsTest.java @@ -20,6 +20,7 @@ import org.junit.Test; import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.util.List; import java.util.Map; @@ -34,9 +35,38 @@ public class TypeUtilsTest { public void parameterize() { ParameterizedType stringComparableType = TypeUtils.parameterize(List.class, String.class); Assert.assertEquals("java.util.List", stringComparableType.toString()); + Assert.assertEquals(List.class, stringComparableType.getRawType()); + Assert.assertNull(stringComparableType.getOwnerType()); + Assert.assertEquals(1, stringComparableType.getActualTypeArguments().length); + Assert.assertEquals(String.class, stringComparableType.getActualTypeArguments()[0]); ParameterizedType stringIntegerComparableType = TypeUtils.parameterize(Map.class, String.class, Integer.class); Assert.assertEquals("java.util.Map", stringIntegerComparableType.toString()); + Assert.assertEquals(Map.class, stringIntegerComparableType.getRawType()); + Assert.assertNull(stringComparableType.getOwnerType()); + Assert.assertEquals(2, stringIntegerComparableType.getActualTypeArguments().length); + Assert.assertEquals(String.class, stringIntegerComparableType.getActualTypeArguments()[0]); + Assert.assertEquals(Integer.class, stringIntegerComparableType.getActualTypeArguments()[1]); + } + + @Test(expected = NullPointerException.class) + public void testParameterizeForNull() { + TypeUtils.parameterize(null, String.class); + } + + @Test(expected = NullPointerException.class) + public void testParameterizeForNullType() { + TypeUtils.parameterize(List.class, (Type[]) null); + } + + @Test(expected = IllegalArgumentException.class) + public void testParameterizeForNullTypeArray() { + TypeUtils.parameterize(List.class, (Type) null); + } + + @Test(expected = IllegalArgumentException.class) + public void testParameterizeForDiffLength() { + TypeUtils.parameterize(List.class, String.class, Integer.class); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/UuidUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/UuidUtilsTest.java new file mode 100644 index 00000000000..1d40252d1e0 --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/utils/UuidUtilsTest.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package com.alibaba.nacos.common.utils; + +import org.junit.Test; + +import java.util.UUID; + +public class UuidUtilsTest { + + @Test + public void testGenerateUuid() { + String uuid = UuidUtils.generateUuid(); + // try parse to UUID. + UUID.fromString(uuid); + } +} \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/VersionUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/VersionUtilsTest.java index 02412a0a6b4..4978a1cb039 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/VersionUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/VersionUtilsTest.java @@ -87,4 +87,9 @@ public void testVersionCompareVersionNotValid3() { VersionUtils.compareVersion("1.2.1.1", "1.2.1"); } + @Test + public void testFullClientVersion() { + Assert.assertNotNull(VersionUtils.getFullClientVersion()); + Assert.assertTrue(VersionUtils.getFullClientVersion().startsWith("Nacos-Java-Client:v")); + } } \ No newline at end of file diff --git a/common/src/test/resources/resource_utils_test.properties b/common/src/test/resources/resource_utils_test.properties new file mode 100644 index 00000000000..4d96b9daa10 --- /dev/null +++ b/common/src/test/resources/resource_utils_test.properties @@ -0,0 +1,17 @@ +# +# 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. +# + +a=b \ No newline at end of file diff --git a/console-ui/src/components/ShowCodeing/ShowCodeing.js b/console-ui/src/components/ShowCodeing/ShowCodeing.js index 0039c746397..f5f18f57bdf 100644 --- a/console-ui/src/components/ShowCodeing/ShowCodeing.js +++ b/console-ui/src/components/ShowCodeing/ShowCodeing.js @@ -165,7 +165,7 @@ public class ConfigExample { configService.addListener(dataId, group, new Listener() { @Override public void receiveConfigInfo(String configInfo) { - System.out.println("recieve:" + configInfo); + System.out.println("receive:" + configInfo); } @Override @@ -276,7 +276,7 @@ class Program { public void ReceiveConfigInfo(string configInfo) { - Console.WriteLine("recieve:" + configInfo); + Console.WriteLine("receive:" + configInfo); } } } diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsContextBuilderTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsContextBuilderTest.java index 7a8224bb779..f947a367a83 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsContextBuilderTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsContextBuilderTest.java @@ -18,14 +18,23 @@ import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; +import com.alibaba.nacos.sys.env.EnvUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.mock.env.MockEnvironment; + +import java.lang.reflect.Field; public class DefaultTlsContextBuilderTest { + private ConfigurableEnvironment environment; + @Before public void setUp() throws Exception { + environment = new MockEnvironment(); + EnvUtil.setEnvironment(environment); RpcServerTlsConfig.getInstance().setEnableTls(true); } @@ -40,6 +49,7 @@ public void tearDown() throws Exception { RpcServerTlsConfig.getInstance().setProtocols(null); RpcServerTlsConfig.getInstance().setTrustCollectionCertFile(null); RpcServerTlsConfig.getInstance().setSslProvider(""); + clearRpcServerTlsConfigInstance(); } @Test(expected = IllegalArgumentException.class) @@ -101,4 +111,10 @@ public void testGetSslContextForNonExistFile() { grpcServerConfig.setCertChainFile("non-exist-cert.pem"); DefaultTlsContextBuilder.getSslContext(RpcServerTlsConfig.getInstance()); } + + private static void clearRpcServerTlsConfigInstance() throws Exception { + Field instanceField = RpcServerTlsConfig.class.getDeclaredField("instance"); + instanceField.setAccessible(true); + instanceField.set(null, null); + } } \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsProtocolNegotiatorBuilderTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsProtocolNegotiatorBuilderTest.java index ac8be81b618..24e0a6fd782 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsProtocolNegotiatorBuilderTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsProtocolNegotiatorBuilderTest.java @@ -17,19 +17,28 @@ package com.alibaba.nacos.core.remote.grpc.negotiator.tls; import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; +import com.alibaba.nacos.sys.env.EnvUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.mock.env.MockEnvironment; + +import java.lang.reflect.Field; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class DefaultTlsProtocolNegotiatorBuilderTest { + private ConfigurableEnvironment environment; + private DefaultTlsProtocolNegotiatorBuilder builder; @Before public void setUp() throws Exception { + environment = new MockEnvironment(); + EnvUtil.setEnvironment(environment); builder = new DefaultTlsProtocolNegotiatorBuilder(); } @@ -38,6 +47,7 @@ public void tearDown() throws Exception { RpcServerTlsConfig.getInstance().setEnableTls(false); RpcServerTlsConfig.getInstance().setCertChainFile(null); RpcServerTlsConfig.getInstance().setCertPrivateKey(null); + clearRpcServerTlsConfigInstance(); } @Test @@ -52,4 +62,10 @@ public void testBuildEnabled() { RpcServerTlsConfig.getInstance().setCertChainFile("test-server-cert.pem"); assertNotNull(builder.build()); } + + private static void clearRpcServerTlsConfigInstance() throws Exception { + Field instanceField = RpcServerTlsConfig.class.getDeclaredField("instance"); + instanceField.setAccessible(true); + instanceField.set(null, null); + } } \ No newline at end of file diff --git a/plugin/control/src/main/java/com/alibaba/nacos/plugin/control/connection/response/ConnectionCheckCode.java b/plugin/control/src/main/java/com/alibaba/nacos/plugin/control/connection/response/ConnectionCheckCode.java index 60d35f5dcc2..692d189782d 100644 --- a/plugin/control/src/main/java/com/alibaba/nacos/plugin/control/connection/response/ConnectionCheckCode.java +++ b/plugin/control/src/main/java/com/alibaba/nacos/plugin/control/connection/response/ConnectionCheckCode.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.plugin.control.connection.response; /** - * conection check code. + * connection check code. * * @author shiyiyue */ diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/MapperManager.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/MapperManager.java index d27513ad1fd..fd6185701a1 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/MapperManager.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/MapperManager.java @@ -64,11 +64,10 @@ public static MapperManager instance(boolean isDataSourceLogEnable) { /** * The init method. */ - public void loadInitial() { + public synchronized void loadInitial() { Collection mappers = NacosServiceLoader.load(Mapper.class); for (Mapper mapper : mappers) { - Map mapperMap = MAPPER_SPI_MAP.computeIfAbsent(mapper.getDataSource(), (r) -> new HashMap<>(16)); - mapperMap.put(mapper.getTableName(), mapper); + putMapper(mapper); LOGGER.info("[MapperManager] Load Mapper({}) datasource({}) tableName({}) successfully.", mapper.getClass(), mapper.getDataSource(), mapper.getTableName()); } @@ -82,10 +81,14 @@ public static synchronized void join(Mapper mapper) { if (Objects.isNull(mapper)) { return; } - Map mapperMap = MAPPER_SPI_MAP.getOrDefault(mapper.getDataSource(), new HashMap<>(16)); - mapperMap.put(mapper.getTableName(), mapper); - MAPPER_SPI_MAP.put(mapper.getDataSource(), mapperMap); - LOGGER.warn("[MapperManager] join successfully."); + putMapper(mapper); + LOGGER.info("[MapperManager] join successfully."); + } + + private static void putMapper(Mapper mapper) { + Map mapperMap = MAPPER_SPI_MAP.computeIfAbsent(mapper.getDataSource(), key -> + new HashMap<>(16)); + mapperMap.putIfAbsent(mapper.getTableName(), mapper); } /** @@ -111,7 +114,7 @@ public R findMapper(String dataSource, String tableName) { "[MapperManager] Failed to find the table ,tableName:" + tableName); } if (dataSourceLogEnable) { - return (R) MapperProxy.createSingleProxy(mapper); + return MapperProxy.createSingleProxy(mapper); } return (R) mapper; } diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxy.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxy.java index 43f25c6557c..38e34ca8fe9 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxy.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxy.java @@ -25,10 +25,8 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; -import java.util.HashMap; import java.util.Map; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.concurrent.ConcurrentHashMap; /** * DataSource plugin Mapper sql proxy. @@ -41,9 +39,7 @@ public class MapperProxy implements InvocationHandler { private Mapper mapper; - private static final Map SINGLE_MAPPER_PROXY_MAP = new HashMap<>(16); - - private static final ReadWriteLock LOCK = new ReentrantReadWriteLock(true); + private static final Map SINGLE_MAPPER_PROXY_MAP = new ConcurrentHashMap<>(16); public R createProxy(Mapper mapper) { this.mapper = mapper; @@ -54,24 +50,8 @@ public R createProxy(Mapper mapper) { * create proxy-mapper single instead of using method createProxy. */ public static R createSingleProxy(Mapper mapper) { - String key = mapper.getClass().getSimpleName(); - if (!SINGLE_MAPPER_PROXY_MAP.containsKey(key)) { - try { - LOCK.writeLock().lock(); - if (!SINGLE_MAPPER_PROXY_MAP.containsKey(key)) { - MapperProxy mapperProxy = new MapperProxy(); - SINGLE_MAPPER_PROXY_MAP.put(key, mapperProxy.createProxy(mapper)); - } - } finally { - LOCK.writeLock().unlock(); - } - } - try { - LOCK.readLock().lock(); - return (R) SINGLE_MAPPER_PROXY_MAP.get(key); - } finally { - LOCK.readLock().unlock(); - } + return (R) SINGLE_MAPPER_PROXY_MAP.computeIfAbsent(mapper.getClass().getSimpleName(), key -> + new MapperProxy().createProxy(mapper)); } @Override