repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Service;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.common.utils.AnnotationUtils.excludedType;
import static org.apache.dubbo.common.utils.AnnotationUtils.filterDefaultValues;
import static org.apache.dubbo.common.utils.AnnotationUtils.findAnnotation;
import static org.apache.dubbo.common.utils.AnnotationUtils.findMetaAnnotation;
import static org.apache.dubbo.common.utils.AnnotationUtils.findMetaAnnotations;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAllDeclaredAnnotations;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAllMetaAnnotations;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAnnotation;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAttribute;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAttributes;
import static org.apache.dubbo.common.utils.AnnotationUtils.getDeclaredAnnotations;
import static org.apache.dubbo.common.utils.AnnotationUtils.getDefaultValue;
import static org.apache.dubbo.common.utils.AnnotationUtils.getMetaAnnotations;
import static org.apache.dubbo.common.utils.AnnotationUtils.getValue;
import static org.apache.dubbo.common.utils.AnnotationUtils.isAnnotationPresent;
import static org.apache.dubbo.common.utils.AnnotationUtils.isAnyAnnotationPresent;
import static org.apache.dubbo.common.utils.AnnotationUtils.isSameType;
import static org.apache.dubbo.common.utils.AnnotationUtils.isType;
import static org.apache.dubbo.common.utils.MethodUtils.findMethod;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link AnnotationUtils} Test
*
* @since 2.7.6
*/
class AnnotationUtilsTest {
@Test
void testIsType() {
// null checking
assertFalse(isType(null));
// Method checking
assertFalse(isType(findMethod(A.class, "execute")));
// Class checking
assertTrue(isType(A.class));
}
@Test
void testIsSameType() {
assertTrue(isSameType(A.class.getAnnotation(Service.class), Service.class));
assertFalse(isSameType(A.class.getAnnotation(Service.class), Deprecated.class));
assertFalse(isSameType(A.class.getAnnotation(Service.class), null));
assertFalse(isSameType(null, Deprecated.class));
assertFalse(isSameType(null, null));
}
@Test
void testExcludedType() {
assertFalse(excludedType(Service.class).test(A.class.getAnnotation(Service.class)));
assertTrue(excludedType(Service.class).test(A.class.getAnnotation(Deprecated.class)));
}
@Test
void testGetAttribute() {
Annotation annotation = A.class.getAnnotation(Service.class);
assertEquals("java.lang.CharSequence", getAttribute(annotation, "interfaceName"));
assertEquals(CharSequence.class, getAttribute(annotation, "interfaceClass"));
assertEquals("", getAttribute(annotation, "version"));
assertEquals("", getAttribute(annotation, "group"));
assertEquals("", getAttribute(annotation, "path"));
assertEquals(true, getAttribute(annotation, "export"));
assertEquals(false, getAttribute(annotation, "deprecated"));
}
@Test
void testGetAttributesMap() {
Annotation annotation = A.class.getAnnotation(Service.class);
Map<String, Object> attributes = getAttributes(annotation, false);
assertEquals("java.lang.CharSequence", attributes.get("interfaceName"));
assertEquals(CharSequence.class, attributes.get("interfaceClass"));
assertEquals("", attributes.get("group"));
assertEquals(getDefaultValue(annotation, "export"), attributes.get("export"));
Map<String, Object> filteredAttributes = filterDefaultValues(annotation, attributes);
assertEquals(2, filteredAttributes.size());
assertEquals("java.lang.CharSequence", filteredAttributes.get("interfaceName"));
assertEquals(CharSequence.class, filteredAttributes.get("interfaceClass"));
assertFalse(filteredAttributes.containsKey("group"));
assertFalse(filteredAttributes.containsKey("export"));
Map<String, Object> nonDefaultAttributes = getAttributes(annotation, true);
assertEquals(nonDefaultAttributes, filteredAttributes);
}
@Test
void testGetValue() {
Adaptive adaptive = A.class.getAnnotation(Adaptive.class);
String[] value = getValue(adaptive);
assertEquals(asList("a", "b", "c"), asList(value));
}
@Test
void testGetDeclaredAnnotations() {
List<Annotation> annotations = getDeclaredAnnotations(A.class);
assertADeclaredAnnotations(annotations, 0);
annotations = getDeclaredAnnotations(A.class, a -> isSameType(a, Service.class));
assertEquals(1, annotations.size());
Service service = (Service) annotations.get(0);
assertEquals("java.lang.CharSequence", service.interfaceName());
assertEquals(CharSequence.class, service.interfaceClass());
}
@Test
void testGetAllDeclaredAnnotations() {
List<Annotation> annotations = getAllDeclaredAnnotations(A.class);
assertADeclaredAnnotations(annotations, 0);
annotations = getAllDeclaredAnnotations(B.class);
assertTrue(isSameType(annotations.get(0), Service5.class));
assertADeclaredAnnotations(annotations, 1);
annotations = new LinkedList<>(getAllDeclaredAnnotations(C.class));
assertTrue(isSameType(annotations.get(0), MyAdaptive.class));
assertTrue(isSameType(annotations.get(1), Service5.class));
assertADeclaredAnnotations(annotations, 2);
annotations = getAllDeclaredAnnotations(findMethod(A.class, "execute"));
MyAdaptive myAdaptive = (MyAdaptive) annotations.get(0);
assertArrayEquals(new String[] {"e"}, myAdaptive.value());
annotations = getAllDeclaredAnnotations(findMethod(B.class, "execute"));
Adaptive adaptive = (Adaptive) annotations.get(0);
assertArrayEquals(new String[] {"f"}, adaptive.value());
}
@Test
void testGetMetaAnnotations() {
List<Annotation> metaAnnotations = getMetaAnnotations(Service.class, a -> isSameType(a, Inherited.class));
assertEquals(1, metaAnnotations.size());
assertEquals(Inherited.class, metaAnnotations.get(0).annotationType());
metaAnnotations = getMetaAnnotations(Service.class);
HashSet<Object> set1 = new HashSet<>();
metaAnnotations.forEach(t -> set1.add(t.annotationType()));
HashSet<Object> set2 = new HashSet<>();
set2.add(Inherited.class);
set2.add(Deprecated.class);
assertEquals(2, metaAnnotations.size());
assertEquals(set1, set2);
}
@Test
void testGetAllMetaAnnotations() {
List<Annotation> metaAnnotations = getAllMetaAnnotations(Service5.class);
int offset = 0;
HashSet<Object> set1 = new HashSet<>();
metaAnnotations.forEach(t -> set1.add(t.annotationType()));
HashSet<Object> set2 = new HashSet<>();
set2.add(Inherited.class);
set2.add(DubboService.class);
set2.add(Service4.class);
set2.add(Service3.class);
set2.add(Service2.class);
assertEquals(9, metaAnnotations.size());
assertEquals(set1, set2);
metaAnnotations = getAllMetaAnnotations(MyAdaptive.class);
HashSet<Object> set3 = new HashSet<>();
metaAnnotations.forEach(t -> set3.add(t.annotationType()));
HashSet<Object> set4 = new HashSet<>();
metaAnnotations.forEach(t -> set3.add(t.annotationType()));
set4.add(Inherited.class);
set4.add(Adaptive.class);
assertEquals(2, metaAnnotations.size());
assertEquals(set3, set4);
}
@Test
void testIsAnnotationPresent() {
assertTrue(isAnnotationPresent(A.class, true, Service.class));
// assertTrue(isAnnotationPresent(A.class, true, Service.class,
// com.alibaba.dubbo.config.annotation.Service.class));
assertTrue(isAnnotationPresent(A.class, Service.class));
assertTrue(isAnnotationPresent(A.class, "org.apache.dubbo.config.annotation.Service"));
// assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class,
// com.alibaba.dubbo.config.annotation.Service.class));
assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class));
assertTrue(isAnnotationPresent(A.class, Deprecated.class));
}
@Test
void testIsAnyAnnotationPresent() {
// assertTrue(isAnyAnnotationPresent(A.class, Service.class,
// com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class));
// assertTrue(isAnyAnnotationPresent(A.class, Service.class,
// com.alibaba.dubbo.config.annotation.Service.class));
assertTrue(isAnyAnnotationPresent(A.class, Service.class, Deprecated.class));
// assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class,
// Deprecated.class));
assertTrue(isAnyAnnotationPresent(A.class, Deprecated.class));
assertTrue(isAnyAnnotationPresent(A.class, Service.class));
// assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class));
assertTrue(isAnyAnnotationPresent(A.class, Deprecated.class));
}
@Test
void testGetAnnotation() {
assertNotNull(getAnnotation(A.class, "org.apache.dubbo.config.annotation.Service"));
// assertNotNull(getAnnotation(A.class, "com.alibaba.dubbo.config.annotation.Service"));
assertNotNull(getAnnotation(A.class, "org.apache.dubbo.common.extension.Adaptive"));
assertNull(getAnnotation(A.class, "java.lang.Deprecated"));
assertNull(getAnnotation(A.class, "java.lang.String"));
assertNull(getAnnotation(A.class, "NotExistedClass"));
}
@Test
void testFindAnnotation() {
Service service = findAnnotation(A.class, Service.class);
assertEquals("java.lang.CharSequence", service.interfaceName());
assertEquals(CharSequence.class, service.interfaceClass());
service = findAnnotation(B.class, Service.class);
assertEquals(CharSequence.class, service.interfaceClass());
}
@Test
void testFindMetaAnnotations() {
List<DubboService> services = findMetaAnnotations(B.class, DubboService.class);
assertEquals(1, services.size());
DubboService service = services.get(0);
assertEquals("", service.interfaceName());
assertEquals(Cloneable.class, service.interfaceClass());
services = findMetaAnnotations(Service5.class, DubboService.class);
assertEquals(1, services.size());
service = services.get(0);
assertEquals("", service.interfaceName());
assertEquals(Cloneable.class, service.interfaceClass());
}
@Test
void testFindMetaAnnotation() {
DubboService service = findMetaAnnotation(B.class, DubboService.class);
assertEquals(Cloneable.class, service.interfaceClass());
service = findMetaAnnotation(B.class, "org.apache.dubbo.config.annotation.DubboService");
assertEquals(Cloneable.class, service.interfaceClass());
service = findMetaAnnotation(Service5.class, DubboService.class);
assertEquals(Cloneable.class, service.interfaceClass());
}
@Service(interfaceName = "java.lang.CharSequence", interfaceClass = CharSequence.class)
@Adaptive(value = {"a", "b", "c"})
static class A {
@MyAdaptive("e")
public void execute() {}
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
@DubboService(interfaceClass = Cloneable.class)
@interface Service2 {}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
@Service2
@interface Service3 {}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
@Service3
@interface Service4 {}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
@Service4
@interface Service5 {}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited
@Adaptive
@interface MyAdaptive {
String[] value() default {};
}
@Service5
static class B extends A {
@Adaptive("f")
@Override
public void execute() {}
}
@MyAdaptive
static class C extends B {}
private void assertADeclaredAnnotations(List<Annotation> annotations, int offset) {
int size = 2 + offset;
assertEquals(size, annotations.size());
boolean apacheServiceFound = false;
boolean adaptiveFound = false;
for (Annotation annotation : annotations) {
if (!apacheServiceFound && (annotation instanceof Service)) {
assertEquals("java.lang.CharSequence", ((Service) annotation).interfaceName());
assertEquals(CharSequence.class, ((Service) annotation).interfaceClass());
apacheServiceFound = true;
continue;
}
if (!adaptiveFound && (annotation instanceof Adaptive)) {
assertArrayEquals(new String[] {"a", "b", "c"}, ((Adaptive) annotation).value());
adaptiveFound = true;
continue;
}
}
assertTrue(apacheServiceFound && adaptiveFound);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TestAllowClassNotifyListener.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/TestAllowClassNotifyListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class TestAllowClassNotifyListener implements AllowClassNotifyListener {
private static final AtomicReference<SerializeCheckStatus> status = new AtomicReference<>();
private static final AtomicReference<Set<String>> allowedList = new AtomicReference<>();
private static final AtomicReference<Set<String>> disAllowedList = new AtomicReference<>();
private static final AtomicBoolean checkSerializable = new AtomicBoolean();
private static final AtomicInteger count = new AtomicInteger(0);
@Override
public void notifyPrefix(Set<String> allowedList, Set<String> disAllowedList) {
TestAllowClassNotifyListener.allowedList.set(allowedList);
TestAllowClassNotifyListener.disAllowedList.set(disAllowedList);
count.incrementAndGet();
}
@Override
public void notifyCheckStatus(SerializeCheckStatus status) {
TestAllowClassNotifyListener.status.set(status);
count.incrementAndGet();
}
@Override
public void notifyCheckSerializable(boolean checkSerializable) {
TestAllowClassNotifyListener.checkSerializable.set(checkSerializable);
count.incrementAndGet();
}
public static SerializeCheckStatus getStatus() {
return status.get();
}
public static Set<String> getAllowedList() {
return allowedList.get();
}
public static Set<String> getDisAllowedList() {
return disAllowedList.get();
}
public static boolean isCheckSerializable() {
return checkSerializable.get();
}
public static int getCount() {
return count.get();
}
public static void setCount(int count) {
TestAllowClassNotifyListener.count.set(count);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LFUCacheTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/LFUCacheTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class LFUCacheTest {
@Test
void testCacheEviction() {
LFUCache<String, Integer> cache = new LFUCache<>(8, 0.8f);
cache.put("one", 1);
cache.put("two", 2);
cache.put("three", 3);
assertThat(cache.get("one"), equalTo(1));
assertThat(cache.get("two"), equalTo(2));
assertThat(cache.get("three"), equalTo(3));
assertThat(cache.getSize(), equalTo(3));
cache.put("four", 4);
assertThat(cache.getSize(), equalTo(4));
cache.put("five", 5);
cache.put("six", 6);
assertThat(cache.getSize(), equalTo(6));
cache.put("seven", 7);
cache.put("eight", 8);
cache.put("nine", 9);
assertThat(cache.getSize(), equalTo(2));
}
@Test
void testCacheRemove() {
LFUCache<String, Integer> cache = new LFUCache<>(8, 0.8f);
cache.put("one", 1);
cache.put("two", 2);
cache.put("three", 3);
assertThat(cache.get("one"), equalTo(1));
assertThat(cache.get("two"), equalTo(2));
assertThat(cache.get("three"), equalTo(3));
assertThat(cache.getSize(), equalTo(3));
cache.put("four", 4);
assertThat(cache.getSize(), equalTo(4));
cache.remove("four");
assertThat(cache.getSize(), equalTo(3));
cache.put("five", 5);
assertThat(cache.getSize(), equalTo(4));
cache.put("six", 6);
assertThat(cache.getSize(), equalTo(5));
}
@Test
void testDefaultCapacity() {
LFUCache<String, Integer> cache = new LFUCache<>();
assertThat(cache.getCapacity(), equalTo(1000));
}
@Test
void testErrorConstructArguments() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(0, 0.8f));
Assertions.assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(-1, 0.8f));
Assertions.assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(100, 0.0f));
Assertions.assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(100, -0.1f));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/IOUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/IOUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class IOUtilsTest {
private static String TEXT = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
private InputStream is;
private OutputStream os;
private Reader reader;
private Writer writer;
@BeforeEach
public void setUp() throws Exception {
is = new ByteArrayInputStream(TEXT.getBytes(StandardCharsets.UTF_8));
os = new ByteArrayOutputStream();
reader = new StringReader(TEXT);
writer = new StringWriter();
}
@AfterEach
public void tearDown() throws Exception {
is.close();
os.close();
reader.close();
writer.close();
}
@Test
void testWrite1() throws Exception {
assertThat((int) IOUtils.write(is, os, 16), equalTo(TEXT.length()));
}
@Test
void testWrite2() throws Exception {
assertThat((int) IOUtils.write(reader, writer, 16), equalTo(TEXT.length()));
}
@Test
void testWrite3() throws Exception {
assertThat((int) IOUtils.write(writer, TEXT), equalTo(TEXT.length()));
}
@Test
void testWrite4() throws Exception {
assertThat((int) IOUtils.write(is, os), equalTo(TEXT.length()));
}
@Test
void testWrite5() throws Exception {
assertThat((int) IOUtils.write(reader, writer), equalTo(TEXT.length()));
}
@Test
void testLines(@TempDir Path tmpDir) throws Exception {
File file = tmpDir.getFileName().toAbsolutePath().toFile();
IOUtils.writeLines(file, new String[] {TEXT});
String[] lines = IOUtils.readLines(file);
assertThat(lines.length, equalTo(1));
assertThat(lines[0], equalTo(TEXT));
tmpDir.getFileName().toAbsolutePath().toFile().delete();
}
@Test
void testReadLines() throws Exception {
String[] lines = IOUtils.readLines(is);
assertThat(lines.length, equalTo(1));
assertThat(lines[0], equalTo(TEXT));
}
@Test
void testWriteLines() throws Exception {
IOUtils.writeLines(os, new String[] {TEXT});
ByteArrayOutputStream bos = (ByteArrayOutputStream) os;
assertThat(new String(bos.toByteArray()), equalTo(TEXT + System.lineSeparator()));
}
@Test
void testRead() throws Exception {
assertThat(IOUtils.read(reader), equalTo(TEXT));
}
@Test
void testAppendLines(@TempDir Path tmpDir) throws Exception {
File file = tmpDir.getFileName().toAbsolutePath().toFile();
IOUtils.appendLines(file, new String[] {"a", "b", "c"});
String[] lines = IOUtils.readLines(file);
assertThat(lines.length, equalTo(3));
assertThat(lines[0], equalTo("a"));
assertThat(lines[1], equalTo("b"));
assertThat(lines[2], equalTo("c"));
tmpDir.getFileName().toAbsolutePath().toFile().delete();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MyEnum.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/MyEnum.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
/**
* MyEnum
*/
public enum MyEnum {
A,
B
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonCompatibilityUtilTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonCompatibilityUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.utils.json.Service;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class JsonCompatibilityUtilTest {
private static Class<?> service = Service.class;
private static final Logger logger = LoggerFactory.getLogger(JsonCompatibilityUtil.class);
@Test
public void testCheckClassCompatibility() {
boolean res = JsonCompatibilityUtil.checkClassCompatibility(service);
assertFalse(res);
}
@Test
public void testGetUnsupportedMethods() {
List<String> res = JsonCompatibilityUtil.getUnsupportedMethods(service);
assert res != null;
logger.info(res.toString());
assert (res.size() != 0);
}
@Test
public void testInt() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testInt"));
assertTrue(res);
}
@Test
public void testIntArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testIntArr"));
assertTrue(res);
}
@Test
public void testInteger() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testInteger"));
assertTrue(res);
}
@Test
public void testIntegerArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testIntegerArr"));
assertTrue(res);
}
@Test
public void testIntegerList() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testIntegerList"));
assertTrue(res);
}
@Test
public void testShort() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testShort"));
assertTrue(res);
}
@Test
public void testShortArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testShortArr"));
assertTrue(res);
}
@Test
public void testSShort() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testSShort"));
assertTrue(res);
}
@Test
public void testSShortArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testSShortArr"));
assertTrue(res);
}
@Test
public void testShortList() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testShortList"));
assertTrue(res);
}
@Test
public void testByte() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testByte"));
assertTrue(res);
}
@Test
public void testByteArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testByteArr"));
assertTrue(res);
}
@Test
public void testBByte() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testBByte"));
assertTrue(res);
}
@Test
public void testBByteArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testBByteArr"));
assertTrue(res);
}
@Test
public void testByteList() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testByteList"));
assertTrue(res);
}
@Test
public void testFloat() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testFloat"));
assertTrue(res);
}
@Test
public void testFloatArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testFloatArr"));
assertTrue(res);
}
@Test
public void testFFloat() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testFFloat"));
assertTrue(res);
}
@Test
public void testFloatArray() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testFloatArray"));
assertTrue(res);
}
@Test
public void testFloatList() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testFloatList"));
assertTrue(res);
}
@Test
public void testBoolean() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testBoolean"));
assertTrue(res);
}
@Test
public void testBooleanArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testBooleanArr"));
assertTrue(res);
}
@Test
public void testBBoolean() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testBBoolean"));
assertTrue(res);
}
@Test
public void testBooleanArray() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testBooleanArray"));
assertTrue(res);
}
@Test
public void testBooleanList() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testBooleanList"));
assertTrue(res);
}
@Test
public void testChar() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testChar"));
assertTrue(res);
}
@Test
public void testCharArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testCharArr"));
assertTrue(res);
}
@Test
public void testCharacter() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testCharacter"));
assertTrue(res);
}
@Test
public void testCharacterArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testCharacterArr"));
assertTrue(res);
}
@Test
public void testCharacterList() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testCharacterList"));
assertTrue(res);
}
@Test
public void testCharacterListArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testCharacterListArr"));
assertTrue(res);
}
@Test
public void testString() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testString"));
assertTrue(res);
}
@Test
public void testStringArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testStringArr"));
assertTrue(res);
}
@Test
public void testStringList() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testStringList"));
assertTrue(res);
}
@Test
public void testStringListArr() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testStringListArr"));
assertTrue(res);
}
@Test
public void testDate() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testDate"));
assertTrue(res);
}
@Test
public void testCalendar() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testCalendar"));
assertFalse(res);
}
@Test
public void testLocalTime() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testLocalTime"));
assertTrue(res);
}
@Test
public void testLocalDate() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testLocalDate"));
assertTrue(res);
}
@Test
public void testLocalDateTime() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testLocalDateTime"));
assertTrue(res);
}
@Test
public void testZoneDateTime() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testZoneDateTime"));
assertTrue(res);
}
@Test
public void testMap() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testMap"));
assertTrue(res);
}
@Test
public void testSet() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testSet"));
assertTrue(res);
}
@Test
public void testOptionalEmpty() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testOptionalEmpty"));
assertFalse(res);
}
@Test
public void testOptionalInteger() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testOptionalInteger"));
assertFalse(res);
}
@Test
public void testOptionalString() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testOptionalString"));
assertFalse(res);
}
@Test
public void testEnum() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testEnum"));
assertTrue(res);
}
@Test
public void testRecord() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testRecord"));
assertTrue(res);
}
@Test
public void testInterface() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testInterface"));
assertFalse(res);
}
@Test
public void testObject() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testObject"));
assertTrue(res);
}
@Test
public void testObjectList() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testObjectList"));
assertTrue(res);
}
@Test
public void testTemplate() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testTemplate"));
assertTrue(res);
}
@Test
public void testStream() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testStream"));
assertFalse(res);
}
@Test
public void testIterator() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testIterator"));
assertFalse(res);
}
@Test
public void testAbstract() throws NoSuchMethodException {
boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testAbstract"));
assertFalse(res);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JVMUtilTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/JVMUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
class JVMUtilTest {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ArrayUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/ArrayUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ArrayUtilsTest {
@Test
void isEmpty() {
assertTrue(ArrayUtils.isEmpty(null));
assertTrue(ArrayUtils.isEmpty(new Object[0]));
assertFalse(ArrayUtils.isEmpty(new Object[] {"abc"}));
}
@Test
void isNotEmpty() {
assertFalse(ArrayUtils.isNotEmpty(null));
assertFalse(ArrayUtils.isNotEmpty(new Object[0]));
assertTrue(ArrayUtils.isNotEmpty(new Object[] {"abc"}));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StackTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/StackTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.EmptyStackException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
class StackTest {
@Test
void testOps() throws Exception {
Stack<String> stack = new Stack<String>();
stack.push("one");
assertThat(stack.get(0), equalTo("one"));
assertThat(stack.peek(), equalTo("one"));
assertThat(stack.size(), equalTo(1));
stack.push("two");
assertThat(stack.get(0), equalTo("one"));
assertThat(stack.peek(), equalTo("two"));
assertThat(stack.size(), equalTo(2));
assertThat(stack.set(0, "three"), equalTo("one"));
assertThat(stack.remove(0), equalTo("three"));
assertThat(stack.size(), equalTo(1));
assertThat(stack.isEmpty(), is(false));
assertThat(stack.get(0), equalTo("two"));
assertThat(stack.peek(), equalTo("two"));
assertThat(stack.pop(), equalTo("two"));
assertThat(stack.isEmpty(), is(true));
}
@Test
void testClear() throws Exception {
Stack<String> stack = new Stack<String>();
stack.push("one");
stack.push("two");
assertThat(stack.isEmpty(), is(false));
stack.clear();
assertThat(stack.isEmpty(), is(true));
}
@Test
void testIllegalPop() throws Exception {
Assertions.assertThrows(EmptyStackException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.pop();
});
}
@Test
void testIllegalPeek() throws Exception {
Assertions.assertThrows(EmptyStackException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.peek();
});
}
@Test
void testIllegalGet() throws Exception {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.get(1);
});
}
@Test
void testIllegalGetNegative() throws Exception {
Stack<String> stack = new Stack<String>();
stack.push("one");
stack.get(-1);
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
stack.get(-10);
});
}
@Test
void testIllegalSet() throws Exception {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.set(1, "illegal");
});
}
@Test
void testIllegalSetNegative() throws Exception {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.set(-1, "illegal");
});
}
@Test
void testIllegalRemove() throws Exception {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.remove(1);
});
}
@Test
void testIllegalRemoveNegative() throws Exception {
Stack<String> stack = new Stack<String>();
stack.push("one");
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
stack.remove(-2);
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CompatibleTypeUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/CompatibleTypeUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CompatibleTypeUtilsTest {
@SuppressWarnings("unchecked")
@Test
void testCompatibleTypeConvert() throws Exception {
Object result;
{
Object input = new Object();
result = CompatibleTypeUtils.compatibleTypeConvert(input, Date.class);
assertSame(input, result);
result = CompatibleTypeUtils.compatibleTypeConvert(input, null);
assertSame(input, result);
result = CompatibleTypeUtils.compatibleTypeConvert(null, Date.class);
assertNull(result);
}
{
result = CompatibleTypeUtils.compatibleTypeConvert("a", char.class);
assertEquals(Character.valueOf('a'), (Character) result);
result = CompatibleTypeUtils.compatibleTypeConvert("A", MyEnum.class);
assertEquals(MyEnum.A, (MyEnum) result);
result = CompatibleTypeUtils.compatibleTypeConvert("3", BigInteger.class);
assertEquals(new BigInteger("3"), (BigInteger) result);
result = CompatibleTypeUtils.compatibleTypeConvert("3", BigDecimal.class);
assertEquals(new BigDecimal("3"), (BigDecimal) result);
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", Date.class);
assertEquals(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2011-12-11 12:24:12"), (Date) result);
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", java.sql.Date.class);
assertEquals(new SimpleDateFormat("yyyy-MM-dd").format((java.sql.Date) result), "2011-12-11");
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", java.sql.Time.class);
assertEquals(new SimpleDateFormat("HH:mm:ss").format((java.sql.Time) result), "12:24:12");
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", java.sql.Timestamp.class);
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((java.sql.Timestamp) result),
"2011-12-11 12:24:12");
result =
CompatibleTypeUtils.compatibleTypeConvert("2011-12-11T12:24:12.047", java.time.LocalDateTime.class);
assertEquals(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format((java.time.LocalDateTime) result),
"2011-12-11 12:24:12");
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11T12:24:12.047", java.time.LocalTime.class);
assertEquals(DateTimeFormatter.ofPattern("HH:mm:ss").format((java.time.LocalTime) result), "12:24:12");
result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11", java.time.LocalDate.class);
assertEquals(DateTimeFormatter.ofPattern("yyyy-MM-dd").format((java.time.LocalDate) result), "2011-12-11");
result = CompatibleTypeUtils.compatibleTypeConvert("ab", char[].class);
assertEquals(2, ((char[]) result).length);
assertEquals('a', ((char[]) result)[0]);
assertEquals('b', ((char[]) result)[1]);
result = CompatibleTypeUtils.compatibleTypeConvert("", char[].class);
assertEquals(0, ((char[]) result).length);
result = CompatibleTypeUtils.compatibleTypeConvert(null, char[].class);
assertNull(result);
}
{
result = CompatibleTypeUtils.compatibleTypeConvert(3, byte.class);
assertEquals(Byte.valueOf((byte) 3), (Byte) result);
result = CompatibleTypeUtils.compatibleTypeConvert((byte) 3, int.class);
assertEquals(Integer.valueOf(3), (Integer) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3, short.class);
assertEquals(Short.valueOf((short) 3), (Short) result);
result = CompatibleTypeUtils.compatibleTypeConvert((short) 3, int.class);
assertEquals(Integer.valueOf(3), (Integer) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3, int.class);
assertEquals(Integer.valueOf(3), (Integer) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3, long.class);
assertEquals(Long.valueOf(3), (Long) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3L, int.class);
assertEquals(Integer.valueOf(3), (Integer) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3L, BigInteger.class);
assertEquals(BigInteger.valueOf(3L), (BigInteger) result);
result = CompatibleTypeUtils.compatibleTypeConvert(BigInteger.valueOf(3L), int.class);
assertEquals(Integer.valueOf(3), (Integer) result);
}
{
result = CompatibleTypeUtils.compatibleTypeConvert(3D, float.class);
assertEquals(Float.valueOf(3), (Float) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3F, double.class);
assertEquals(Double.valueOf(3), (Double) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3D, double.class);
assertEquals(Double.valueOf(3), (Double) result);
result = CompatibleTypeUtils.compatibleTypeConvert(3D, BigDecimal.class);
assertEquals(BigDecimal.valueOf(3D), (BigDecimal) result);
result = CompatibleTypeUtils.compatibleTypeConvert(BigDecimal.valueOf(3D), double.class);
assertEquals(Double.valueOf(3), (Double) result);
}
{
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
Set<String> set = new HashSet<String>();
set.add("a");
set.add("b");
String[] array = new String[] {"a", "b"};
result = CompatibleTypeUtils.compatibleTypeConvert(array, List.class);
assertEquals(ArrayList.class, result.getClass());
assertEquals(2, ((List<String>) result).size());
assertTrue(((List<String>) result).contains("a"));
assertTrue(((List<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(set, List.class);
assertEquals(ArrayList.class, result.getClass());
assertEquals(2, ((List<String>) result).size());
assertTrue(((List<String>) result).contains("a"));
assertTrue(((List<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(array, CopyOnWriteArrayList.class);
assertEquals(CopyOnWriteArrayList.class, result.getClass());
assertEquals(2, ((List<String>) result).size());
assertTrue(((List<String>) result).contains("a"));
assertTrue(((List<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(set, CopyOnWriteArrayList.class);
assertEquals(CopyOnWriteArrayList.class, result.getClass());
assertEquals(2, ((List<String>) result).size());
assertTrue(((List<String>) result).contains("a"));
assertTrue(((List<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(set, String[].class);
assertEquals(String[].class, result.getClass());
assertEquals(2, ((String[]) result).length);
assertTrue(((String[]) result)[0].equals("a") || ((String[]) result)[0].equals("b"));
assertTrue(((String[]) result)[1].equals("a") || ((String[]) result)[1].equals("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(array, Set.class);
assertEquals(HashSet.class, result.getClass());
assertEquals(2, ((Set<String>) result).size());
assertTrue(((Set<String>) result).contains("a"));
assertTrue(((Set<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(list, Set.class);
assertEquals(HashSet.class, result.getClass());
assertEquals(2, ((Set<String>) result).size());
assertTrue(((Set<String>) result).contains("a"));
assertTrue(((Set<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(array, ConcurrentHashSet.class);
assertEquals(ConcurrentHashSet.class, result.getClass());
assertEquals(2, ((Set<String>) result).size());
assertTrue(((Set<String>) result).contains("a"));
assertTrue(((Set<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(list, ConcurrentHashSet.class);
assertEquals(ConcurrentHashSet.class, result.getClass());
assertEquals(2, ((Set<String>) result).size());
assertTrue(((Set<String>) result).contains("a"));
assertTrue(((Set<String>) result).contains("b"));
result = CompatibleTypeUtils.compatibleTypeConvert(list, String[].class);
assertEquals(String[].class, result.getClass());
assertEquals(2, ((String[]) result).length);
assertTrue(((String[]) result)[0].equals("a"));
assertTrue(((String[]) result)[1].equals("b"));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CIDRUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/CIDRUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.net.UnknownHostException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class CIDRUtilsTest {
@Test
void testIpv4() throws UnknownHostException {
CIDRUtils cidrUtils = new CIDRUtils("192.168.1.0/26");
Assertions.assertTrue(cidrUtils.isInRange("192.168.1.63"));
Assertions.assertFalse(cidrUtils.isInRange("192.168.1.65"));
cidrUtils = new CIDRUtils("192.168.1.192/26");
Assertions.assertTrue(cidrUtils.isInRange("192.168.1.199"));
Assertions.assertFalse(cidrUtils.isInRange("192.168.1.190"));
}
@Test
void testIpv6() throws UnknownHostException {
CIDRUtils cidrUtils = new CIDRUtils("234e:0:4567::3d/64");
Assertions.assertTrue(cidrUtils.isInRange("234e:0:4567::3e"));
Assertions.assertTrue(cidrUtils.isInRange("234e:0:4567::ffff:3e"));
Assertions.assertFalse(cidrUtils.isInRange("234e:1:4567::3d"));
Assertions.assertFalse(cidrUtils.isInRange("234e:0:4567:1::3d"));
cidrUtils = new CIDRUtils("3FFE:FFFF:0:CC00::/54");
Assertions.assertTrue(cidrUtils.isInRange("3FFE:FFFF:0:CC00::dd"));
Assertions.assertTrue(cidrUtils.isInRange("3FFE:FFFF:0:CC00:0000:eeee:0909:dd"));
Assertions.assertTrue(cidrUtils.isInRange("3FFE:FFFF:0:CC0F:0000:eeee:0909:dd"));
Assertions.assertFalse(cidrUtils.isInRange("3EFE:FFFE:0:C107::dd"));
Assertions.assertFalse(cidrUtils.isInRange("1FFE:FFFE:0:CC00::dd"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.utils.CollectionUtils.ofSet;
import static org.apache.dubbo.common.utils.StringUtils.splitToList;
import static org.apache.dubbo.common.utils.StringUtils.splitToSet;
import static org.apache.dubbo.common.utils.StringUtils.startsWithIgnoreCase;
import static org.apache.dubbo.common.utils.StringUtils.toCommaDelimitedString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StringUtilsTest {
@Test
void testLength() throws Exception {
assertThat(StringUtils.length(null), equalTo(0));
assertThat(StringUtils.length("abc"), equalTo(3));
}
@Test
void testRepeat() throws Exception {
assertThat(StringUtils.repeat(null, 2), nullValue());
assertThat(StringUtils.repeat("", 0), equalTo(""));
assertThat(StringUtils.repeat("", 2), equalTo(""));
assertThat(StringUtils.repeat("a", 3), equalTo("aaa"));
assertThat(StringUtils.repeat("ab", 2), equalTo("abab"));
assertThat(StringUtils.repeat("a", -2), equalTo(""));
assertThat(StringUtils.repeat(null, null, 2), nullValue());
assertThat(StringUtils.repeat(null, "x", 2), nullValue());
assertThat(StringUtils.repeat("", null, 0), equalTo(""));
assertThat(StringUtils.repeat("", "", 2), equalTo(""));
assertThat(StringUtils.repeat("", "x", 3), equalTo("xx"));
assertThat(StringUtils.repeat("?", ", ", 3), equalTo("?, ?, ?"));
assertThat(StringUtils.repeat('e', 0), equalTo(""));
assertThat(StringUtils.repeat('e', 3), equalTo("eee"));
}
@Test
void testStripEnd() throws Exception {
assertThat(StringUtils.stripEnd(null, "*"), nullValue());
assertThat(StringUtils.stripEnd("", null), equalTo(""));
assertThat(StringUtils.stripEnd("abc", ""), equalTo("abc"));
assertThat(StringUtils.stripEnd("abc", null), equalTo("abc"));
assertThat(StringUtils.stripEnd(" abc", null), equalTo(" abc"));
assertThat(StringUtils.stripEnd("abc ", null), equalTo("abc"));
assertThat(StringUtils.stripEnd(" abc ", null), equalTo(" abc"));
assertThat(StringUtils.stripEnd(" abcyx", "xyz"), equalTo(" abc"));
assertThat(StringUtils.stripEnd("120.00", ".0"), equalTo("12"));
}
@Test
void testReplace() throws Exception {
assertThat(StringUtils.replace(null, "*", "*"), nullValue());
assertThat(StringUtils.replace("", "*", "*"), equalTo(""));
assertThat(StringUtils.replace("any", null, "*"), equalTo("any"));
assertThat(StringUtils.replace("any", "*", null), equalTo("any"));
assertThat(StringUtils.replace("any", "", "*"), equalTo("any"));
assertThat(StringUtils.replace("aba", "a", null), equalTo("aba"));
assertThat(StringUtils.replace("aba", "a", ""), equalTo("b"));
assertThat(StringUtils.replace("aba", "a", "z"), equalTo("zbz"));
assertThat(StringUtils.replace(null, "*", "*", 64), nullValue());
assertThat(StringUtils.replace("", "*", "*", 64), equalTo(""));
assertThat(StringUtils.replace("any", null, "*", 64), equalTo("any"));
assertThat(StringUtils.replace("any", "*", null, 64), equalTo("any"));
assertThat(StringUtils.replace("any", "", "*", 64), equalTo("any"));
assertThat(StringUtils.replace("any", "*", "*", 0), equalTo("any"));
assertThat(StringUtils.replace("abaa", "a", null, -1), equalTo("abaa"));
assertThat(StringUtils.replace("abaa", "a", "", -1), equalTo("b"));
assertThat(StringUtils.replace("abaa", "a", "z", 0), equalTo("abaa"));
assertThat(StringUtils.replace("abaa", "a", "z", 1), equalTo("zbaa"));
assertThat(StringUtils.replace("abaa", "a", "z", 2), equalTo("zbza"));
}
@Test
void testIsBlank() throws Exception {
assertTrue(StringUtils.isBlank(null));
assertTrue(StringUtils.isBlank(""));
assertFalse(StringUtils.isBlank("abc"));
}
@Test
void testIsEmpty() throws Exception {
assertTrue(StringUtils.isEmpty(null));
assertTrue(StringUtils.isEmpty(""));
assertFalse(StringUtils.isEmpty("abc"));
}
@Test
void testIsNoneEmpty() throws Exception {
assertFalse(StringUtils.isNoneEmpty(null));
assertFalse(StringUtils.isNoneEmpty(""));
assertTrue(StringUtils.isNoneEmpty(" "));
assertTrue(StringUtils.isNoneEmpty("abc"));
assertTrue(StringUtils.isNoneEmpty("abc", "def"));
assertFalse(StringUtils.isNoneEmpty("abc", null));
assertFalse(StringUtils.isNoneEmpty("abc", ""));
assertTrue(StringUtils.isNoneEmpty("abc", " "));
}
@Test
void testIsAnyEmpty() throws Exception {
assertTrue(StringUtils.isAnyEmpty(null));
assertTrue(StringUtils.isAnyEmpty(""));
assertFalse(StringUtils.isAnyEmpty(" "));
assertFalse(StringUtils.isAnyEmpty("abc"));
assertFalse(StringUtils.isAnyEmpty("abc", "def"));
assertTrue(StringUtils.isAnyEmpty("abc", null));
assertTrue(StringUtils.isAnyEmpty("abc", ""));
assertFalse(StringUtils.isAnyEmpty("abc", " "));
}
@Test
void testIsNotEmpty() throws Exception {
assertFalse(StringUtils.isNotEmpty(null));
assertFalse(StringUtils.isNotEmpty(""));
assertTrue(StringUtils.isNotEmpty("abc"));
}
@Test
void testIsEquals() throws Exception {
assertTrue(StringUtils.isEquals(null, null));
assertFalse(StringUtils.isEquals(null, ""));
assertTrue(StringUtils.isEquals("abc", "abc"));
assertFalse(StringUtils.isEquals("abc", "ABC"));
}
@Test
void testIsInteger() throws Exception {
assertFalse(StringUtils.isNumber(null));
assertFalse(StringUtils.isNumber(""));
assertTrue(StringUtils.isNumber("123"));
}
@Test
void testParseInteger() throws Exception {
assertThat(StringUtils.parseInteger(null), equalTo(0));
assertThat(StringUtils.parseInteger("123"), equalTo(123));
}
@Test
void testIsJavaIdentifier() throws Exception {
assertThat(StringUtils.isJavaIdentifier(""), is(false));
assertThat(StringUtils.isJavaIdentifier("1"), is(false));
assertThat(StringUtils.isJavaIdentifier("abc123"), is(true));
assertThat(StringUtils.isJavaIdentifier("abc(23)"), is(false));
}
@Test
void testExceptionToString() throws Exception {
assertThat(
StringUtils.toString(new RuntimeException("abc")), containsString("java.lang.RuntimeException: abc"));
}
@Test
void testExceptionToStringWithMessage() throws Exception {
String s = StringUtils.toString("greeting", new RuntimeException("abc"));
assertThat(s, containsString("greeting"));
assertThat(s, containsString("java.lang.RuntimeException: abc"));
}
@Test
void testParseQueryString() throws Exception {
assertThat(StringUtils.getQueryStringValue("key1=value1&key2=value2", "key1"), equalTo("value1"));
assertThat(StringUtils.getQueryStringValue("key1=value1&key2=value2", "key2"), equalTo("value2"));
assertThat(StringUtils.getQueryStringValue("", "key1"), isEmptyOrNullString());
}
@Test
void testGetServiceKey() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put(GROUP_KEY, "dubbo");
map.put(INTERFACE_KEY, "a.b.c.Foo");
map.put(VERSION_KEY, "1.0.0");
assertThat(StringUtils.getServiceKey(map), equalTo("dubbo/a.b.c.Foo:1.0.0"));
}
@Test
void testToQueryString() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
String queryString = StringUtils.toQueryString(map);
assertThat(queryString, containsString("key1=value1"));
assertThat(queryString, containsString("key2=value2"));
}
@Test
void testJoin() throws Exception {
String[] s = {"1", "2", "3"};
assertEquals(StringUtils.join(s), "123");
assertEquals(StringUtils.join(s, ','), "1,2,3");
assertEquals(StringUtils.join(s, ","), "1,2,3");
assertEquals(StringUtils.join(s, ',', 0, 1), "1");
assertEquals(StringUtils.join(s, ',', 0, 2), "1,2");
assertEquals(StringUtils.join(s, ',', 0, 3), "1,2,3");
assertEquals("", StringUtils.join(s, ',', 2, 0), "1,2");
}
@Test
void testSplit() throws Exception {
String str = "d,1,2,4";
assertEquals(4, StringUtils.split(str, ',').length);
assertArrayEquals(str.split(","), StringUtils.split(str, ','));
assertEquals(1, StringUtils.split(str, 'a').length);
assertArrayEquals(str.split("a"), StringUtils.split(str, 'a'));
assertEquals(0, StringUtils.split("", 'a').length);
assertEquals(0, StringUtils.split(null, 'a').length);
}
@Test
void testSplitToList() throws Exception {
String str = "d,1,2,4";
assertEquals(4, splitToList(str, ',').size());
assertEquals(asList(str.split(",")), splitToList(str, ','));
assertEquals(1, splitToList(str, 'a').size());
assertEquals(asList(str.split("a")), splitToList(str, 'a'));
assertEquals(0, splitToList("", 'a').size());
assertEquals(0, splitToList(null, 'a').size());
}
/**
* Test {@link StringUtils#splitToSet(String, char, boolean)}
*
* @since 2.7.8
*/
@Test
void testSplitToSet() {
String value = "1# 2#3 #4#3";
Set<String> values = splitToSet(value, '#', false);
assertEquals(ofSet("1", " 2", "3 ", "4", "3"), values);
values = splitToSet(value, '#', true);
assertEquals(ofSet("1", "2", "3", "4"), values);
}
@Test
void testTranslate() throws Exception {
String s = "16314";
assertEquals(StringUtils.translate(s, "123456", "abcdef"), "afcad");
assertEquals(StringUtils.translate(s, "123456", "abcd"), "acad");
}
@Test
void testIsContains() throws Exception {
assertThat(StringUtils.isContains("a,b, c", "b"), is(true));
assertThat(StringUtils.isContains("", "b"), is(false));
assertThat(StringUtils.isContains(new String[] {"a", "b", "c"}, "b"), is(true));
assertThat(StringUtils.isContains((String[]) null, null), is(false));
assertTrue(StringUtils.isContains("abc", 'a'));
assertFalse(StringUtils.isContains("abc", 'd'));
assertFalse(StringUtils.isContains("", 'a'));
assertFalse(StringUtils.isContains(null, 'a'));
assertTrue(StringUtils.isNotContains("abc", 'd'));
assertFalse(StringUtils.isNotContains("abc", 'a'));
assertTrue(StringUtils.isNotContains("", 'a'));
assertTrue(StringUtils.isNotContains(null, 'a'));
}
@Test
void testIsNumeric() throws Exception {
assertThat(StringUtils.isNumeric("123", false), is(true));
assertThat(StringUtils.isNumeric("1a3", false), is(false));
assertThat(StringUtils.isNumeric(null, false), is(false));
assertThat(StringUtils.isNumeric("0", true), is(true));
assertThat(StringUtils.isNumeric("0.1", true), is(true));
assertThat(StringUtils.isNumeric("DUBBO", true), is(false));
assertThat(StringUtils.isNumeric("", true), is(false));
assertThat(StringUtils.isNumeric(" ", true), is(false));
assertThat(StringUtils.isNumeric(" ", true), is(false));
assertThat(StringUtils.isNumeric("123.3.3", true), is(false));
assertThat(StringUtils.isNumeric("123.", true), is(true));
assertThat(StringUtils.isNumeric(".123", true), is(true));
assertThat(StringUtils.isNumeric("..123", true), is(false));
}
@Test
void testJoinCollectionString() throws Exception {
List<String> list = new ArrayList<String>();
assertEquals("", StringUtils.join(list, ","));
list.add("v1");
assertEquals("v1", StringUtils.join(list, "-"));
list.add("v2");
list.add("v3");
String out = StringUtils.join(list, ":");
assertEquals("v1:v2:v3", out);
}
@Test
void testCamelToSplitName() throws Exception {
assertEquals("ab-cd-ef", StringUtils.camelToSplitName("abCdEf", "-"));
assertEquals("ab-cd-ef", StringUtils.camelToSplitName("AbCdEf", "-"));
assertEquals("abcdef", StringUtils.camelToSplitName("abcdef", "-"));
// assertEquals("name", StringUtils.camelToSplitName("NAME", "-"));
assertEquals("ab-cd-ef", StringUtils.camelToSplitName("ab-cd-ef", "-"));
assertEquals("ab-cd-ef", StringUtils.camelToSplitName("Ab-Cd-Ef", "-"));
assertEquals("Ab_Cd_Ef", StringUtils.camelToSplitName("Ab_Cd_Ef", "-"));
assertEquals("AB_CD_EF", StringUtils.camelToSplitName("AB_CD_EF", "-"));
assertEquals("ab.cd.ef", StringUtils.camelToSplitName("AbCdEf", "."));
// assertEquals("ab.cd.ef", StringUtils.camelToSplitName("ab-cd-ef", "."));
}
@Test
void testSnakeCaseToSplitName() throws Exception {
assertEquals("ab-cd-ef", StringUtils.snakeToSplitName("ab_Cd_Ef", "-"));
assertEquals("ab-cd-ef", StringUtils.snakeToSplitName("Ab_Cd_Ef", "-"));
assertEquals("ab-cd-ef", StringUtils.snakeToSplitName("ab_cd_ef", "-"));
assertEquals("ab-cd-ef", StringUtils.snakeToSplitName("AB_CD_EF", "-"));
assertEquals("abcdef", StringUtils.snakeToSplitName("abcdef", "-"));
assertEquals("qosEnable", StringUtils.snakeToSplitName("qosEnable", "-"));
assertEquals("name", StringUtils.snakeToSplitName("NAME", "-"));
}
@Test
void testConvertToSplitName() {
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("ab_Cd_Ef", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("Ab_Cd_Ef", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("ab_cd_ef", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("AB_CD_EF", "-"));
assertEquals("abcdef", StringUtils.convertToSplitName("abcdef", "-"));
assertEquals("qos-enable", StringUtils.convertToSplitName("qosEnable", "-"));
assertEquals("name", StringUtils.convertToSplitName("NAME", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("abCdEf", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("AbCdEf", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("ab-cd-ef", "-"));
assertEquals("ab-cd-ef", StringUtils.convertToSplitName("Ab-Cd-Ef", "-"));
}
@Test
void testToArgumentString() throws Exception {
String s = StringUtils.toArgumentString(new Object[] {"a", 0, Collections.singletonMap("enabled", true)});
assertThat(s, containsString("a,"));
assertThat(s, containsString("0,"));
assertThat(s, containsString("{\"enabled\":true}"));
}
@Test
void testTrim() {
assertEquals("left blank", StringUtils.trim(" left blank"));
assertEquals("right blank", StringUtils.trim("right blank "));
assertEquals("bi-side blank", StringUtils.trim(" bi-side blank "));
}
@Test
void testToURLKey() {
assertEquals("dubbo.tag1", StringUtils.toURLKey("dubbo_tag1"));
assertEquals("dubbo.tag1.tag11", StringUtils.toURLKey("dubbo-tag1_tag11"));
}
@Test
void testToOSStyleKey() {
assertEquals("DUBBO_TAG1", StringUtils.toOSStyleKey("dubbo_tag1"));
assertEquals("DUBBO_TAG1", StringUtils.toOSStyleKey("dubbo.tag1"));
assertEquals("DUBBO_TAG1_TAG11", StringUtils.toOSStyleKey("dubbo.tag1.tag11"));
assertEquals("DUBBO_TAG1", StringUtils.toOSStyleKey("tag1"));
}
@Test
void testParseParameters() {
String legalStr = "[{key1:value1},{key2:value2}]";
Map<String, String> legalMap = StringUtils.parseParameters(legalStr);
assertEquals(2, legalMap.size());
assertEquals("value2", legalMap.get("key2"));
String str = StringUtils.encodeParameters(legalMap);
assertEqualsWithoutSpaces(legalStr, str);
String legalSpaceStr = "[{key1: value1}, {key2 :value2}]";
Map<String, String> legalSpaceMap = StringUtils.parseParameters(legalSpaceStr);
assertEquals(2, legalSpaceMap.size());
assertEquals("value2", legalSpaceMap.get("key2"));
str = StringUtils.encodeParameters(legalSpaceMap);
assertEqualsWithoutSpaces(legalSpaceStr, str);
String legalSpecialStr = "[{key-1: value*.1}, {key.2 :value*.-_2}]";
Map<String, String> legalSpecialMap = StringUtils.parseParameters(legalSpecialStr);
assertEquals(2, legalSpecialMap.size());
assertEquals("value*.1", legalSpecialMap.get("key-1"));
assertEquals("value*.-_2", legalSpecialMap.get("key.2"));
str = StringUtils.encodeParameters(legalSpecialMap);
assertEqualsWithoutSpaces(legalSpecialStr, str);
String illegalStr = "[{key=value},{aa:bb}]";
Map<String, String> illegalMap = StringUtils.parseParameters(illegalStr);
assertEquals(0, illegalMap.size());
str = StringUtils.encodeParameters(illegalMap);
assertEquals(null, str);
String emptyMapStr = "[]";
Map<String, String> emptyMap = StringUtils.parseParameters(emptyMapStr);
assertEquals(0, emptyMap.size());
}
@Test
void testEncodeParameters() {
Map<String, String> nullValueMap = new LinkedHashMap<>();
nullValueMap.put("client", null);
String str = StringUtils.encodeParameters(nullValueMap);
assertEquals("[]", str);
Map<String, String> blankValueMap = new LinkedHashMap<>();
blankValueMap.put("client", " ");
str = StringUtils.encodeParameters(nullValueMap);
assertEquals("[]", str);
blankValueMap = new LinkedHashMap<>();
blankValueMap.put("client", "");
str = StringUtils.encodeParameters(nullValueMap);
assertEquals("[]", str);
}
private void assertEqualsWithoutSpaces(String expect, String actual) {
assertEquals(expect.replaceAll(" ", ""), actual.replaceAll(" ", ""));
}
/**
* Test {@link StringUtils#toCommaDelimitedString(String, String...)}
*
* @since 2.7.8
*/
@Test
void testToCommaDelimitedString() {
String value = toCommaDelimitedString(null);
assertNull(value);
value = toCommaDelimitedString(null, null);
assertNull(value);
value = toCommaDelimitedString("one", null);
assertEquals("one", value);
value = toCommaDelimitedString("");
assertEquals("", value);
value = toCommaDelimitedString("one");
assertEquals("one", value);
value = toCommaDelimitedString("one", "two");
assertEquals("one,two", value);
value = toCommaDelimitedString("one", "two", "three");
assertEquals("one,two,three", value);
}
@Test
void testStartsWithIgnoreCase() {
assertTrue(startsWithIgnoreCase("dubbo.application.name", "dubbo.application."));
assertTrue(startsWithIgnoreCase("dubbo.Application.name", "dubbo.application."));
assertTrue(startsWithIgnoreCase("Dubbo.application.name", "dubbo.application."));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.model.Person;
import org.apache.dubbo.common.model.SerializablePerson;
import org.apache.dubbo.common.model.User;
import org.apache.dubbo.common.model.person.Ageneric;
import org.apache.dubbo.common.model.person.Bgeneric;
import org.apache.dubbo.common.model.person.BigPerson;
import org.apache.dubbo.common.model.person.Cgeneric;
import org.apache.dubbo.common.model.person.Dgeneric;
import org.apache.dubbo.common.model.person.FullAddress;
import org.apache.dubbo.common.model.person.PersonInfo;
import org.apache.dubbo.common.model.person.PersonMap;
import org.apache.dubbo.common.model.person.PersonStatus;
import org.apache.dubbo.common.model.person.Phone;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PojoUtilsTest {
BigPerson bigPerson;
{
bigPerson = new BigPerson();
bigPerson.setPersonId("id1");
bigPerson.setLoginName("name1");
bigPerson.setStatus(PersonStatus.ENABLED);
bigPerson.setEmail("abc@123.com");
bigPerson.setPersonName("pname");
ArrayList<Phone> phones = new ArrayList<Phone>();
Phone phone1 = new Phone("86", "0571", "11223344", "001");
Phone phone2 = new Phone("86", "0571", "11223344", "002");
phones.add(phone1);
phones.add(phone2);
PersonInfo pi = new PersonInfo();
pi.setPhones(phones);
Phone fax = new Phone("86", "0571", "11223344", null);
pi.setFax(fax);
FullAddress addr = new FullAddress("CN", "zj", "1234", "Road1", "333444");
pi.setFullAddress(addr);
pi.setMobileNo("1122334455");
pi.setMale(true);
pi.setDepartment("b2b");
pi.setHomepageUrl("www.abc.com");
pi.setJobTitle("dev");
pi.setName("name2");
bigPerson.setInfoProfile(pi);
}
private static Child newChild(String name, int age) {
Child result = new Child();
result.setName(name);
result.setAge(age);
return result;
}
public void assertObject(Object data) {
assertObject(data, null);
}
public void assertObject(Object data, Type type) {
Object generalize = PojoUtils.generalize(data);
Object realize = PojoUtils.realize(generalize, data.getClass(), type);
assertEquals(data, realize);
}
public <T> void assertArrayObject(T[] data) {
Object generalize = PojoUtils.generalize(data);
@SuppressWarnings("unchecked")
T[] realize = (T[]) PojoUtils.realize(generalize, data.getClass());
assertArrayEquals(data, realize);
}
@Test
void test_primitive() throws Exception {
assertObject(Boolean.TRUE);
assertObject(Boolean.FALSE);
assertObject(Byte.valueOf((byte) 78));
assertObject('a');
assertObject('中');
assertObject(Short.valueOf((short) 37));
assertObject(78);
assertObject(123456789L);
assertObject(3.14F);
assertObject(3.14D);
}
@Test
void test_pojo() throws Exception {
assertObject(new Person());
assertObject(new BasicTestData(false, '\0', (byte) 0, (short) 0, 0, 0L, 0F, 0D));
assertObject(new SerializablePerson(Character.MIN_VALUE, false));
}
@Test
void test_has_no_nullary_constructor_pojo() {
assertObject(new User(1, "fibbery"));
}
@Test
void test_Map_List_pojo() throws Exception {
Map<String, List<Object>> map = new HashMap<String, List<Object>>();
List<Object> list = new ArrayList<Object>();
list.add(new Person());
list.add(new SerializablePerson(Character.MIN_VALUE, false));
map.put("k", list);
Object generalize = PojoUtils.generalize(map);
Object realize = PojoUtils.realize(generalize, Map.class);
assertEquals(map, realize);
}
@Test
void test_PrimitiveArray() throws Exception {
assertObject(new boolean[] {true, false});
assertObject(new Boolean[] {true, false, true});
assertObject(new byte[] {1, 12, 28, 78});
assertObject(new Byte[] {1, 12, 28, 78});
assertObject(new char[] {'a', '中', '无'});
assertObject(new Character[] {'a', '中', '无'});
assertObject(new short[] {37, 39, 12});
assertObject(new Short[] {37, 39, 12});
assertObject(new int[] {37, -39, 12456});
assertObject(new Integer[] {37, -39, 12456});
assertObject(new long[] {37L, -39L, 123456789L});
assertObject(new Long[] {37L, -39L, 123456789L});
assertObject(new float[] {37F, -3.14F, 123456.7F});
assertObject(new Float[] {37F, -39F, 123456.7F});
assertObject(new double[] {37D, -3.14D, 123456.7D});
assertObject(new Double[] {37D, -39D, 123456.7D});
assertArrayObject(new Boolean[] {true, false, true});
assertArrayObject(new Byte[] {1, 12, 28, 78});
assertArrayObject(new Character[] {'a', '中', '无'});
assertArrayObject(new Short[] {37, 39, 12});
assertArrayObject(new Integer[] {37, -39, 12456});
assertArrayObject(new Long[] {37L, -39L, 123456789L});
assertArrayObject(new Float[] {37F, -39F, 123456.7F});
assertArrayObject(new Double[] {37D, -39D, 123456.7D});
assertObject(new int[][] {{37, -39, 12456}});
assertObject(new Integer[][][] {{{37, -39, 12456}}});
assertArrayObject(new Integer[] {37, -39, 12456});
}
@Test
void test_PojoArray() throws Exception {
Person[] array = new Person[2];
array[0] = new Person();
{
Person person = new Person();
person.setName("xxxx");
array[1] = person;
}
assertArrayObject(array);
}
@Test
void testArrayToCollection() throws Exception {
Person[] array = new Person[2];
Person person1 = new Person();
person1.setName("person1");
Person person2 = new Person();
person2.setName("person2");
array[0] = person1;
array[1] = person2;
Object o = PojoUtils.realize(PojoUtils.generalize(array), LinkedList.class);
assertTrue(o instanceof LinkedList);
assertEquals(((List) o).get(0), person1);
assertEquals(((List) o).get(1), person2);
}
@Test
void testCollectionToArray() throws Exception {
Person person1 = new Person();
person1.setName("person1");
Person person2 = new Person();
person2.setName("person2");
List<Person> list = new LinkedList<Person>();
list.add(person1);
list.add(person2);
Object o = PojoUtils.realize(PojoUtils.generalize(list), Person[].class);
assertTrue(o instanceof Person[]);
assertEquals(((Person[]) o)[0], person1);
assertEquals(((Person[]) o)[1], person2);
}
@Test
void testMapToEnum() throws Exception {
Map map = new HashMap();
map.put("name", "MONDAY");
Object o = PojoUtils.realize(map, Day.class);
assertEquals(o, Day.MONDAY);
}
@Test
void testGeneralizeEnumArray() throws Exception {
Object days = new Enum[] {Day.FRIDAY, Day.SATURDAY};
Object o = PojoUtils.generalize(days);
assertTrue(o instanceof String[]);
assertEquals(((String[]) o)[0], "FRIDAY");
assertEquals(((String[]) o)[1], "SATURDAY");
}
@Test
void testGeneralizePersons() throws Exception {
Object persons = new Person[] {new Person(), new Person()};
Object o = PojoUtils.generalize(persons);
assertTrue(o instanceof Object[]);
assertEquals(((Object[]) o).length, 2);
}
@Test
void testMapToInterface() throws Exception {
Map map = new HashMap();
map.put("content", "greeting");
map.put("from", "dubbo");
map.put("urgent", true);
Object o = PojoUtils.realize(map, Message.class);
Message message = (Message) o;
assertThat(message.getContent(), equalTo("greeting"));
assertThat(message.getFrom(), equalTo("dubbo"));
assertTrue(message.isUrgent());
}
@Test
void testJsonObjectToMap() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setMap", Map.class);
assertNotNull(method);
JSONObject jsonObject = new JSONObject();
jsonObject.put("1", "test");
@SuppressWarnings("unchecked")
Map<Integer, Object> value = (Map<Integer, Object>)
PojoUtils.realize(jsonObject, method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), value);
assertEquals("test", value.get(1));
}
@Test
void testListJsonObjectToListMap() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setListMap", List.class);
assertNotNull(method);
JSONObject jsonObject = new JSONObject();
jsonObject.put("1", "test");
List<JSONObject> list = new ArrayList<>(1);
list.add(jsonObject);
@SuppressWarnings("unchecked")
List<Map<Integer, Object>> result = (List<Map<Integer, Object>>)
PojoUtils.realize(list, method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), result);
assertEquals("test", result.get(0).get(1));
}
public void setMap(Map<Integer, Object> map) {}
public void setListMap(List<Map<Integer, Object>> list) {}
@Test
void testException() throws Exception {
Map map = new HashMap();
map.put("message", "dubbo exception");
Object o = PojoUtils.realize(map, RuntimeException.class);
assertEquals(((Throwable) o).getMessage(), "dubbo exception");
}
@Test
void testIsPojo() throws Exception {
assertFalse(PojoUtils.isPojo(boolean.class));
assertFalse(PojoUtils.isPojo(Map.class));
assertFalse(PojoUtils.isPojo(List.class));
assertTrue(PojoUtils.isPojo(Person.class));
}
public List<Person> returnListPersonMethod() {
return null;
}
public BigPerson returnBigPersonMethod() {
return null;
}
public Type getType(String methodName) {
Method method;
try {
method = getClass().getDeclaredMethod(methodName, new Class<?>[] {});
} catch (Exception e) {
throw new IllegalStateException(e);
}
Type gtype = method.getGenericReturnType();
return gtype;
}
@Test
void test_simpleCollection() throws Exception {
Type gtype = getType("returnListPersonMethod");
List<Person> list = new ArrayList<Person>();
list.add(new Person());
{
Person person = new Person();
person.setName("xxxx");
list.add(person);
}
assertObject(list, gtype);
}
@Test
void test_total() throws Exception {
Object generalize = PojoUtils.generalize(bigPerson);
Type gtype = getType("returnBigPersonMethod");
Object realize = PojoUtils.realize(generalize, BigPerson.class, gtype);
assertEquals(bigPerson, realize);
}
@Test
void test_total_Array() throws Exception {
Object[] persons = new Object[] {bigPerson, bigPerson, bigPerson};
Object generalize = PojoUtils.generalize(persons);
Object[] realize = (Object[]) PojoUtils.realize(generalize, Object[].class);
assertArrayEquals(persons, realize);
}
@Test
void test_Loop_pojo() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
Object generalize = PojoUtils.generalize(p);
Parent parent = (Parent) PojoUtils.realize(generalize, Parent.class);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
}
@Test
void test_Loop_Map() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("k", "v");
map.put("m", map);
assertSame(map, map.get("m"));
Object generalize = PojoUtils.generalize(map);
@SuppressWarnings("unchecked")
Map<String, Object> ret = (Map<String, Object>) PojoUtils.realize(generalize, Map.class);
assertEquals("v", ret.get("k"));
assertSame(ret, ret.get("m"));
}
@Test
void test_LoopPojoInMap() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
Map<String, Object> map = new HashMap<String, Object>();
map.put("k", p);
Object generalize = PojoUtils.generalize(map);
@SuppressWarnings("unchecked")
Map<String, Object> realize =
(Map<String, Object>) PojoUtils.realize(generalize, Map.class, getType("getMapGenericType"));
Parent parent = (Parent) realize.get("k");
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
}
@Test
void test_LoopPojoInList() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
Child c = new Child();
c.setToy("haha");
p.setChild(c);
c.setParent(p);
List<Object> list = new ArrayList<Object>();
list.add(p);
Object generalize = PojoUtils.generalize(list);
@SuppressWarnings("unchecked")
List<Object> realize = (List<Object>) PojoUtils.realize(generalize, List.class, getType("getListGenericType"));
Parent parent = (Parent) realize.get(0);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
assertEquals("haha", parent.getChild().getToy());
assertSame(parent, parent.getChild().getParent());
Object[] objects = PojoUtils.realize(
new Object[] {generalize}, new Class[] {List.class}, new Type[] {getType("getListGenericType")});
assertTrue(((List) objects[0]).get(0) instanceof Parent);
}
@Test
void test_PojoInList() throws Exception {
Parent p = new Parent();
p.setAge(10);
p.setName("jerry");
List<Object> list = new ArrayList<Object>();
list.add(p);
Object generalize = PojoUtils.generalize(list);
@SuppressWarnings("unchecked")
List<Object> realize = (List<Object>) PojoUtils.realize(generalize, List.class, getType("getListGenericType"));
Parent parent = (Parent) realize.get(0);
assertEquals(10, parent.getAge());
assertEquals("jerry", parent.getName());
}
public void setLong(long l) {}
public void setInt(int l) {}
public List<Parent> getListGenericType() {
return null;
}
public Map<String, Parent> getMapGenericType() {
return null;
}
// java.lang.IllegalArgumentException: argument type mismatch
@Test
void test_realize_LongPararmter_IllegalArgumentException() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setLong", long.class);
assertNotNull(method);
Object value = PojoUtils.realize(
"563439743927993", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), value);
}
// java.lang.IllegalArgumentException: argument type mismatch
@Test
void test_realize_IntPararmter_IllegalArgumentException() throws Exception {
Method method = PojoUtilsTest.class.getMethod("setInt", int.class);
assertNotNull(method);
Object value = PojoUtils.realize("123", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]);
method.invoke(new PojoUtilsTest(), value);
}
@Test
void testStackOverflow() throws Exception {
Parent parent = Parent.getNewParent();
parent.setAge(Integer.MAX_VALUE);
String name = UUID.randomUUID().toString();
parent.setName(name);
Object generalize = PojoUtils.generalize(parent);
assertTrue(generalize instanceof Map);
Map map = (Map) generalize;
assertEquals(Integer.MAX_VALUE, map.get("age"));
assertEquals(name, map.get("name"));
Parent realize = (Parent) PojoUtils.realize(generalize, Parent.class);
assertEquals(Integer.MAX_VALUE, realize.getAge());
assertEquals(name, realize.getName());
}
@Test
void testGenerializeAndRealizeClass() throws Exception {
Object generalize = PojoUtils.generalize(Integer.class);
assertEquals(Integer.class.getName(), generalize);
Object real = PojoUtils.realize(generalize, Integer.class.getClass());
assertEquals(Integer.class, real);
generalize = PojoUtils.generalize(int[].class);
assertEquals(int[].class.getName(), generalize);
real = PojoUtils.realize(generalize, int[].class.getClass());
assertEquals(int[].class, real);
}
@Test
void testPublicField() throws Exception {
Parent parent = new Parent();
parent.gender = "female";
parent.email = "email@host.com";
parent.setEmail("securityemail@host.com");
Child child = new Child();
parent.setChild(child);
child.gender = "male";
child.setAge(20);
child.setParent(parent);
Object obj = PojoUtils.generalize(parent);
Parent realizedParent = (Parent) PojoUtils.realize(obj, Parent.class);
Assertions.assertEquals(parent.gender, realizedParent.gender);
Assertions.assertEquals(child.gender, parent.getChild().gender);
Assertions.assertEquals(child.age, realizedParent.getChild().getAge());
Assertions.assertEquals(parent.getEmail(), realizedParent.getEmail());
Assertions.assertNull(realizedParent.email);
}
@Test
void testMapField() throws Exception {
TestData data = new TestData();
Child child = newChild("first", 1);
data.addChild(child);
child = newChild("second", 2);
data.addChild(child);
child = newChild("third", 3);
data.addChild(child);
data.setList(Arrays.asList(newChild("forth", 4)));
Object obj = PojoUtils.generalize(data);
Assertions.assertEquals(3, data.getChildren().size());
assertSame(data.getChildren().get("first").getClass(), Child.class);
Assertions.assertEquals(1, data.getList().size());
assertSame(data.getList().get(0).getClass(), Child.class);
TestData realizadData = (TestData) PojoUtils.realize(obj, TestData.class);
Assertions.assertEquals(
data.getChildren().size(), realizadData.getChildren().size());
Assertions.assertEquals(
data.getChildren().keySet(), realizadData.getChildren().keySet());
for (Map.Entry<String, Child> entry : data.getChildren().entrySet()) {
Child c = realizadData.getChildren().get(entry.getKey());
Assertions.assertNotNull(c);
Assertions.assertEquals(entry.getValue().getName(), c.getName());
Assertions.assertEquals(entry.getValue().getAge(), c.getAge());
}
Assertions.assertEquals(1, realizadData.getList().size());
Assertions.assertEquals(
data.getList().get(0).getName(), realizadData.getList().get(0).getName());
Assertions.assertEquals(
data.getList().get(0).getAge(), realizadData.getList().get(0).getAge());
}
@Test
void testRealize() throws Exception {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("key", "value");
Object obj = PojoUtils.generalize(map);
assertTrue(obj instanceof LinkedHashMap);
Object outputObject = PojoUtils.realize(map, LinkedHashMap.class);
assertTrue(outputObject instanceof LinkedHashMap);
Object[] objects = PojoUtils.realize(new Object[] {map}, new Class[] {LinkedHashMap.class});
assertTrue(objects[0] instanceof LinkedHashMap);
assertEquals(objects[0], outputObject);
}
@Test
void testRealizeLinkedList() throws Exception {
LinkedList<Person> input = new LinkedList<Person>();
Person person = new Person();
person.setAge(37);
input.add(person);
Object obj = PojoUtils.generalize(input);
assertTrue(obj instanceof List);
assertTrue(input.get(0) instanceof Person);
Object output = PojoUtils.realize(obj, LinkedList.class);
assertTrue(output instanceof LinkedList);
}
@Test
void testPojoList() throws Exception {
ListResult<Parent> result = new ListResult<Parent>();
List<Parent> list = new ArrayList<Parent>();
Parent parent = new Parent();
parent.setAge(Integer.MAX_VALUE);
parent.setName("zhangsan");
list.add(parent);
result.setResult(list);
Object generializeObject = PojoUtils.generalize(result);
Object realizeObject = PojoUtils.realize(generializeObject, ListResult.class);
assertTrue(realizeObject instanceof ListResult);
ListResult listResult = (ListResult) realizeObject;
List l = listResult.getResult();
assertEquals(1, l.size());
assertTrue(l.get(0) instanceof Parent);
Parent realizeParent = (Parent) l.get(0);
Assertions.assertEquals(parent.getName(), realizeParent.getName());
Assertions.assertEquals(parent.getAge(), realizeParent.getAge());
}
@Test
void testListPojoListPojo() throws Exception {
InnerPojo<Parent> parentList = new InnerPojo<Parent>();
Parent parent = new Parent();
parent.setName("zhangsan");
parent.setAge(Integer.MAX_VALUE);
parentList.setList(Arrays.asList(parent));
ListResult<InnerPojo<Parent>> list = new ListResult<InnerPojo<Parent>>();
list.setResult(Arrays.asList(parentList));
Object generializeObject = PojoUtils.generalize(list);
Object realizeObject = PojoUtils.realize(generializeObject, ListResult.class);
assertTrue(realizeObject instanceof ListResult);
ListResult realizeList = (ListResult) realizeObject;
List realizeInnerList = realizeList.getResult();
Assertions.assertEquals(1, realizeInnerList.size());
assertTrue(realizeInnerList.get(0) instanceof InnerPojo);
InnerPojo realizeParentList = (InnerPojo) realizeInnerList.get(0);
Assertions.assertEquals(1, realizeParentList.getList().size());
assertTrue(realizeParentList.getList().get(0) instanceof Parent);
Parent realizeParent = (Parent) realizeParentList.getList().get(0);
Assertions.assertEquals(parent.getName(), realizeParent.getName());
Assertions.assertEquals(parent.getAge(), realizeParent.getAge());
}
@Test
void testDateTimeTimestamp() throws Exception {
String dateStr = "2018-09-12";
String timeStr = "10:12:33";
String dateTimeStr = "2018-09-12 10:12:33";
String[] dateFormat = new String[] {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "HH:mm:ss"};
// java.util.Date
Object date = PojoUtils.realize(dateTimeStr, Date.class, (Type) Date.class);
assertEquals(Date.class, date.getClass());
assertEquals(dateTimeStr, new SimpleDateFormat(dateFormat[0]).format(date));
// java.sql.Time
Object time = PojoUtils.realize(dateTimeStr, java.sql.Time.class, (Type) java.sql.Time.class);
assertEquals(java.sql.Time.class, time.getClass());
assertEquals(timeStr, new SimpleDateFormat(dateFormat[2]).format(time));
// java.sql.Date
Object sqlDate = PojoUtils.realize(dateTimeStr, java.sql.Date.class, (Type) java.sql.Date.class);
assertEquals(java.sql.Date.class, sqlDate.getClass());
assertEquals(dateStr, new SimpleDateFormat(dateFormat[1]).format(sqlDate));
// java.sql.Timestamp
Object timestamp = PojoUtils.realize(dateTimeStr, java.sql.Timestamp.class, (Type) java.sql.Timestamp.class);
assertEquals(java.sql.Timestamp.class, timestamp.getClass());
assertEquals(dateTimeStr, new SimpleDateFormat(dateFormat[0]).format(timestamp));
}
@Test
void testIntToBoolean() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("name", "myname");
map.put("male", 1);
map.put("female", 0);
PersonInfo personInfo = (PersonInfo) PojoUtils.realize(map, PersonInfo.class);
assertEquals("myname", personInfo.getName());
assertTrue(personInfo.isMale());
assertFalse(personInfo.isFemale());
}
@Test
void testRealizeCollectionWithNullElement() {
LinkedList<String> listStr = new LinkedList<>();
listStr.add("arrayValue");
listStr.add(null);
HashSet<String> setStr = new HashSet<>();
setStr.add("setValue");
setStr.add(null);
Object listResult = PojoUtils.realize(listStr, LinkedList.class);
assertEquals(LinkedList.class, listResult.getClass());
assertEquals(listResult, listStr);
Object setResult = PojoUtils.realize(setStr, HashSet.class);
assertEquals(HashSet.class, setResult.getClass());
assertEquals(setResult, setStr);
}
@Test
void testJava8Time() {
Object localDateTimeGen = PojoUtils.generalize(LocalDateTime.now());
Object localDateTime = PojoUtils.realize(localDateTimeGen, LocalDateTime.class);
assertEquals(localDateTimeGen, localDateTime.toString());
Object localDateGen = PojoUtils.generalize(LocalDate.now());
Object localDate = PojoUtils.realize(localDateGen, LocalDate.class);
assertEquals(localDateGen, localDate.toString());
Object localTimeGen = PojoUtils.generalize(LocalTime.now());
Object localTime = PojoUtils.realize(localTimeGen, LocalTime.class);
assertEquals(localTimeGen, localTime.toString());
}
@Test
public void testJSONObjectToPersonMapPojo() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("personId", "1");
jsonObject.put("personName", "hand");
Object result = PojoUtils.realize(jsonObject, PersonMap.class);
assertEquals(PersonMap.class, result.getClass());
}
protected PersonInfo createPersonInfoByName(String name) {
PersonInfo dataPerson = new PersonInfo();
dataPerson.setName(name);
return dataPerson;
}
protected Ageneric<PersonInfo> createAGenericPersonInfo(String name) {
Ageneric<PersonInfo> ret = new Ageneric();
ret.setData(createPersonInfoByName(name));
return ret;
}
protected Bgeneric<PersonInfo> createBGenericPersonInfo(String name) {
Bgeneric<PersonInfo> ret = new Bgeneric();
ret.setData(createPersonInfoByName(name));
return ret;
}
@Test
public void testPojoGeneric1() throws NoSuchMethodException {
String personName = "testName";
{
Ageneric<PersonInfo> genericPersonInfo = createAGenericPersonInfo(personName);
Object o = JSON.toJSON(genericPersonInfo);
{
Ageneric personInfo = (Ageneric) PojoUtils.realize(o, Ageneric.class);
assertEquals(Ageneric.NAME, personInfo.getName());
assertTrue(personInfo.getData() instanceof Map);
}
{
Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(
PojoUtilsTest.class.getDeclaredMethod("createAGenericPersonInfo", String.class));
Ageneric personInfo = (Ageneric)
PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]);
assertEquals(Ageneric.NAME, personInfo.getName());
assertEquals(personInfo.getData().getClass(), PersonInfo.class);
assertEquals(personName, ((PersonInfo) personInfo.getData()).getName());
}
}
{
Bgeneric<PersonInfo> genericPersonInfo = createBGenericPersonInfo(personName);
Object o = JSON.toJSON(genericPersonInfo);
{
Bgeneric personInfo = (Bgeneric) PojoUtils.realize(o, Bgeneric.class);
assertEquals(Bgeneric.NAME, personInfo.getName());
assertTrue(personInfo.getData() instanceof Map);
}
{
Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(
PojoUtilsTest.class.getDeclaredMethod("createBGenericPersonInfo", String.class));
Bgeneric personInfo = (Bgeneric)
PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]);
assertEquals(Bgeneric.NAME, personInfo.getName());
assertEquals(personInfo.getData().getClass(), PersonInfo.class);
assertEquals(personName, ((PersonInfo) personInfo.getData()).getName());
}
}
}
protected Ageneric<Ageneric<PersonInfo>> createAGenericLoop(String name) {
Ageneric<Ageneric<PersonInfo>> ret = new Ageneric();
ret.setData(createAGenericPersonInfo(name));
return ret;
}
protected Bgeneric<Ageneric<PersonInfo>> createBGenericWithAgeneric(String name) {
Bgeneric<Ageneric<PersonInfo>> ret = new Bgeneric();
ret.setData(createAGenericPersonInfo(name));
return ret;
}
@Test
public void testPojoGeneric2() throws NoSuchMethodException {
String personName = "testName";
{
Ageneric<Ageneric<PersonInfo>> generic2PersonInfo = createAGenericLoop(personName);
Object o = JSON.toJSON(generic2PersonInfo);
{
Ageneric personInfo = (Ageneric) PojoUtils.realize(o, Ageneric.class);
assertEquals(Ageneric.NAME, personInfo.getName());
assertTrue(personInfo.getData() instanceof Map);
}
{
Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(
PojoUtilsTest.class.getDeclaredMethod("createAGenericLoop", String.class));
Ageneric personInfo = (Ageneric)
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.hamcrest.Matchers.startsWith;
import static org.mockito.Mockito.verify;
class ClassUtilsTest {
@Test
void testForNameWithThreadContextClassLoader() throws Exception {
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
try {
ClassLoader classLoader = Mockito.mock(ClassLoader.class);
Thread.currentThread().setContextClassLoader(classLoader);
ClassUtils.forNameWithThreadContextClassLoader("a.b.c.D");
verify(classLoader).loadClass("a.b.c.D");
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
@Test
void tetForNameWithCallerClassLoader() throws Exception {
Class c = ClassUtils.forNameWithCallerClassLoader(ClassUtils.class.getName(), ClassUtilsTest.class);
assertThat(c == ClassUtils.class, is(true));
}
@Test
void testGetCallerClassLoader() {
assertThat(
ClassUtils.getCallerClassLoader(ClassUtilsTest.class),
sameInstance(ClassUtilsTest.class.getClassLoader()));
}
@Test
void testGetClassLoader1() {
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
try {
assertThat(ClassUtils.getClassLoader(ClassUtilsTest.class), sameInstance(oldClassLoader));
Thread.currentThread().setContextClassLoader(null);
assertThat(
ClassUtils.getClassLoader(ClassUtilsTest.class),
sameInstance(ClassUtilsTest.class.getClassLoader()));
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
@Test
void testGetClassLoader2() {
assertThat(ClassUtils.getClassLoader(), sameInstance(ClassUtils.class.getClassLoader()));
}
@Test
void testForName1() throws Exception {
assertThat(ClassUtils.forName(ClassUtilsTest.class.getName()) == ClassUtilsTest.class, is(true));
}
@Test
void testForName2() throws Exception {
assertThat(ClassUtils.forName("byte") == byte.class, is(true));
assertThat(ClassUtils.forName("java.lang.String[]") == String[].class, is(true));
assertThat(ClassUtils.forName("[Ljava.lang.String;") == String[].class, is(true));
}
@Test
void testForName3() throws Exception {
ClassLoader classLoader = Mockito.mock(ClassLoader.class);
ClassUtils.forName("a.b.c.D", classLoader);
verify(classLoader).loadClass("a.b.c.D");
}
@Test
void testResolvePrimitiveClassName() {
assertThat(ClassUtils.resolvePrimitiveClassName("boolean") == boolean.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("byte") == byte.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("char") == char.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("double") == double.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("float") == float.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("int") == int.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("long") == long.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("short") == short.class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[Z") == boolean[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[B") == byte[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[C") == char[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[D") == double[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[F") == float[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[I") == int[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[J") == long[].class, is(true));
assertThat(ClassUtils.resolvePrimitiveClassName("[S") == short[].class, is(true));
}
@Test
void testToShortString() {
assertThat(ClassUtils.toShortString(null), equalTo("null"));
assertThat(ClassUtils.toShortString(new ClassUtilsTest()), startsWith("ClassUtilsTest@"));
}
@Test
void testConvertPrimitive() {
assertThat(ClassUtils.convertPrimitive(char.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(char.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(char.class, "6"), equalTo(Character.valueOf('6')));
assertThat(ClassUtils.convertPrimitive(boolean.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(boolean.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(boolean.class, "true"), equalTo(Boolean.TRUE));
assertThat(ClassUtils.convertPrimitive(byte.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(byte.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(byte.class, "127"), equalTo(Byte.MAX_VALUE));
assertThat(ClassUtils.convertPrimitive(short.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(short.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(short.class, "32767"), equalTo(Short.MAX_VALUE));
assertThat(ClassUtils.convertPrimitive(int.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(int.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(int.class, "6"), equalTo(6));
assertThat(ClassUtils.convertPrimitive(long.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(long.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(long.class, "6"), equalTo(Long.valueOf(6)));
assertThat(ClassUtils.convertPrimitive(float.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(float.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(float.class, "1.1"), equalTo(Float.valueOf(1.1F)));
assertThat(ClassUtils.convertPrimitive(double.class, ""), equalTo(null));
assertThat(ClassUtils.convertPrimitive(double.class, null), equalTo(null));
assertThat(ClassUtils.convertPrimitive(double.class, "10.1"), equalTo(Double.valueOf(10.1)));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.utils.MethodUtils.excludedDeclaredClass;
import static org.apache.dubbo.common.utils.MethodUtils.findMethod;
import static org.apache.dubbo.common.utils.MethodUtils.findNearestOverriddenMethod;
import static org.apache.dubbo.common.utils.MethodUtils.findOverriddenMethod;
import static org.apache.dubbo.common.utils.MethodUtils.getAllDeclaredMethods;
import static org.apache.dubbo.common.utils.MethodUtils.getAllMethods;
import static org.apache.dubbo.common.utils.MethodUtils.getDeclaredMethods;
import static org.apache.dubbo.common.utils.MethodUtils.getMethods;
import static org.apache.dubbo.common.utils.MethodUtils.invokeMethod;
import static org.apache.dubbo.common.utils.MethodUtils.overrides;
class MethodUtilsTest {
@Test
void testGetMethod() {
Method getMethod = null;
for (Method method : MethodTestClazz.class.getMethods()) {
if (MethodUtils.isGetter(method)) {
getMethod = method;
}
}
Assertions.assertNotNull(getMethod);
Assertions.assertEquals("getValue", getMethod.getName());
}
@Test
void testSetMethod() {
Method setMethod = null;
for (Method method : MethodTestClazz.class.getMethods()) {
if (MethodUtils.isSetter(method)) {
setMethod = method;
}
}
Assertions.assertNotNull(setMethod);
Assertions.assertEquals("setValue", setMethod.getName());
}
@Test
void testIsDeprecated() throws Exception {
Assertions.assertTrue(MethodUtils.isDeprecated(MethodTestClazz.class.getMethod("deprecatedMethod")));
Assertions.assertFalse(MethodUtils.isDeprecated(MethodTestClazz.class.getMethod("getValue")));
}
@Test
void testIsMetaMethod() {
boolean containMetaMethod = false;
for (Method method : MethodTestClazz.class.getMethods()) {
if (MethodUtils.isMetaMethod(method)) {
containMetaMethod = true;
}
}
Assertions.assertTrue(containMetaMethod);
}
@Test
void testGetMethods() throws NoSuchMethodException {
Assertions.assertTrue(getDeclaredMethods(MethodTestClazz.class, excludedDeclaredClass(String.class))
.size()
> 0);
Assertions.assertTrue(getMethods(MethodTestClazz.class).size() > 0);
Assertions.assertTrue(getAllDeclaredMethods(MethodTestClazz.class).size() > 0);
Assertions.assertTrue(getAllMethods(MethodTestClazz.class).size() > 0);
Assertions.assertNotNull(findMethod(MethodTestClazz.class, "getValue"));
MethodTestClazz methodTestClazz = new MethodTestClazz();
invokeMethod(methodTestClazz, "setValue", "Test");
Assertions.assertEquals(methodTestClazz.getValue(), "Test");
Assertions.assertTrue(
overrides(MethodOverrideClazz.class.getMethod("get"), MethodTestClazz.class.getMethod("get")));
Assertions.assertEquals(
findNearestOverriddenMethod(MethodOverrideClazz.class.getMethod("get")),
MethodTestClazz.class.getMethod("get"));
Assertions.assertEquals(
findOverriddenMethod(MethodOverrideClazz.class.getMethod("get"), MethodOverrideClazz.class),
MethodTestClazz.class.getMethod("get"));
}
@Test
void testExtractFieldName() throws Exception {
Method m1 = MethodFieldTestClazz.class.getMethod("is");
Method m2 = MethodFieldTestClazz.class.getMethod("get");
Method m3 = MethodFieldTestClazz.class.getMethod("getClass");
Method m4 = MethodFieldTestClazz.class.getMethod("getObject");
Method m5 = MethodFieldTestClazz.class.getMethod("getFieldName1");
Method m6 = MethodFieldTestClazz.class.getMethod("setFieldName2");
Method m7 = MethodFieldTestClazz.class.getMethod("isFieldName3");
Assertions.assertEquals("", MethodUtils.extractFieldName(m1));
Assertions.assertEquals("", MethodUtils.extractFieldName(m2));
Assertions.assertEquals("", MethodUtils.extractFieldName(m3));
Assertions.assertEquals("", MethodUtils.extractFieldName(m4));
Assertions.assertEquals("fieldName1", MethodUtils.extractFieldName(m5));
Assertions.assertEquals("fieldName2", MethodUtils.extractFieldName(m6));
Assertions.assertEquals("fieldName3", MethodUtils.extractFieldName(m7));
}
public class MethodFieldTestClazz {
public String is() {
return "";
}
public String get() {
return "";
}
public String getObject() {
return "";
}
public String getFieldName1() {
return "";
}
public String setFieldName2() {
return "";
}
public String isFieldName3() {
return "";
}
}
public class MethodTestClazz {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public MethodTestClazz get() {
return this;
}
@Deprecated
public Boolean deprecatedMethod() {
return true;
}
}
public class MethodOverrideClazz extends MethodTestClazz {
@Override
public MethodTestClazz get() {
return this;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/SerializeSecurityConfiguratorTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/SerializeSecurityConfiguratorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import com.service.DemoService1;
import com.service.DemoService2;
import com.service.DemoService4;
import com.service.Params;
import com.service.Service;
import com.service.User;
import com.service.UserService;
import com.service.deep1.deep2.deep3.DemoService3;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SerializeSecurityConfiguratorTest {
@Test
void test() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.getAllowedPrefix().contains("java.util.HashMap"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.example.DemoInterface"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.sun.Interface1"));
Assertions.assertTrue(ssm.getDisAllowedPrefix().contains("com.exampletest.DemoInterface"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.sun.Interface2"));
Assertions.assertEquals(AllowClassNotifyListener.DEFAULT_STATUS, ssm.getCheckStatus());
frameworkModel.destroy();
}
@Test
void testStatus1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setSerializeCheckStatus(SerializeCheckStatus.DISABLE.name());
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertEquals(SerializeCheckStatus.DISABLE, ssm.getCheckStatus());
frameworkModel.destroy();
}
@Test
void testStatus2() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setSerializeCheckStatus(SerializeCheckStatus.WARN.name());
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertEquals(SerializeCheckStatus.WARN, ssm.getCheckStatus());
frameworkModel.destroy();
}
@Test
void testStatus3() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setSerializeCheckStatus(SerializeCheckStatus.STRICT.name());
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertEquals(SerializeCheckStatus.STRICT, ssm.getCheckStatus());
frameworkModel.destroy();
}
@Test
void testStatus4() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_OPEN_CHECK, "false");
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertEquals(SerializeCheckStatus.DISABLE, ssm.getCheckStatus());
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_OPEN_CHECK);
frameworkModel.destroy();
}
@Test
void testStatus5() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCK_ALL, "true");
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertEquals(SerializeCheckStatus.STRICT, ssm.getCheckStatus());
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCK_ALL);
frameworkModel.destroy();
}
@Test
void testConfig1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_ALLOWED_LIST, "test.package1, test.package2, ,");
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package2"));
SystemPropertyConfigUtils.clearSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_ALLOWED_LIST);
frameworkModel.destroy();
}
@Test
void testConfig2() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCKED_LIST, "test.package1, test.package2, ,");
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.getDisAllowedPrefix().contains("test.package1"));
Assertions.assertTrue(ssm.getDisAllowedPrefix().contains("test.package2"));
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCK_ALL);
frameworkModel.destroy();
}
@Test
void testConfig3() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_ALLOWED_LIST, "test.package1, test.package2, ,");
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCKED_LIST, "test.package1, test.package2, ,");
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package2"));
SystemPropertyConfigUtils.clearSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_ALLOWED_LIST);
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCK_ALL);
frameworkModel.destroy();
}
@Test
void testSerializable1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setCheckSerializable(false);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertFalse(ssm.isCheckSerializable());
frameworkModel.destroy();
}
@Test
void testSerializable2() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.isCheckSerializable());
frameworkModel.destroy();
}
@Test
void testGeneric() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService4.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.DemoService4"));
frameworkModel.destroy();
}
@Test
void testGenericClass() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(UserService.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains(UserService.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Service.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Params.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(User.class.getName()));
frameworkModel.destroy();
}
@Test
void testRegister1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService1.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.DemoService1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo2"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo3"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo4"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo5"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo6"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo7"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo8"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Simple"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(List.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Set.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Map.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(LinkedList.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Vector.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(HashSet.class.getName()));
frameworkModel.destroy();
}
@Test
void testRegister2() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService2.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.DemoService2"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo2"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo3"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo4"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo5"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo6"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo7"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Demo8"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.pojo.Simple"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(List.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Set.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Map.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(LinkedList.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(Vector.class.getName()));
Assertions.assertTrue(ssm.getAllowedPrefix().contains(HashSet.class.getName()));
frameworkModel.destroy();
}
@Test
void testRegister3() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setAutoTrustSerializeClass(false);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService1.class);
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.service.DemoService1"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo1"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo2"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo3"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo4"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo5"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo6"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo7"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Demo8"));
Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.pojo.Simple"));
frameworkModel.destroy();
}
@Test
void testRegister4() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setTrustSerializeClassLevel(4);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService3.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.deep1.deep2."));
frameworkModel.destroy();
}
@Test
void testRegister5() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ApplicationConfig applicationConfig = new ApplicationConfig("Test");
applicationConfig.setTrustSerializeClassLevel(10);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
serializeSecurityConfigurator.registerInterface(DemoService3.class);
Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.deep1.deep2.deep3.DemoService3"));
frameworkModel.destroy();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultSerializeClassCheckerTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultSerializeClassCheckerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.net.Socket;
import java.util.LinkedList;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class DefaultSerializeClassCheckerTest {
@BeforeEach
void setUp() {
FrameworkModel.destroyAll();
}
@AfterEach
void tearDown() {
FrameworkModel.destroyAll();
}
@Test
void testCommon() throws ClassNotFoundException {
FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.setCheckStatus(SerializeCheckStatus.WARN);
DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance();
for (int i = 0; i < 10; i++) {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.ReadLock.class.getName());
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), LinkedList.class.getName());
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), Integer.class.getName());
defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), int.class.getName());
}
Assertions.assertThrows(IllegalArgumentException.class, () -> {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), Socket.class.getName());
});
Assertions.assertTrue(FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.getWarnedClasses()
.contains(Socket.class.getName()));
}
@Test
void testAddAllow() throws ClassNotFoundException {
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_ALLOWED_LIST,
ReentrantReadWriteLock.WriteLock.class.getName() + ","
+ ReentrantReadWriteLock.ReadLock.class.getName());
DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance();
for (int i = 0; i < 10; i++) {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.WriteLock.class.getName());
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.ReadLock.class.getName());
}
SystemPropertyConfigUtils.clearSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_ALLOWED_LIST);
}
@Test
void testAddBlock() {
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCKED_LIST,
Runtime.class.getName() + "," + Thread.class.getName());
DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance();
for (int i = 0; i < 10; i++) {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), Runtime.class.getName());
});
Assertions.assertTrue(FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.getWarnedClasses()
.contains(Runtime.class.getName()));
Assertions.assertThrows(IllegalArgumentException.class, () -> {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), Thread.class.getName());
});
Assertions.assertTrue(FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.getWarnedClasses()
.contains(Thread.class.getName()));
}
SystemPropertyConfigUtils.clearSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCKED_LIST);
}
@Test
void testBlockAll() throws ClassNotFoundException {
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCK_ALL, "true");
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_ALLOWED_LIST,
ReentrantReadWriteLock.WriteLock.class.getName());
DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance();
for (int i = 0; i < 10; i++) {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.WriteLock.class.getName());
Assertions.assertThrows(IllegalArgumentException.class, () -> {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(),
ReentrantReadWriteLock.ReadLock.class.getName());
});
Assertions.assertTrue(FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.getWarnedClasses()
.contains(ReentrantReadWriteLock.ReadLock.class.getName()));
}
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCK_ALL);
SystemPropertyConfigUtils.clearSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_ALLOWED_LIST);
}
@Test
void testStatus() throws ClassNotFoundException {
FrameworkModel frameworkModel = FrameworkModel.defaultModel();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
ssm.setCheckStatus(SerializeCheckStatus.STRICT);
DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance();
Assertions.assertEquals(
Integer.class,
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), Integer.class.getName()));
Assertions.assertThrows(IllegalArgumentException.class, () -> {
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName());
});
Assertions.assertTrue(FrameworkModel.defaultModel()
.getBeanFactory()
.getBean(SerializeSecurityManager.class)
.getWarnedClasses()
.contains(ReentrantReadWriteLock.class.getName()));
ssm.setCheckStatus(SerializeCheckStatus.WARN);
Assertions.assertEquals(
ReentrantReadWriteLock.class,
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName()));
ssm.setCheckStatus(SerializeCheckStatus.DISABLE);
Assertions.assertEquals(
ReentrantReadWriteLock.class,
defaultSerializeClassChecker.loadClass(
Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName()));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/HolderTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/HolderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
class HolderTest {
@Test
void testSetAndGet() throws Exception {
Holder<String> holder = new Holder<String>();
String message = "hello";
holder.set(message);
assertThat(holder.get(), is(message));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.logger.Level;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
class LogTest {
@Test
void testLogName() {
Log log1 = new Log();
Log log2 = new Log();
Log log3 = new Log();
log1.setLogName("log-name");
log2.setLogName("log-name");
log3.setLogName("log-name-other");
assertThat(log1.getLogName(), equalTo("log-name"));
Assertions.assertEquals(log1, log2);
Assertions.assertEquals(log1.hashCode(), log2.hashCode());
Assertions.assertNotEquals(log1, log3);
}
@Test
void testLogLevel() {
Log log1 = new Log();
Log log2 = new Log();
Log log3 = new Log();
log1.setLogLevel(Level.ALL);
log2.setLogLevel(Level.ALL);
log3.setLogLevel(Level.DEBUG);
assertThat(log1.getLogLevel(), is(Level.ALL));
Assertions.assertEquals(log1, log2);
Assertions.assertEquals(log1.hashCode(), log2.hashCode());
Assertions.assertNotEquals(log1, log3);
}
@Test
void testLogMessage() {
Log log1 = new Log();
Log log2 = new Log();
Log log3 = new Log();
log1.setLogMessage("log-message");
log2.setLogMessage("log-message");
log3.setLogMessage("log-message-other");
assertThat(log1.getLogMessage(), equalTo("log-message"));
Assertions.assertEquals(log1, log2);
Assertions.assertEquals(log1.hashCode(), log2.hashCode());
Assertions.assertNotEquals(log1, log3);
}
@Test
void testLogThread() {
Log log1 = new Log();
Log log2 = new Log();
Log log3 = new Log();
log1.setLogThread("log-thread");
log2.setLogThread("log-thread");
log3.setLogThread("log-thread-other");
assertThat(log1.getLogThread(), equalTo("log-thread"));
Assertions.assertEquals(log1, log2);
Assertions.assertEquals(log1.hashCode(), log2.hashCode());
Assertions.assertNotEquals(log1, log3);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ProtobufUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/ProtobufUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.vo.UserVo;
import org.apache.dubbo.rpc.model.HelloReply;
import org.apache.dubbo.rpc.model.HelloRequest;
import org.apache.dubbo.rpc.model.Person;
import org.apache.dubbo.rpc.model.SerializablePerson;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class ProtobufUtilsTest {
@Test
void testIsProtobufClass() {
Assertions.assertTrue(ProtobufUtils.isProtobufClass(HelloRequest.class));
Assertions.assertTrue(ProtobufUtils.isProtobufClass(HelloReply.class));
Assertions.assertFalse(ProtobufUtils.isProtobufClass(Person.class));
Assertions.assertFalse(ProtobufUtils.isProtobufClass(SerializablePerson.class));
Assertions.assertFalse(ProtobufUtils.isProtobufClass(UserVo.class));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/UrlUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/UrlUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.URL;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.*;
class UrlUtilsTest {
String localAddress = "127.0.0.1";
@Test
void testAddressNull() {
String exceptionMessage = "Address is not allowed to be empty, please re-enter.";
try {
UrlUtils.parseURL(null, null);
} catch (IllegalArgumentException illegalArgumentException) {
assertEquals(exceptionMessage, illegalArgumentException.getMessage());
}
}
@Test
void testParseUrl() {
String address = "remote://root:alibaba@127.0.0.1:9090/dubbo.test.api";
URL url = UrlUtils.parseURL(address, null);
assertEquals(localAddress + ":9090", url.getAddress());
assertEquals("root", url.getUsername());
assertEquals("alibaba", url.getPassword());
assertEquals("dubbo.test.api", url.getPath());
assertEquals(9090, url.getPort());
assertEquals("remote", url.getProtocol());
}
@Test
void testParseURLWithSpecial() {
String address = "127.0.0.1:2181?backup=127.0.0.1:2182,127.0.0.1:2183";
assertEquals("dubbo://" + address, UrlUtils.parseURL(address, null).toString());
}
@Test
void testDefaultUrl() {
String address = "127.0.0.1";
URL url = UrlUtils.parseURL(address, null);
assertEquals(localAddress + ":9090", url.getAddress());
assertEquals(9090, url.getPort());
assertEquals("dubbo", url.getProtocol());
assertNull(url.getUsername());
assertNull(url.getPassword());
assertNull(url.getPath());
}
@Test
void testParseFromParameter() {
String address = "127.0.0.1";
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("username", "root");
parameters.put("password", "alibaba");
parameters.put("port", "10000");
parameters.put("protocol", "dubbo");
parameters.put("path", "dubbo.test.api");
parameters.put("aaa", "bbb");
parameters.put("ccc", "ddd");
URL url = UrlUtils.parseURL(address, parameters);
assertEquals(localAddress + ":10000", url.getAddress());
assertEquals("root", url.getUsername());
assertEquals("alibaba", url.getPassword());
assertEquals(10000, url.getPort());
assertEquals("dubbo", url.getProtocol());
assertEquals("dubbo.test.api", url.getPath());
assertEquals("bbb", url.getParameter("aaa"));
assertEquals("ddd", url.getParameter("ccc"));
}
@Test
void testParseUrl2() {
String address = "192.168.0.1";
String backupAddress1 = "192.168.0.2";
String backupAddress2 = "192.168.0.3";
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("username", "root");
parameters.put("password", "alibaba");
parameters.put("port", "10000");
parameters.put("protocol", "dubbo");
URL url = UrlUtils.parseURL(address + "," + backupAddress1 + "," + backupAddress2, parameters);
assertEquals("192.168.0.1:10000", url.getAddress());
assertEquals("root", url.getUsername());
assertEquals("alibaba", url.getPassword());
assertEquals(10000, url.getPort());
assertEquals("dubbo", url.getProtocol());
assertEquals("192.168.0.2" + "," + "192.168.0.3", url.getParameter("backup"));
}
@Test
void testParseUrls() {
String addresses = "192.168.0.1|192.168.0.2|192.168.0.3";
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("username", "root");
parameters.put("password", "alibaba");
parameters.put("port", "10000");
parameters.put("protocol", "dubbo");
List<URL> urls = UrlUtils.parseURLs(addresses, parameters);
assertEquals("192.168.0.1" + ":10000", urls.get(0).getAddress());
assertEquals("192.168.0.2" + ":10000", urls.get(1).getAddress());
}
@Test
void testParseUrlsAddressNull() {
String exceptionMessage = "Address is not allowed to be empty, please re-enter.";
try {
UrlUtils.parseURLs(null, null);
} catch (IllegalArgumentException illegalArgumentException) {
assertEquals(exceptionMessage, illegalArgumentException.getMessage());
}
}
@Test
void testConvertRegister() {
String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, Map<String, String>> register = new HashMap<String, Map<String, String>>();
register.put(key, null);
Map<String, Map<String, String>> newRegister = UrlUtils.convertRegister(register);
assertEquals(register, newRegister);
}
@Test
void testConvertRegister2() {
String key = "dubbo.test.api.HelloService";
Map<String, Map<String, String>> register = new HashMap<String, Map<String, String>>();
Map<String, String> service = new HashMap<String, String>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "version=1.0.0&group=test&dubbo.version=2.0.0");
register.put(key, service);
Map<String, Map<String, String>> newRegister = UrlUtils.convertRegister(register);
Map<String, String> newService = new HashMap<String, String>();
newService.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "dubbo.version=2.0.0&group=test&version=1.0.0");
assertEquals(newService, newRegister.get("test/dubbo.test.api.HelloService:1.0.0"));
}
@Test
void testSubscribe() {
String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, String> subscribe = new HashMap<String, String>();
subscribe.put(key, null);
Map<String, String> newSubscribe = UrlUtils.convertSubscribe(subscribe);
assertEquals(subscribe, newSubscribe);
}
@Test
void testSubscribe2() {
String key = "dubbo.test.api.HelloService";
Map<String, String> subscribe = new HashMap<String, String>();
subscribe.put(key, "version=1.0.0&group=test&dubbo.version=2.0.0");
Map<String, String> newSubscribe = UrlUtils.convertSubscribe(subscribe);
assertEquals(
"dubbo.version=2.0.0&group=test&version=1.0.0",
newSubscribe.get("test/dubbo.test.api.HelloService:1.0.0"));
}
@Test
void testRevertRegister() {
String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, Map<String, String>> register = new HashMap<String, Map<String, String>>();
Map<String, String> service = new HashMap<String, String>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", null);
register.put(key, service);
Map<String, Map<String, String>> newRegister = UrlUtils.revertRegister(register);
Map<String, Map<String, String>> expectedRegister = new HashMap<String, Map<String, String>>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
expectedRegister.put("dubbo.test.api.HelloService", service);
assertEquals(expectedRegister, newRegister);
}
@Test
void testRevertRegister2() {
String key = "dubbo.test.api.HelloService";
Map<String, Map<String, String>> register = new HashMap<String, Map<String, String>>();
Map<String, String> service = new HashMap<String, String>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", null);
register.put(key, service);
Map<String, Map<String, String>> newRegister = UrlUtils.revertRegister(register);
Map<String, Map<String, String>> expectedRegister = new HashMap<String, Map<String, String>>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", null);
expectedRegister.put("dubbo.test.api.HelloService", service);
assertEquals(expectedRegister, newRegister);
}
@Test
void testRevertSubscribe() {
String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, String> subscribe = new HashMap<String, String>();
subscribe.put(key, null);
Map<String, String> newSubscribe = UrlUtils.revertSubscribe(subscribe);
Map<String, String> expectSubscribe = new HashMap<String, String>();
expectSubscribe.put("dubbo.test.api.HelloService", "group=perf&version=1.0.0");
assertEquals(expectSubscribe, newSubscribe);
}
@Test
void testRevertSubscribe2() {
String key = "dubbo.test.api.HelloService";
Map<String, String> subscribe = new HashMap<String, String>();
subscribe.put(key, null);
Map<String, String> newSubscribe = UrlUtils.revertSubscribe(subscribe);
assertEquals(subscribe, newSubscribe);
}
@Test
void testRevertNotify() {
String key = "dubbo.test.api.HelloService";
Map<String, Map<String, String>> notify = new HashMap<String, Map<String, String>>();
Map<String, String> service = new HashMap<String, String>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
notify.put(key, service);
Map<String, Map<String, String>> newRegister = UrlUtils.revertNotify(notify);
Map<String, Map<String, String>> expectedRegister = new HashMap<String, Map<String, String>>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
expectedRegister.put("perf/dubbo.test.api.HelloService:1.0.0", service);
assertEquals(expectedRegister, newRegister);
}
@Test
void testRevertNotify2() {
String key = "perf/dubbo.test.api.HelloService:1.0.0";
Map<String, Map<String, String>> notify = new HashMap<String, Map<String, String>>();
Map<String, String> service = new HashMap<String, String>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
notify.put(key, service);
Map<String, Map<String, String>> newRegister = UrlUtils.revertNotify(notify);
Map<String, Map<String, String>> expectedRegister = new HashMap<String, Map<String, String>>();
service.put("dubbo://127.0.0.1:20880/com.xxx.XxxService", "group=perf&version=1.0.0");
expectedRegister.put("perf/dubbo.test.api.HelloService:1.0.0", service);
assertEquals(expectedRegister, newRegister);
}
// backward compatibility for version 2.0.0
@Test
void testRevertForbid() {
String service = "dubbo.test.api.HelloService";
List<String> forbid = new ArrayList<String>();
forbid.add(service);
Set<URL> subscribed = new HashSet<URL>();
subscribed.add(URL.valueOf("dubbo://127.0.0.1:20880/" + service + "?group=perf&version=1.0.0"));
List<String> newForbid = UrlUtils.revertForbid(forbid, subscribed);
List<String> expectForbid = new ArrayList<String>();
expectForbid.add("perf/" + service + ":1.0.0");
assertEquals(expectForbid, newForbid);
}
@Test
void testRevertForbid2() {
List<String> newForbid = UrlUtils.revertForbid(null, null);
assertNull(newForbid);
}
@Test
void testRevertForbid3() {
String service1 = "dubbo.test.api.HelloService:1.0.0";
String service2 = "dubbo.test.api.HelloService:2.0.0";
List<String> forbid = new ArrayList<String>();
forbid.add(service1);
forbid.add(service2);
List<String> newForbid = UrlUtils.revertForbid(forbid, null);
assertEquals(forbid, newForbid);
}
@Test
void testIsMatch() {
URL consumerUrl = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?version=1.0.0&group=test");
URL providerUrl = URL.valueOf("http://127.0.0.1:8080/com.xxx.XxxService?version=1.0.0&group=test");
assertTrue(UrlUtils.isMatch(consumerUrl, providerUrl));
}
@Test
void testIsMatch2() {
URL consumerUrl = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?version=2.0.0&group=test");
URL providerUrl = URL.valueOf("http://127.0.0.1:8080/com.xxx.XxxService?version=1.0.0&group=test");
assertFalse(UrlUtils.isMatch(consumerUrl, providerUrl));
}
@Test
void testIsMatch3() {
URL consumerUrl = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?version=1.0.0&group=aa");
URL providerUrl = URL.valueOf("http://127.0.0.1:8080/com.xxx.XxxService?version=1.0.0&group=test");
assertFalse(UrlUtils.isMatch(consumerUrl, providerUrl));
}
@Test
void testIsMatch4() {
URL consumerUrl = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?version=1.0.0&group=*");
URL providerUrl = URL.valueOf("http://127.0.0.1:8080/com.xxx.XxxService?version=1.0.0&group=test");
assertTrue(UrlUtils.isMatch(consumerUrl, providerUrl));
}
@Test
void testIsMatch5() {
URL consumerUrl = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?version=*&group=test");
URL providerUrl = URL.valueOf("http://127.0.0.1:8080/com.xxx.XxxService?version=1.0.0&group=test");
assertTrue(UrlUtils.isMatch(consumerUrl, providerUrl));
}
@Test
void testIsItemMatch() throws Exception {
assertTrue(UrlUtils.isItemMatch(null, null));
assertTrue(!UrlUtils.isItemMatch("1", null));
assertTrue(!UrlUtils.isItemMatch(null, "1"));
assertTrue(UrlUtils.isItemMatch("1", "1"));
assertTrue(UrlUtils.isItemMatch("*", null));
assertTrue(UrlUtils.isItemMatch("*", "*"));
assertTrue(UrlUtils.isItemMatch("*", "1234"));
assertTrue(!UrlUtils.isItemMatch(null, "*"));
}
@Test
void testIsServiceKeyMatch() throws Exception {
URL url = URL.valueOf("test://127.0.0.1");
URL pattern = url.addParameter(GROUP_KEY, "test")
.addParameter(INTERFACE_KEY, "test")
.addParameter(VERSION_KEY, "test");
URL value = pattern;
assertTrue(UrlUtils.isServiceKeyMatch(pattern, value));
pattern = pattern.addParameter(GROUP_KEY, "*");
assertTrue(UrlUtils.isServiceKeyMatch(pattern, value));
pattern = pattern.addParameter(VERSION_KEY, "*");
assertTrue(UrlUtils.isServiceKeyMatch(pattern, value));
}
@Test
void testGetEmptyUrl() throws Exception {
URL url = UrlUtils.getEmptyUrl("dubbo/a.b.c.Foo:1.0.0", "test");
assertThat(url.toFullString(), equalTo("empty://0.0.0.0/a.b.c.Foo?category=test&group=dubbo&version=1.0.0"));
}
@Test
void testIsMatchGlobPattern() throws Exception {
assertTrue(UrlUtils.isMatchGlobPattern("*", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("", null));
assertFalse(UrlUtils.isMatchGlobPattern("", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("value", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("v*", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("*e", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("v*e", "value"));
assertTrue(UrlUtils.isMatchGlobPattern("$key", "value", URL.valueOf("dubbo://localhost:8080/Foo?key=v*e")));
}
@Test
void testIsMatchUrlWithDefaultPrefix() {
URL url = URL.valueOf("dubbo://127.0.0.1:20880/com.xxx.XxxService?default.version=1.0.0&default.group=test");
assertEquals("1.0.0", url.getVersion());
assertEquals("1.0.0", url.getParameter("default.version"));
URL consumerUrl = URL.valueOf("consumer://127.0.0.1/com.xxx.XxxService?version=1.0.0&group=test");
assertTrue(UrlUtils.isMatch(consumerUrl, url));
URL consumerUrl1 =
URL.valueOf("consumer://127.0.0.1/com.xxx.XxxService?default.version=1.0.0&default.group=test");
assertTrue(UrlUtils.isMatch(consumerUrl1, url));
}
@Test
public void testIsConsumer() {
String address1 = "remote://root:alibaba@127.0.0.1:9090";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "consumer://root:alibaba@127.0.0.1:9090";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "consumer://root:alibaba@127.0.0.1";
URL url3 = UrlUtils.parseURL(address3, null);
assertFalse(UrlUtils.isConsumer(url1));
assertTrue(UrlUtils.isConsumer(url2));
assertTrue(UrlUtils.isConsumer(url3));
}
@Test
public void testPrivateConstructor() throws Exception {
Constructor<UrlUtils> constructor = UrlUtils.class.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
assertThrows(InvocationTargetException.class, () -> {
constructor.newInstance();
});
}
@Test
public void testClassifyUrls() {
String address1 = "remote://root:alibaba@127.0.0.1:9090";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "consumer://root:alibaba@127.0.0.1:9090";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "remote://root:alibaba@127.0.0.1";
URL url3 = UrlUtils.parseURL(address3, null);
String address4 = "consumer://root:alibaba@127.0.0.1";
URL url4 = UrlUtils.parseURL(address4, null);
List<URL> urls = new ArrayList<>();
urls.add(url1);
urls.add(url2);
urls.add(url3);
urls.add(url4);
List<URL> consumerUrls = UrlUtils.classifyUrls(urls, UrlUtils::isConsumer);
assertEquals(2, consumerUrls.size());
assertTrue(consumerUrls.contains(url2));
assertTrue(consumerUrls.contains(url4));
List<URL> nonConsumerUrls = UrlUtils.classifyUrls(urls, url -> !UrlUtils.isConsumer(url));
assertEquals(2, nonConsumerUrls.size());
assertTrue(nonConsumerUrls.contains(url1));
assertTrue(nonConsumerUrls.contains(url3));
}
@Test
public void testHasServiceDiscoveryRegistryProtocol() {
String address1 = "http://root:alibaba@127.0.0.1:9090/dubbo.test.api";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "service-discovery-registry://root:alibaba@127.0.0.1:9090/dubbo.test.api";
URL url2 = UrlUtils.parseURL(address2, null);
assertFalse(UrlUtils.hasServiceDiscoveryRegistryProtocol(url1));
assertTrue(UrlUtils.hasServiceDiscoveryRegistryProtocol(url2));
}
private static final String SERVICE_REGISTRY_TYPE = "service";
private static final String REGISTRY_TYPE_KEY = "registry-type";
@Test
public void testHasServiceDiscoveryRegistryTypeKey() {
Map<String, String> parameters1 = new HashMap<>();
parameters1.put(REGISTRY_TYPE_KEY, "value2");
assertFalse(UrlUtils.hasServiceDiscoveryRegistryTypeKey(parameters1));
Map<String, String> parameters2 = new HashMap<>();
parameters2.put(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE);
assertTrue(UrlUtils.hasServiceDiscoveryRegistryTypeKey(parameters2));
}
@Test
public void testIsConfigurator() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "override://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "http://example.com?category=configurators";
URL url3 = UrlUtils.parseURL(address3, null);
assertFalse(UrlUtils.isConfigurator(url1));
assertTrue(UrlUtils.isConfigurator(url2));
assertTrue(UrlUtils.isConfigurator(url3));
}
@Test
public void testIsRoute() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "route://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "http://example.com?category=routers";
URL url3 = UrlUtils.parseURL(address3, null);
assertFalse(UrlUtils.isRoute(url1));
assertTrue(UrlUtils.isRoute(url2));
assertTrue(UrlUtils.isRoute(url3));
}
@Test
public void testIsProvider() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "override://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "route://example.com";
URL url3 = UrlUtils.parseURL(address3, null);
String address4 = "http://example.com?category=providers";
URL url4 = UrlUtils.parseURL(address4, null);
String address5 = "http://example.com?category=something-else";
URL url5 = UrlUtils.parseURL(address5, null);
assertTrue(UrlUtils.isProvider(url1));
assertFalse(UrlUtils.isProvider(url2));
assertFalse(UrlUtils.isProvider(url3));
assertTrue(UrlUtils.isProvider(url4));
assertFalse(UrlUtils.isProvider(url5));
}
@Test
public void testIsRegistry() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "registry://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "sr://example.com";
URL url3 = UrlUtils.parseURL(address3, null);
String address4 = "custom-registry-protocol://example.com";
URL url4 = UrlUtils.parseURL(address4, null);
assertFalse(UrlUtils.isRegistry(url1));
assertTrue(UrlUtils.isRegistry(url2));
assertFalse(UrlUtils.isRegistry(url3));
assertTrue(UrlUtils.isRegistry(url4));
}
@Test
public void testIsServiceDiscoveryURL() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "service-discovery-registry://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "SERVICE-DISCOVERY-REGISTRY://example.com";
URL url3 = UrlUtils.parseURL(address3, null);
String address4 = "http://example.com?registry-type=service";
URL url4 = UrlUtils.parseURL(address4, null);
url4.addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE);
assertFalse(UrlUtils.isServiceDiscoveryURL(url1));
assertTrue(UrlUtils.isServiceDiscoveryURL(url2));
assertTrue(UrlUtils.isServiceDiscoveryURL(url3));
assertTrue(UrlUtils.isServiceDiscoveryURL(url4));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicateTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicateTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.function.Predicate;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringConstantFieldValuePredicate} Test
*
* @since 2.7.8
*/
class StringConstantFieldValuePredicateTest {
public static final String S1 = "1";
public static final Object O1 = "2";
public static final Object O2 = 3;
@Test
void test() {
Predicate<String> predicate = of(getClass());
assertTrue(predicate.test("1"));
assertTrue(predicate.test("2"));
assertFalse(predicate.test("3"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AssertTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/AssertTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.utils.Assert.notEmptyString;
import static org.apache.dubbo.common.utils.Assert.notNull;
class AssertTest {
@Test
void testNotNull1() {
Assertions.assertThrows(IllegalArgumentException.class, () -> notNull(null, "null object"));
}
@Test
void testNotNull2() {
Assertions.assertThrows(
IllegalStateException.class, () -> notNull(null, new IllegalStateException("null object")));
}
@Test
void testNotNullWhenInputNotNull1() {
notNull(new Object(), "null object");
}
@Test
void testNotNullWhenInputNotNull2() {
notNull(new Object(), new IllegalStateException("null object"));
}
@Test
void testNotNullString() {
Assertions.assertThrows(IllegalArgumentException.class, () -> notEmptyString(null, "Message can't be null"));
}
@Test
void testNotEmptyString() {
Assertions.assertThrows(
IllegalArgumentException.class, () -> notEmptyString("", "Message can't be null or empty"));
}
@Test
void testNotNullNotEmptyString() {
notEmptyString("abcd", "Message can'be null or empty");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MemberUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/MemberUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.utils.MemberUtils.isPrivate;
import static org.apache.dubbo.common.utils.MemberUtils.isPublic;
import static org.apache.dubbo.common.utils.MemberUtils.isStatic;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link MemberUtils} Test
*
* @since 2.7.6
*/
class MemberUtilsTest {
@Test
void test() throws NoSuchMethodException {
assertFalse(isStatic(getClass().getMethod("noStatic")));
assertTrue(isStatic(getClass().getMethod("staticMethod")));
assertTrue(isPrivate(getClass().getDeclaredMethod("privateMethod")));
assertTrue(isPublic(getClass().getMethod("publicMethod")));
}
public void noStatic() {}
public static void staticMethod() {}
private void privateMethod() {}
public void publicMethod() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NamedThreadFactoryTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/NamedThreadFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class NamedThreadFactoryTest {
private static final int INITIAL_THREAD_NUM = 1;
@Test
void testNewThread() {
NamedThreadFactory factory = new NamedThreadFactory();
Thread t = factory.newThread(Mockito.mock(Runnable.class));
assertThat(t.getName(), allOf(containsString("pool-"), containsString("-thread-")));
assertFalse(t.isDaemon());
// since security manager is not installed.
assertSame(t.getThreadGroup(), Thread.currentThread().getThreadGroup());
}
@Test
void testPrefixAndDaemon() {
NamedThreadFactory factory = new NamedThreadFactory("prefix", true);
Thread t = factory.newThread(Mockito.mock(Runnable.class));
assertThat(t.getName(), allOf(containsString("prefix-"), containsString("-thread-")));
assertTrue(t.isDaemon());
}
@Test
public void testGetThreadNum() {
NamedThreadFactory threadFactory = new NamedThreadFactory();
AtomicInteger threadNum = threadFactory.getThreadNum();
assertNotNull(threadNum);
assertEquals(INITIAL_THREAD_NUM, threadNum.get());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AtomicPositiveIntegerTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/AtomicPositiveIntegerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
class AtomicPositiveIntegerTest {
private AtomicPositiveInteger i1 = new AtomicPositiveInteger();
private AtomicPositiveInteger i2 = new AtomicPositiveInteger(127);
private AtomicPositiveInteger i3 = new AtomicPositiveInteger(Integer.MAX_VALUE);
@Test
void testGet() {
assertEquals(0, i1.get());
assertEquals(127, i2.get());
assertEquals(Integer.MAX_VALUE, i3.get());
}
@Test
void testSet() {
i1.set(100);
assertEquals(100, i1.get());
try {
i1.set(-1);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), allOf(containsString("new value"), containsString("< 0")));
}
}
@Test
void testGetAndIncrement() {
int get = i1.getAndIncrement();
assertEquals(0, get);
assertEquals(1, i1.get());
get = i2.getAndIncrement();
assertEquals(127, get);
assertEquals(128, i2.get());
get = i3.getAndIncrement();
assertEquals(Integer.MAX_VALUE, get);
assertEquals(0, i3.get());
}
@Test
void testGetAndDecrement() {
int get = i1.getAndDecrement();
assertEquals(0, get);
assertEquals(Integer.MAX_VALUE, i1.get());
get = i2.getAndDecrement();
assertEquals(127, get);
assertEquals(126, i2.get());
get = i3.getAndDecrement();
assertEquals(Integer.MAX_VALUE, get);
assertEquals(Integer.MAX_VALUE - 1, i3.get());
}
@Test
void testIncrementAndGet() {
int get = i1.incrementAndGet();
assertEquals(1, get);
assertEquals(1, i1.get());
get = i2.incrementAndGet();
assertEquals(128, get);
assertEquals(128, i2.get());
get = i3.incrementAndGet();
assertEquals(0, get);
assertEquals(0, i3.get());
}
@Test
void testDecrementAndGet() {
int get = i1.decrementAndGet();
assertEquals(Integer.MAX_VALUE, get);
assertEquals(Integer.MAX_VALUE, i1.get());
get = i2.decrementAndGet();
assertEquals(126, get);
assertEquals(126, i2.get());
get = i3.decrementAndGet();
assertEquals(Integer.MAX_VALUE - 1, get);
assertEquals(Integer.MAX_VALUE - 1, i3.get());
}
@Test
void testGetAndSet() {
int get = i1.getAndSet(100);
assertEquals(0, get);
assertEquals(100, i1.get());
try {
i1.getAndSet(-1);
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), allOf(containsString("new value"), containsString("< 0")));
}
}
@Test
void testGetAndAnd() {
int get = i1.getAndAdd(3);
assertEquals(0, get);
assertEquals(3, i1.get());
get = i2.getAndAdd(3);
assertEquals(127, get);
assertEquals(127 + 3, i2.get());
get = i3.getAndAdd(3);
assertEquals(Integer.MAX_VALUE, get);
assertEquals(2, i3.get());
}
@Test
void testAddAndGet() {
int get = i1.addAndGet(3);
assertEquals(3, get);
assertEquals(3, i1.get());
get = i2.addAndGet(3);
assertEquals(127 + 3, get);
assertEquals(127 + 3, i2.get());
get = i3.addAndGet(3);
assertEquals(2, get);
assertEquals(2, i3.get());
}
@Test
void testCompareAndSet1() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
i1.compareAndSet(i1.get(), -1);
});
}
@Test
void testCompareAndSet2() {
assertThat(i1.compareAndSet(i1.get(), 2), is(true));
assertThat(i1.get(), is(2));
}
@Test
void testWeakCompareAndSet1() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
i1.weakCompareAndSet(i1.get(), -1);
});
}
@Test
void testWeakCompareAndSet2() {
assertThat(i1.weakCompareAndSet(i1.get(), 2), is(true));
assertThat(i1.get(), is(2));
}
@Test
void testValues() {
Integer i = i1.get();
assertThat(i1.byteValue(), equalTo(i.byteValue()));
assertThat(i1.shortValue(), equalTo(i.shortValue()));
assertThat(i1.intValue(), equalTo(i.intValue()));
assertThat(i1.longValue(), equalTo(i.longValue()));
assertThat(i1.floatValue(), equalTo(i.floatValue()));
assertThat(i1.doubleValue(), equalTo(i.doubleValue()));
assertThat(i1.toString(), equalTo(i.toString()));
}
@Test
void testEquals() {
assertEquals(new AtomicPositiveInteger(), new AtomicPositiveInteger());
assertEquals(new AtomicPositiveInteger(1), new AtomicPositiveInteger(1));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JRETest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/JRETest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import javax.lang.model.SourceVersion;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_JAVA_VERSION;
class JRETest {
@Test
@Disabled
void blankSystemVersion() {
SystemPropertyConfigUtils.setSystemProperty(SYSTEM_JAVA_VERSION, "");
JRE jre = JRE.currentVersion();
Assertions.assertEquals(JRE.JAVA_8, jre);
}
@Test
void testCurrentVersion() {
// SourceVersion is an enum, which member name is RELEASE_XX.
// e.g., "RELEASE_25"
String sourceVersionName = SourceVersion.latest().name();
String expectedVersion = "UNKNOWN";
if (sourceVersionName.contains("_")) {
expectedVersion = sourceVersionName.split("_")[1];
}
String jreEnumName = JRE.currentVersion().name();
String actualVersion = "UNKNOWN";
if (jreEnumName.contains("_")) {
actualVersion = jreEnumName.split("_")[1];
} else {
actualVersion = jreEnumName;
}
Assertions.assertEquals(expectedVersion, actualVersion);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/FieldUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/FieldUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.utils.FieldUtils.findField;
import static org.apache.dubbo.common.utils.FieldUtils.getDeclaredField;
import static org.apache.dubbo.common.utils.FieldUtils.getFieldValue;
import static org.apache.dubbo.common.utils.FieldUtils.setFieldValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* {@link FieldUtils} Test-cases
*
* @since 2.7.6
*/
class FieldUtilsTest {
@Test
void testGetDeclaredField() {
assertEquals("a", getDeclaredField(A.class, "a").getName());
assertEquals("b", getDeclaredField(B.class, "b").getName());
assertEquals("c", getDeclaredField(C.class, "c").getName());
assertNull(getDeclaredField(B.class, "a"));
assertNull(getDeclaredField(C.class, "a"));
}
@Test
void testFindField() {
assertEquals("a", findField(A.class, "a").getName());
assertEquals("a", findField(new A(), "a").getName());
assertEquals("a", findField(B.class, "a").getName());
assertEquals("b", findField(B.class, "b").getName());
assertEquals("a", findField(C.class, "a").getName());
assertEquals("b", findField(C.class, "b").getName());
assertEquals("c", findField(C.class, "c").getName());
}
@Test
void testGetFieldValue() {
assertEquals("a", getFieldValue(new A(), "a"));
assertEquals("a", getFieldValue(new B(), "a"));
assertEquals("b", getFieldValue(new B(), "b"));
assertEquals("a", getFieldValue(new C(), "a"));
assertEquals("b", getFieldValue(new C(), "b"));
assertEquals("c", getFieldValue(new C(), "c"));
}
@Test
void setSetFieldValue() {
A a = new A();
assertEquals("a", setFieldValue(a, "a", "x"));
assertEquals("x", getFieldValue(a, "a"));
}
}
class A {
private String a = "a";
}
class B extends A {
private String b = "b";
}
class C extends B {
private String c = "c";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultCharSequence.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultCharSequence.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.lang.Prioritized;
/**
* Default {@link CharSequence}
*
* @since 2.7.5
*/
public class DefaultCharSequence implements CharSequence, Prioritized {
@Override
public int length() {
return 0;
}
@Override
public char charAt(int index) {
return 0;
}
@Override
public CharSequence subSequence(int start, int end) {
return null;
}
@Override
public int getPriority() {
return MAX_PRIORITY;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DubboAppenderTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/DubboAppenderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.message.SimpleMessage;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class DubboAppenderTest {
private Log4jLogEvent event;
@BeforeEach
public void setUp() throws Exception {
event = mock(Log4jLogEvent.class);
when(event.getLoggerName()).thenReturn("logger-name");
when(event.getLevel()).thenReturn(Level.INFO);
when(event.getThreadName()).thenReturn("thread-name");
when(event.getMessage()).thenReturn(new SimpleMessage("message"));
DubboAppender.clear();
DubboAppender.doStop();
}
@AfterEach
public void tearDown() throws Exception {
DubboAppender.clear();
DubboAppender.doStop();
}
@Test
void testAvailable() {
assertThat(DubboAppender.available, is(false));
DubboAppender.doStart();
assertThat(DubboAppender.available, is(true));
DubboAppender.doStop();
assertThat(DubboAppender.available, is(false));
}
@Test
void testAppend() {
DubboAppender appender = new DubboAppender();
assertThat(DubboAppender.logList, hasSize(0));
appender.append(event);
assertThat(DubboAppender.logList, hasSize(0));
DubboAppender.doStart();
appender.append(event);
assertThat(DubboAppender.logList, hasSize(1));
assertThat(DubboAppender.logList.get(0).getLogThread(), equalTo("thread-name"));
}
@Test
void testClear() {
DubboAppender.doStart();
DubboAppender appender = new DubboAppender();
appender.append(event);
assertThat(DubboAppender.logList, hasSize(1));
DubboAppender.clear();
assertThat(DubboAppender.logList, hasSize(0));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogUtilTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.logger.Level;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class LogUtilTest {
@AfterEach
public void tearDown() throws Exception {
DubboAppender.logList.clear();
}
@Test
void testStartStop() {
LogUtil.start();
assertThat(DubboAppender.available, is(true));
LogUtil.stop();
assertThat(DubboAppender.available, is(false));
}
@Test
void testCheckNoError() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogLevel()).thenReturn(Level.ERROR);
assertThat(LogUtil.checkNoError(), is(false));
when(log.getLogLevel()).thenReturn(Level.INFO);
assertThat(LogUtil.checkNoError(), is(true));
}
@Test
void testFindName() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogName()).thenReturn("a");
assertThat(LogUtil.findName("a"), equalTo(1));
}
@Test
void testFindLevel() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogLevel()).thenReturn(Level.ERROR);
assertThat(LogUtil.findLevel(Level.ERROR), equalTo(1));
assertThat(LogUtil.findLevel(Level.INFO), equalTo(0));
}
@Test
void testFindLevelWithThreadName() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogLevel()).thenReturn(Level.ERROR);
when(log.getLogThread()).thenReturn("thread-1");
log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogLevel()).thenReturn(Level.ERROR);
when(log.getLogThread()).thenReturn("thread-2");
assertThat(LogUtil.findLevelWithThreadName(Level.ERROR, "thread-2"), equalTo(1));
}
@Test
void testFindThread() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogThread()).thenReturn("thread-1");
assertThat(LogUtil.findThread("thread-1"), equalTo(1));
}
@Test
void testFindMessage1() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogMessage()).thenReturn("message");
assertThat(LogUtil.findMessage("message"), equalTo(1));
}
@Test
void testFindMessage2() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogMessage()).thenReturn("message");
when(log.getLogLevel()).thenReturn(Level.ERROR);
log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogMessage()).thenReturn("message");
when(log.getLogLevel()).thenReturn(Level.INFO);
assertThat(LogUtil.findMessage(Level.ERROR, "message"), equalTo(1));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.config.ProtocolConfig;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty;
import static org.apache.dubbo.common.utils.CollectionUtils.ofSet;
import static org.apache.dubbo.common.utils.CollectionUtils.toMap;
import static org.apache.dubbo.common.utils.CollectionUtils.toStringMap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CollectionUtilsTest {
@Test
void testSort() {
List<Integer> list = new ArrayList<Integer>();
list.add(100);
list.add(10);
list.add(20);
List<Integer> expected = new ArrayList<Integer>();
expected.add(10);
expected.add(20);
expected.add(100);
assertEquals(expected, CollectionUtils.sort(list));
}
@Test
void testSortNull() {
assertNull(CollectionUtils.sort(null));
assertTrue(CollectionUtils.sort(new ArrayList<Integer>()).isEmpty());
}
@Test
void testSortSimpleName() {
List<String> list = new ArrayList<String>();
list.add("aaa.z");
list.add("b");
list.add(null);
list.add("zzz.a");
list.add("c");
list.add(null);
List<String> sorted = CollectionUtils.sortSimpleName(list);
assertNull(sorted.get(0));
assertNull(sorted.get(1));
}
@Test
void testSortSimpleNameNull() {
assertNull(CollectionUtils.sortSimpleName(null));
assertTrue(CollectionUtils.sortSimpleName(new ArrayList<String>()).isEmpty());
}
@Test
void testFlip() {
assertEquals(CollectionUtils.flip(null), null);
Map<String, String> input1 = new HashMap<>();
input1.put("k1", null);
input1.put("k2", "v2");
Map<String, String> output1 = new HashMap<>();
output1.put(null, "k1");
output1.put("v2", "k2");
assertEquals(CollectionUtils.flip(input1), output1);
Map<String, String> input2 = new HashMap<>();
input2.put("k1", null);
input2.put("k2", null);
assertThrows(IllegalArgumentException.class, () -> CollectionUtils.flip(input2));
}
@Test
void testSplitAll() {
assertNull(CollectionUtils.splitAll(null, null));
assertNull(CollectionUtils.splitAll(null, "-"));
assertTrue(CollectionUtils.splitAll(new HashMap<String, List<String>>(), "-")
.isEmpty());
Map<String, List<String>> input = new HashMap<String, List<String>>();
input.put("key1", Arrays.asList("1:a", "2:b", "3:c"));
input.put("key2", Arrays.asList("1:a", "2:b"));
input.put("key3", null);
input.put("key4", new ArrayList<String>());
Map<String, Map<String, String>> expected = new HashMap<String, Map<String, String>>();
expected.put("key1", CollectionUtils.toStringMap("1", "a", "2", "b", "3", "c"));
expected.put("key2", CollectionUtils.toStringMap("1", "a", "2", "b"));
expected.put("key3", null);
expected.put("key4", new HashMap<String, String>());
assertEquals(expected, CollectionUtils.splitAll(input, ":"));
}
@Test
void testJoinAll() {
assertNull(CollectionUtils.joinAll(null, null));
assertNull(CollectionUtils.joinAll(null, "-"));
Map<String, List<String>> expected = new HashMap<String, List<String>>();
expected.put("key1", Arrays.asList("1:a", "2:b", "3:c"));
expected.put("key2", Arrays.asList("1:a", "2:b"));
expected.put("key3", null);
expected.put("key4", new ArrayList<String>());
Map<String, Map<String, String>> input = new HashMap<String, Map<String, String>>();
input.put("key1", CollectionUtils.toStringMap("1", "a", "2", "b", "3", "c"));
input.put("key2", CollectionUtils.toStringMap("1", "a", "2", "b"));
input.put("key3", null);
input.put("key4", new HashMap<String, String>());
Map<String, List<String>> output = CollectionUtils.joinAll(input, ":");
for (Map.Entry<String, List<String>> entry : output.entrySet()) {
if (entry.getValue() == null) continue;
Collections.sort(entry.getValue());
}
assertEquals(expected, output);
}
@Test
void testJoinList() {
List<String> list = emptyList();
assertEquals("", CollectionUtils.join(list, "/"));
list = Arrays.asList("x");
assertEquals("x", CollectionUtils.join(list, "-"));
list = Arrays.asList("a", "b");
assertEquals("a/b", CollectionUtils.join(list, "/"));
}
@Test
void testMapEquals() {
assertTrue(CollectionUtils.mapEquals(null, null));
assertFalse(CollectionUtils.mapEquals(null, new HashMap<String, String>()));
assertFalse(CollectionUtils.mapEquals(new HashMap<String, String>(), null));
assertTrue(CollectionUtils.mapEquals(
CollectionUtils.toStringMap("1", "a", "2", "b"), CollectionUtils.toStringMap("1", "a", "2", "b")));
assertFalse(CollectionUtils.mapEquals(
CollectionUtils.toStringMap("1", "a"), CollectionUtils.toStringMap("1", "a", "2", "b")));
}
@Test
void testStringMap1() {
assertThat(toStringMap("key", "value"), equalTo(Collections.singletonMap("key", "value")));
}
@Test
void testStringMap2() {
Assertions.assertThrows(IllegalArgumentException.class, () -> toStringMap("key", "value", "odd"));
}
@Test
void testToMap1() {
assertTrue(CollectionUtils.toMap().isEmpty());
Map<String, Integer> expected = new HashMap<String, Integer>();
expected.put("a", 1);
expected.put("b", 2);
expected.put("c", 3);
assertEquals(expected, CollectionUtils.toMap("a", 1, "b", 2, "c", 3));
}
@Test
void testObjectToMap() throws Exception {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setSerialization("fastjson2");
assertFalse(CollectionUtils.objToMap(protocolConfig).isEmpty());
}
@Test
void testToMap2() {
Assertions.assertThrows(IllegalArgumentException.class, () -> toMap("a", "b", "c"));
}
@Test
void testIsEmpty() {
assertThat(isEmpty(null), is(true));
assertThat(isEmpty(new HashSet()), is(true));
assertThat(isEmpty(emptyList()), is(true));
}
@Test
void testIsNotEmpty() {
assertThat(isNotEmpty(singleton("a")), is(true));
}
@Test
void testOfSet() {
Set<String> set = ofSet();
assertEquals(emptySet(), set);
set = ofSet(((String[]) null));
assertEquals(emptySet(), set);
set = ofSet("A", "B", "C");
Set<String> expectedSet = new LinkedHashSet<>();
expectedSet.add("A");
expectedSet.add("B");
expectedSet.add("C");
assertEquals(expectedSet, set);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class ReflectUtilsTest {
@Test
void testIsPrimitives() {
assertTrue(ReflectUtils.isPrimitives(boolean[].class));
assertTrue(ReflectUtils.isPrimitives(byte.class));
assertFalse(ReflectUtils.isPrimitive(Map[].class));
}
@Test
void testIsPrimitive() {
assertTrue(ReflectUtils.isPrimitive(boolean.class));
assertTrue(ReflectUtils.isPrimitive(String.class));
assertTrue(ReflectUtils.isPrimitive(Boolean.class));
assertTrue(ReflectUtils.isPrimitive(Character.class));
assertTrue(ReflectUtils.isPrimitive(Number.class));
assertTrue(ReflectUtils.isPrimitive(Date.class));
assertFalse(ReflectUtils.isPrimitive(Map.class));
}
@Test
void testGetBoxedClass() {
assertThat(ReflectUtils.getBoxedClass(int.class), sameInstance(Integer.class));
assertThat(ReflectUtils.getBoxedClass(boolean.class), sameInstance(Boolean.class));
assertThat(ReflectUtils.getBoxedClass(long.class), sameInstance(Long.class));
assertThat(ReflectUtils.getBoxedClass(float.class), sameInstance(Float.class));
assertThat(ReflectUtils.getBoxedClass(double.class), sameInstance(Double.class));
assertThat(ReflectUtils.getBoxedClass(char.class), sameInstance(Character.class));
assertThat(ReflectUtils.getBoxedClass(byte.class), sameInstance(Byte.class));
assertThat(ReflectUtils.getBoxedClass(short.class), sameInstance(Short.class));
assertThat(ReflectUtils.getBoxedClass(String.class), sameInstance(String.class));
}
@Test
void testIsCompatible() {
assertTrue(ReflectUtils.isCompatible(short.class, (short) 1));
assertTrue(ReflectUtils.isCompatible(int.class, 1));
assertTrue(ReflectUtils.isCompatible(double.class, 1.2));
assertTrue(ReflectUtils.isCompatible(Object.class, 1.2));
assertTrue(ReflectUtils.isCompatible(List.class, new ArrayList<String>()));
}
@Test
void testIsCompatibleWithArray() {
assertFalse(ReflectUtils.isCompatible(new Class[] {short.class, int.class}, new Object[] {(short) 1}));
assertFalse(ReflectUtils.isCompatible(new Class[] {double.class}, new Object[] {"hello"}));
assertTrue(ReflectUtils.isCompatible(new Class[] {double.class}, new Object[] {1.2}));
}
@Test
void testGetCodeBase() {
assertNull(ReflectUtils.getCodeBase(null));
assertNull(ReflectUtils.getCodeBase(String.class));
assertNotNull(ReflectUtils.getCodeBase(ReflectUtils.class));
}
@Test
void testGetName() {
// getName
assertEquals("boolean", ReflectUtils.getName(boolean.class));
assertEquals("int[][][]", ReflectUtils.getName(int[][][].class));
assertEquals("java.lang.Object[][]", ReflectUtils.getName(Object[][].class));
}
@Test
void testGetDesc() {
// getDesc
assertEquals("Z", ReflectUtils.getDesc(boolean.class));
assertEquals("[[[I", ReflectUtils.getDesc(int[][][].class));
assertEquals("[[Ljava/lang/Object;", ReflectUtils.getDesc(Object[][].class));
}
@Test
void testName2desc() {
// name2desc
assertEquals("Z", ReflectUtils.name2desc(ReflectUtils.getName(boolean.class)));
assertEquals("[[[I", ReflectUtils.name2desc(ReflectUtils.getName(int[][][].class)));
assertEquals("[[Ljava/lang/Object;", ReflectUtils.name2desc(ReflectUtils.getName(Object[][].class)));
}
@Test
void testDesc2name() {
// desc2name
assertEquals("short[]", ReflectUtils.desc2name(ReflectUtils.getDesc(short[].class)));
assertEquals("boolean[]", ReflectUtils.desc2name(ReflectUtils.getDesc(boolean[].class)));
assertEquals("byte[]", ReflectUtils.desc2name(ReflectUtils.getDesc(byte[].class)));
assertEquals("char[]", ReflectUtils.desc2name(ReflectUtils.getDesc(char[].class)));
assertEquals("double[]", ReflectUtils.desc2name(ReflectUtils.getDesc(double[].class)));
assertEquals("float[]", ReflectUtils.desc2name(ReflectUtils.getDesc(float[].class)));
assertEquals("int[]", ReflectUtils.desc2name(ReflectUtils.getDesc(int[].class)));
assertEquals("long[]", ReflectUtils.desc2name(ReflectUtils.getDesc(long[].class)));
assertEquals("int", ReflectUtils.desc2name(ReflectUtils.getDesc(int.class)));
assertEquals("void", ReflectUtils.desc2name(ReflectUtils.getDesc(void.class)));
assertEquals("java.lang.Object[][]", ReflectUtils.desc2name(ReflectUtils.getDesc(Object[][].class)));
}
@Test
void testGetGenericClass() {
assertThat(ReflectUtils.getGenericClass(Foo1.class), sameInstance(String.class));
}
@Test
void testGetGenericClassWithIndex() {
assertThat(ReflectUtils.getGenericClass(Foo1.class, 0), sameInstance(String.class));
assertThat(ReflectUtils.getGenericClass(Foo1.class, 1), sameInstance(Integer.class));
assertThat(ReflectUtils.getGenericClass(Foo2.class, 0), sameInstance(List.class));
assertThat(ReflectUtils.getGenericClass(Foo2.class, 1), sameInstance(int.class));
assertThat(ReflectUtils.getGenericClass(Foo3.class, 0), sameInstance(Foo1.class));
assertThat(ReflectUtils.getGenericClass(Foo3.class, 1), sameInstance(Foo2.class));
}
@Test
void testGetMethodName() throws Exception {
assertThat(
ReflectUtils.getName(Foo2.class.getDeclaredMethod("hello", int[].class)),
equalTo("java.util.List hello(int[])"));
}
@Test
void testGetSignature() throws Exception {
Method m = Foo2.class.getDeclaredMethod("hello", int[].class);
assertThat(ReflectUtils.getSignature("greeting", m.getParameterTypes()), equalTo("greeting([I)"));
}
@Test
void testGetConstructorName() {
Constructor c = Foo2.class.getConstructors()[0];
assertThat(ReflectUtils.getName(c), equalTo("(java.util.List,int[])"));
}
@Test
void testName2Class() throws Exception {
assertEquals(boolean.class, ReflectUtils.name2class("boolean"));
assertEquals(boolean[].class, ReflectUtils.name2class("boolean[]"));
assertEquals(int[][].class, ReflectUtils.name2class(ReflectUtils.getName(int[][].class)));
assertEquals(ReflectUtilsTest[].class, ReflectUtils.name2class(ReflectUtils.getName(ReflectUtilsTest[].class)));
}
@Test
void testGetDescMethod() throws Exception {
assertThat(
ReflectUtils.getDesc(Foo2.class.getDeclaredMethod("hello", int[].class)),
equalTo("hello([I)Ljava/util/List;"));
}
@Test
void testGetDescConstructor() {
assertThat(ReflectUtils.getDesc(Foo2.class.getConstructors()[0]), equalTo("(Ljava/util/List;[I)V"));
}
@Test
void testGetDescWithoutMethodName() throws Exception {
assertThat(
ReflectUtils.getDescWithoutMethodName(Foo2.class.getDeclaredMethod("hello", int[].class)),
equalTo("([I)Ljava/util/List;"));
}
@Test
void testFindMethodByMethodName1() throws Exception {
assertNotNull(ReflectUtils.findMethodByMethodName(Foo.class, "hello"));
}
@Test
void testFindMethodByMethodName2() {
Assertions.assertThrows(IllegalStateException.class, () -> {
ReflectUtils.findMethodByMethodName(Foo2.class, "hello");
});
}
@Test
void testFindConstructor() throws Exception {
Constructor constructor = ReflectUtils.findConstructor(Foo3.class, Foo2.class);
assertNotNull(constructor);
}
@Test
void testIsInstance() {
assertTrue(ReflectUtils.isInstance(new Foo1(), Foo.class.getName()));
}
@Test
void testIsBeanPropertyReadMethod() throws Exception {
Method method = EmptyClass.class.getMethod("getProperty");
assertTrue(ReflectUtils.isBeanPropertyReadMethod(method));
method = EmptyClass.class.getMethod("getProperties");
assertFalse(ReflectUtils.isBeanPropertyReadMethod(method));
method = EmptyClass.class.getMethod("isProperty");
assertFalse(ReflectUtils.isBeanPropertyReadMethod(method));
method = EmptyClass.class.getMethod("getPropertyIndex", int.class);
assertFalse(ReflectUtils.isBeanPropertyReadMethod(method));
}
@Test
void testGetPropertyNameFromBeanReadMethod() throws Exception {
Method method = EmptyClass.class.getMethod("getProperty");
assertEquals("property", ReflectUtils.getPropertyNameFromBeanReadMethod(method));
method = EmptyClass.class.getMethod("isSet");
assertEquals("set", ReflectUtils.getPropertyNameFromBeanReadMethod(method));
}
@Test
void testIsBeanPropertyWriteMethod() throws Exception {
Method method = EmptyClass.class.getMethod("setProperty", EmptyProperty.class);
assertTrue(ReflectUtils.isBeanPropertyWriteMethod(method));
method = EmptyClass.class.getMethod("setSet", boolean.class);
assertTrue(ReflectUtils.isBeanPropertyWriteMethod(method));
}
@Test
void testGetPropertyNameFromBeanWriteMethod() throws Exception {
Method method = EmptyClass.class.getMethod("setProperty", EmptyProperty.class);
assertEquals("property", ReflectUtils.getPropertyNameFromBeanWriteMethod(method));
}
@Test
void testIsPublicInstanceField() throws Exception {
Field field = EmptyClass.class.getDeclaredField("set");
assertTrue(ReflectUtils.isPublicInstanceField(field));
field = EmptyClass.class.getDeclaredField("property");
assertFalse(ReflectUtils.isPublicInstanceField(field));
}
@Test
void testGetBeanPropertyFields() {
Map<String, Field> map = ReflectUtils.getBeanPropertyFields(EmptyClass.class);
assertThat(map.size(), is(2));
assertThat(map, hasKey("set"));
assertThat(map, hasKey("property"));
for (Field f : map.values()) {
if (!f.isAccessible()) {
fail();
}
}
}
@Test
void testGetBeanPropertyReadMethods() {
Map<String, Method> map = ReflectUtils.getBeanPropertyReadMethods(EmptyClass.class);
assertThat(map.size(), is(2));
assertThat(map, hasKey("set"));
assertThat(map, hasKey("property"));
for (Method m : map.values()) {
if (!m.isAccessible()) {
fail();
}
}
}
@Test
void testDesc2Class() throws Exception {
assertEquals(void.class, ReflectUtils.desc2class("V"));
assertEquals(boolean.class, ReflectUtils.desc2class("Z"));
assertEquals(boolean[].class, ReflectUtils.desc2class("[Z"));
assertEquals(byte.class, ReflectUtils.desc2class("B"));
assertEquals(char.class, ReflectUtils.desc2class("C"));
assertEquals(double.class, ReflectUtils.desc2class("D"));
assertEquals(float.class, ReflectUtils.desc2class("F"));
assertEquals(int.class, ReflectUtils.desc2class("I"));
assertEquals(long.class, ReflectUtils.desc2class("J"));
assertEquals(short.class, ReflectUtils.desc2class("S"));
assertEquals(String.class, ReflectUtils.desc2class("Ljava.lang.String;"));
assertEquals(int[][].class, ReflectUtils.desc2class(ReflectUtils.getDesc(int[][].class)));
assertEquals(ReflectUtilsTest[].class, ReflectUtils.desc2class(ReflectUtils.getDesc(ReflectUtilsTest[].class)));
String desc;
Class<?>[] cs;
cs = new Class<?>[] {int.class, getClass(), String.class, int[][].class, boolean[].class};
desc = ReflectUtils.getDesc(cs);
assertSame(cs, ReflectUtils.desc2classArray(desc));
cs = new Class<?>[] {};
desc = ReflectUtils.getDesc(cs);
assertSame(cs, ReflectUtils.desc2classArray(desc));
cs = new Class<?>[] {void.class, String[].class, int[][].class, ReflectUtilsTest[][].class};
desc = ReflectUtils.getDesc(cs);
assertSame(cs, ReflectUtils.desc2classArray(desc));
}
protected void assertSame(Class<?>[] cs1, Class<?>[] cs2) throws Exception {
assertEquals(cs1.length, cs2.length);
for (int i = 0; i < cs1.length; i++) assertEquals(cs1[i], cs2[i]);
}
@Test
void testFindMethodByMethodSignature() throws Exception {
Method m = ReflectUtils.findMethodByMethodSignature(TestedClass.class, "method1", null);
assertEquals("method1", m.getName());
Class<?>[] parameterTypes = m.getParameterTypes();
assertEquals(1, parameterTypes.length);
assertEquals(int.class, parameterTypes[0]);
}
@Test
void testFindMethodByMethodSignature_override() throws Exception {
{
Method m =
ReflectUtils.findMethodByMethodSignature(TestedClass.class, "overrideMethod", new String[] {"int"});
assertEquals("overrideMethod", m.getName());
Class<?>[] parameterTypes = m.getParameterTypes();
assertEquals(1, parameterTypes.length);
assertEquals(int.class, parameterTypes[0]);
}
{
Method m = ReflectUtils.findMethodByMethodSignature(
TestedClass.class, "overrideMethod", new String[] {"java.lang.Integer"});
assertEquals("overrideMethod", m.getName());
Class<?>[] parameterTypes = m.getParameterTypes();
assertEquals(1, parameterTypes.length);
assertEquals(Integer.class, parameterTypes[0]);
}
}
@Test
void testFindMethodByMethodSignatureOverrideMoreThan1() throws Exception {
try {
ReflectUtils.findMethodByMethodSignature(TestedClass.class, "overrideMethod", null);
fail();
} catch (IllegalStateException expected) {
assertThat(expected.getMessage(), containsString("Not unique method for method name("));
}
}
@Test
void testFindMethodByMethodSignatureNotFound() throws Exception {
try {
ReflectUtils.findMethodByMethodSignature(TestedClass.class, "doesNotExist", null);
fail();
} catch (NoSuchMethodException expected) {
assertThat(expected.getMessage(), containsString("No such method "));
assertThat(expected.getMessage(), containsString("in class"));
}
}
@Test
void testGetEmptyObject() {
assertTrue(ReflectUtils.getEmptyObject(Collection.class) instanceof Collection);
assertTrue(ReflectUtils.getEmptyObject(List.class) instanceof List);
assertTrue(ReflectUtils.getEmptyObject(Set.class) instanceof Set);
assertTrue(ReflectUtils.getEmptyObject(Map.class) instanceof Map);
assertTrue(ReflectUtils.getEmptyObject(Object[].class) instanceof Object[]);
assertEquals("", ReflectUtils.getEmptyObject(String.class));
assertEquals((short) 0, ReflectUtils.getEmptyObject(short.class));
assertEquals((byte) 0, ReflectUtils.getEmptyObject(byte.class));
assertEquals(0, ReflectUtils.getEmptyObject(int.class));
assertEquals(0L, ReflectUtils.getEmptyObject(long.class));
assertEquals((float) 0, ReflectUtils.getEmptyObject(float.class));
assertEquals((double) 0, ReflectUtils.getEmptyObject(double.class));
assertEquals('\0', ReflectUtils.getEmptyObject(char.class));
assertEquals(Boolean.FALSE, ReflectUtils.getEmptyObject(boolean.class));
EmptyClass object = (EmptyClass) ReflectUtils.getEmptyObject(EmptyClass.class);
assertNotNull(object);
assertNotNull(object.getProperty());
}
@Test
void testForName1() {
assertThat(ReflectUtils.forName(ReflectUtils.class.getName()), sameInstance(ReflectUtils.class));
}
@Test
void testForName2() {
Assertions.assertThrows(IllegalStateException.class, () -> {
ReflectUtils.forName("a.c.d.e.F");
});
}
@Test
void testGetReturnTypes() throws Exception {
Class<TypeClass> clazz = TypeClass.class;
Type[] types = ReflectUtils.getReturnTypes(clazz.getMethod("getFuture"));
Assertions.assertEquals("java.lang.String", types[0].getTypeName());
Assertions.assertEquals("java.lang.String", types[1].getTypeName());
Type[] types1 = ReflectUtils.getReturnTypes(clazz.getMethod("getString"));
Assertions.assertEquals("java.lang.String", types1[0].getTypeName());
Assertions.assertEquals("java.lang.String", types1[1].getTypeName());
Type[] types2 = ReflectUtils.getReturnTypes(clazz.getMethod("getT"));
Assertions.assertEquals("java.lang.String", types2[0].getTypeName());
Assertions.assertEquals("T", types2[1].getTypeName());
Type[] types3 = ReflectUtils.getReturnTypes(clazz.getMethod("getS"));
Assertions.assertEquals("java.lang.Object", types3[0].getTypeName());
Assertions.assertEquals("S", types3[1].getTypeName());
Type[] types4 = ReflectUtils.getReturnTypes(clazz.getMethod("getListFuture"));
Assertions.assertEquals("java.util.List", types4[0].getTypeName());
Assertions.assertEquals("java.util.List<java.lang.String>", types4[1].getTypeName());
Type[] types5 = ReflectUtils.getReturnTypes(clazz.getMethod("getGenericWithUpperFuture"));
// T extends String, the first arg should be the upper bound of param
Assertions.assertEquals("java.lang.String", types5[0].getTypeName());
Assertions.assertEquals("T", types5[1].getTypeName());
Type[] types6 = ReflectUtils.getReturnTypes(clazz.getMethod("getGenericFuture"));
// default upper bound is Object
Assertions.assertEquals("java.lang.Object", types6[0].getTypeName());
Assertions.assertEquals("S", types6[1].getTypeName());
}
public interface TypeClass<T extends String, S> {
CompletableFuture<String> getFuture();
String getString();
T getT();
S getS();
CompletableFuture<List<String>> getListFuture();
CompletableFuture<T> getGenericWithUpperFuture();
CompletableFuture<S> getGenericFuture();
}
public static class EmptyClass {
private EmptyProperty property;
public boolean set;
public static String s;
private transient int i;
public EmptyProperty getProperty() {
return property;
}
public EmptyProperty getPropertyIndex(int i) {
return property;
}
public static EmptyProperty getProperties() {
return null;
}
public void isProperty() {}
public boolean isSet() {
return set;
}
public void setProperty(EmptyProperty property) {
this.property = property;
}
public void setSet(boolean set) {
this.set = set;
}
}
public static class EmptyProperty {}
static class TestedClass {
public void method1(int x) {}
public void overrideMethod(int x) {}
public void overrideMethod(Integer x) {}
public void overrideMethod(String s) {}
public void overrideMethod(String s1, String s2) {}
}
interface Foo<A, B> {
A hello(B b);
}
static class Foo1 implements Foo<String, Integer> {
@Override
public String hello(Integer integer) {
return null;
}
}
static class Foo2 implements Foo<List<String>, int[]> {
public Foo2(List<String> list, int[] ints) {}
@Override
public List<String> hello(int[] ints) {
return null;
}
}
static class Foo3 implements Foo<Foo1, Foo2> {
public Foo3(Foo foo) {}
@Override
public Foo1 hello(Foo2 foo2) {
return null;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.config.CompositeConfiguration;
import org.apache.dubbo.common.config.InmemoryConfiguration;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ConfigUtilsTest {
private Properties properties;
@BeforeEach
public void setUp() throws Exception {
properties = ConfigUtils.getProperties(Collections.emptySet());
}
@AfterEach
public void tearDown() throws Exception {}
@Test
void testIsNotEmpty() throws Exception {
assertThat(ConfigUtils.isNotEmpty("abc"), is(true));
}
@Test
void testIsEmpty() throws Exception {
assertThat(ConfigUtils.isEmpty(null), is(true));
assertThat(ConfigUtils.isEmpty(""), is(true));
assertThat(ConfigUtils.isEmpty("false"), is(true));
assertThat(ConfigUtils.isEmpty("FALSE"), is(true));
assertThat(ConfigUtils.isEmpty("0"), is(true));
assertThat(ConfigUtils.isEmpty("null"), is(true));
assertThat(ConfigUtils.isEmpty("NULL"), is(true));
assertThat(ConfigUtils.isEmpty("n/a"), is(true));
assertThat(ConfigUtils.isEmpty("N/A"), is(true));
}
@Test
void testIsDefault() throws Exception {
assertThat(ConfigUtils.isDefault("true"), is(true));
assertThat(ConfigUtils.isDefault("TRUE"), is(true));
assertThat(ConfigUtils.isDefault("default"), is(true));
assertThat(ConfigUtils.isDefault("DEFAULT"), is(true));
}
@Test
void testMergeValues() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"aaa,bbb,default.custom",
asList("fixed", "default.limited", "cached"));
assertEquals(asList("fixed", "cached", "aaa", "bbb", "default.custom"), merged);
}
@Test
void testMergeValuesAddDefault() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"aaa,bbb,default,zzz",
asList("fixed", "default.limited", "cached"));
assertEquals(asList("aaa", "bbb", "fixed", "cached", "zzz"), merged);
}
@Test
void testMergeValuesDeleteDefault() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"-default",
asList("fixed", "default.limited", "cached"));
assertEquals(Collections.emptyList(), merged);
}
@Test
void testMergeValuesDeleteDefault_2() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"-default,aaa",
asList("fixed", "default.limited", "cached"));
assertEquals(asList("aaa"), merged);
}
/**
* The user configures -default, which will delete all the default parameters
*/
@Test
void testMergeValuesDelete() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"-fixed,aaa",
asList("fixed", "default.limited", "cached"));
assertEquals(asList("cached", "aaa"), merged);
}
@Test
void testReplaceProperty() throws Exception {
String s = ConfigUtils.replaceProperty("1${a.b.c}2${a.b.c}3", Collections.singletonMap("a.b.c", "ABC"));
assertEquals("1ABC2ABC3", s);
s = ConfigUtils.replaceProperty("1${a.b.c}2${a.b.c}3", Collections.<String, String>emptyMap());
assertEquals("1${a.b.c}2${a.b.c}3", s);
}
@Test
void testReplaceProperty2() {
InmemoryConfiguration configuration1 = new InmemoryConfiguration();
configuration1.getProperties().put("zookeeper.address", "127.0.0.1");
InmemoryConfiguration configuration2 = new InmemoryConfiguration();
configuration2.getProperties().put("zookeeper.port", "2181");
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
compositeConfiguration.addConfiguration(configuration1);
compositeConfiguration.addConfiguration(configuration2);
String s = ConfigUtils.replaceProperty(
"zookeeper://${zookeeper.address}:${zookeeper.port}", compositeConfiguration);
assertEquals("zookeeper://127.0.0.1:2181", s);
// should not replace inner class name
String interfaceName = "dubbo.service.io.grpc.examples.helloworld.DubboGreeterGrpc$IGreeter";
s = ConfigUtils.replaceProperty(interfaceName, compositeConfiguration);
Assertions.assertEquals(interfaceName, s);
}
@Test
void testGetProperties1() throws Exception {
try {
SystemPropertyConfigUtils.getSystemProperty(CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY);
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY, "properties.load");
Properties p = ConfigUtils.getProperties(Collections.emptySet());
assertThat((String) p.get("a"), equalTo("12"));
assertThat((String) p.get("b"), equalTo("34"));
assertThat((String) p.get("c"), equalTo("56"));
} finally {
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY);
}
}
@Test
void testGetProperties2() throws Exception {
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY);
Properties p = ConfigUtils.getProperties(Collections.emptySet());
assertThat((String) p.get("dubbo"), equalTo("properties"));
}
@Test
void testLoadPropertiesNoFile() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "notExisted", true);
Properties expected = new Properties();
assertEquals(expected, p);
p = ConfigUtils.loadProperties(Collections.emptySet(), "notExisted", false);
assertEquals(expected, p);
}
@Test
void testGetProperty() throws Exception {
assertThat(properties.getProperty("dubbo"), equalTo("properties"));
}
@Test
void testGetPropertyDefaultValue() throws Exception {
assertThat(properties.getProperty("not-exist", "default"), equalTo("default"));
}
@Test
void testGetSystemProperty() throws Exception {
try {
System.setProperty("dubbo", "system-only");
assertThat(ConfigUtils.getSystemProperty("dubbo"), equalTo("system-only"));
} finally {
System.clearProperty("dubbo");
}
}
@Test
void testLoadProperties() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "dubbo.properties");
assertThat((String) p.get("dubbo"), equalTo("properties"));
}
@Test
void testLoadPropertiesOneFile() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "properties.load", false);
Properties expected = new Properties();
expected.put("a", "12");
expected.put("b", "34");
expected.put("c", "56");
assertEquals(expected, p);
}
@Test
void testLoadPropertiesOneFileAllowMulti() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "properties.load", true);
Properties expected = new Properties();
expected.put("a", "12");
expected.put("b", "34");
expected.put("c", "56");
assertEquals(expected, p);
}
@Test
void testLoadPropertiesOneFileNotRootPath() throws Exception {
Properties p = ConfigUtils.loadProperties(
Collections.emptySet(), "META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.ThreadPool", false);
Properties expected = new Properties();
expected.put("fixed", "org.apache.dubbo.common.threadpool.support.fixed.FixedThreadPool");
expected.put("cached", "org.apache.dubbo.common.threadpool.support.cached.CachedThreadPool");
expected.put("limited", "org.apache.dubbo.common.threadpool.support.limited.LimitedThreadPool");
expected.put("eager", "org.apache.dubbo.common.threadpool.support.eager.EagerThreadPool");
assertEquals(expected, p);
}
@Disabled("Not know why disabled, the original link explaining this was reachable.")
@Test
void testLoadPropertiesMultiFileNotRootPathException() throws Exception {
try {
ConfigUtils.loadProperties(
Collections.emptySet(), "META-INF/services/org.apache.dubbo.common.status.StatusChecker", false);
Assertions.fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"only 1 META-INF/services/org.apache.dubbo.common.status.StatusChecker file is expected, but 2 dubbo.properties files found on class path:"));
}
}
@Test
void testLoadPropertiesMultiFileNotRootPath() throws Exception {
Properties p = ConfigUtils.loadProperties(
Collections.emptySet(), "META-INF/dubbo/internal/org.apache.dubbo.common.status.StatusChecker", true);
Properties expected = new Properties();
expected.put("memory", "org.apache.dubbo.common.status.support.MemoryStatusChecker");
expected.put("load", "org.apache.dubbo.common.status.support.LoadStatusChecker");
expected.put("aa", "12");
assertEquals(expected, p);
}
@Test
void testGetPid() throws Exception {
assertThat(ConfigUtils.getPid(), greaterThan(0));
}
@Test
void testPropertiesWithStructedValue() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "parameters.properties", false);
Properties expected = new Properties();
expected.put("dubbo.parameters", "[{a:b},{c_.d: r*}]");
assertEquals(expected, p);
}
@Test
void testLoadMigrationRule() {
Set<ClassLoader> classLoaderSet = new HashSet<>();
classLoaderSet.add(ClassUtils.getClassLoader());
String rule = ConfigUtils.loadMigrationRule(classLoaderSet, "dubbo-migration.yaml");
Assertions.assertNotNull(rule);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JavassistParameterNameReaderTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/JavassistParameterNameReaderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.URL;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.equalTo;
class JavassistParameterNameReaderTest {
private final ParameterNameReader reader = new JavassistParameterNameReader();
@Test
void readFromConstructor() {
Class<?> clazz = URL.class;
for (Constructor<?> ctor : clazz.getConstructors()) {
String[] names = reader.readParameterNames(ctor);
if (names.length == 7) {
assertThat(names[0], equalTo("protocol"));
}
}
}
@Test
void readFromMethod() {
Class<?> clazz = URL.class;
for (Method method : clazz.getMethods()) {
String[] names = reader.readParameterNames(method);
switch (method.getName()) {
case "getAddress":
assertThat(names, emptyArray());
break;
case "setAddress":
assertThat(names[0], equalTo("address"));
break;
case "buildKey":
assertThat(names[0], equalTo("path"));
break;
default:
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ExecutorUtilTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/ExecutorUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ExecutorUtilTest {
@Test
void testIsTerminated() throws Exception {
ExecutorService executor = Mockito.mock(ExecutorService.class);
when(executor.isTerminated()).thenReturn(true);
assertThat(ExecutorUtil.isTerminated(executor), is(true));
Executor executor2 = Mockito.mock(Executor.class);
assertThat(ExecutorUtil.isTerminated(executor2), is(false));
}
@Test
void testGracefulShutdown1() throws Exception {
ExecutorService executor = Mockito.mock(ExecutorService.class);
when(executor.isTerminated()).thenReturn(false, true);
when(executor.awaitTermination(20, TimeUnit.MILLISECONDS)).thenReturn(false);
ExecutorUtil.gracefulShutdown(executor, 20);
verify(executor).shutdown();
verify(executor).shutdownNow();
}
@Test
void testGracefulShutdown2() throws Exception {
ExecutorService executor = Mockito.mock(ExecutorService.class);
when(executor.isTerminated()).thenReturn(false, false, false);
when(executor.awaitTermination(20, TimeUnit.MILLISECONDS)).thenReturn(false);
when(executor.awaitTermination(10, TimeUnit.MILLISECONDS)).thenReturn(false, true);
ExecutorUtil.gracefulShutdown(executor, 20);
await().untilAsserted(() -> verify(executor, times(2)).awaitTermination(10, TimeUnit.MILLISECONDS));
verify(executor, times(1)).shutdown();
verify(executor, times(3)).shutdownNow();
}
@Test
void testShutdownNow() throws Exception {
ExecutorService executor = Mockito.mock(ExecutorService.class);
when(executor.isTerminated()).thenReturn(false, true);
ExecutorUtil.shutdownNow(executor, 20);
verify(executor).shutdownNow();
verify(executor).awaitTermination(20, TimeUnit.MILLISECONDS);
}
@Test
void testSetThreadName() throws Exception {
URL url = new ServiceConfigURL("dubbo", "localhost", 1234).addParameter(THREAD_NAME_KEY, "custom-thread");
url = ExecutorUtil.setThreadName(url, "default-name");
assertThat(url.getParameter(THREAD_NAME_KEY), equalTo("custom-thread-localhost:1234"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ConcurrentHashMapUtilsTest {
@Test
public void testComputeIfAbsent() {
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
String ifAbsent = ConcurrentHashMapUtils.computeIfAbsent(map, "mxsm", k -> "mxsm");
assertEquals("mxsm", ifAbsent);
ifAbsent = ConcurrentHashMapUtils.computeIfAbsent(map, "mxsm", k -> "mxsm1");
assertEquals("mxsm", ifAbsent);
map.remove("mxsm");
ifAbsent = ConcurrentHashMapUtils.computeIfAbsent(map, "mxsm", k -> "mxsm1");
assertEquals("mxsm1", ifAbsent);
}
@Test
@EnabledForJreRange(max = org.junit.jupiter.api.condition.JRE.JAVA_8)
public void issue11986ForJava8Test() {
// https://github.com/apache/dubbo/issues/11986
final ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// // map.computeIfAbsent("AaAa", key->map.computeIfAbsent("BBBB",key2->42));
// In JDK8,for the bug of JDK-8161372,may cause dead cycle when use computeIfAbsent
// ConcurrentHashMapUtils.computeIfAbsent method to resolve this bug
ConcurrentHashMapUtils.computeIfAbsent(map, "AaAa", key -> map.computeIfAbsent("BBBB", key2 -> 42));
assertEquals(2, map.size());
assertEquals(Integer.valueOf(42), map.get("AaAa"));
assertEquals(Integer.valueOf(42), map.get("BBBB"));
}
@Test
@EnabledForJreRange(min = org.junit.jupiter.api.condition.JRE.JAVA_9)
public void issue11986ForJava17Test() {
// https://github.com/apache/dubbo/issues/11986
final ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// JDK9+ has been resolved JDK-8161372 bug, when cause dead then throw IllegalStateException
assertThrows(IllegalStateException.class, () -> {
ConcurrentHashMapUtils.computeIfAbsent(map, "AaAa", key -> map.computeIfAbsent("BBBB", key2 -> 42));
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultPageTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultPageTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
/**
* {@link DefaultPage}
*
* @since 2.7.5
*/
class DefaultPageTest {
@Test
void test() {
List<Integer> data = asList(1, 2, 3, 4, 5);
DefaultPage<Integer> page = new DefaultPage<>(0, 1, data.subList(0, 1), data.size());
Assertions.assertEquals(page.getOffset(), 0);
Assertions.assertEquals(page.getPageSize(), 1);
Assertions.assertEquals(page.getTotalSize(), data.size());
Assertions.assertEquals(page.getData(), data.subList(0, 1));
Assertions.assertEquals(page.getTotalPages(), 5);
Assertions.assertTrue(page.hasNext());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TimeUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/TimeUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
class TimeUtilsTest {
@Test
void testCurrentTimeMillis() {
assertTrue(0 < TimeUtils.currentTimeMillis());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ParametersTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/ParametersTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ParametersTest {
final String ServiceName = "org.apache.dubbo.rpc.service.GenericService";
final String ServiceVersion = "1.0.15";
final String LoadBalance = "lcr";
public void testMap2Parameters() {
Map<String, String> map = new HashMap<String, String>();
map.put("name", "org.apache.dubbo.rpc.service.GenericService");
map.put("version", "1.0.15");
map.put("lb", "lcr");
map.put("max.active", "500");
assertEquals(map.get("name"), ServiceName);
assertEquals(map.get("version"), ServiceVersion);
assertEquals(map.get("lb"), LoadBalance);
}
public void testString2Parameters() throws Exception {
String qs = "name=org.apache.dubbo.rpc.service.GenericService&version=1.0.15&lb=lcr";
Map<String, String> map = StringUtils.parseQueryString(qs);
assertEquals(map.get("name"), ServiceName);
assertEquals(map.get("version"), ServiceVersion);
assertEquals(map.get("lb"), LoadBalance);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LockUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/LockUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.lang.Thread.State;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.RepeatedTest;
import static org.awaitility.Awaitility.await;
public class LockUtilsTest {
@RepeatedTest(5)
void testLockFailed() {
ReentrantLock reentrantLock = new ReentrantLock();
AtomicBoolean releaseLock = new AtomicBoolean(false);
new Thread(() -> {
reentrantLock.lock();
while (!releaseLock.get()) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
reentrantLock.unlock();
})
.start();
await().until(reentrantLock::isLocked);
AtomicLong lockTime = new AtomicLong(0);
long startTime = System.currentTimeMillis();
LockUtils.safeLock(reentrantLock, 1000, () -> {
lockTime.set(System.currentTimeMillis());
});
Assertions.assertTrue(lockTime.get() - startTime >= 1000);
releaseLock.set(true);
while (reentrantLock.isLocked()) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
lockTime.set(0);
startTime = System.currentTimeMillis();
LockUtils.safeLock(reentrantLock, 1000, () -> {
lockTime.set(System.currentTimeMillis());
});
Assertions.assertTrue(lockTime.get() - startTime < 1000);
}
@RepeatedTest(5)
void testReentrant() {
ReentrantLock reentrantLock = new ReentrantLock();
reentrantLock.lock();
AtomicLong lockTime = new AtomicLong(0);
long startTime = System.currentTimeMillis();
LockUtils.safeLock(reentrantLock, 1000, () -> {
lockTime.set(System.currentTimeMillis());
});
Assertions.assertTrue(lockTime.get() - startTime < 1000);
reentrantLock.lock();
lockTime.set(0);
startTime = System.currentTimeMillis();
LockUtils.safeLock(reentrantLock, 1000, () -> {
lockTime.set(System.currentTimeMillis());
});
Assertions.assertTrue(lockTime.get() - startTime < 1000);
Assertions.assertTrue(reentrantLock.isLocked());
reentrantLock.unlock();
Assertions.assertTrue(reentrantLock.isLocked());
reentrantLock.unlock();
Assertions.assertFalse(reentrantLock.isLocked());
}
@RepeatedTest(5)
void testInterrupt() {
ReentrantLock reentrantLock = new ReentrantLock();
reentrantLock.lock();
AtomicBoolean locked = new AtomicBoolean(false);
Thread thread = new Thread(() -> {
LockUtils.safeLock(reentrantLock, 10000, () -> {
locked.set(true);
});
});
thread.start();
await().until(() -> thread.getState() == State.TIMED_WAITING);
thread.interrupt();
await().until(() -> thread.getState() == State.TERMINATED);
Assertions.assertTrue(locked.get());
reentrantLock.unlock();
}
@RepeatedTest(5)
void testHoldLock() throws InterruptedException {
ReentrantLock reentrantLock = new ReentrantLock();
reentrantLock.lock();
AtomicLong lockTime = new AtomicLong(0);
long startTime = System.currentTimeMillis();
Thread thread = new Thread(() -> {
LockUtils.safeLock(reentrantLock, 10000, () -> {
lockTime.set(System.currentTimeMillis());
});
});
thread.start();
await().until(() -> thread.getState() == State.TIMED_WAITING);
Thread.sleep(1000);
reentrantLock.unlock();
await().until(() -> thread.getState() == State.TERMINATED);
Assertions.assertTrue(lockTime.get() - startTime > 1000);
Assertions.assertTrue(lockTime.get() - startTime < 10000);
}
@RepeatedTest(5)
void testInterrupted() throws InterruptedException {
ReentrantLock reentrantLock = new ReentrantLock();
reentrantLock.lock();
AtomicLong lockTime = new AtomicLong(0);
long startTime = System.currentTimeMillis();
Thread thread = new Thread(() -> {
Thread.currentThread().interrupt();
LockUtils.safeLock(reentrantLock, 10000, () -> {
lockTime.set(System.currentTimeMillis());
});
});
thread.start();
await().until(() -> thread.getState() == State.TERMINATED);
Assertions.assertTrue(lockTime.get() >= startTime);
Assertions.assertTrue(lockTime.get() - startTime < 10000);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MD5UtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/MD5UtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class MD5UtilsTest {
private static final Logger logger = LoggerFactory.getLogger(MD5UtilsTest.class);
@Test
void test() {
MD5Utils sharedMd5Utils = new MD5Utils();
final String[] input = {
"provider-appgroup-one/org.apache.dubbo.config.spring.api.HelloService:dubboorg.apache.dubbo.config.spring.api.HelloService{REGISTRY_CLUSTER=registry-one, anyhost=true, application=provider-app, background=false, compiler=javassist, deprecated=false, dubbo=2.0.2, dynamic=true, file.cache=false, generic=false, group=group-one, interface=org.apache.dubbo.config.spring.api.HelloService, logger=slf4j, metadata-type=remote, methods=sayHello, organization=test, owner=com.test, release=, service-name-mapping=true, side=provider}",
"provider-appgroup-two/org.apache.dubbo.config.spring.api.DemoService:dubboorg.apache.dubbo.config.spring.api.DemoService{REGISTRY_CLUSTER=registry-two, anyhost=true, application=provider-app, background=false, compiler=javassist, deprecated=false, dubbo=2.0.2, dynamic=true, file.cache=false, generic=false, group=group-two, interface=org.apache.dubbo.config.spring.api.DemoService, logger=slf4j, metadata-type=remote, methods=sayName,getBox, organization=test, owner=com.test, release=, service-name-mapping=true, side=provider}"
};
final String[] result = {sharedMd5Utils.getMd5(input[0]), new MD5Utils().getMd5(input[1])};
logger.info("Expected result: {}", Arrays.asList(result));
int nThreads = 8;
CountDownLatch latch = new CountDownLatch(nThreads);
List<Throwable> errors = Collections.synchronizedList(new ArrayList<>());
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
try {
for (int i = 0; i < nThreads; i++) {
MD5Utils md5Utils = i < nThreads / 2 ? sharedMd5Utils : new MD5Utils();
executorService.submit(new Md5Task(input[i % 2], result[i % 2], md5Utils, latch, errors));
}
latch.await();
Assertions.assertEquals(Collections.EMPTY_LIST, errors);
Assertions.assertEquals(0, latch.getCount());
} catch (Throwable e) {
Assertions.fail(StringUtils.toString(e));
} finally {
executorService.shutdown();
}
}
static class Md5Task implements Runnable {
private final String input;
private final String expected;
private final MD5Utils md5Utils;
private final CountDownLatch latch;
private final List<Throwable> errorCollector;
public Md5Task(
String input,
String expected,
MD5Utils md5Utils,
CountDownLatch latch,
List<Throwable> errorCollector) {
this.input = input;
this.expected = expected;
this.md5Utils = md5Utils;
this.latch = latch;
this.errorCollector = errorCollector;
}
@Override
public void run() {
int i = 0;
long start = System.currentTimeMillis();
try {
for (; i < 200; i++) {
Assertions.assertEquals(expected, md5Utils.getMd5(input));
md5Utils.getMd5("test#" + i);
}
} catch (Throwable e) {
errorCollector.add(e);
e.printStackTrace();
} finally {
long cost = System.currentTimeMillis() - start;
logger.info(
"[{}] progress: {}, cost: {}", Thread.currentThread().getName(), i, cost);
latch.countDown();
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestEnum.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestEnum.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
public enum TestEnum {
TYPE_A,
TYPE_B,
TYPE_C
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Service.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Service.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public interface Service {
String sayHi(String name);
List<String> testList();
int testInt();
int[] testIntArr();
Integer testInteger();
Integer[] testIntegerArr();
List<Integer> testIntegerList();
short testShort();
short[] testShortArr();
Short testSShort();
Short[] testSShortArr();
List<Short> testShortList();
byte testByte();
byte[] testByteArr();
Byte testBByte();
Byte[] testBByteArr();
ArrayList<Byte> testByteList();
float testFloat();
float[] testFloatArr();
Float testFFloat();
Float[] testFloatArray();
List<Float> testFloatList();
boolean testBoolean();
boolean[] testBooleanArr();
Boolean testBBoolean();
Boolean[] testBooleanArray();
List<Boolean> testBooleanList();
char testChar();
char[] testCharArr();
Character testCharacter();
Character[] testCharacterArr();
List<Character> testCharacterList();
List<Character[]> testCharacterListArr();
String testString();
String[] testStringArr();
List<String> testStringList();
List<String[]> testStringListArr();
String testNull();
Date testDate();
Calendar testCalendar();
LocalTime testLocalTime();
LocalDate testLocalDate();
LocalDateTime testLocalDateTime();
ZonedDateTime testZoneDateTime();
Map<Integer, String> testMap();
Set<Integer> testSet();
Optional<Integer> testOptionalEmpty();
Optional<Integer> testOptionalInteger();
Optional<String> testOptionalString();
Color testEnum();
Range testRecord();
Printer testInterface();
Teacher testObject();
List<Teacher> testObjectList();
Student<Integer> testTemplate();
InputStream testStream() throws FileNotFoundException;
Iterator<String> testIterator();
AbstractObject testAbstract();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Student.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Student.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
import java.io.Serializable;
import java.util.List;
public class Student<W> implements Serializable {
private Integer type;
private List<String> names;
private List<W> namesT;
private W age;
private String name;
public Student(Integer type, String name) {
this.type = type;
this.name = name;
}
@Override
public String toString() {
return "Student{" + "type=" + type + ", name='" + name + '\'' + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Color.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Color.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
public enum Color {
RED("红色", 1),
GREEN("绿色", 2),
BLANK("白色", 3),
YELLOW("黄色", 4);
private String name;
private int index;
private Color(String name, int index) {
this.name = name;
this.index = index;
}
public static String getName(int index) {
for (Color c : Color.values()) {
if (c.getIndex() == index) {
return c.name;
}
}
return null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectB.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectB.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
public class TestObjectB {
private Inner innerA;
private Inner innerB;
public Inner getInnerA() {
return innerA;
}
public void setInnerA(Inner innerA) {
this.innerA = innerA;
}
public Inner getInnerB() {
return innerB;
}
public void setInnerB(Inner innerB) {
this.innerB = innerB;
}
public static class Inner {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Teacher.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Teacher.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
import java.io.Serializable;
public class Teacher implements Serializable {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Teacher(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Teacher{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Printer.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Printer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
public interface Printer {
String print();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectA.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectA.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
public class TestObjectA {
private String name;
private int age;
private TestEnum testEnum;
public TestObjectA() {}
public TestObjectA(String name, int age, TestEnum testEnum) {
this.name = name;
this.age = age;
this.testEnum = testEnum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public TestEnum getTestEnum() {
return testEnum;
}
public void setTestEnum(TestEnum testEnum) {
this.testEnum = testEnum;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Range.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Range.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
// public record Range(Integer left, Integer right) {
// public Integer sum() {
// return left + right;
// }
// }
public class Range {
private Integer left;
private Integer right;
public Range(Integer left, Integer right) {
this.left = left;
this.right = right;
}
public Integer sum() {
return left + right;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/AbstractObject.java | dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/AbstractObject.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.utils.json;
public abstract class AbstractObject {
public abstract String sayHello();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/concurrent/CompletableFutureTaskTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/concurrent/CompletableFutureTaskTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.concurrent;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class CompletableFutureTaskTest {
private static final ExecutorService executor = new ThreadPoolExecutor(
0,
10,
60L,
TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new NamedThreadFactory("DubboMonitorCreator", true));
@Test
void testCreate() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(1);
CompletableFuture<Boolean> completableFuture = CompletableFuture.supplyAsync(
() -> {
countDownLatch.countDown();
return true;
},
executor);
countDownLatch.await();
}
@Test
void testRunnableResponse() throws ExecutionException, InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
CompletableFuture<Boolean> completableFuture = CompletableFuture.supplyAsync(
() -> {
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return true;
},
executor);
Assertions.assertNull(completableFuture.getNow(null));
latch.countDown();
Boolean result = completableFuture.get();
assertThat(result, is(true));
}
@Test
void testListener() throws InterruptedException {
AtomicBoolean run = new AtomicBoolean(false);
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(
() -> {
run.set(true);
return "hello";
},
executor);
final CountDownLatch countDownLatch = new CountDownLatch(1);
completableFuture.thenRunAsync(countDownLatch::countDown);
countDownLatch.await();
Assertions.assertTrue(run.get());
}
@Test
void testCustomExecutor() {
Executor mockedExecutor = mock(Executor.class);
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
return 0;
});
completableFuture
.thenRunAsync(mock(Runnable.class), mockedExecutor)
.whenComplete((s, e) -> verify(mockedExecutor, times(1)).execute(any(Runnable.class)));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/timer/HashedWheelTimerTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/timer/HashedWheelTimerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.timer;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.awaitility.Awaitility.await;
class HashedWheelTimerTest {
private CountDownLatch tryStopTaskCountDownLatch = new CountDownLatch(1);
private CountDownLatch errorTaskCountDownLatch = new CountDownLatch(1);
private static class EmptyTask implements TimerTask {
@Override
public void run(Timeout timeout) {}
}
private static class BlockTask implements TimerTask {
@Override
public void run(Timeout timeout) throws InterruptedException {
this.wait();
}
}
private class ErrorTask implements TimerTask {
@Override
public void run(Timeout timeout) {
errorTaskCountDownLatch.countDown();
throw new RuntimeException("Test");
}
}
private class TryStopTask implements TimerTask {
private Timer timer;
public TryStopTask(Timer timer) {
this.timer = timer;
}
@Override
public void run(Timeout timeout) {
Assertions.assertThrows(RuntimeException.class, () -> timer.stop());
tryStopTaskCountDownLatch.countDown();
}
}
@Test
void constructorTest() {
// use weak reference to let gc work every time
// which can check finalize method and reduce memory usage in time
WeakReference<Timer> timer = new WeakReference<>(new HashedWheelTimer());
timer = new WeakReference<>(new HashedWheelTimer(100, TimeUnit.MILLISECONDS));
timer = new WeakReference<>(new HashedWheelTimer(100, TimeUnit.MILLISECONDS, 8));
// to cover arg check branches
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(null, 100, TimeUnit.MILLISECONDS, 8, -1);
});
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 0, TimeUnit.MILLISECONDS, 8, -1);
});
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 100, null, 8, -1);
});
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(
new NamedThreadFactory("dubbo-future-timeout", true), 100, TimeUnit.MILLISECONDS, 0, -1);
});
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(
new NamedThreadFactory("dubbo-future-timeout", true), Long.MAX_VALUE, TimeUnit.MILLISECONDS, 8, -1);
});
Assertions.assertThrows(RuntimeException.class, () -> {
new HashedWheelTimer(
new NamedThreadFactory("dubbo-future-timeout", true),
100,
TimeUnit.MILLISECONDS,
Integer.MAX_VALUE,
-1);
});
for (int i = 0; i < 128; i++) {
// to trigger INSTANCE_COUNT_LIMIT
timer = new WeakReference<>(new HashedWheelTimer());
}
System.gc();
}
@Test
void createTaskTest() throws InterruptedException {
HashedWheelTimer timer = new HashedWheelTimer(
new NamedThreadFactory("dubbo-future-timeout", true), 10, TimeUnit.MILLISECONDS, 8, 8);
EmptyTask emptyTask = new EmptyTask();
Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(null, 5, TimeUnit.SECONDS));
Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(emptyTask, 5, null));
Timeout timeout = timer.newTimeout(new ErrorTask(), 10, TimeUnit.MILLISECONDS);
errorTaskCountDownLatch.await();
Assertions.assertFalse(timeout.cancel());
Assertions.assertFalse(timeout.isCancelled());
Assertions.assertNotNull(timeout.toString());
Assertions.assertEquals(timeout.timer(), timer);
timeout = timer.newTimeout(emptyTask, 1000, TimeUnit.SECONDS);
timeout.cancel();
Assertions.assertTrue(timeout.isCancelled());
List<Timeout> timeouts = new LinkedList<>();
BlockTask blockTask = new BlockTask();
while (timer.pendingTimeouts() < 8) {
// to trigger maxPendingTimeouts
timeout = timer.newTimeout(blockTask, -1, TimeUnit.MILLISECONDS);
timeouts.add(timeout);
Assertions.assertNotNull(timeout.toString());
}
Assertions.assertEquals(8, timer.pendingTimeouts());
// this will throw an exception because of maxPendingTimeouts
Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(blockTask, 1, TimeUnit.MILLISECONDS));
Timeout secondTimeout = timeouts.get(2);
// wait until the task expired
await().until(secondTimeout::isExpired);
timer.stop();
}
@Test
void stopTaskTest() throws InterruptedException {
Timer timer = new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true));
timer.newTimeout(new TryStopTask(timer), 10, TimeUnit.MILLISECONDS);
tryStopTaskCountDownLatch.await();
for (int i = 0; i < 8; i++) {
timer.newTimeout(new EmptyTask(), 0, TimeUnit.SECONDS);
}
// stop timer
timer.stop();
Assertions.assertTrue(timer.isStop());
// this will throw an exception
Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(new EmptyTask(), 5, TimeUnit.SECONDS));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/vo/UserVo.java | dubbo-common/src/test/java/org/apache/dubbo/common/vo/UserVo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.vo;
import java.util.Objects;
public class UserVo {
private String name;
private String addr;
private int age;
public UserVo(String name, String addr, int age) {
this.name = name;
this.addr = addr;
this.age = age;
}
public UserVo() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static UserVo getInstance() {
return new UserVo("dubbo", "hangzhou", 10);
}
@Override
public String toString() {
return "UserVo{" + "name='" + name + '\'' + ", addr='" + addr + '\'' + ", age=" + age + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserVo userVo = (UserVo) o;
return age == userVo.age && Objects.equals(name, userVo.name) && Objects.equals(addr, userVo.addr);
}
@Override
public int hashCode() {
return Objects.hash(name, addr, age);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/CertManagerTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/ssl/CertManagerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.ssl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class CertManagerTest {
private FrameworkModel frameworkModel;
private URL url;
@BeforeEach
void setup() {
FirstCertProvider.setProviderCert(null);
FirstCertProvider.setCert(null);
FirstCertProvider.setSupport(false);
SecondCertProvider.setProviderCert(null);
SecondCertProvider.setCert(null);
SecondCertProvider.setSupport(false);
frameworkModel = new FrameworkModel();
url = URL.valueOf("dubbo://").setScopeModel(frameworkModel.newApplication());
}
@AfterEach
void teardown() {
frameworkModel.destroy();
}
@Test
void testGetConsumerConnectionConfig() {
CertManager certManager = new CertManager(frameworkModel);
Assertions.assertNull(certManager.getConsumerConnectionConfig(url));
Cert cert1 = Mockito.mock(Cert.class);
FirstCertProvider.setCert(cert1);
Assertions.assertNull(certManager.getConsumerConnectionConfig(url));
FirstCertProvider.setSupport(true);
Assertions.assertEquals(cert1, certManager.getConsumerConnectionConfig(url));
Cert cert2 = Mockito.mock(Cert.class);
SecondCertProvider.setCert(cert2);
Assertions.assertEquals(cert1, certManager.getConsumerConnectionConfig(url));
SecondCertProvider.setSupport(true);
Assertions.assertEquals(cert1, certManager.getConsumerConnectionConfig(url));
FirstCertProvider.setSupport(false);
Assertions.assertEquals(cert2, certManager.getConsumerConnectionConfig(url));
FirstCertProvider.setSupport(true);
FirstCertProvider.setCert(null);
Assertions.assertEquals(cert2, certManager.getConsumerConnectionConfig(url));
}
@Test
void testGetProviderConnectionConfig() {
CertManager certManager = new CertManager(frameworkModel);
Assertions.assertNull(certManager.getProviderConnectionConfig(url, null));
ProviderCert providerCert1 = Mockito.mock(ProviderCert.class);
FirstCertProvider.setProviderCert(providerCert1);
Assertions.assertNull(certManager.getProviderConnectionConfig(url, null));
FirstCertProvider.setSupport(true);
Assertions.assertEquals(providerCert1, certManager.getProviderConnectionConfig(url, null));
ProviderCert providerCert2 = Mockito.mock(ProviderCert.class);
SecondCertProvider.setProviderCert(providerCert2);
Assertions.assertEquals(providerCert1, certManager.getProviderConnectionConfig(url, null));
SecondCertProvider.setSupport(true);
Assertions.assertEquals(providerCert1, certManager.getProviderConnectionConfig(url, null));
FirstCertProvider.setSupport(false);
Assertions.assertEquals(providerCert2, certManager.getProviderConnectionConfig(url, null));
FirstCertProvider.setSupport(true);
FirstCertProvider.setProviderCert(null);
Assertions.assertEquals(providerCert2, certManager.getProviderConnectionConfig(url, null));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SSLConfigCertProviderTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SSLConfigCertProviderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.ssl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.ssl.impl.SSLConfigCertProvider;
import org.apache.dubbo.common.utils.IOUtils;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SSLConfigCertProviderTest {
@Test
void testSupported() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
SSLConfigCertProvider sslConfigCertProvider = new SSLConfigCertProvider();
URL url = URL.valueOf("").setScopeModel(applicationModel);
Assertions.assertFalse(sslConfigCertProvider.isSupport(url));
SslConfig sslConfig = new SslConfig();
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
Assertions.assertTrue(sslConfigCertProvider.isSupport(url));
frameworkModel.destroy();
}
@Test
void testGetProviderConnectionConfig() throws IOException {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
SSLConfigCertProvider sslConfigCertProvider = new SSLConfigCertProvider();
URL url = URL.valueOf("").setScopeModel(applicationModel);
Assertions.assertNull(sslConfigCertProvider.getProviderConnectionConfig(url));
SslConfig sslConfig = new SslConfig();
sslConfig.setServerKeyCertChainPath("keyCert");
sslConfig.setServerPrivateKeyPath("private");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
ProviderCert providerCert = sslConfigCertProvider.getProviderConnectionConfig(url);
Assertions.assertNull(providerCert);
sslConfig.setServerKeyCertChainPath(
this.getClass().getClassLoader().getResource("certs/cert.pem").getFile());
sslConfig.setServerPrivateKeyPath(
this.getClass().getClassLoader().getResource("certs/key.pem").getFile());
providerCert = sslConfigCertProvider.getProviderConnectionConfig(url);
Assertions.assertNotNull(providerCert);
Assertions.assertArrayEquals(
IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")),
providerCert.getKeyCertChain());
Assertions.assertArrayEquals(
IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")),
providerCert.getPrivateKey());
Assertions.assertNull(providerCert.getTrustCert());
sslConfig.setServerTrustCertCollectionPath(
this.getClass().getClassLoader().getResource("certs/ca.pem").getFile());
providerCert = sslConfigCertProvider.getProviderConnectionConfig(url);
Assertions.assertNotNull(providerCert);
Assertions.assertArrayEquals(
IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")),
providerCert.getKeyCertChain());
Assertions.assertArrayEquals(
IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")),
providerCert.getPrivateKey());
Assertions.assertArrayEquals(
IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/ca.pem")),
providerCert.getTrustCert());
frameworkModel.destroy();
}
@Test
void testGetConsumerConnectionConfig() throws IOException {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
SSLConfigCertProvider sslConfigCertProvider = new SSLConfigCertProvider();
URL url = URL.valueOf("").setScopeModel(applicationModel);
Assertions.assertNull(sslConfigCertProvider.getConsumerConnectionConfig(url));
SslConfig sslConfig = new SslConfig();
sslConfig.setClientKeyCertChainPath("keyCert");
sslConfig.setClientPrivateKeyPath("private");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
Cert cert = sslConfigCertProvider.getConsumerConnectionConfig(url);
Assertions.assertNull(cert);
sslConfig.setClientKeyCertChainPath(
this.getClass().getClassLoader().getResource("certs/cert.pem").getFile());
sslConfig.setClientPrivateKeyPath(
this.getClass().getClassLoader().getResource("certs/key.pem").getFile());
cert = sslConfigCertProvider.getConsumerConnectionConfig(url);
Assertions.assertNotNull(cert);
Assertions.assertArrayEquals(
IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")),
cert.getKeyCertChain());
Assertions.assertArrayEquals(
IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")),
cert.getPrivateKey());
sslConfig.setClientTrustCertCollectionPath(
this.getClass().getClassLoader().getResource("certs/ca.pem").getFile());
cert = sslConfigCertProvider.getConsumerConnectionConfig(url);
Assertions.assertNotNull(cert);
Assertions.assertArrayEquals(
IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")),
cert.getKeyCertChain());
Assertions.assertArrayEquals(
IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")),
cert.getPrivateKey());
Assertions.assertArrayEquals(
IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/ca.pem")),
cert.getTrustCert());
frameworkModel.destroy();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/FirstCertProvider.java | dubbo-common/src/test/java/org/apache/dubbo/common/ssl/FirstCertProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.ssl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
@Activate(order = -10000)
public class FirstCertProvider implements CertProvider {
private static final AtomicBoolean isSupport = new AtomicBoolean(false);
private static final AtomicReference<ProviderCert> providerCert = new AtomicReference<>();
private static final AtomicReference<Cert> cert = new AtomicReference<>();
@Override
public boolean isSupport(URL address) {
return isSupport.get();
}
@Override
public ProviderCert getProviderConnectionConfig(URL localAddress) {
return providerCert.get();
}
@Override
public Cert getConsumerConnectionConfig(URL remoteAddress) {
return cert.get();
}
public static void setSupport(boolean support) {
isSupport.set(support);
}
public static void setProviderCert(ProviderCert providerCert) {
FirstCertProvider.providerCert.set(providerCert);
}
public static void setCert(Cert cert) {
FirstCertProvider.cert.set(cert);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SecondCertProvider.java | dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SecondCertProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.ssl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
@Activate(order = 10000)
public class SecondCertProvider implements CertProvider {
private static final AtomicBoolean isSupport = new AtomicBoolean(false);
private static final AtomicReference<ProviderCert> providerCert = new AtomicReference<>();
private static final AtomicReference<Cert> cert = new AtomicReference<>();
@Override
public boolean isSupport(URL address) {
return isSupport.get();
}
@Override
public ProviderCert getProviderConnectionConfig(URL localAddress) {
return providerCert.get();
}
@Override
public Cert getConsumerConnectionConfig(URL remoteAddress) {
return cert.get();
}
public static void setSupport(boolean support) {
isSupport.set(support);
}
public static void setProviderCert(ProviderCert providerCert) {
SecondCertProvider.providerCert.set(providerCert);
}
public static void setCert(Cert cert) {
SecondCertProvider.cert.set(cert);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/PropertiesConfigurationTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/PropertiesConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link PropertiesConfiguration}
*/
class PropertiesConfigurationTest {
@Test
void test() {
PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration(ApplicationModel.defaultModel());
Map<String, String> properties = propertiesConfiguration.getProperties();
Assertions.assertEquals(properties.get("dubbo"), "properties");
Assertions.assertEquals(properties.get("dubbo.application.enable-file-cache"), "false");
Assertions.assertEquals(properties.get("dubbo.service.shutdown.wait"), "200");
Assertions.assertEquals(propertiesConfiguration.getProperty("dubbo"), "properties");
Assertions.assertEquals(propertiesConfiguration.getInternalProperty("dubbo"), "properties");
propertiesConfiguration.setProperty("k1", "v1");
Assertions.assertEquals(propertiesConfiguration.getProperty("k1"), "v1");
propertiesConfiguration.remove("k1");
Assertions.assertNull(propertiesConfiguration.getProperty("k1"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/InmemoryConfigurationTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/InmemoryConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.beanutil.JavaBeanAccessor;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit test of class InmemoryConfiguration, and interface Configuration.
*/
class InmemoryConfigurationTest {
private InmemoryConfiguration memConfig;
private static final String MOCK_KEY = "mockKey";
private static final String MOCK_VALUE = "mockValue";
private static final String MOCK_ONE_KEY = "one";
private static final String MOCK_TWO_KEY = "two";
private static final String MOCK_THREE_KEY = "three";
/**
* Init.
*/
@BeforeEach
public void init() {
memConfig = new InmemoryConfiguration();
}
/**
* Test get mem property.
*/
@Test
void testGetMemProperty() {
Assertions.assertNull(memConfig.getInternalProperty(MOCK_KEY));
Assertions.assertFalse(memConfig.containsKey(MOCK_KEY));
Assertions.assertNull(memConfig.getString(MOCK_KEY));
Assertions.assertNull(memConfig.getProperty(MOCK_KEY));
memConfig.addProperty(MOCK_KEY, MOCK_VALUE);
Assertions.assertTrue(memConfig.containsKey(MOCK_KEY));
Assertions.assertEquals(MOCK_VALUE, memConfig.getInternalProperty(MOCK_KEY));
Assertions.assertEquals(MOCK_VALUE, memConfig.getString(MOCK_KEY, MOCK_VALUE));
Assertions.assertEquals(MOCK_VALUE, memConfig.getProperty(MOCK_KEY, MOCK_VALUE));
}
/**
* Test get properties.
*/
@Test
void testGetProperties() {
Assertions.assertNull(memConfig.getInternalProperty(MOCK_ONE_KEY));
Assertions.assertNull(memConfig.getInternalProperty(MOCK_TWO_KEY));
Map<String, String> proMap = new HashMap<>();
proMap.put(MOCK_ONE_KEY, MOCK_VALUE);
proMap.put(MOCK_TWO_KEY, MOCK_VALUE);
memConfig.addProperties(proMap);
Assertions.assertNotNull(memConfig.getInternalProperty(MOCK_ONE_KEY));
Assertions.assertNotNull(memConfig.getInternalProperty(MOCK_TWO_KEY));
Map<String, String> anotherProMap = new HashMap<>();
anotherProMap.put(MOCK_THREE_KEY, MOCK_VALUE);
memConfig.setProperties(anotherProMap);
Assertions.assertNotNull(memConfig.getInternalProperty(MOCK_THREE_KEY));
Assertions.assertNull(memConfig.getInternalProperty(MOCK_ONE_KEY));
Assertions.assertNull(memConfig.getInternalProperty(MOCK_TWO_KEY));
}
@Test
void testGetInt() {
memConfig.addProperty("a", "1");
Assertions.assertEquals(1, memConfig.getInt("a"));
Assertions.assertEquals(Integer.valueOf(1), memConfig.getInteger("a", 2));
Assertions.assertEquals(2, memConfig.getInt("b", 2));
}
@Test
void getBoolean() {
memConfig.addProperty("a", Boolean.TRUE.toString());
Assertions.assertTrue(memConfig.getBoolean("a"));
Assertions.assertFalse(memConfig.getBoolean("b", false));
Assertions.assertTrue(memConfig.getBoolean("b", Boolean.TRUE));
}
@Test
void testIllegalType() {
memConfig.addProperty("it", "aaa");
Assertions.assertThrows(IllegalStateException.class, () -> memConfig.getInteger("it", 1));
Assertions.assertThrows(IllegalStateException.class, () -> memConfig.getInt("it", 1));
Assertions.assertThrows(IllegalStateException.class, () -> memConfig.getInt("it"));
}
@Test
void testDoesNotExist() {
Assertions.assertThrows(NoSuchElementException.class, () -> memConfig.getInt("ne"));
Assertions.assertThrows(NoSuchElementException.class, () -> memConfig.getBoolean("ne"));
}
@Test
void testConversions() {
memConfig.addProperty("long", "2147483648");
memConfig.addProperty("byte", "127");
memConfig.addProperty("short", "32767");
memConfig.addProperty("float", "3.14");
memConfig.addProperty("double", "3.14159265358979323846264338327950");
memConfig.addProperty("enum", "FIELD");
Object longObject = memConfig.convert(Long.class, "long", 1L);
Object byteObject = memConfig.convert(Byte.class, "byte", (byte) 1);
Object shortObject = memConfig.convert(Short.class, "short", (short) 1);
Object floatObject = memConfig.convert(Float.class, "float", 3.14F);
Object doubleObject = memConfig.convert(Double.class, "double", 3.14159265358979323846264338327950);
JavaBeanAccessor javaBeanAccessor = memConfig.convert(JavaBeanAccessor.class, "enum", JavaBeanAccessor.ALL);
Assertions.assertEquals(Long.class, longObject.getClass());
Assertions.assertEquals(2147483648L, longObject);
Assertions.assertEquals(Byte.class, byteObject.getClass());
Assertions.assertEquals((byte) 127, byteObject);
Assertions.assertEquals(Short.class, shortObject.getClass());
Assertions.assertEquals((short) 32767, shortObject);
Assertions.assertEquals(Float.class, floatObject.getClass());
Assertions.assertEquals(3.14F, floatObject);
Assertions.assertEquals(Double.class, doubleObject.getClass());
Assertions.assertEquals(3.14159265358979323846264338327950, doubleObject);
Assertions.assertEquals(JavaBeanAccessor.class, javaBeanAccessor.getClass());
Assertions.assertEquals(JavaBeanAccessor.FIELD, javaBeanAccessor);
}
/**
* Clean.
*/
@AfterEach
public void clean() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/MockOrderedPropertiesProvider1.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/MockOrderedPropertiesProvider1.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import java.util.Properties;
public class MockOrderedPropertiesProvider1 implements OrderedPropertiesProvider {
@Override
public int priority() {
return 3;
}
@Override
public Properties initProperties() {
Properties properties = new Properties();
properties.put("testKey", "333");
return properties;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/SystemConfigurationTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/SystemConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* The type System configuration test.
*/
class SystemConfigurationTest {
private static SystemConfiguration sysConfig;
private static final String MOCK_KEY = "mockKey";
private static final String MOCK_STRING_VALUE = "mockValue";
private static final Boolean MOCK_BOOL_VALUE = Boolean.FALSE;
private static final Integer MOCK_INT_VALUE = Integer.MAX_VALUE;
private static final Long MOCK_LONG_VALUE = Long.MIN_VALUE;
private static final Short MOCK_SHORT_VALUE = Short.MIN_VALUE;
private static final Float MOCK_FLOAT_VALUE = Float.MIN_VALUE;
private static final Double MOCK_DOUBLE_VALUE = Double.MIN_VALUE;
private static final Byte MOCK_BYTE_VALUE = Byte.MIN_VALUE;
private static final String NOT_EXIST_KEY = "NOTEXIST";
/**
* Init.
*/
@BeforeEach
public void init() {
sysConfig = new SystemConfiguration();
}
/**
* Test get sys property.
*/
@Test
void testGetSysProperty() {
Assertions.assertNull(sysConfig.getInternalProperty(MOCK_KEY));
Assertions.assertFalse(sysConfig.containsKey(MOCK_KEY));
Assertions.assertNull(sysConfig.getString(MOCK_KEY));
Assertions.assertNull(sysConfig.getProperty(MOCK_KEY));
System.setProperty(MOCK_KEY, MOCK_STRING_VALUE);
Assertions.assertTrue(sysConfig.containsKey(MOCK_KEY));
Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.getInternalProperty(MOCK_KEY));
Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.getString(MOCK_KEY, MOCK_STRING_VALUE));
Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.getProperty(MOCK_KEY, MOCK_STRING_VALUE));
}
/**
* Test convert.
*/
@Test
void testConvert() {
Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.convert(String.class, NOT_EXIST_KEY, MOCK_STRING_VALUE));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_BOOL_VALUE));
Assertions.assertEquals(MOCK_BOOL_VALUE, sysConfig.convert(Boolean.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_STRING_VALUE));
Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.convert(String.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_INT_VALUE));
Assertions.assertEquals(MOCK_INT_VALUE, sysConfig.convert(Integer.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_LONG_VALUE));
Assertions.assertEquals(MOCK_LONG_VALUE, sysConfig.convert(Long.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_SHORT_VALUE));
Assertions.assertEquals(MOCK_SHORT_VALUE, sysConfig.convert(Short.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_FLOAT_VALUE));
Assertions.assertEquals(MOCK_FLOAT_VALUE, sysConfig.convert(Float.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_DOUBLE_VALUE));
Assertions.assertEquals(MOCK_DOUBLE_VALUE, sysConfig.convert(Double.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(MOCK_BYTE_VALUE));
Assertions.assertEquals(MOCK_BYTE_VALUE, sysConfig.convert(Byte.class, MOCK_KEY, null));
System.setProperty(MOCK_KEY, String.valueOf(ConfigMock.MockOne));
Assertions.assertEquals(ConfigMock.MockOne, sysConfig.convert(ConfigMock.class, MOCK_KEY, null));
}
/**
* Clean.
*/
@AfterEach
public void clean() {
if (null != System.getProperty(MOCK_KEY)) {
System.clearProperty(MOCK_KEY);
}
}
/**
* The enum Config mock.
*/
enum ConfigMock {
/**
* Mock one config mock.
*/
MockOne,
/**
* Mock two config mock.
*/
MockTwo
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/MockOrderedPropertiesProvider2.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/MockOrderedPropertiesProvider2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import java.util.Properties;
public class MockOrderedPropertiesProvider2 implements OrderedPropertiesProvider {
@Override
public int priority() {
return 1;
}
@Override
public Properties initProperties() {
Properties properties = new Properties();
properties.put("testKey", "999");
return properties;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
class ConfigurationUtilsTest {
@Test
void testCachedProperties() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
Environment originApplicationEnvironment = applicationModel.modelEnvironment();
Environment applicationEnvironment = Mockito.spy(originApplicationEnvironment);
applicationModel.setEnvironment(applicationEnvironment);
Configuration configuration = Mockito.mock(Configuration.class);
Mockito.when(applicationEnvironment.getDynamicGlobalConfiguration()).thenReturn(configuration);
Mockito.when(configuration.getString("TestKey", "")).thenReturn("a");
Assertions.assertEquals("a", ConfigurationUtils.getCachedDynamicProperty(applicationModel, "TestKey", "xxx"));
Mockito.when(configuration.getString("TestKey", "")).thenReturn("b");
// cached key
Assertions.assertEquals("a", ConfigurationUtils.getCachedDynamicProperty(applicationModel, "TestKey", "xxx"));
ModuleModel moduleModel = applicationModel.newModule();
ModuleEnvironment originModuleEnvironment = moduleModel.modelEnvironment();
ModuleEnvironment moduleEnvironment = Mockito.spy(originModuleEnvironment);
moduleModel.setModuleEnvironment(moduleEnvironment);
Mockito.when(moduleEnvironment.getDynamicGlobalConfiguration()).thenReturn(configuration);
// ApplicationModel should not affect ModuleModel
Assertions.assertEquals("b", ConfigurationUtils.getCachedDynamicProperty(moduleModel, "TestKey", "xxx"));
Mockito.when(configuration.getString("TestKey", "")).thenReturn("c");
// cached key
Assertions.assertEquals("b", ConfigurationUtils.getCachedDynamicProperty(moduleModel, "TestKey", "xxx"));
moduleModel.setModuleEnvironment(originModuleEnvironment);
applicationModel.setEnvironment(originApplicationEnvironment);
frameworkModel.destroy();
}
@Test
void testGetServerShutdownTimeout() {
System.setProperty(SHUTDOWN_WAIT_KEY, " 10000");
Assertions.assertEquals(10000, ConfigurationUtils.getServerShutdownTimeout(ApplicationModel.defaultModel()));
System.clearProperty(SHUTDOWN_WAIT_KEY);
}
@Test
void testGetProperty() {
System.setProperty(SHUTDOWN_WAIT_KEY, " 10000");
Assertions.assertEquals(
"10000", ConfigurationUtils.getProperty(ApplicationModel.defaultModel(), SHUTDOWN_WAIT_KEY));
System.clearProperty(SHUTDOWN_WAIT_KEY);
}
@Test
void testParseSingleProperties() throws Exception {
String p1 = "aaa=bbb";
Map<String, String> result = ConfigurationUtils.parseProperties(p1);
Assertions.assertEquals(1, result.size());
Assertions.assertEquals("bbb", result.get("aaa"));
}
@Test
void testParseMultipleProperties() throws Exception {
String p1 = "aaa=bbb\nccc=ddd";
Map<String, String> result = ConfigurationUtils.parseProperties(p1);
Assertions.assertEquals(2, result.size());
Assertions.assertEquals("bbb", result.get("aaa"));
Assertions.assertEquals("ddd", result.get("ccc"));
}
@Test
void testEscapedNewLine() throws Exception {
String p1 = "dubbo.registry.address=zookeeper://127.0.0.1:2181\\\\ndubbo.protocol.port=20880";
Map<String, String> result = ConfigurationUtils.parseProperties(p1);
Assertions.assertEquals(1, result.size());
Assertions.assertEquals(
"zookeeper://127.0.0.1:2181\\ndubbo.protocol.port=20880", result.get("dubbo.registry.address"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/OrderedPropertiesConfigurationTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/OrderedPropertiesConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link OrderedPropertiesConfiguration}
*/
class OrderedPropertiesConfigurationTest {
@Test
void testOrderPropertiesProviders() {
OrderedPropertiesConfiguration configuration = new OrderedPropertiesConfiguration(
ApplicationModel.defaultModel().getDefaultModule());
Assertions.assertEquals("999", configuration.getInternalProperty("testKey"));
}
@Test
void testGetPropertyFromOrderedPropertiesConfiguration() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
ModuleEnvironment moduleEnvironment = moduleModel.modelEnvironment();
Configuration configuration = moduleEnvironment.getDynamicGlobalConfiguration();
// MockOrderedPropertiesProvider2 initProperties
Assertions.assertEquals("999", configuration.getString("testKey"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationCacheTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationCacheTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link ConfigurationCache}
*/
class ConfigurationCacheTest {
@Test
void test() {
ConfigurationCache configurationCache = new ConfigurationCache();
String value = configurationCache.computeIfAbsent("k1", k -> "v1");
Assertions.assertEquals(value, "v1");
value = configurationCache.computeIfAbsent("k1", k -> "v2");
Assertions.assertEquals(value, "v1");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.config.configcenter.wrapper.CompositeDynamicConfiguration;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link Environment}
*/
class EnvironmentTest {
@Test
void testResolvePlaceholders() {
Environment environment = ApplicationModel.defaultModel().modelEnvironment();
Map<String, String> externalMap = new LinkedHashMap<>();
externalMap.put("zookeeper.address", "127.0.0.1");
externalMap.put("zookeeper.port", "2181");
environment.updateAppExternalConfigMap(externalMap);
Map<String, String> sysprops = new LinkedHashMap<>();
sysprops.put("zookeeper.address", "192.168.10.1");
System.getProperties().putAll(sysprops);
try {
String s = environment.resolvePlaceholders("zookeeper://${zookeeper.address}:${zookeeper.port}");
assertEquals("zookeeper://192.168.10.1:2181", s);
} finally {
for (String key : sysprops.keySet()) {
System.clearProperty(key);
}
}
}
@Test
void test() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
Environment environment = applicationModel.modelEnvironment();
// test getPrefixedConfiguration
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("127.0.0.1");
registryConfig.setPort(2181);
String prefix = "dubbo.registry";
Configuration prefixedConfiguration = environment.getPrefixedConfiguration(registryConfig, prefix);
Assertions.assertTrue(prefixedConfiguration instanceof PrefixedConfiguration);
// test getConfigurationMaps(AbstractConfig config, String prefix)
List<Map<String, String>> configurationMaps = environment.getConfigurationMaps(registryConfig, prefix);
Assertions.assertEquals(7, configurationMaps.size());
// test getConfigurationMaps()
configurationMaps = environment.getConfigurationMaps();
Assertions.assertEquals(6, configurationMaps.size());
CompositeConfiguration configuration1 = environment.getConfiguration();
CompositeConfiguration configuration2 = environment.getConfiguration();
Assertions.assertEquals(configuration1, configuration2);
// test getDynamicConfiguration
Optional<DynamicConfiguration> dynamicConfiguration = environment.getDynamicConfiguration();
Assertions.assertFalse(dynamicConfiguration.isPresent());
// test getDynamicGlobalConfiguration
Configuration dynamicGlobalConfiguration = environment.getDynamicGlobalConfiguration();
Assertions.assertEquals(dynamicGlobalConfiguration, configuration1);
CompositeDynamicConfiguration compositeDynamicConfiguration = new CompositeDynamicConfiguration();
environment.setDynamicConfiguration(compositeDynamicConfiguration);
dynamicConfiguration = environment.getDynamicConfiguration();
Assertions.assertEquals(dynamicConfiguration.get(), compositeDynamicConfiguration);
dynamicGlobalConfiguration = environment.getDynamicGlobalConfiguration();
Assertions.assertNotEquals(dynamicGlobalConfiguration, configuration1);
// test destroy
environment.destroy();
Assertions.assertNull(environment.getSystemConfiguration());
Assertions.assertNull(environment.getEnvironmentConfiguration());
Assertions.assertNull(environment.getAppExternalConfiguration());
Assertions.assertNull(environment.getExternalConfiguration());
Assertions.assertNull(environment.getAppConfiguration());
frameworkModel.destroy();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentConfigurationTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* The type Environment configuration test.
*/
class EnvironmentConfigurationTest {
private static final String MOCK_KEY = "DUBBO_KEY";
private static final String MOCK_VALUE = "mockValue";
private EnvironmentConfiguration envConfig(Map<String, String> map) {
return new EnvironmentConfiguration() {
@Override
protected Map<String, String> getenv() {
return map;
}
};
}
@Test
void testGetInternalProperty() {
Map<String, String> map = new HashMap<>();
map.put(MOCK_KEY, MOCK_VALUE);
EnvironmentConfiguration configuration = envConfig(map);
Assertions.assertEquals(MOCK_VALUE, configuration.getInternalProperty("dubbo.key"));
Assertions.assertEquals(MOCK_VALUE, configuration.getInternalProperty("key"));
Assertions.assertEquals(MOCK_VALUE, configuration.getInternalProperty("dubbo_key"));
Assertions.assertEquals(MOCK_VALUE, configuration.getInternalProperty(MOCK_KEY));
}
@Test
void testGetProperties() {
Map<String, String> map = new HashMap<>();
map.put(MOCK_KEY, MOCK_VALUE);
EnvironmentConfiguration configuration = new EnvironmentConfiguration() {
@Override
protected Map<String, String> getenv() {
return map;
}
};
Assertions.assertEquals(map, configuration.getProperties());
}
@Test
void testHyphenAndDotKeyResolveFromEnv() {
Map<String, String> envMap = new HashMap<>();
envMap.put("DUBBO_ABC_DEF_GHI", "v1");
envMap.put("DUBBO_ABCDEF_GHI", "v2");
envMap.put("DUBBO_ABC-DEF_GHI", "v3");
envMap.put("dubbo_abc_def_ghi", "v4");
EnvironmentConfiguration configuration = envConfig(envMap);
String dubboKey = "dubbo.abc-def.ghi";
Assertions.assertEquals("v1", configuration.getProperty(dubboKey));
envMap.remove("DUBBO_ABC_DEF_GHI");
configuration = envConfig(envMap);
Assertions.assertEquals("v2", configuration.getProperty(dubboKey));
envMap.remove("DUBBO_ABCDEF_GHI");
configuration = envConfig(envMap);
Assertions.assertEquals("v3", configuration.getProperty(dubboKey));
envMap.remove("DUBBO_ABC-DEF_GHI");
configuration = envConfig(envMap);
Assertions.assertEquals("v4", configuration.getProperty(dubboKey));
envMap.remove("dubbo_abc_def_ghi");
configuration = envConfig(envMap);
Assertions.assertNull(configuration.getProperty(dubboKey));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/PrefixedConfigurationTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/PrefixedConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class PrefixedConfigurationTest {
@Test
void testPrefixedConfiguration() {
Map<String, String> props = new LinkedHashMap<>();
props.put("dubbo.protocol.name", "dubbo");
props.put("dubbo.protocol.port", "1234");
props.put("dubbo.protocols.rest.port", "2345");
InmemoryConfiguration inmemoryConfiguration = new InmemoryConfiguration();
inmemoryConfiguration.addProperties(props);
// prefixed over InmemoryConfiguration
PrefixedConfiguration prefixedConfiguration =
new PrefixedConfiguration(inmemoryConfiguration, "dubbo.protocol");
Assertions.assertEquals("dubbo", prefixedConfiguration.getProperty("name"));
Assertions.assertEquals("1234", prefixedConfiguration.getProperty("port"));
prefixedConfiguration = new PrefixedConfiguration(inmemoryConfiguration, "dubbo.protocols.rest");
Assertions.assertEquals("2345", prefixedConfiguration.getProperty("port"));
// prefixed over composite configuration
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
compositeConfiguration.addConfiguration(inmemoryConfiguration);
prefixedConfiguration = new PrefixedConfiguration(compositeConfiguration, "dubbo.protocols.rest");
Assertions.assertEquals("2345", prefixedConfiguration.getProperty("port"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/CompositeConfigurationTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/CompositeConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link CompositeConfiguration}
*/
class CompositeConfigurationTest {
@Test
void test() {
InmemoryConfiguration inmemoryConfiguration1 = new InmemoryConfiguration();
InmemoryConfiguration inmemoryConfiguration2 = new InmemoryConfiguration();
InmemoryConfiguration inmemoryConfiguration3 = new InmemoryConfiguration();
CompositeConfiguration configuration = new CompositeConfiguration(new Configuration[] {inmemoryConfiguration1});
configuration.addConfiguration(inmemoryConfiguration2);
configuration.addConfigurationFirst(inmemoryConfiguration3);
inmemoryConfiguration1.addProperty("k", "v1");
inmemoryConfiguration2.addProperty("k", "v2");
inmemoryConfiguration3.addProperty("k", "v3");
Assertions.assertEquals(configuration.getInternalProperty("k"), "v3");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEventTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEventTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* {@link ConfigChangedEvent} Test
*
* @since 2.7.5
*/
class ConfigChangedEventTest {
private static final String KEY = "k";
private static final String GROUP = "g";
private static final String CONTENT = "c";
@Test
void testGetter() {
ConfigChangedEvent event = new ConfigChangedEvent(KEY, GROUP, CONTENT);
assertEquals(KEY, event.getKey());
assertEquals(GROUP, event.getGroup());
assertEquals(CONTENT, event.getContent());
assertEquals(ConfigChangeType.MODIFIED, event.getChangeType());
assertEquals("k,g", event.getSource());
event = new ConfigChangedEvent(KEY, GROUP, CONTENT, ConfigChangeType.ADDED);
assertEquals(KEY, event.getKey());
assertEquals(GROUP, event.getGroup());
assertEquals(CONTENT, event.getContent());
assertEquals(ConfigChangeType.ADDED, event.getChangeType());
assertEquals("k,g", event.getSource());
}
@Test
void testEqualsAndHashCode() {
for (ConfigChangeType type : ConfigChangeType.values()) {
assertEquals(
new ConfigChangedEvent(KEY, GROUP, CONTENT, type),
new ConfigChangedEvent(KEY, GROUP, CONTENT, type));
assertEquals(
new ConfigChangedEvent(KEY, GROUP, CONTENT, type).hashCode(),
new ConfigChangedEvent(KEY, GROUP, CONTENT, type).hashCode());
assertEquals(
new ConfigChangedEvent(KEY, GROUP, CONTENT, type).toString(),
new ConfigChangedEvent(KEY, GROUP, CONTENT, type).toString());
}
}
@Test
void testToString() {
ConfigChangedEvent event = new ConfigChangedEvent(KEY, GROUP, CONTENT);
assertNotNull(event.toString());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactoryTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.nop.NopDynamicConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link AbstractDynamicConfigurationFactory} Test
*
* @see AbstractDynamicConfigurationFactory
* @since 2.7.5
*/
class AbstractDynamicConfigurationFactoryTest {
private AbstractDynamicConfigurationFactory factory;
@BeforeEach
public void init() {
factory = new AbstractDynamicConfigurationFactory() {
@Override
protected DynamicConfiguration createDynamicConfiguration(URL url) {
return new NopDynamicConfiguration(url);
}
};
}
@Test
void testGetDynamicConfiguration() {
URL url = URL.valueOf("nop://127.0.0.1");
assertEquals(factory.getDynamicConfiguration(url), factory.getDynamicConfiguration(url));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.apache.dubbo.common.URL;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.DEFAULT_THREAD_POOL_PREFIX;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.DEFAULT_THREAD_POOL_SIZE;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.GROUP_PARAM_NAME;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.PARAM_NAME_PREFIX;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.THREAD_POOL_PREFIX_PARAM_NAME;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.THREAD_POOL_SIZE_PARAM_NAME;
import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.TIMEOUT_PARAM_NAME;
import static org.apache.dubbo.common.config.configcenter.DynamicConfiguration.DEFAULT_GROUP;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* {@link AbstractDynamicConfiguration} Test
*
* @since 2.7.5
*/
class AbstractDynamicConfigurationTest {
private AbstractDynamicConfiguration configuration;
@BeforeEach
public void init() {
configuration = new AbstractDynamicConfiguration(null) {
@Override
protected String doGetConfig(String key, String group) {
return null;
}
@Override
protected void doClose() {}
@Override
protected boolean doRemoveConfig(String key, String group) {
return false;
}
};
}
@Test
void testConstants() {
assertEquals("dubbo.config-center.", PARAM_NAME_PREFIX);
assertEquals("dubbo.config-center.workers", DEFAULT_THREAD_POOL_PREFIX);
assertEquals("dubbo.config-center.thread-pool.prefix", THREAD_POOL_PREFIX_PARAM_NAME);
assertEquals("dubbo.config-center.thread-pool.size", THREAD_POOL_SIZE_PARAM_NAME);
assertEquals("dubbo.config-center.thread-pool.keep-alive-time", THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME);
assertEquals(1, DEFAULT_THREAD_POOL_SIZE);
assertEquals(60 * 1000, DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME);
// @since 2.7.8
assertEquals("dubbo.config-center.group", GROUP_PARAM_NAME);
assertEquals("dubbo.config-center.timeout", TIMEOUT_PARAM_NAME);
}
@Test
void testConstructor() {
URL url = URL.valueOf("default://")
.addParameter(THREAD_POOL_PREFIX_PARAM_NAME, "test")
.addParameter(THREAD_POOL_SIZE_PARAM_NAME, 10)
.addParameter(THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME, 100);
AbstractDynamicConfiguration configuration = new AbstractDynamicConfiguration(url) {
@Override
protected String doGetConfig(String key, String group) {
return null;
}
@Override
protected void doClose() {}
@Override
protected boolean doRemoveConfig(String key, String group) {
return false;
}
};
ThreadPoolExecutor threadPoolExecutor = configuration.getWorkersThreadPool();
ThreadFactory threadFactory = threadPoolExecutor.getThreadFactory();
Thread thread = threadFactory.newThread(() -> {});
assertEquals(10, threadPoolExecutor.getCorePoolSize());
assertEquals(10, threadPoolExecutor.getMaximumPoolSize());
assertEquals(100, threadPoolExecutor.getKeepAliveTime(TimeUnit.MILLISECONDS));
assertEquals("test-thread-1", thread.getName());
}
@Test
void testPublishConfig() {
assertFalse(configuration.publishConfig(null, null));
assertFalse(configuration.publishConfig(null, null, null));
}
//
// @Test
// public void testGetConfigKeys() {
// assertTrue(configuration.getConfigKeys(null).isEmpty());
// }
@Test
void testGetConfig() {
assertNull(configuration.getConfig(null, null));
assertNull(configuration.getConfig(null, null, 200));
}
@Test
void testGetInternalProperty() {
assertNull(configuration.getInternalProperty(null));
}
@Test
void testGetProperties() {
assertNull(configuration.getProperties(null, null));
assertNull(configuration.getProperties(null, null, 100L));
}
@Test
void testAddListener() {
configuration.addListener(null, null);
configuration.addListener(null, null, null);
}
@Test
void testRemoveListener() {
configuration.removeListener(null, null);
configuration.removeListener(null, null, null);
}
@Test
void testClose() throws Exception {
configuration.close();
}
/**
* Test {@link AbstractDynamicConfiguration#getGroup()} and
* {@link AbstractDynamicConfiguration#getDefaultGroup()} methods
*
* @since 2.7.8
*/
@Test
void testGetGroupAndGetDefaultGroup() {
assertEquals(configuration.getGroup(), configuration.getDefaultGroup());
assertEquals(DEFAULT_GROUP, configuration.getDefaultGroup());
}
/**
* Test {@link AbstractDynamicConfiguration#getTimeout()} and
* {@link AbstractDynamicConfiguration#getDefaultTimeout()} methods
*
* @since 2.7.8
*/
@Test
void testGetTimeoutAndGetDefaultTimeout() {
assertEquals(configuration.getTimeout(), configuration.getDefaultTimeout());
assertEquals(-1L, configuration.getDefaultTimeout());
}
/**
* Test {@link AbstractDynamicConfiguration#removeConfig(String, String)} and
* {@link AbstractDynamicConfiguration#doRemoveConfig(String, String)} methods
*
* @since 2.7.8
*/
@Test
void testRemoveConfigAndDoRemoveConfig() throws Exception {
String key = null;
String group = null;
assertEquals(configuration.removeConfig(key, group), configuration.doRemoveConfig(key, group));
assertFalse(configuration.removeConfig(key, group));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangeTypeTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangeTypeTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.config.configcenter.ConfigChangeType.ADDED;
import static org.apache.dubbo.common.config.configcenter.ConfigChangeType.DELETED;
import static org.apache.dubbo.common.config.configcenter.ConfigChangeType.MODIFIED;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
/**
* {@link ConfigChangeType} Test
*
* @see ConfigChangeType
* @since 2.7.5
*/
class ConfigChangeTypeTest {
@Test
void testMembers() {
assertArrayEquals(new ConfigChangeType[] {ADDED, MODIFIED, DELETED}, ConfigChangeType.values());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactoryTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.config.configcenter;
import org.apache.dubbo.common.config.configcenter.nop.NopDynamicConfigurationFactory;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link DynamicConfigurationFactory} Test
*
* @since 2.7.5
*/
class DynamicConfigurationFactoryTest {
@Test
void testDefaultExtension() {
DynamicConfigurationFactory factory =
getExtensionLoader(DynamicConfigurationFactory.class).getDefaultExtension();
assertEquals(NopDynamicConfigurationFactory.class, factory.getClass());
assertEquals(
NopDynamicConfigurationFactory.class,
getExtensionLoader(DynamicConfigurationFactory.class)
.getExtension("nop")
.getClass());
}
private <T> ExtensionLoader<T> getExtensionLoader(Class<T> extClass) {
return ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(extClass);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueueTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueueTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool;
import java.lang.instrument.Instrumentation;
import net.bytebuddy.agent.ByteBuddyAgent;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
class MemoryLimitedLinkedBlockingQueueTest {
private static final Logger logger = LoggerFactory.getLogger(MemoryLimitedLinkedBlockingQueueTest.class);
@Test
void test() {
ByteBuddyAgent.install();
final Instrumentation instrumentation = ByteBuddyAgent.getInstrumentation();
MemoryLimitedLinkedBlockingQueue<Runnable> queue = new MemoryLimitedLinkedBlockingQueue<>(1, instrumentation);
// an object needs more than 1 byte of space, so it will fail here
assertThat(queue.offer(() -> logger.info("add fail")), is(false));
// will success
queue.setMemoryLimit(Integer.MAX_VALUE);
assertThat(queue.offer(() -> logger.info("add success")), is(true));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueueTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueueTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool;
import org.apache.dubbo.common.concurrent.AbortPolicy;
import org.apache.dubbo.common.concurrent.RejectException;
import java.lang.instrument.Instrumentation;
import java.util.concurrent.LinkedBlockingQueue;
import net.bytebuddy.agent.ByteBuddyAgent;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
class MemorySafeLinkedBlockingQueueTest {
private static final Logger logger = LoggerFactory.getLogger(MemorySafeLinkedBlockingQueueTest.class);
@Test
void test() {
ByteBuddyAgent.install();
final Instrumentation instrumentation = ByteBuddyAgent.getInstrumentation();
final long objectSize = instrumentation.getObjectSize((Runnable) () -> {});
long maxFreeMemory = (long) MemoryLimitCalculator.maxAvailable();
MemorySafeLinkedBlockingQueue<Runnable> queue = new MemorySafeLinkedBlockingQueue<>(maxFreeMemory);
// all memory is reserved for JVM, so it will fail here
assertThat(queue.offer(() -> {}), is(false));
// maxFreeMemory-objectSize Byte memory is reserved for the JVM, so this will succeed
queue.setMaxFreeMemory((int) (MemoryLimitCalculator.maxAvailable() - objectSize));
assertThat(queue.offer(() -> {}), is(true));
}
@Test
void testCustomReject() {
MemorySafeLinkedBlockingQueue<Runnable> queue = new MemorySafeLinkedBlockingQueue<>(Long.MAX_VALUE);
queue.setRejector(new AbortPolicy<>());
assertThrows(RejectException.class, () -> queue.offer(() -> {}));
}
@Test
@Disabled("This test is not stable, it may fail due to performance (C1, C2)")
void testEfficiency() throws InterruptedException {
// if length is vert large(unit test may runs for a long time), so you may need to modify JVM param such as :
// -Xms=1024m -Xmx=2048m
// if you want to test efficiency of MemorySafeLinkedBlockingQueue, you may modify following param: length and
// times
int length = 1000, times = 1;
// LinkedBlockingQueue insert Integer: 500W * 20 times
long spent1 = spend(new LinkedBlockingQueue<>(), length, times);
// MemorySafeLinkedBlockingQueue insert Integer: 500W * 20 times
long spent2 = spend(newMemorySafeLinkedBlockingQueue(), length, times);
System.gc();
logger.info(
"LinkedBlockingQueue spent {} millis, MemorySafeLinkedBlockingQueue spent {} millis", spent1, spent2);
// efficiency between LinkedBlockingQueue and MemorySafeLinkedBlockingQueue is very nearly the same
Assertions.assertTrue(spent1 - spent2 <= 1);
}
private static long spend(LinkedBlockingQueue<Integer> lbq, int length, int times) throws InterruptedException {
// new Queue
if (lbq instanceof MemorySafeLinkedBlockingQueue) {
lbq = newMemorySafeLinkedBlockingQueue();
} else {
lbq = new LinkedBlockingQueue<>();
}
long total = 0L;
for (int i = 0; i < times; i++) {
long start = System.currentTimeMillis();
for (int j = 0; j < length; j++) {
lbq.offer(j);
}
long end = System.currentTimeMillis();
long spent = end - start;
total += spent;
}
long result = total / times;
// gc
System.gc();
return result;
}
private static MemorySafeLinkedBlockingQueue<Integer> newMemorySafeLinkedBlockingQueue() {
ByteBuddyAgent.install();
final Instrumentation instrumentation = ByteBuddyAgent.getInstrumentation();
final long objectSize = instrumentation.getObjectSize((Runnable) () -> {});
int maxFreeMemory = (int) MemoryLimitCalculator.maxAvailable();
MemorySafeLinkedBlockingQueue<Integer> queue = new MemorySafeLinkedBlockingQueue<>(maxFreeMemory);
queue.setMaxFreeMemory((int) (MemoryLimitCalculator.maxAvailable() - objectSize));
queue.setRejector(new AbortPolicy<>());
return queue;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/ThreadlessExecutorTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/ThreadlessExecutorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class ThreadlessExecutorTest {
private static final ThreadlessExecutor executor;
static {
executor = new ThreadlessExecutor();
}
@Test
void test() throws InterruptedException {
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
throw new RuntimeException("test");
});
}
executor.waitAndDrain(123);
AtomicBoolean invoked = new AtomicBoolean(false);
executor.execute(() -> {
invoked.set(true);
});
executor.waitAndDrain(123);
Assertions.assertTrue(invoked.get());
executor.shutdown();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReportTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReportTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory;
import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedEvent;
import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedListener;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import java.io.FileOutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.common.constants.CommonConstants.OS_WIN_PREFIX;
import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_OS_NAME;
import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.USER_HOME;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AbortPolicyWithReportTest {
private static final Logger logger = LoggerFactory.getLogger(AbortPolicyWithReportTest.class);
@BeforeEach
public void setUp() {
AbortPolicyWithReport.lastPrintTime = 0;
}
@Test
void jStackDumpTest() {
URL url = URL.valueOf(
"dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory=/tmp&version=1.0.0&application=morgan&noValue=");
AtomicReference<FileOutputStream> fileOutputStream = new AtomicReference<>();
AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url) {
@Override
protected void jstack(FileOutputStream jStackStream) {
fileOutputStream.set(jStackStream);
}
};
ExecutorService executorService = Executors.newFixedThreadPool(1);
AbortPolicyWithReport.lastPrintTime = 0;
Assertions.assertThrows(RejectedExecutionException.class, () -> {
abortPolicyWithReport.rejectedExecution(() -> logger.debug("hello"), (ThreadPoolExecutor) executorService);
});
await().until(() -> AbortPolicyWithReport.guard.availablePermits() == 1);
Assertions.assertNotNull(fileOutputStream.get());
executorService.shutdown();
}
@Test
void jStack_ConcurrencyDump_Silence_10Min() {
URL url = URL.valueOf(
"dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory=/tmp&version=1.0.0&application=morgan&noValue=");
AtomicInteger jStackCount = new AtomicInteger(0);
AtomicInteger failureCount = new AtomicInteger(0);
AtomicInteger finishedCount = new AtomicInteger(0);
AtomicInteger timeoutCount = new AtomicInteger(0);
AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url) {
@Override
protected void jstack(FileOutputStream jStackStream) {
jStackCount.incrementAndGet();
// try to simulate the jstack cost long time, so that AbortPolicyWithReport may jstack repeatedly.
long startTime = System.currentTimeMillis();
await().atLeast(200, TimeUnit.MILLISECONDS).until(() -> System.currentTimeMillis() - startTime >= 300);
}
};
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
4,
4,
0,
TimeUnit.MILLISECONDS,
new SynchronousQueue<>(),
new NamedInternalThreadFactory("jStack_ConcurrencyDump_Silence_10Min", false),
abortPolicyWithReport);
int runTimes = 100;
List<Future<?>> futureList = new LinkedList<>();
for (int i = 0; i < runTimes; i++) {
try {
futureList.add(threadPoolExecutor.submit(() -> {
finishedCount.incrementAndGet();
long start = System.currentTimeMillis();
// try to await 1s to make sure jstack dump thread scheduled
await().atLeast(300, TimeUnit.MILLISECONDS).until(() -> System.currentTimeMillis() - start >= 300);
}));
} catch (Exception ignored) {
failureCount.incrementAndGet();
}
}
futureList.forEach(f -> {
try {
f.get(500, TimeUnit.MILLISECONDS);
} catch (Exception ignored) {
timeoutCount.incrementAndGet();
}
});
logger.info(
"jStackCount: {}, finishedCount: {}, failureCount: {}, timeoutCount: {}",
jStackCount.get(),
finishedCount.get(),
failureCount.get(),
timeoutCount.get());
Assertions.assertEquals(
runTimes, finishedCount.get() + failureCount.get(), "all the test thread should be run completely");
Assertions.assertEquals(1, jStackCount.get(), "'jstack' should be called only once in 10 minutes");
threadPoolExecutor.shutdown();
}
@Test
void jStackDumpTest_dumpDirectoryNotExists_cannotBeCreatedTakeUserHome() {
final String dumpDirectory = dumpDirectoryCannotBeCreated();
URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory="
+ dumpDirectory
+ "&version=1.0.0&application=morgan&noValue=true");
AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url);
Assertions.assertEquals(
SystemPropertyConfigUtils.getSystemProperty(USER_HOME), abortPolicyWithReport.getDumpPath());
}
private String dumpDirectoryCannotBeCreated() {
final String os =
SystemPropertyConfigUtils.getSystemProperty(SYSTEM_OS_NAME).toLowerCase();
if (os.contains(OS_WIN_PREFIX)) {
// colon is a reserved character which could not be used in a file or directory name,
// https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
return "c:o:n";
} else {
return "/dev/full/" + UUID.randomUUID().toString();
}
}
@Test
void jStackDumpTest_dumpDirectoryNotExists_canBeCreated() {
final String dumpDirectory = UUID.randomUUID().toString();
URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory="
+ dumpDirectory
+ "&version=1.0.0&application=morgan&noValue=true");
AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url);
Assertions.assertNotEquals(
SystemPropertyConfigUtils.getSystemProperty(USER_HOME), abortPolicyWithReport.getDumpPath());
}
@Test
void test_dispatchThreadPoolExhaustedEvent() {
URL url = URL.valueOf(
"dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory=/tmp&version=1.0.0&application=morgan&noValue=");
AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url);
String msg =
"Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1";
MyListener listener = new MyListener();
abortPolicyWithReport.addThreadPoolExhaustedEventListener(listener);
abortPolicyWithReport.dispatchThreadPoolExhaustedEvent(msg);
assertEquals(listener.getThreadPoolExhaustedEvent().getMsg(), msg);
}
static class MyListener implements ThreadPoolExhaustedListener {
private ThreadPoolExhaustedEvent threadPoolExhaustedEvent;
@Override
public void onEvent(ThreadPoolExhaustedEvent event) {
this.threadPoolExhaustedEvent = event;
}
public ThreadPoolExhaustedEvent getThreadPoolExhaustedEvent() {
return threadPoolExhaustedEvent;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPoolTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPoolTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.limited;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.InternalThread;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
class LimitedThreadPoolTest {
@Test
void getExecutor1() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY
+ "=demo&" + CORE_THREADS_KEY
+ "=1&" + THREADS_KEY
+ "=2&" + QUEUES_KEY
+ "=0");
ThreadPool threadPool = new LimitedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getCorePoolSize(), is(1));
assertThat(executor.getMaximumPoolSize(), is(2));
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(SynchronousQueue.class));
assertThat(
executor.getRejectedExecutionHandler(),
Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class));
final CountDownLatch latch = new CountDownLatch(1);
executor.execute(new Runnable() {
@Override
public void run() {
Thread thread = Thread.currentThread();
assertThat(thread, instanceOf(InternalThread.class));
assertThat(thread.getName(), startsWith("demo"));
latch.countDown();
}
});
latch.await();
assertThat(latch.getCount(), is(0L));
}
@Test
void getExecutor2() {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=1");
ThreadPool threadPool = new LimitedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(LinkedBlockingQueue.class));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPoolTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPoolTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.cached;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.InternalThread;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
class CachedThreadPoolTest {
@Test
void getExecutor1() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY
+ "=demo&" + CORE_THREADS_KEY
+ "=1&" + THREADS_KEY
+ "=2&" + ALIVE_KEY
+ "=1000&" + QUEUES_KEY
+ "=0");
ThreadPool threadPool = new CachedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getCorePoolSize(), is(1));
assertThat(executor.getMaximumPoolSize(), is(2));
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(SynchronousQueue.class));
assertThat(
executor.getRejectedExecutionHandler(),
Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class));
final CountDownLatch latch = new CountDownLatch(1);
executor.execute(() -> {
Thread thread = Thread.currentThread();
assertThat(thread, instanceOf(InternalThread.class));
assertThat(thread.getName(), startsWith("demo"));
latch.countDown();
});
latch.await();
assertThat(latch.getCount(), is(0L));
}
@Test
void getExecutor2() {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=1");
ThreadPool threadPool = new CachedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(LinkedBlockingQueue.class));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPoolTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPoolTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.fixed;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.InternalThread;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
class FixedThreadPoolTest {
@Test
void getExecutor1() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY
+ "=demo&" + CORE_THREADS_KEY
+ "=1&" + THREADS_KEY
+ "=2&" + QUEUES_KEY
+ "=0");
ThreadPool threadPool = new FixedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getCorePoolSize(), is(2));
assertThat(executor.getMaximumPoolSize(), is(2));
assertThat(executor.getKeepAliveTime(TimeUnit.MILLISECONDS), is(0L));
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(SynchronousQueue.class));
assertThat(
executor.getRejectedExecutionHandler(),
Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class));
final CountDownLatch latch = new CountDownLatch(1);
executor.execute(new Runnable() {
@Override
public void run() {
Thread thread = Thread.currentThread();
assertThat(thread, instanceOf(InternalThread.class));
assertThat(thread.getName(), startsWith("demo"));
latch.countDown();
}
});
latch.await();
assertThat(latch.getCount(), is(0L));
}
@Test
void getExecutor2() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=1");
ThreadPool threadPool = new FixedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(LinkedBlockingQueue.class));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueueTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueueTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.eager;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
class TaskQueueTest {
private TaskQueue<Runnable> queue;
private EagerThreadPoolExecutor executor;
@BeforeEach
void setup() {
queue = new TaskQueue<Runnable>(1);
executor = mock(EagerThreadPoolExecutor.class);
queue.setExecutor(executor);
}
@Test
void testOffer1() throws Exception {
Assertions.assertThrows(RejectedExecutionException.class, () -> {
TaskQueue<Runnable> queue = new TaskQueue<Runnable>(1);
queue.offer(mock(Runnable.class));
});
}
@Test
void testOffer2() throws Exception {
Mockito.when(executor.getPoolSize()).thenReturn(2);
Mockito.when(executor.getActiveCount()).thenReturn(1);
assertThat(queue.offer(mock(Runnable.class)), is(true));
}
@Test
void testOffer3() throws Exception {
Mockito.when(executor.getPoolSize()).thenReturn(2);
Mockito.when(executor.getActiveCount()).thenReturn(2);
Mockito.when(executor.getMaximumPoolSize()).thenReturn(4);
assertThat(queue.offer(mock(Runnable.class)), is(false));
}
@Test
void testOffer4() throws Exception {
Mockito.when(executor.getPoolSize()).thenReturn(4);
Mockito.when(executor.getActiveCount()).thenReturn(4);
Mockito.when(executor.getMaximumPoolSize()).thenReturn(4);
assertThat(queue.offer(mock(Runnable.class)), is(true));
}
@Test
void testRetryOffer1() throws Exception {
Assertions.assertThrows(RejectedExecutionException.class, () -> {
Mockito.when(executor.isShutdown()).thenReturn(true);
queue.retryOffer(mock(Runnable.class), 1000, TimeUnit.MILLISECONDS);
});
}
@Test
void testRetryOffer2() throws Exception {
Mockito.when(executor.isShutdown()).thenReturn(false);
assertThat(queue.retryOffer(mock(Runnable.class), 1000, TimeUnit.MILLISECONDS), is(true));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutorTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.eager;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.awaitility.Awaitility.await;
class EagerThreadPoolExecutorTest {
private static final Logger logger = LoggerFactory.getLogger(EagerThreadPoolExecutorTest.class);
private static final URL URL = new ServiceConfigURL("dubbo", "localhost", 8080);
/**
* It print like this:
* thread number in current pool:1, task number in task queue:0 executor size: 1
* thread number in current pool:2, task number in task queue:0 executor size: 2
* thread number in current pool:3, task number in task queue:0 executor size: 3
* thread number in current pool:4, task number in task queue:0 executor size: 4
* thread number in current pool:5, task number in task queue:0 executor size: 5
* thread number in current pool:6, task number in task queue:0 executor size: 6
* thread number in current pool:7, task number in task queue:0 executor size: 7
* thread number in current pool:8, task number in task queue:0 executor size: 8
* thread number in current pool:9, task number in task queue:0 executor size: 9
* thread number in current pool:10, task number in task queue:0 executor size: 10
* thread number in current pool:10, task number in task queue:4 executor size: 10
* thread number in current pool:10, task number in task queue:3 executor size: 10
* thread number in current pool:10, task number in task queue:2 executor size: 10
* thread number in current pool:10, task number in task queue:1 executor size: 10
* thread number in current pool:10, task number in task queue:0 executor size: 10
* <p>
* We can see , when the core threads are in busy,
* the thread pool create thread (but thread nums always less than max) instead of put task into queue.
*/
@Disabled("replaced to testEagerThreadPoolFast for performance")
@Test
void testEagerThreadPool() throws Exception {
String name = "eager-tf";
int queues = 5;
int cores = 5;
int threads = 10;
// alive 1 second
long alive = 1000;
// init queue and executor
TaskQueue<Runnable> taskQueue = new TaskQueue<Runnable>(queues);
final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(
cores,
threads,
alive,
TimeUnit.MILLISECONDS,
taskQueue,
new NamedThreadFactory(name, true),
new AbortPolicyWithReport(name, URL));
taskQueue.setExecutor(executor);
for (int i = 0; i < 15; i++) {
Thread.sleep(50);
executor.execute(() -> {
logger.info(
"thread number in current pool:{}, task number in task queue:{} executor size: {}",
executor.getPoolSize(),
executor.getQueue().size(),
executor.getPoolSize());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
Thread.sleep(5000);
// cores theads are all alive.
Assertions.assertEquals(executor.getPoolSize(), cores, "more than cores threads alive!");
executor.shutdown();
}
@Test
void testEagerThreadPoolFast() {
String name = "eager-tf";
int queues = 5;
int cores = 5;
// github actions usually run on 4 cores which could be determined by LoadStatusCheckerTest
int threads = 5;
// alive 1 second
long alive = 1000;
// init queue and executor
TaskQueue<Runnable> taskQueue = new TaskQueue<>(queues);
final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(
cores,
threads,
alive,
TimeUnit.MILLISECONDS,
taskQueue,
new NamedThreadFactory(name, true),
new AbortPolicyWithReport(name, URL));
taskQueue.setExecutor(executor);
CountDownLatch countDownLatch1 = new CountDownLatch(1);
for (int i = 0; i < 5; i++) {
executor.execute(() -> {
try {
countDownLatch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
await().until(() -> executor.getPoolSize() == 5);
Assertions.assertEquals(5, executor.getActiveCount());
CountDownLatch countDownLatch2 = new CountDownLatch(1);
AtomicBoolean started = new AtomicBoolean(false);
for (int i = 0; i < 5; i++) {
executor.execute(() -> {
started.set(true);
try {
countDownLatch2.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
await().until(() -> executor.getQueue().size() == 5);
Assertions.assertEquals(5, executor.getActiveCount());
Assertions.assertEquals(5, executor.getPoolSize());
Assertions.assertFalse(started.get());
countDownLatch1.countDown();
await().until(() -> executor.getActiveCount() == 5);
Assertions.assertTrue(started.get());
countDownLatch2.countDown();
await().until(() -> executor.getActiveCount() == 0);
await().until(() -> executor.getPoolSize() == cores);
executor.shutdown();
}
@Test
void testSPI() {
ExtensionLoader<ThreadPool> extensionLoader =
ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(ThreadPool.class);
ExecutorService executorService =
(ExecutorService) extensionLoader.getExtension("eager").getExecutor(URL);
Assertions.assertEquals(
"EagerThreadPoolExecutor", executorService.getClass().getSimpleName(), "test spi fail!");
}
@Test
void testEagerThreadPool_rejectExecution1() {
String name = "eager-tf";
int cores = 1;
int threads = 3;
int queues = 2;
long alive = 1000;
// init queue and executor
TaskQueue<Runnable> taskQueue = new TaskQueue<>(queues);
final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(
cores,
threads,
alive,
TimeUnit.MILLISECONDS,
taskQueue,
new NamedThreadFactory(name, true),
new AbortPolicyWithReport(name, URL));
taskQueue.setExecutor(executor);
CountDownLatch countDownLatch = new CountDownLatch(1);
Runnable runnable = () -> {
try {
countDownLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
for (int i = 0; i < 5; i++) {
executor.execute(runnable);
}
await().until(() -> executor.getPoolSize() == threads);
await().until(() -> executor.getQueue().size() == queues);
Assertions.assertThrows(RejectedExecutionException.class, () -> executor.execute(runnable));
countDownLatch.countDown();
await().until(() -> executor.getActiveCount() == 0);
executor.execute(runnable);
executor.shutdown();
}
@Test
void testEagerThreadPool_rejectExecution2() {
String name = "eager-tf";
int cores = 1;
int threads = 3;
int queues = 2;
long alive = 1000;
// init queue and executor
AtomicReference<Runnable> runnableWhenRetryOffer = new AtomicReference<>();
TaskQueue<Runnable> taskQueue = new TaskQueue<Runnable>(queues) {
@Override
public boolean retryOffer(Runnable o, long timeout, TimeUnit unit) throws InterruptedException {
if (runnableWhenRetryOffer.get() != null) {
runnableWhenRetryOffer.get().run();
}
return super.retryOffer(o, timeout, unit);
}
};
final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(
cores,
threads,
alive,
TimeUnit.MILLISECONDS,
taskQueue,
new NamedThreadFactory(name, true),
new AbortPolicyWithReport(name, URL));
taskQueue.setExecutor(executor);
Semaphore semaphore = new Semaphore(0);
Runnable runnable = () -> {
try {
semaphore.acquire();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
for (int i = 0; i < 5; i++) {
executor.execute(runnable);
}
await().until(() -> executor.getPoolSize() == threads);
await().until(() -> executor.getQueue().size() == queues);
Assertions.assertThrows(RejectedExecutionException.class, () -> executor.execute(runnable));
runnableWhenRetryOffer.set(() -> {
semaphore.release();
await().until(() -> executor.getCompletedTaskCount() == 1);
});
executor.execute(runnable);
semaphore.release(5);
await().until(() -> executor.getActiveCount() == 0);
executor.shutdown();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.support.eager;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.InternalThread;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
class EagerThreadPoolTest {
@Test
void getExecutor1() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY
+ "=demo&" + CORE_THREADS_KEY
+ "=1&" + THREADS_KEY
+ "=2&" + ALIVE_KEY
+ "=1000&" + QUEUES_KEY
+ "=0");
ThreadPool threadPool = new EagerThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor, instanceOf(EagerThreadPoolExecutor.class));
assertThat(executor.getCorePoolSize(), is(1));
assertThat(executor.getMaximumPoolSize(), is(2));
assertThat(executor.getKeepAliveTime(TimeUnit.MILLISECONDS), is(1000L));
assertThat(executor.getQueue().remainingCapacity(), is(1));
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(TaskQueue.class));
assertThat(
executor.getRejectedExecutionHandler(),
Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class));
final CountDownLatch latch = new CountDownLatch(1);
executor.execute(() -> {
Thread thread = Thread.currentThread();
assertThat(thread, instanceOf(InternalThread.class));
assertThat(thread.getName(), startsWith("demo"));
latch.countDown();
});
latch.await();
assertThat(latch.getCount(), is(0L));
}
@Test
void getExecutor2() {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=2");
ThreadPool threadPool = new EagerThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getQueue().remainingCapacity(), is(2));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepositoryTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepositoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.manager;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.awaitility.Awaitility.await;
class ExecutorRepositoryTest {
private ApplicationModel applicationModel;
private ExecutorRepository executorRepository;
@BeforeEach
public void setup() {
applicationModel = FrameworkModel.defaultModel().newApplication();
executorRepository = ExecutorRepository.getInstance(applicationModel);
}
@AfterEach
public void teardown() {
applicationModel.destroy();
}
@Test
void testGetExecutor() {
testGet(URL.valueOf("dubbo://127.0.0.1:23456/TestService"));
testGet(URL.valueOf("dubbo://127.0.0.1:23456/TestService?side=consumer"));
Assertions.assertNotNull(executorRepository.getSharedExecutor());
Assertions.assertNotNull(executorRepository.getServiceExportExecutor());
Assertions.assertNotNull(executorRepository.getServiceReferExecutor());
executorRepository.nextScheduledExecutor();
}
private void testGet(URL url) {
ExecutorService executorService = executorRepository.createExecutorIfAbsent(url);
executorService.shutdown();
executorService = executorRepository.createExecutorIfAbsent(url);
Assertions.assertFalse(executorService.isShutdown());
Assertions.assertEquals(executorService, executorRepository.getExecutor(url));
executorService.shutdown();
Assertions.assertNotEquals(executorService, executorRepository.getExecutor(url));
}
@Test
void testUpdateExecutor() {
URL url = URL.valueOf("dubbo://127.0.0.1:23456/TestService?threads=5");
ThreadPoolExecutor executorService = (ThreadPoolExecutor) executorRepository.createExecutorIfAbsent(url);
executorService.setCorePoolSize(3);
executorRepository.updateThreadpool(url, executorService);
executorService.setCorePoolSize(3);
executorService.setMaximumPoolSize(3);
executorRepository.updateThreadpool(url, executorService);
executorService.setMaximumPoolSize(20);
executorService.setCorePoolSize(10);
executorRepository.updateThreadpool(url, executorService);
executorService.setCorePoolSize(10);
executorService.setMaximumPoolSize(10);
executorRepository.updateThreadpool(url, executorService);
executorService.setCorePoolSize(5);
executorRepository.updateThreadpool(url, executorService);
}
@Test
void testSharedExecutor() throws Exception {
ExecutorService sharedExecutor = executorRepository.getSharedExecutor();
CountDownLatch latch = new CountDownLatch(3);
CountDownLatch latch1 = new CountDownLatch(1);
sharedExecutor.execute(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
sharedExecutor.execute(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
sharedExecutor.submit(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
await().until(() -> latch.getCount() == 0);
Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getActiveCount());
latch1.countDown();
await().until(() -> ((ThreadPoolExecutor) sharedExecutor).getActiveCount() == 0);
Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getCompletedTaskCount());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepositoryTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepositoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.manager;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.awaitility.Awaitility.await;
class FrameworkExecutorRepositoryTest {
private FrameworkModel frameworkModel;
private FrameworkExecutorRepository frameworkExecutorRepository;
@BeforeEach
public void setup() {
frameworkModel = new FrameworkModel();
frameworkExecutorRepository = frameworkModel.getBeanFactory().getBean(FrameworkExecutorRepository.class);
}
@AfterEach
public void teardown() {
frameworkModel.destroy();
}
@Test
void testGetExecutor() {
Assertions.assertNotNull(frameworkExecutorRepository.getSharedExecutor());
frameworkExecutorRepository.nextScheduledExecutor();
}
@Test
void testSharedExecutor() throws Exception {
ExecutorService sharedExecutor = frameworkExecutorRepository.getSharedExecutor();
CountDownLatch latch = new CountDownLatch(3);
CountDownLatch latch1 = new CountDownLatch(1);
sharedExecutor.execute(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
sharedExecutor.execute(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
sharedExecutor.submit(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
await().until(() -> latch.getCount() == 0);
Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getActiveCount());
latch1.countDown();
await().until(() -> ((ThreadPoolExecutor) sharedExecutor).getActiveCount() == 0);
Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getCompletedTaskCount());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventListenerTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventListenerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.event;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link ThreadPoolExhaustedEvent} Test
*/
class ThreadPoolExhaustedEventListenerTest {
private MyListener listener;
@BeforeEach
public void init() {
this.listener = new MyListener();
}
@Test
void testOnEvent() {
String msg =
"Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1";
ThreadPoolExhaustedEvent exhaustedEvent = new ThreadPoolExhaustedEvent(msg);
listener.onEvent(exhaustedEvent);
assertEquals(exhaustedEvent, listener.getThreadPoolExhaustedEvent());
}
static class MyListener implements ThreadPoolExhaustedListener {
private ThreadPoolExhaustedEvent threadPoolExhaustedEvent;
@Override
public void onEvent(ThreadPoolExhaustedEvent event) {
this.threadPoolExhaustedEvent = event;
}
public ThreadPoolExhaustedEvent getThreadPoolExhaustedEvent() {
return threadPoolExhaustedEvent;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.event;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link ThreadPoolExhaustedEvent} Test
*/
class ThreadPoolExhaustedEventTest {
@Test
void test() {
String msg =
"Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1";
ThreadPoolExhaustedEvent event = new ThreadPoolExhaustedEvent(msg);
assertEquals(msg, event.getMsg());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutorTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.threadpool.serial;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.awaitility.Awaitility.await;
class SerializingExecutorTest {
private ExecutorService service;
private SerializingExecutor serializingExecutor;
@BeforeEach
public void before() {
service = Executors.newFixedThreadPool(4);
serializingExecutor = new SerializingExecutor(service);
}
@Test
void testSerial() throws InterruptedException {
int total = 10000;
Map<String, Integer> map = new HashMap<>();
map.put("val", 0);
Semaphore semaphore = new Semaphore(1);
CountDownLatch startLatch = new CountDownLatch(1);
AtomicBoolean failed = new AtomicBoolean(false);
for (int i = 0; i < total; i++) {
final int index = i;
serializingExecutor.execute(() -> {
if (!semaphore.tryAcquire()) {
failed.set(true);
}
try {
startLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
int num = map.get("val");
map.put("val", num + 1);
if (num != index) {
failed.set(true);
}
semaphore.release();
});
}
startLatch.countDown();
await().until(() -> map.get("val") == total);
Assertions.assertFalse(failed.get());
}
@Test
void testNonSerial() {
int total = 10;
Map<String, Integer> map = new HashMap<>();
map.put("val", 0);
Semaphore semaphore = new Semaphore(1);
CountDownLatch startLatch = new CountDownLatch(1);
AtomicBoolean failed = new AtomicBoolean(false);
for (int i = 0; i < total; i++) {
final int index = i;
service.execute(() -> {
if (!semaphore.tryAcquire()) {
failed.set(true);
}
try {
startLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
int num = map.get("val");
map.put("val", num + 1);
if (num != index) {
failed.set(true);
}
semaphore.release();
});
}
await().until(() -> ((ThreadPoolExecutor) service).getActiveCount() == 4);
startLatch.countDown();
await().until(() -> ((ThreadPoolExecutor) service).getCompletedTaskCount() == total);
Assertions.assertTrue(failed.get());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/status/StatusTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/status/StatusTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.status.Status.Level.OK;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
class StatusTest {
@Test
void testConstructor1() throws Exception {
Status status = new Status(OK, "message", "description");
assertThat(status.getLevel(), is(OK));
assertThat(status.getMessage(), equalTo("message"));
assertThat(status.getDescription(), equalTo("description"));
}
@Test
void testConstructor2() throws Exception {
Status status = new Status(OK, "message");
assertThat(status.getLevel(), is(OK));
assertThat(status.getMessage(), equalTo("message"));
assertThat(status.getDescription(), isEmptyOrNullString());
}
@Test
void testConstructor3() throws Exception {
Status status = new Status(OK);
assertThat(status.getLevel(), is(OK));
assertThat(status.getMessage(), isEmptyOrNullString());
assertThat(status.getDescription(), isEmptyOrNullString());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/StatusUtilsTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/status/support/StatusUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status.support;
import org.apache.dubbo.common.status.Status;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.not;
class StatusUtilsTest {
@Test
void testGetSummaryStatus1() throws Exception {
Status status1 = new Status(Status.Level.ERROR);
Status status2 = new Status(Status.Level.WARN);
Status status3 = new Status(Status.Level.OK);
Map<String, Status> statuses = new HashMap<String, Status>();
statuses.put("status1", status1);
statuses.put("status2", status2);
statuses.put("status3", status3);
Status status = StatusUtils.getSummaryStatus(statuses);
assertThat(status.getLevel(), is(Status.Level.ERROR));
assertThat(status.getMessage(), containsString("status1"));
assertThat(status.getMessage(), containsString("status2"));
assertThat(status.getMessage(), not(containsString("status3")));
}
@Test
void testGetSummaryStatus2() throws Exception {
Status status1 = new Status(Status.Level.WARN);
Status status2 = new Status(Status.Level.OK);
Map<String, Status> statuses = new HashMap<String, Status>();
statuses.put("status1", status1);
statuses.put("status2", status2);
Status status = StatusUtils.getSummaryStatus(statuses);
assertThat(status.getLevel(), is(Status.Level.WARN));
assertThat(status.getMessage(), containsString("status1"));
assertThat(status.getMessage(), not(containsString("status2")));
}
@Test
void testGetSummaryStatus3() throws Exception {
Status status1 = new Status(Status.Level.OK);
Map<String, Status> statuses = new HashMap<String, Status>();
statuses.put("status1", status1);
Status status = StatusUtils.getSummaryStatus(statuses);
assertThat(status.getLevel(), is(Status.Level.OK));
assertThat(status.getMessage(), isEmptyOrNullString());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/MemoryStatusCheckerTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/status/support/MemoryStatusCheckerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status.support;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.status.Status;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.status.Status.Level.OK;
import static org.apache.dubbo.common.status.Status.Level.WARN;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
class MemoryStatusCheckerTest {
private static final Logger logger = LoggerFactory.getLogger(MemoryStatusCheckerTest.class);
@Test
void test() {
MemoryStatusChecker statusChecker = new MemoryStatusChecker();
Status status = statusChecker.check();
assertThat(status.getLevel(), anyOf(is(OK), is(WARN)));
logger.info("memory status level: " + status.getLevel());
logger.info("memory status message: " + status.getMessage());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/LoadStatusCheckerTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/status/support/LoadStatusCheckerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status.support;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.status.Status;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
class LoadStatusCheckerTest {
private static Logger logger = LoggerFactory.getLogger(LoadStatusCheckerTest.class);
@Test
void test() {
LoadStatusChecker statusChecker = new LoadStatusChecker();
Status status = statusChecker.check();
assertThat(status, notNullValue());
logger.info("load status level: " + status.getLevel());
logger.info("load status message: " + status.getMessage());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportServiceTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportServiceTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status.reporter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_INSTANCE;
import static org.apache.dubbo.common.status.reporter.FrameworkStatusReportService.ADDRESS_CONSUMPTION_STATUS;
import static org.apache.dubbo.common.status.reporter.FrameworkStatusReportService.MIGRATION_STEP_STATUS;
import static org.apache.dubbo.common.status.reporter.FrameworkStatusReportService.REGISTRATION_STATUS;
/**
* {@link FrameworkStatusReportService}
*/
class FrameworkStatusReportServiceTest {
@Test
void test() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ApplicationConfig app = new ApplicationConfig("APP");
applicationModel.getApplicationConfigManager().setApplication(app);
FrameworkStatusReportService reportService =
applicationModel.getBeanFactory().getBean(FrameworkStatusReportService.class);
// 1. reportRegistrationStatus
reportService.reportRegistrationStatus(reportService.createRegistrationReport(DEFAULT_REGISTER_MODE_INSTANCE));
// 2. createConsumptionReport
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceInterface()).thenReturn("Test");
Mockito.when(consumerURL.getGroup()).thenReturn("Group");
Mockito.when(consumerURL.getVersion()).thenReturn("0.0.0");
Mockito.when(consumerURL.getServiceKey()).thenReturn("Group/Test:0.0.0");
Mockito.when(consumerURL.getDisplayServiceKey()).thenReturn("Test:0.0.0");
reportService.reportConsumptionStatus(reportService.createConsumptionReport(
consumerURL.getServiceInterface(), consumerURL.getVersion(), consumerURL.getGroup(), "status"));
// 3. reportMigrationStepStatus
reportService.reportMigrationStepStatus(reportService.createMigrationStepReport(
consumerURL.getServiceInterface(),
consumerURL.getVersion(),
consumerURL.getGroup(),
"FORCE_INTERFACE",
"FORCE_APPLICATION",
"true"));
MockFrameworkStatusReporter statusReporter =
(MockFrameworkStatusReporter) applicationModel.getExtension(FrameworkStatusReporter.class, "mock");
// "migrationStepStatus" ->
// "{"originStep":"FORCE_INTERFACE","application":"APP","service":"Test","success":"true","newStep":"FORCE_APPLICATION","type":"migrationStepStatus","version":"0.0.0","group":"Group"}"
// "registration" -> "{"application":"APP","status":"instance"}"
// "consumption" ->
// "{"application":"APP","service":"Test","type":"consumption","version":"0.0.0","group":"Group","status":"status"}"
Map<String, Object> reportContent = statusReporter.getReportContent();
Assertions.assertEquals(reportContent.size(), 3);
// verify registrationStatus
Object registrationStatus = reportContent.get(REGISTRATION_STATUS);
Map<String, String> registrationMap = JsonUtils.toJavaObject(String.valueOf(registrationStatus), Map.class);
Assertions.assertEquals(registrationMap.get("application"), "APP");
Assertions.assertEquals(registrationMap.get("status"), "instance");
// verify addressConsumptionStatus
Object addressConsumptionStatus = reportContent.get(ADDRESS_CONSUMPTION_STATUS);
Map<String, String> consumptionMap =
JsonUtils.toJavaObject(String.valueOf(addressConsumptionStatus), Map.class);
Assertions.assertEquals(consumptionMap.get("application"), "APP");
Assertions.assertEquals(consumptionMap.get("service"), "Test");
Assertions.assertEquals(consumptionMap.get("status"), "status");
Assertions.assertEquals(consumptionMap.get("type"), "consumption");
Assertions.assertEquals(consumptionMap.get("version"), "0.0.0");
Assertions.assertEquals(consumptionMap.get("group"), "Group");
// verify migrationStepStatus
Object migrationStepStatus = reportContent.get(MIGRATION_STEP_STATUS);
Map<String, String> migrationStepStatusMap =
JsonUtils.toJavaObject(String.valueOf(migrationStepStatus), Map.class);
Assertions.assertEquals(migrationStepStatusMap.get("originStep"), "FORCE_INTERFACE");
Assertions.assertEquals(migrationStepStatusMap.get("application"), "APP");
Assertions.assertEquals(migrationStepStatusMap.get("service"), "Test");
Assertions.assertEquals(migrationStepStatusMap.get("success"), "true");
Assertions.assertEquals(migrationStepStatusMap.get("newStep"), "FORCE_APPLICATION");
Assertions.assertEquals(migrationStepStatusMap.get("type"), "migrationStepStatus");
Assertions.assertEquals(migrationStepStatusMap.get("version"), "0.0.0");
Assertions.assertEquals(migrationStepStatusMap.get("group"), "Group");
frameworkModel.destroy();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/status/reporter/MockFrameworkStatusReporter.java | dubbo-common/src/test/java/org/apache/dubbo/common/status/reporter/MockFrameworkStatusReporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.status.reporter;
import java.util.HashMap;
import java.util.Map;
public class MockFrameworkStatusReporter implements FrameworkStatusReporter {
Map<String, Object> reportContent = new HashMap<>();
@Override
public void report(String type, Object obj) {
reportContent.put(type, obj);
}
public Map<String, Object> getReportContent() {
return reportContent;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStreamTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStreamTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
class UnsafeByteArrayInputStreamTest {
@Test
void testMark() {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes(), 1);
assertThat(stream.markSupported(), is(true));
stream.mark(2);
stream.read();
assertThat(stream.position(), is(2));
stream.reset();
assertThat(stream.position(), is(1));
}
@Test
void testRead() throws IOException {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
assertThat(stream.read(), is((int) 'a'));
assertThat(stream.available(), is(2));
stream.skip(1);
assertThat(stream.available(), is(1));
byte[] bytes = new byte[1];
int read = stream.read(bytes);
assertThat(read, is(1));
assertThat(bytes, is("c".getBytes()));
stream.reset();
assertThat(stream.position(), is(0));
assertThat(stream.size(), is(3));
stream.position(1);
assertThat(stream.read(), is((int) 'b'));
}
@Test
void testWrongLength() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
stream.read(new byte[1], 0, 100);
});
}
@Test
void testWrongOffset() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
stream.read(new byte[1], -1, 1);
});
}
@Test
void testReadEmptyByteArray() {
Assertions.assertThrows(NullPointerException.class, () -> {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
stream.read(null, 0, 1);
});
}
@Test
void testSkipZero() {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
long skip = stream.skip(-1);
assertThat(skip, is(0L));
assertThat(stream.position(), is(0));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStreamTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStreamTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
class UnsafeByteArrayOutputStreamTest {
@Test
void testWrongSize() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new UnsafeByteArrayOutputStream(-1));
}
@Test
void testWrite() {
UnsafeByteArrayOutputStream outputStream = new UnsafeByteArrayOutputStream(1);
outputStream.write((int) 'a');
outputStream.write("bc".getBytes(), 0, 2);
assertThat(outputStream.size(), is(3));
assertThat(outputStream.toString(), is("abc"));
}
@Test
void testToByteBuffer() {
UnsafeByteArrayOutputStream outputStream = new UnsafeByteArrayOutputStream(1);
outputStream.write((int) 'a');
ByteBuffer byteBuffer = outputStream.toByteBuffer();
assertThat(byteBuffer.get(), is("a".getBytes()[0]));
}
@Test
void testExtendLengthForBuffer() throws IOException {
UnsafeByteArrayOutputStream outputStream = new UnsafeByteArrayOutputStream(1);
for (int i = 0; i < 10; i++) {
outputStream.write(i);
}
assertThat(outputStream.size(), is(10));
OutputStream stream = mock(OutputStream.class);
outputStream.writeTo(stream);
Mockito.verify(stream).write(any(byte[].class), anyInt(), eq(10));
}
@Test
void testToStringWithCharset() throws IOException {
UnsafeByteArrayOutputStream outputStream = new UnsafeByteArrayOutputStream();
outputStream.write("Hòa Bình".getBytes(StandardCharsets.UTF_8));
assertThat(outputStream.toString("UTF-8"), is("Hòa Bình"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringReaderTest.java | dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringReaderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.dubbo.common.io;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
class UnsafeStringReaderTest {
@Test
void testRead() throws IOException {
UnsafeStringReader reader = new UnsafeStringReader("abc");
assertThat(reader.markSupported(), is(true));
assertThat(reader.read(), is((int) 'a'));
assertThat(reader.read(), is((int) 'b'));
assertThat(reader.read(), is((int) 'c'));
assertThat(reader.read(), is(-1));
reader.reset();
reader.mark(0);
assertThat(reader.read(), is((int) 'a'));
char[] chars = new char[2];
reader.read(chars);
reader.close();
assertThat(chars[0], is('b'));
assertThat(chars[1], is('c'));
}
@Test
void testSkip() throws IOException {
UnsafeStringReader reader = new UnsafeStringReader("abc");
assertThat(reader.ready(), is(true));
reader.skip(1);
assertThat(reader.read(), is((int) 'b'));
}
@Test
void testSkipTooLong() throws IOException {
UnsafeStringReader reader = new UnsafeStringReader("abc");
reader.skip(10);
long skip = reader.skip(10);
assertThat(skip, is(0L));
}
@Test
void testWrongLength() throws IOException {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
UnsafeStringReader reader = new UnsafeStringReader("abc");
char[] chars = new char[1];
reader.read(chars, 0, 2);
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.